-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcommand_selfupdate.go
90 lines (77 loc) · 2.21 KB
/
command_selfupdate.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
package main
import (
"fmt"
"context"
"log"
"runtime"
"strings"
"github.com/google/go-github/github"
"github.com/inconshreveable/go-update"
"net/http"
)
type SelfUpdateCommand struct {
CurrentVersion string
GithubOrganization string
GithubRepository string
GithubAssetTemplate string
}
func (conf *SelfUpdateCommand) Execute(args []string) error {
fmt.Println("Starting self update")
client := github.NewClient(nil)
release, _, err := client.Repositories.GetLatestRelease(context.Background(), conf.GithubOrganization, conf.GithubRepository)
if _, ok := err.(*github.RateLimitError); ok {
log.Println("GitHub rate limit, please try again later")
}
fmt.Println(fmt.Sprintf(" - latest version is %s", release.GetName()))
// check if latest version is current version
if release.GetName() == conf.CurrentVersion {
fmt.Println(" - already using the latest version")
return nil
}
// translate OS names
os := runtime.GOOS
switch (runtime.GOOS) {
case "darwin":
os = "osx"
}
// translate arch names
arch := runtime.GOARCH
switch (arch) {
case "amd64":
arch = "x64"
case "386":
arch = "x32"
}
// build asset name
assetName := conf.GithubAssetTemplate
assetName = strings.Replace(assetName, "%OS%", os, -1)
assetName = strings.Replace(assetName, "%ARCH%", arch, -1)
// search assets in release for the desired filename
fmt.Println(fmt.Sprintf(" - searching for asset \"%s\"", assetName))
for _, asset := range release.Assets {
if asset.GetName() == assetName {
downloadUrl := asset.GetBrowserDownloadURL()
fmt.Println(fmt.Sprintf(" - found new update url \"%s\"", downloadUrl))
conf.runUpdate(downloadUrl)
fmt.Println(fmt.Sprintf(" - finished update to version %s", release.GetName()))
return nil
}
}
fmt.Println(" - unable to find asset, please contact maintainer")
return nil
}
func (conf *SelfUpdateCommand) runUpdate(url string) error {
fmt.Println(" - downloading update")
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
fmt.Println(" - applying update")
err = update.Apply(resp.Body, update.Options{})
if err != nil {
// error handling
fmt.Println(fmt.Sprintf(" - updating application failed: %s", err))
}
return err
}