generated from gleich/go_template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
release.go
74 lines (68 loc) · 1.88 KB
/
release.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
package release
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
)
// Check for an update. Takes in the current version and GitHub repo URL.
// Returns true or false if there is an update or not as well as the version
// value. Will return false if there is no network connection.
func Check(localVersion string, repoURL string) (bool, string, error) {
hasConnection := checkConnection()
if !hasConnection {
return false, "", nil
}
requestURL := convertURL(repoURL)
currentVersion, err := getVersion(requestURL)
if err != nil {
return false, "", err
}
if localVersion != currentVersion {
return true, currentVersion, nil
}
return false, currentVersion, nil
}
// Check for a network connection
func checkConnection() bool {
resp, err := http.Get("http://clients3.google.com/generate_204")
if err != nil || resp.StatusCode != 204 {
return false
}
return true
}
// Convert repo url to api url
// From: https://github.com/gleich/nuke
// To: https://api.github.com/repos/gleich/nuke/releases/latest
func convertURL(repoURL string) string {
var fixedURL string
fixedURL = strings.Replace(repoURL, "https://github.com/", "https://api.github.com/repos/", 1)
if fixedURL[len(fixedURL)-1:] == "/" {
fixedURL = fixedURL + "releases/latest"
} else {
fixedURL = fixedURL + "/releases/latest"
}
return fixedURL
}
// Make the actual get request to get the version
func getVersion(requestURL string) (string, error) {
resp, err := http.Get(requestURL)
if err != nil {
return "", err
}
defer resp.Body.Close()
var data map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return "", err
}
version := fmt.Sprintf("%v", data["tag_name"])
if version == "" {
return "", errors.New("Version number for repo is blank")
}
if version == "<nil>" {
return "", errors.New("Latest release not found for given repo URL")
}
return version, nil
}