forked from fanaticscripter/EggLedger
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathversion.go
96 lines (86 loc) · 2.5 KB
/
version.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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"time"
version "github.com/hashicorp/go-version"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
const (
_githubRepo = "fanaticscripter/EggLedger"
_updateCheckInterval = time.Hour * 23
)
func checkForUpdates() (newVersion string, err error) {
wrap := func(err error) error {
return errors.Wrap(err, "failed to check for new version")
}
runningVersion, err := version.NewVersion(_appVersion)
if err != nil {
err = errors.Wrapf(err, "failed to parse running version %s", _appVersion)
return "", wrap(err)
}
_storage.Lock()
lastUpdateCheckAt := _storage.LastUpdateCheckAt
knownLatestTag := _storage.KnownLatestVersion
_storage.Unlock()
if knownLatestTag != "" {
if knownLatestVersion, err := version.NewVersion(knownLatestTag); err == nil {
if knownLatestVersion.GreaterThan(runningVersion) {
// A known new version is already stored, skip remote check.
return knownLatestTag, nil
}
} else {
log.Warnf("storage: failed to parse known_latest_version %s: %s", knownLatestTag, err)
}
}
if time.Since(lastUpdateCheckAt) < _updateCheckInterval {
log.Infof("%s since last update check, skipping", time.Since(lastUpdateCheckAt))
return "", nil
}
latestTag, err := getLatestTag()
if err != nil {
return "", wrap(err)
}
log.Infof("latest tag: %s", latestTag)
latestVersion, err := version.NewVersion(latestTag)
if err != nil {
err = errors.Wrapf(err, "failed to parse latest version %s", latestTag)
return "", wrap(err)
}
_storage.SetUpdateCheck(latestTag)
if runningVersion.LessThan(latestVersion) {
return latestTag, nil
}
return "", nil
}
func getLatestTag() (string, error) {
client := &http.Client{
Timeout: time.Second * 10,
}
url := "https://api.github.com/repos/" + _githubRepo + "/releases/latest"
resp, err := client.Get(url)
if err != nil {
return "", errors.Wrapf(err, "GET %s", url)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrapf(err, "GET %s: %#v", url, string(body))
}
if resp.StatusCode != 200 {
return "", errors.Errorf("GET %s: HTTP %d: %#v", url, resp.StatusCode, string(body))
}
var release struct {
TagName string `json:"tag_name"`
}
err = json.Unmarshal(body, &release)
if err != nil {
return "", errors.Wrapf(err, "GET %s: %#v", url, string(body))
}
if release.TagName == "" {
return "", errors.Errorf("GET %s: tag_name is empty: %#v", url, string(body))
}
return release.TagName, nil
}