generated from AlexanderMac/go-app-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgosu.go
352 lines (306 loc) · 8.33 KB
/
gosu.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package gosu
import (
"context"
_ "embed"
"errors"
"fmt"
"os"
"runtime"
"strings"
"time"
"golang.org/x/exp/slices"
)
//go:embed scripts/linux.txt
var linuxScript string
//go:embed scripts/windows.txt
var windowsScript string
const (
_LINUX_SCRIPT_NAME = "update.sh"
_WIN_SCRIPT_NAME = "update.cmd"
)
const (
// CheckUpdates
CODE_LATEST_VERSION_IS_ALREADY_IN_USE = iota
CODE_UNRELEASED_VERSION_IS_IN_USE = iota
CODE_NEW_VERSION_DETECTED = iota
// DownloadAsset
CODE_DOWNLOADING_CANCELLED = iota
CODE_DOWNLOADING_COMPLETED = iota
CODE_ERROR = iota
)
type Updater struct {
ReleasesUrl string
ChangelogUrl string
LocalVersion string
GhAccessToken string
DownloadChangelog bool
lastRelease *_GhRelease
releaseAsset *_GhReleaseAsset
downloadingCtx context.Context
cancelDownloading context.CancelFunc
}
type UpdateResult struct {
Code int
Message string
Details string
}
type DownloadingProgress struct {
TotalSize int
CurrentSize int
ProgressPercent int
}
type _GhRelease struct {
TagName string `json:"tag_name"`
CreatedAt string `json:"created_at"`
Assets []_GhReleaseAsset `json:"assets"`
Body string `json:"body"`
}
type _GhReleaseAsset struct {
Name string `json:"name"`
Url string `json:"url"`
Size int `json:"size"`
updateScriptName string
updateScriptBody string
}
func New(orgRepoName, ghAccessToken, localVersion string) *Updater {
return &Updater{
ReleasesUrl: fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", orgRepoName),
ChangelogUrl: fmt.Sprintf("https://api.github.com/repos/%s/contents/CHANGELOG.md", orgRepoName),
LocalVersion: localVersion,
GhAccessToken: ghAccessToken,
}
}
func (updater *Updater) CheckUpdates() UpdateResult {
logger.Info("Checking for updates")
lastRelease, err := updater.getLastRelease()
if err != nil {
return UpdateResult{
Code: CODE_ERROR,
Message: "Unable to get updates.",
Details: parseHttpError(err),
}
}
updater.lastRelease = &lastRelease
remoteSemver := parseSemVer(lastRelease.TagName)
localSemver := parseSemVer(updater.LocalVersion)
if remoteSemver == nil || localSemver == nil {
return UpdateResult{
Code: CODE_ERROR,
Message: "Unable to get updates. The SemVer is invalid.",
}
}
// up-to-date
if remoteSemver.Equal(localSemver) {
logger.Info("The latest version is already used")
return UpdateResult{
Code: CODE_LATEST_VERSION_IS_ALREADY_IN_USE,
Message: "You already use the latest version.",
}
}
// local version is higher
if remoteSemver.LessThan(localSemver) {
logger.Info("The local version is higher than remote")
return UpdateResult{
Code: CODE_UNRELEASED_VERSION_IS_IN_USE,
Message: "You use the unreleased version.",
}
}
// new version detected
lastReleaseDetails := lastRelease.Body
if updater.DownloadChangelog {
changelog, err := updater.getChangelog()
if err != nil {
logger.Warnf("Unable to download changelog, error: %s", err.Error())
}
lastReleaseDetails = changelog
}
logger.Infof("New version detected %s", lastRelease.TagName)
return UpdateResult{
Code: CODE_NEW_VERSION_DETECTED,
Message: fmt.Sprintf(
"New version detected. Current version is %s, new version is %s. Download update?",
updater.LocalVersion,
lastRelease.TagName,
),
Details: lastReleaseDetails,
}
}
func (updater *Updater) DownloadAsset(progressCh chan<- DownloadingProgress) UpdateResult {
if updater.lastRelease == nil {
panic(errors.New("lastRelease is nil"))
}
stopCh := make(chan bool)
defer func() {
if progressCh != nil {
close(progressCh)
}
close(stopCh)
}()
ctx, cancel := context.WithCancel(context.Background())
updater.downloadingCtx = ctx
updater.cancelDownloading = cancel
var asset _GhReleaseAsset
if strings.Contains(runtime.GOOS, "linux") {
assetIndex := slices.IndexFunc(updater.lastRelease.Assets, func(a _GhReleaseAsset) bool {
return strings.Contains(a.Name, "-linux")
})
asset = updater.lastRelease.Assets[assetIndex]
asset.updateScriptName = _LINUX_SCRIPT_NAME
asset.updateScriptBody = linuxScript
} else if strings.Contains(runtime.GOOS, "windows") {
assetIndex := slices.IndexFunc(updater.lastRelease.Assets, func(a _GhReleaseAsset) bool {
return strings.Contains(a.Name, "-win")
})
asset = updater.lastRelease.Assets[assetIndex]
asset.updateScriptName = _WIN_SCRIPT_NAME
asset.updateScriptBody = windowsScript
} else {
return UpdateResult{
Code: CODE_ERROR,
Message: "Unsupported OS: " + runtime.GOOS,
}
}
updater.releaseAsset = &asset
err := removeFile(asset.Name)
if err != nil {
return UpdateResult{
Code: CODE_ERROR,
Message: "Unable to delete the old asset: " + asset.Name,
Details: err.Error(),
}
}
if progressCh != nil {
go getDownloadingPercent(progressCh, stopCh, asset.Name, asset.Size)
}
err = updater.downloadAsset(&asset)
if err != nil {
if errors.Is(err, context.Canceled) {
return UpdateResult{
Code: CODE_DOWNLOADING_CANCELLED,
Message: "The asset downloading has been cancelled.",
}
}
return UpdateResult{
Code: CODE_ERROR,
Message: "Unable to download asset.",
Details: err.Error(),
}
}
if progressCh != nil {
progressCh <- DownloadingProgress{
TotalSize: asset.Size,
CurrentSize: asset.Size,
ProgressPercent: 100,
}
}
return UpdateResult{
Code: CODE_DOWNLOADING_COMPLETED,
Message: "A new application version downloaded successfully. Restart to complete update?",
}
}
func (updater *Updater) CancelAssetDownloading() {
if updater.cancelDownloading == nil {
panic(errors.New("cancelDownloading is nil"))
}
logger.Info("Cancel the asset downloading")
updater.cancelDownloading()
}
func (updater *Updater) UpdateApp() UpdateResult {
if updater.releaseAsset == nil {
panic(errors.New("releaseAsset is nil"))
}
err := createAndRunExtractor(updater.releaseAsset)
if err != nil {
return UpdateResult{
Code: CODE_ERROR,
Message: "Unable to create or run extractor.",
Details: err.Error(),
}
}
logger.Info("Terminating the app")
os.Exit(0)
return UpdateResult{}
}
func (updater *Updater) getLastRelease() (_GhRelease, error) {
logger.Debug("Getting the last release")
var ghRelease _GhRelease
res, err := getHttpClient(updater.GhAccessToken).
R().
SetResult(&ghRelease).
Get(updater.ReleasesUrl)
if err != nil {
return _GhRelease{}, err
}
if err := checkHttpResponse(res); err != nil {
return _GhRelease{}, err
}
logger.Debugf("The last release: %v has been gotten successfully", ghRelease)
return ghRelease, nil
}
func (updater *Updater) getChangelog() (string, error) {
logger.Debug("Getting the changelog")
res, err := getHttpClient(updater.GhAccessToken).
R().
SetHeader("Accept", "application/vnd.github.raw").
Get(updater.ChangelogUrl)
if err != nil {
return "", err
}
if err := checkHttpResponse(res); err != nil {
return "", err
}
logger.Debug("The changelog has been gotten successfully")
return string(res.Body()), nil
}
func (updater *Updater) downloadAsset(asset *_GhReleaseAsset) error {
logger.Debugf("Downloading the asset %s from %s", asset.Name, asset.Url)
res, err := getHttpClient(updater.GhAccessToken).
SetRetryCount(3).
SetTimeout(time.Minute).
R().
SetContext(updater.downloadingCtx).
SetHeader("Accept", "application/octet-stream").
SetOutput(asset.Name).
Get(asset.Url)
if err != nil {
return err
}
if err := checkHttpResponse(res); err != nil {
return err
}
logger.Debugf("The asset %s has been downloaded successfully", asset.Name)
return nil
}
func getDownloadingPercent(progressCh chan<- DownloadingProgress, stopCh <-chan bool, fileName string, totalSize int) {
for {
select {
case <-stopCh:
return
default:
file, err := os.Open(fileName)
if err != nil {
if os.IsNotExist(err) {
break
}
logger.Error(err)
return
}
fi, err := file.Stat()
if err != nil {
logger.Error(err)
return
}
currentSize := fi.Size()
if currentSize == 0 {
currentSize = 1
}
progressPercent := float64(currentSize) / float64(totalSize) * 100
progressCh <- DownloadingProgress{
TotalSize: totalSize,
CurrentSize: int(currentSize),
ProgressPercent: int(progressPercent),
}
}
time.Sleep(time.Millisecond * 25)
}
}