forked from parse-community/parse-cli
/
update_cmd.go
94 lines (79 loc) · 2.23 KB
/
update_cmd.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
package main
import (
"fmt"
"net/http"
"net/url"
"path"
"runtime"
"strings"
"github.com/facebookgo/stackerr"
"github.com/inconshreveable/go-update"
"github.com/kardianos/osext"
"github.com/spf13/cobra"
)
const (
macCliDownloadURL = "https://parse.com/downloads/cloud_code/cli/parse-osx/latest"
unixCliDownloadURL = "https://parse.com/downloads/cloud_code/cli/parse-linux/latest"
windowsCliDownloadURL = "https://parse.com/downloads/cloud_code/cli/parse-windows/latest"
)
type updateCmd struct{}
func (u *updateCmd) latestVersion(e *env, downloadURL string) (string, error) {
dURL, err := url.Parse(downloadURL)
if err != nil {
return "", stackerr.Wrap(err)
}
resp, err := e.Client.Do(&http.Request{Method: "HEAD", URL: dURL}, nil, nil)
if err != nil {
return "", nil // if unable to fetch latest cli version, do not abort!
}
base := path.Base(resp.Header.Get("Location"))
base = strings.TrimSuffix(base, ".exe")
//parse-os-2.0.2
splits := strings.Split(base, "-")
return splits[len(splits)-1], nil
}
func (u *updateCmd) updateCLI(e *env) (bool, error) {
downloadURL := unixCliDownloadURL
switch runtime.GOOS {
case "windows":
downloadURL = windowsCliDownloadURL
case "darwin":
downloadURL = macCliDownloadURL
}
latestVersion, err := u.latestVersion(e, downloadURL)
if err != nil {
return false, stackerr.Wrap(err)
}
if latestVersion == "" || latestVersion == version {
return false, nil
}
exec, err := osext.Executable()
if err != nil {
return false, stackerr.Wrap(err)
}
fmt.Fprintf(e.Out, "Downloading binary from %s.\n", downloadURL)
if err, _ := update.New().Target(exec).FromUrl(downloadURL); err != nil {
return false, stackerr.Newf("Update failed: %v", err)
}
fmt.Fprintf(e.Out, "Successfully updated binary at: %s\n", exec)
return true, nil
}
func (u *updateCmd) run(e *env) error {
updated, err := u.updateCLI(e)
if err != nil {
return err
}
if !updated {
fmt.Fprintf(e.Out, "Already using the latest cli version: %s\n", version)
}
return nil
}
func newUpdateCmd(e *env) *cobra.Command {
var u updateCmd
return &cobra.Command{
Use: "update",
Short: "Updates this tool to the latest version",
Long: "Updates this tool to the latest version.",
Run: runNoArgs(e, u.run),
}
}