-
Notifications
You must be signed in to change notification settings - Fork 1
/
artifact.go
101 lines (77 loc) · 2.23 KB
/
artifact.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 published
import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"io"
"net/http"
"runtime"
"github.com/can3p/kleiner/shared/types"
"github.com/go-resty/resty/v2"
"github.com/minio/selfupdate"
"github.com/pkg/errors"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
func compileDownloadURL(buildinfo *types.BuildInfo, tag string) string {
return fmt.Sprintf(
"https://github.com/%s/releases/download/v%s/%s",
buildinfo.GithubRepo, tag, compileArtifactName(buildinfo))
}
func compileArtifactName(buildinfo *types.BuildInfo) string {
arch := buildinfo.Architecture
switch arch {
case "amd64":
arch = "x86_64"
case "386":
arch = "i386"
case "arm68":
arch = "armv64"
}
return fmt.Sprintf("%s_%s_%s.tar.gz", buildinfo.ProjectName, cases.Title(language.English).String(runtime.GOOS), arch)
}
func DownloadAndReplaceBinary(buildinfo *types.BuildInfo, tag string) error {
b, err := downloadBinary(buildinfo, tag)
if err != nil {
return err
}
err = selfupdate.Apply(bytes.NewReader(b), selfupdate.Options{})
if err != nil {
return errors.Wrapf(err, "failed to update the binary")
}
return nil
}
func downloadBinary(buildinfo *types.BuildInfo, tag string) ([]byte, error) {
url := compileDownloadURL(buildinfo, tag)
fileToExtract := buildinfo.ProjectName
client := resty.New()
resp, err := client.R().Get(url)
if err != nil {
return nil, errors.Wrapf(err, "failed to download the binary, url = %s", url)
}
body := resp.Body()
if rc := resp.StatusCode(); rc != http.StatusOK {
return nil, errors.Errorf("failed to download the binary, url = %s, status code = %d, body = [%s]", url, rc, string(body))
}
bodyReader := bytes.NewReader(body)
gzipReader, err := gzip.NewReader(bodyReader)
if err != nil {
return nil, errors.Wrapf(err, "failed to decompress gzip, url = %s, size = %d bytes", url, len(body))
}
tarReader := tar.NewReader(gzipReader)
for {
header, err := tarReader.Next()
if err == io.EOF {
break
}
if header.Typeflag == tar.TypeReg && header.Name == fileToExtract {
b, err := io.ReadAll(tarReader)
if err != nil {
return nil, err
}
return b, nil
}
}
return nil, errors.Errorf("file with the name [%s] has not been found in the archive", fileToExtract)
}