-
Notifications
You must be signed in to change notification settings - Fork 0
/
ghru.go
283 lines (230 loc) · 6.27 KB
/
ghru.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package ghru
import (
"compress/bzip2"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/axllent/semver"
)
// AllowPrereleases defines whether pre-releases may be included
var AllowPrereleases = false
// Releases struct for Github releases json
type Releases []struct {
Name string `json:"name"` // release name
Tag string `json:"tag_name"` // release tag
Prerelease bool `json:"prerelease"` // Github pre-release
Assets []struct {
BrowserDownloadURL string `json:"browser_download_url"`
ID int64 `json:"id"`
Name string `json:"name"`
Size int64 `json:"size"`
} `json:"assets"`
}
// Release struct contains the file data for downloadable release
type Release struct {
Name string
Tag string
URL string
Size int64
}
// Latest fetches the latest release info & returns release tag, filename & download url
func Latest(repo, name string) (string, string, string, error) {
releaseURL := fmt.Sprintf("https://api.github.com/repos/%s/releases", repo)
resp, err := http.Get(releaseURL)
if err != nil {
return "", "", "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", "", "", err
}
linkOS := runtime.GOOS
linkArch := runtime.GOARCH
linkExt := ""
if linkOS == "windows" {
linkExt = ".exe"
}
var allReleases = []Release{}
var releases Releases
json.Unmarshal(body, &releases)
// loop through releases
for _, r := range releases {
if !semver.IsValid(r.Tag) {
// Invalid semversion, skip
continue
}
if !AllowPrereleases && (semver.Prerelease(r.Tag) != "" || r.Prerelease) {
// we don't accept AllowPrereleases, skip
continue
}
binaryName := fmt.Sprintf("%s_%s_%s_%s%s.bz2", name, r.Tag, linkOS, linkArch, linkExt)
for _, a := range r.Assets {
if a.Name == binaryName {
thisRelease := Release{a.Name, r.Tag, a.BrowserDownloadURL, a.Size}
allReleases = append(allReleases, thisRelease)
break
}
}
}
if len(allReleases) == 0 {
// no releases with suitable assets found
return "", "", "", fmt.Errorf("No binary releases found")
}
var latestRelease = Release{}
for _, r := range allReleases {
// detect the latest release
if semver.Compare(r.Tag, latestRelease.Tag) == 1 {
latestRelease = r
}
}
return latestRelease.Tag, latestRelease.Name, latestRelease.URL, nil
}
// GreaterThan compares the current version to a different version
// returning < 1 not upgradeable
func GreaterThan(toVer, fromVer string) bool {
return semver.Compare(toVer, fromVer) == 1
}
// Update the running binary with the latest release binary from Github
func Update(repo, appName, currentVersion string) (string, error) {
ver, filename, downloadURL, err := Latest(repo, appName)
if err != nil {
return "", err
}
if ver == currentVersion {
return "", fmt.Errorf("No new release found")
}
if semver.Compare(ver, currentVersion) < 1 {
return "", fmt.Errorf("No newer releases found (latest %s)", ver)
}
tmpDir := os.TempDir()
bz2File := filepath.Join(tmpDir, filename)
extractedFile := strings.TrimSuffix(bz2File, ".bz2")
if err := DownloadToFile(downloadURL, bz2File); err != nil {
return "", err
}
// open the bz2
f, err := os.OpenFile(bz2File, 0, 0)
if err != nil {
return "", err
}
// create a bzip2 reader
br := bzip2.NewReader(f)
// get the running binary
oldExec, err := os.Executable()
if err != nil {
panic(err)
}
// get src permissions
fi, _ := os.Stat(oldExec)
srcPerms := fi.Mode().Perm()
// write the file
out, err := os.OpenFile(extractedFile, os.O_CREATE|os.O_RDWR, srcPerms)
if err != nil {
return "", err
}
_, err = io.Copy(out, br)
if err != nil {
return "", err
}
// close immediately else Windows has a fit
f.Close()
out.Close()
if err = ReplaceFile(oldExec, extractedFile); err != nil {
return "", err
}
// remove the src file
if err := os.Remove(bz2File); err != nil {
return "", err
}
return ver, nil
}
// DownloadToFile downloads a URL to a file
func DownloadToFile(url, filepath string) error {
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Write the body to file
_, err = io.Copy(out, resp.Body)
return err
}
// ReplaceFile replaces one file with another.
// Running files cannot be overwritten, so it has to be moved
// and the new binary saved to the original path. This requires
// read & write permissions to both the original file and directory.
// Note, on Windows it is not possible to delete a running program,
// so the old exe is renamed and moved to os.TempDir()
func ReplaceFile(dst, src string) error {
// open the source file for reading
source, err := os.Open(src)
if err != nil {
return err
}
// destination directory eg: /usr/local/bin
dstDir := filepath.Dir(dst)
// binary filename
binaryFilename := filepath.Base(dst)
// old binary tmp name
dstOld := fmt.Sprintf("%s.old", binaryFilename)
// new binary tmp name
dstNew := fmt.Sprintf("%s.new", binaryFilename)
// absolute path of new tmp file
newTmpAbs := filepath.Join(dstDir, dstNew)
// absolute path of old tmp file
oldTmpAbs := filepath.Join(dstDir, dstOld)
// get src permissions
fi, _ := os.Stat(dst)
srcPerms := fi.Mode().Perm()
// create the new file
tmpNew, err := os.OpenFile(newTmpAbs, os.O_CREATE|os.O_RDWR, srcPerms)
if err != nil {
return err
}
// copy new binary to <binary>.new
if _, err := io.Copy(tmpNew, source); err != nil {
return err
}
// close immediately else Windows has a fit
tmpNew.Close()
source.Close()
// rename the current executable to <binary>.old
if err := os.Rename(dst, oldTmpAbs); err != nil {
return err
}
// rename the <binary>.new to current executable
if err := os.Rename(newTmpAbs, dst); err != nil {
return err
}
// delete the old binary
if runtime.GOOS == "windows" {
tmpDir := os.TempDir()
delFile := filepath.Join(tmpDir, filepath.Base(oldTmpAbs))
if err := os.Rename(oldTmpAbs, delFile); err != nil {
return err
}
} else {
if err := os.Remove(oldTmpAbs); err != nil {
return err
}
}
// remove the src file
if err := os.Remove(src); err != nil {
return err
}
return nil
}