-
-
Notifications
You must be signed in to change notification settings - Fork 286
/
get.go
497 lines (392 loc) · 12 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package get
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"strings"
"text/template"
"time"
"github.com/alexellis/arkade/pkg"
"github.com/alexellis/arkade/pkg/env"
)
const GitHubVersionStrategy = "github"
const k8sVersionStrategy = "k8s"
var supportedOS = [...]string{"linux", "darwin", "ming"}
var supportedArchitectures = [...]string{"x86_64", "arm", "amd64", "armv6l", "armv7l", "arm64", "aarch64"}
// githubTimeout expanded from the original 5 seconds due to #693
var githubTimeout = time.Second * 10
// Tool describes how to download a CLI tool from a binary
// release - whether a single binary, or an archive.
type Tool struct {
// The name of the tool for download
Name string
// Repo is a GitHub repo, when no repo exists, use the same
// as the name.
Repo string
// Owner is the name of the GitHub account, when no account
// exists, use the vendor name lowercase.
Owner string
// Version pinned or left empty to pull the latest release
// if any only if only BinaryTemplate is specified.
Version string
// Bespoke approach for finding version when none is set.
VersionStrategy string
// Description of what the tool is used for.
Description string
// URLTemplate specifies a Go template for the download URL
// override the OS, architecture and extension
// All whitespace will be trimmed/
URLTemplate string
// The binary template can be used when downloading GitHub
// It assumes that the only part of the URL needing to be
// templated is the binary name on a standard GitHub download
// URL.
BinaryTemplate string
// NoExtension is required for tooling such as kubectx
// which at time of writing is a bash script.
NoExtension bool
}
type ToolLocal struct {
Name string
Path string
}
var templateFuncs = map[string]interface{}{
"HasPrefix": func(s, prefix string) bool { return strings.HasPrefix(s, prefix) },
}
func (tool Tool) IsArchive(quiet bool) (bool, error) {
arch, operatingSystem := env.GetClientArch()
version := ""
downloadURL, err := GetDownloadURL(&tool, strings.ToLower(operatingSystem), strings.ToLower(arch), version, quiet)
if err != nil {
return false, err
}
return strings.HasSuffix(downloadURL, "tar.gz") ||
strings.HasSuffix(downloadURL, "zip") ||
strings.HasSuffix(downloadURL, "tgz"), nil
}
func isArchiveStr(downloadURL string) bool {
return strings.HasSuffix(downloadURL, "tar.gz") ||
strings.HasSuffix(downloadURL, "zip") ||
strings.HasSuffix(downloadURL, "tgz")
}
// GetDownloadURL fetches the download URL for a release of a tool
// for a given os, architecture and version
func GetDownloadURL(tool *Tool, os, arch, version string, quiet bool) (string, error) {
ver := GetToolVersion(tool, version)
dlURL, err := tool.GetURL(os, arch, ver, quiet)
if err != nil {
return "", err
}
return dlURL, nil
}
func GetToolVersion(tool *Tool, version string) string {
ver := tool.Version
if len(version) > 0 {
ver = version
}
return ver
}
func (tool Tool) Head(uri string) (int, string, http.Header, error) {
req, err := http.NewRequest(http.MethodHead, uri, nil)
if err != nil {
return http.StatusBadRequest, "", nil, err
}
req.Header.Set("User-Agent", pkg.UserAgent())
res, err := http.DefaultClient.Do(req)
if err != nil {
return http.StatusBadRequest, "", nil, err
}
var body string
if res.Body != nil {
b, _ := io.ReadAll(res.Body)
body = string(b)
}
return res.StatusCode, body, res.Header, nil
}
func (tool Tool) GetURL(os, arch, version string, quiet bool) (string, error) {
if len(version) == 0 {
if !quiet {
log.Printf("Looking up version for %s", tool.Name)
}
if len(tool.URLTemplate) == 0 ||
strings.Contains(tool.URLTemplate, "https://github.com/") ||
tool.VersionStrategy == GitHubVersionStrategy {
v, err := FindGitHubRelease(tool.Owner, tool.Repo)
if err != nil {
return "", err
}
version = v
}
if tool.VersionStrategy == k8sVersionStrategy {
v, err := FindK8sRelease()
if err != nil {
return "", err
}
version = v
}
if !quiet {
log.Printf("Found: %s", version)
}
}
if len(tool.URLTemplate) > 0 {
return getByDownloadTemplate(tool, os, arch, version)
}
return getURLByGithubTemplate(tool, os, arch, version)
}
func getURLByGithubTemplate(tool Tool, os, arch, version string) (string, error) {
var err error
t := template.New(tool.Name + "binary")
t = t.Funcs(templateFuncs)
t, err = t.Parse(tool.BinaryTemplate)
if err != nil {
return "", err
}
var buf bytes.Buffer
pref := map[string]string{
"OS": os,
"Arch": arch,
"Name": tool.Name,
"Version": version,
"VersionNumber": strings.TrimPrefix(version, "v"),
}
err = t.Execute(&buf, pref)
if err != nil {
return "", err
}
downloadName := strings.TrimSpace(buf.String())
return getBinaryURL(tool.Owner, tool.Repo, version, downloadName), nil
}
func FindGitHubRelease(owner, repo string) (string, error) {
url := fmt.Sprintf("https://github.com/%s/%s/releases/latest", owner, repo)
client := makeHTTPClient(&githubTimeout, false)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
req, err := http.NewRequest(http.MethodHead, url, nil)
if err != nil {
return "", err
}
req.Header.Set("User-Agent", pkg.UserAgent())
res, err := client.Do(req)
if err != nil {
return "", err
}
if res.Body != nil {
defer res.Body.Close()
}
if res.StatusCode != http.StatusMovedPermanently && res.StatusCode != http.StatusFound {
return "", fmt.Errorf("server returned status: %d", res.StatusCode)
}
loc := res.Header.Get("Location")
if len(loc) == 0 {
return "", fmt.Errorf("unable to determine release of tool")
}
version := loc[strings.LastIndex(loc, "/")+1:]
return version, nil
}
func FindK8sRelease() (string, error) {
url := "https://cdn.dl.k8s.io/release/stable.txt"
timeout := time.Second * 5
client := makeHTTPClient(&timeout, false)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
req.Header.Set("User-Agent", pkg.UserAgent())
res, err := client.Do(req)
if err != nil {
return "", err
}
if res.Body == nil {
return "", fmt.Errorf("unable to determine release of tool")
}
defer res.Body.Close()
bodyBytes, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
version := string(bodyBytes)
return version, nil
}
func getBinaryURL(owner, repo, version, downloadName string) string {
if in := strings.Index(downloadName, "/"); in > -1 {
return fmt.Sprintf(
"https://github.com/%s/%s/releases/download/%s",
owner, repo, downloadName)
}
return fmt.Sprintf(
"https://github.com/%s/%s/releases/download/%s/%s",
owner, repo, version, downloadName)
}
func getByDownloadTemplate(tool Tool, os, arch, version string) (string, error) {
var err error
t := template.New(tool.Name)
t = t.Funcs(templateFuncs)
t, err = t.Parse(tool.URLTemplate)
if err != nil {
return "", err
}
var buf bytes.Buffer
inputs := map[string]string{
"OS": os,
"Arch": arch,
"Version": version,
"VersionNumber": strings.TrimPrefix(version, "v"),
"Repo": tool.Repo,
"Owner": tool.Owner,
"Name": tool.Name,
}
if err := t.Execute(&buf, inputs); err != nil {
return "", err
}
res := strings.TrimSpace(buf.String())
return res, nil
}
// makeHTTPClient makes a HTTP client with good defaults for timeouts.
func makeHTTPClient(timeout *time.Duration, tlsInsecure bool) http.Client {
return makeHTTPClientWithDisableKeepAlives(timeout, tlsInsecure, false)
}
// makeHTTPClientWithDisableKeepAlives makes a HTTP client with good defaults for timeouts.
func makeHTTPClientWithDisableKeepAlives(timeout *time.Duration, tlsInsecure bool, disableKeepAlives bool) http.Client {
client := http.Client{}
if timeout != nil || tlsInsecure {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DisableKeepAlives: disableKeepAlives,
}
if timeout != nil {
client.Timeout = *timeout
tr.DialContext = (&net.Dialer{
Timeout: *timeout,
}).DialContext
tr.IdleConnTimeout = 120 * time.Millisecond
tr.ExpectContinueTimeout = 1500 * time.Millisecond
}
if tlsInsecure {
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: tlsInsecure}
}
tr.DisableKeepAlives = disableKeepAlives
client.Transport = tr
}
return client
}
// GetBinaryName returns the name of a binary for the given tool or an
// error if the tool's template cannot be parsed or executed.
func GetBinaryName(tool *Tool, os, arch, version string) (string, error) {
if len(tool.BinaryTemplate) > 0 {
var err error
t := template.New(tool.Name + "_binaryname")
t = t.Funcs(templateFuncs)
t, err = t.Parse(tool.BinaryTemplate)
if err != nil {
return "", err
}
var buf bytes.Buffer
ver := GetToolVersion(tool, version)
if err := t.Execute(&buf, map[string]string{
"OS": os,
"Arch": arch,
"Name": tool.Name,
"Version": ver,
"VersionNumber": strings.TrimPrefix(ver, "v"),
}); err != nil {
return "", err
}
res := strings.TrimSpace(buf.String())
return res, nil
}
return "", errors.New("BinaryTemplate is not set")
}
// GetDownloadURLs generates a list of URL for each tool, for download
func GetDownloadURLs(tools Tools, toolArgs []string, version string) (Tools, error) {
arkadeTools := []Tool{}
for _, arg := range toolArgs {
name := arg
// Handle version specified tool name
if i := strings.LastIndex(arg, "@"); i > -1 {
name = arg[:i]
if len(version) > 0 {
return nil, fmt.Errorf("cannot specify --version flag and @ syntax at the same time for %s", name)
}
version = arg[i+1:]
}
err := toolExists(&arkadeTools, tools, name, version)
if err != nil {
return nil, err
}
// unset value for the next iteration of versioned tool
version = ""
}
return arkadeTools, nil
}
// toolExists checks if user provided tool exists on arkade
func toolExists(arkadeTools *[]Tool, tools Tools, name, version string) error {
for _, tool := range tools {
if name == tool.Name {
if len(version) > 0 {
tool.Version = version
}
*arkadeTools = append(*arkadeTools, tool)
return nil
}
}
return fmt.Errorf("tool %s not found", name)
}
func PostToolNotFoundMsg(url string) string {
return fmt.Sprintf("Look like this tool isn't available for your OS or/and platform. Check out the link to see if the tool you're after is available: %s.\nIf it is there, don't hesitate to open an issue and contribute to Arkade!", url)
}
// PostInstallationMsg generates installation message after tool has been downloaded
func PostInstallationMsg(movePath string, localToolsStore []ToolLocal) ([]byte, error) {
t := template.New("Installation Instructions")
if movePath != "" {
t.Parse(`Run the following to copy to install the tool:
{{- range . }}
sudo install -m 755 {{.Path}} /usr/local/bin/{{.Name}}
{{- end}}`)
} else {
t.Parse(`# Add arkade binary directory to your PATH variable
export PATH=$PATH:$HOME/.arkade/bin/
# Test the binary:
{{- range . }}
{{.Path}}
{{- end }}
# Or install with:
{{- range . }}
sudo mv {{.Path}} /usr/local/bin/
{{- end}}`)
}
var tpl bytes.Buffer
err := t.Execute(&tpl, localToolsStore)
if err != nil {
return nil, err
}
return tpl.Bytes(), err
}
// ValidateOS returns whether a given operating system is supported
func ValidateOS(name string) error {
for _, os := range supportedOS {
if strings.HasPrefix(strings.ToLower(name), os) {
return nil
}
}
return fmt.Errorf("operating system %q is not supported. Available prefixes: %s.",
name, strings.Join(supportedOS[:], ", "))
}
// ValidateArch returns whether a given cpu architecture is supported
func ValidateArch(name string) error {
for _, arch := range supportedArchitectures {
if arch == strings.ToLower(name) {
return nil
}
}
return fmt.Errorf("cpu architecture %q is not supported. Available: %s.",
name, strings.Join(supportedArchitectures[:], ", "))
}