-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
SelfUpdateCommand.go
101 lines (79 loc) · 2.05 KB
/
SelfUpdateCommand.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
package Command
import (
"encoding/json"
"fmt"
"net/http"
"runtime"
"strings"
"github.com/minio/selfupdate"
)
type SelfUpdateCommand struct {
releaseUrl string
currentVersion string
}
type GithubAsset struct {
Name string
Browser_download_url string
}
type GithubRelease struct {
Assets []GithubAsset
Name string
}
func NewSelfUpdateCommand(currentVersion string) *SelfUpdateCommand {
return &SelfUpdateCommand{
releaseUrl: "https://api.github.com/repos/Halleck45/ast-metrics/releases/latest",
currentVersion: currentVersion,
}
}
func (v *SelfUpdateCommand) Execute() error {
latest, err := v.GetLatestRelease()
if err != nil {
return err
}
// get current architecture
arch := runtime.GOARCH
os := runtime.GOOS
os = strings.Title(os)
// for arch, amd64 is x86_64
if arch == "amd64" {
arch = "x86_64"
}
fmt.Println("Versions:")
fmt.Printf(" Current: %s (your version)\n", v.currentVersion)
fmt.Printf(" Latest: %s", latest.Name)
fmt.Println()
for _, asset := range latest.Assets {
if asset.Name == fmt.Sprintf("ast-metrics_%s_%s", os, arch) {
binaryUrl := asset.Browser_download_url
fmt.Printf("Updating to %s (%s_%s) ...\n", latest.Name, os, arch)
// Download the latest version of the binary
resp, err := http.Get(binaryUrl)
if err != nil {
return err
}
defer resp.Body.Close()
// Apply self update
err = selfupdate.Apply(resp.Body, selfupdate.Options{})
if err != nil {
return err
}
fmt.Println("Update complete")
return nil
}
}
fmt.Printf("No update found for your platform (%s_%s)\n", os, arch)
fmt.Println("Please download it manually from: https://github.com/Halleck45/ast-metrics/releases/latest")
return nil
}
func (v *SelfUpdateCommand) GetLatestRelease() (*GithubRelease, error) {
// get JSON from Github API
resp, err := http.Get(v.releaseUrl)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// unmarshal response to struct
response := GithubRelease{}
err = json.NewDecoder(resp.Body).Decode(&response)
return &response, nil
}