-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselfupdate.go
173 lines (143 loc) · 4.92 KB
/
selfupdate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path"
)
type githubReleaseAsset struct {
URL string `json:"url"`
ID int `json:"id"`
Name string `json:"name"`
Label string `json:"label"`
ContentType string `json:"content_type"`
State string `json:"state"`
Size int `json:"size"`
DownloadCount int `json:"download_count"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
BrowserDownloadURL string `json:"browser_download_url"`
// skipped "uploader"
}
type githubRelease struct {
URL string `json:"url"`
AssetsURL string `json:"assets_url"`
UploadURL string `json:"upload_url"`
HTMLURL string `json:"html_url"`
ID int `json:"id"`
TagName string `json:"tag_name"`
TargetCommitish string `json:"target_commitish"`
Name *interface{} `json:"name"`
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
CreatedAt string `json:"created_at"`
PublishedAt string `json:"published_at"`
Assets []githubReleaseAsset `json:"assets"`
TarballURL string `json:"tarball_url"`
ZipballURL string `json:"zipball_url"`
Body *interface{} `json:"body"`
// skipped "author"
}
type selfupdateOpts struct {
Force bool `short:"f" long:"force" description:"Force installing the current latest release"`
}
func (o *selfupdateOpts) Execute(args []string) error {
err := runSelfUpdate(o.Force)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return nil
}
func runSelfUpdate(force bool) error {
if force {
fmt.Println("Forcing a self-update.")
}
if VersionTag == "" && !force {
fmt.Println("Running a development binary, skipping update.")
return nil
}
latestRelease, err := getLatestPlatconfRelease()
if err != nil {
return err
}
fmt.Printf("Latest release is %s\n", latestRelease.TagName)
if latestRelease.TagName == VersionTag && !force {
fmt.Println("Already up-to-date.")
return nil
}
if len(latestRelease.Assets) != 1 {
return fmt.Errorf("Latest release has %d assets. Cancelling.", len(latestRelease.Assets))
}
// Previous steps made no changes. Now let's check if we're root before we actually try to do something.
requireRoot()
err = installPlatconfFromURL(latestRelease.Assets[0].BrowserDownloadURL)
if err != nil {
return err
}
fmt.Println("Self-update completed successfully.")
return nil
}
func installPlatconfFromURL(url string) error {
targetBinaryDir := "/opt/bin"
targetBinaryFullPath := path.Join(targetBinaryDir, "platconf")
tempFileFullPath := path.Join(targetBinaryDir, "platconf-download.tmp")
// first we download the binary from github release assets to a temporary file
tempFile, err := os.OpenFile(tempFileFullPath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0755)
if err != nil {
return fmt.Errorf("installPlatconfFromURL: OpenFile: %s", err.Error())
}
defer os.Remove(tempFileFullPath)
defer tempFile.Close()
fmt.Printf("Downloading new binary to '%s'\n", tempFileFullPath)
resp, err := http.Get(url)
if err != nil {
return fmt.Errorf("installPlatconfFromURL: http.Get: %s", err.Error())
}
_, err = io.Copy(tempFile, resp.Body)
if err != nil {
return fmt.Errorf("installPlatconfFromURL: Copy: %s", err.Error())
}
err = tempFile.Sync()
if err != nil {
return fmt.Errorf("installPlatconfFromURL: Sync: %s", err.Error())
}
tempFile.Close()
// Now we relink the new file under the old binary's path.
// We cannot just write to the destination path directly for two reasons:
// 1. If we fail halfway through the operation, we have no working platconf.
// 2. We would overwrite the currently running binary code, causing it to bail.
// Yes, I checked, it actually dies.
fmt.Printf("Installing the new binary to '%s'\n", targetBinaryFullPath)
err = os.MkdirAll(targetBinaryDir, 0755)
if err != nil {
return fmt.Errorf("installPlatconfFromURL: MkdirAll: %s", err.Error())
}
err = os.Rename(tempFileFullPath, targetBinaryFullPath)
if err != nil {
return fmt.Errorf("installPlatconfFromURL: Rename: %s", err.Error())
}
err = os.Chmod(targetBinaryFullPath, 0755)
if err != nil {
return fmt.Errorf("installPlatconfFromURL: Chmod: %s", err.Error())
}
return nil
}
func getLatestPlatconfRelease() (*githubRelease, error) {
resp, err := http.Get("https://api.github.com/repos/experimental-platform/platconf/releases/latest")
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("No releases found.")
}
decoder := json.NewDecoder(resp.Body)
var result githubRelease
err = decoder.Decode(&result)
if err != nil {
return nil, err
}
return &result, nil
}