generated from LinuxSuRen/github-go
/
get.go
257 lines (225 loc) · 6.32 KB
/
get.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package cmd
import (
"bytes"
"fmt"
"github.com/ghodss/yaml"
"github.com/linuxsuren/http-downloader/pkg"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"io/ioutil"
"net/url"
"os"
"path"
"runtime"
"strings"
"text/template"
)
// NewGetCmd return the get command
func NewGetCmd() (cmd *cobra.Command) {
opt := &downloadOption{}
cmd = &cobra.Command{
Use: "get",
Short: "download the file",
Example: "hd get jenkins-zh/jenkins-cli/jcli --thread 6",
PreRunE: opt.preRunE,
RunE: opt.runE,
}
// set flags
flags := cmd.Flags()
flags.StringVarP(&opt.Output, "output", "o", "", "Write output to <file> instead of stdout.")
flags.BoolVarP(&opt.ShowProgress, "show-progress", "", true, "If show the progress of download")
flags.Int64VarP(&opt.ContinueAt, "continue-at", "", -1, "ContinueAt")
flags.IntVarP(&opt.Thread, "thread", "t", 0,
`Download file with multi-threads. It only works when its value is bigger than 1`)
flags.BoolVarP(&opt.KeepPart, "keep-part", "", false,
"If you want to keep the part files instead of deleting them")
flags.StringVarP(&opt.Provider, "provider", "", ProviderGitHub, "The file provider")
flags.StringVarP(&opt.OS, "os", "", runtime.GOOS, "The OS of target binary file")
flags.StringVarP(&opt.Arch, "arch", "", runtime.GOARCH, "The arch of target binary file")
return
}
type downloadOption struct {
URL string
Output string
ShowProgress bool
ContinueAt int64
Provider string
Arch string
OS string
Thread int
KeepPart bool
// inner fields
name string
Tar bool
}
const (
// ProviderGitHub represents https://github.com
ProviderGitHub = "github"
)
func (o *downloadOption) providerURLParse(path string) (url string, err error) {
url = path
if o.Provider != ProviderGitHub {
return
}
var (
org string
repo string
name string
version string
)
addr := strings.Split(url, "/")
if len(addr) >= 2 {
org = addr[0]
repo = addr[1]
name = repo
} else {
err = fmt.Errorf("only support format xx/xx or xx/xx/xx")
return
}
if len(addr) == 3 {
name = addr[2]
} else if len(addr) > 3 {
err = fmt.Errorf("only support format xx/xx or xx/xx/xx")
}
// extract version from name
if strings.Contains(name, "@") {
nameWithVer := strings.Split(name, "@")
name = nameWithVer[0]
version = nameWithVer[1]
url = fmt.Sprintf("https://github.com/%s/%s/releases/download/%s/%s-%s-%s.tar.gz",
org, repo, version, name, o.OS, o.Arch)
} else {
version = "latest"
url = fmt.Sprintf("https://github.com/%s/%s/releases/%s/download/%s-%s-%s.tar.gz",
org, repo, version, name, o.OS, o.Arch)
}
o.name = name
// try to parse from config
userHome, _ := homedir.Dir()
configDir := userHome + "/.config/hd-home"
matchedFile := configDir + "/config/" + org + "/" + repo + ".yml"
if ok, _ := pathExists(matchedFile); ok {
var data []byte
if data, err = ioutil.ReadFile(matchedFile); err == nil {
cfg := hdConfig{}
if err = yaml.Unmarshal(data, &cfg); err == nil {
hdPackage := &hdPackage{
Name: o.name,
Version: version,
OS: getReplacement(runtime.GOOS, cfg.Replacements),
Arch: getReplacement(runtime.GOARCH, cfg.Replacements),
VersionNum: strings.TrimPrefix(version, "v"),
}
if version == "latest" {
ghClient := pkg.ReleaseClient{
Org: org,
Repo: repo,
}
ghClient.Init()
if asset, err := ghClient.GetLatestJCLIAsset(); err == nil {
hdPackage.Version = asset.TagName
hdPackage.VersionNum = strings.TrimPrefix(asset.TagName, "v")
} else {
fmt.Println(err, "cannot get the asset")
}
}
if cfg.URL != "" {
// it does not come from GitHub release
tmp, _ := template.New("hd").Parse(cfg.URL)
var buf bytes.Buffer
if err = tmp.Execute(&buf, hdPackage); err == nil {
url = buf.String()
} else {
return
}
} else if cfg.Filename != "" {
tmp, _ := template.New("hd").Parse(cfg.Filename)
var buf bytes.Buffer
if err = tmp.Execute(&buf, hdPackage); err == nil {
url = fmt.Sprintf("https://github.com/%s/%s/releases/%s/download/%s",
org, repo, version, buf.String())
o.Output = buf.String()
} else {
return
}
}
o.Tar = cfg.Tar != "false"
if cfg.Binary != "" {
o.name = cfg.Binary
}
}
}
}
return
}
type hdConfig struct {
Name string
Filename string
Binary string
URL string `yaml:"url"`
Tar string
Replacements map[string]string
}
type hdPackage struct {
Name string
Version string // e.g. v1.0.1
VersionNum string // e.g. 1.0.1
OS string // e.g. linux, darwin
Arch string // e.g. amd64
}
func (o *downloadOption) preRunE(cmd *cobra.Command, args []string) (err error) {
if len(args) <= 0 {
return fmt.Errorf("no URL provided")
}
targetURL := args[0]
if !strings.HasPrefix(targetURL, "http://") && !strings.HasPrefix(targetURL, "https://") {
if targetURL, err = o.providerURLParse(targetURL); err != nil {
err = fmt.Errorf("only http:// or https:// supported, error: %v", err)
return
}
cmd.Printf("start to download from %s\n", targetURL)
}
o.URL = targetURL
if o.Output == "" {
var urlObj *url.URL
if urlObj, err = url.Parse(o.URL); err == nil {
o.Output = path.Base(urlObj.Path)
if o.Output == "" {
err = fmt.Errorf("output cannot be empty")
}
} else {
err = fmt.Errorf("cannot parse the target URL, error: '%v'", err)
}
}
return
}
func (o *downloadOption) runE(cmd *cobra.Command, args []string) (err error) {
if o.Thread <= 1 {
err = pkg.DownloadWithContinue(o.URL, o.Output, o.ContinueAt, 0, o.ShowProgress)
} else {
err = pkg.DownloadFileWithMultipleThreadKeepParts(o.URL, o.Output, o.Thread, o.KeepPart, o.ShowProgress)
}
return
}
func (o *downloadOption) fetchHomeConfig() (err error) {
userHome, _ := homedir.Dir()
configDir := userHome + "/.config/hd-home"
if ok, _ := pathExists(configDir); ok {
err = execCommand("git", "pull", "-C", configDir)
} else {
if err = os.MkdirAll(configDir, 0644); err == nil {
err = execCommand("git", "clone", "https://github.com/LinuxSuRen/hd-home", configDir)
}
}
return
}
func pathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}