-
Notifications
You must be signed in to change notification settings - Fork 18
/
auto_update.go
83 lines (69 loc) · 2.11 KB
/
auto_update.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
package main
import (
"fmt"
"os"
"runtime"
"time"
"github.com/blang/semver/v4"
)
const locallyBuilt = "(Locally Built)"
const autoUpdateFile = "TGFAutoUpdate"
//go:generate moq -out runner_updater_moq_test.go . RunnerUpdater
// RunnerUpdater allows flexibility for testing
type RunnerUpdater interface {
GetUpdateVersion() (string, error)
GetLastRefresh(file string) time.Duration
SetLastRefresh(file string)
ShouldUpdate() bool
DoUpdate(url string) (err error)
Run() int
Restart() int
}
// RunWithUpdateCheck checks if an update is due, checks if current version is outdated and performs update if needed
func RunWithUpdateCheck(c RunnerUpdater) int {
if !c.ShouldUpdate() {
return c.Run()
}
log.Debug("Comparing local and latest versions...")
c.SetLastRefresh(autoUpdateFile)
updateVersion, err := c.GetUpdateVersion()
if err != nil {
log.Errorln("Error fetching update version:", err)
return c.Run()
}
latestVersion, err := semver.Make(updateVersion)
if err != nil {
log.Errorf(`Semver error on retrieved version "%s" : %v`, updateVersion, err)
return c.Run()
}
currentVersion, err := semver.Make(version)
if err != nil {
log.Warningf(`Semver error on current version "%s": %v`, version, err)
return c.Run()
}
if currentVersion.GTE(latestVersion) {
log.Debugf("Your current version (%v) is up to date.", currentVersion)
return c.Run()
}
url := PlatformZipURL(latestVersion.String())
executablePath, err := os.Executable()
if err != nil {
log.Errorln("Executable path error:", err)
}
log.Warningf("Updating %s from %s ==> %v", executablePath, version, latestVersion)
if err := c.DoUpdate(url); err != nil {
log.Errorf("Failed update for %s: %v", url, err)
return c.Run()
}
log.Infoln("TGF updated to", latestVersion)
log.Warning("TGF is restarting...")
return c.Restart()
}
// PlatformZipURL compute the uri pointing at the given version of tgf zip
func PlatformZipURL(version string) string {
name := runtime.GOOS
if name == "darwin" {
name = "macOS"
}
return fmt.Sprintf("https://github.com/coveo/tgf/releases/download/v%[1]s/tgf_%[1]s_%[2]s_64-bits.zip", version, name)
}