-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselfupdate.go
283 lines (240 loc) · 6.16 KB
/
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
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
package selfupdate
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"github.com/carapace-sh/carapace"
"github.com/carapace-sh/carapace-selfupdate/filter"
"github.com/carapace-sh/carapace-selfupdate/transport"
"github.com/carapace-sh/carapace/pkg/traverse"
)
type config struct {
repo string
binary string
filter func(asset string) bool
force bool
progress io.Writer
t transport.Transport
}
type option func(c *config)
func New(owner, repository string, opts ...option) *config {
c := &config{
repo: fmt.Sprintf("%v/%v", owner, repository),
binary: repository,
filter: filter.Goreleaser(repository),
t: &transport.Curl{},
}
for _, opt := range opts {
opt(c)
}
if runtime.GOOS == "windows" {
c.binary += ".exe"
}
return c
}
func WithBinary(s string) func(c *config) {
return func(c *config) {
c.binary = s
}
}
func WithAssetFilter(f func(s string) bool) func(c *config) {
return func(c *config) {
c.filter = f
}
}
func WithForce(b bool) func(c *config) {
return func(c *config) {
c.force = b
}
}
func WithTransport(t transport.Transport) func(c *config) {
return func(c *config) {
c.t = t
}
}
func WithProgress(w io.Writer) func(c *config) {
return func(c *config) {
c.progress = w
}
}
func (c config) Assets(tag string) ([]string, error) {
var b bytes.Buffer
if err := c.t.Assets(c.repo, tag, &b, c.progress); err != nil {
return nil, err
}
var response struct {
Name string
Assets []struct {
Name string
}
}
if err := json.Unmarshal(b.Bytes(), &response); err != nil {
return nil, err
}
names := make([]string, 0, len(response.Assets))
for _, asset := range response.Assets {
if c.filter == nil || c.filter(asset.Name) {
names = append(names, asset.Name)
}
}
return names, nil
}
func (c config) Tags() ([]string, error) {
var b bytes.Buffer
if err := c.t.Tags(c.repo, &b, c.progress); err != nil {
return nil, err
}
var tags []struct {
Name string
}
if err := json.Unmarshal(b.Bytes(), &tags); err != nil {
return nil, err
}
names := make([]string, 0, len(tags))
for _, tag := range tags {
names = append(names, tag.Name)
}
return names, nil
}
func (c config) Println(s string) {
c.Printf(s + "\n")
}
func (c config) Printf(format string, any ...any) {
fmt.Fprintf(c.progress, "\x1b[1;2m"+format+"\x1b[0m", any...)
}
func (c config) confirm(format string, any ...any) error {
if c.force {
return nil
}
fmt.Fprintf(os.Stderr, "\x1b[1;2m"+format+" [y/n]: \x1b[0m", any...) // stderr should be configurable
var input string
if _, err := fmt.Scanln(&input); err != nil {
return err
}
if strings.ToLower(input) != "y" {
return errors.New("aborted")
}
return nil
}
func (c config) Install(tag, asset string) error {
if !strings.HasSuffix(asset, ".tar.gz") && !strings.HasSuffix(asset, ".zip") {
return errors.New("invalid extension [expected: .tar.gz|.zip]") // fail early
}
ext := strings.Replace(filepath.Ext(asset), ".gz", ".tar.gz", 1)
tmpArchive, err := os.CreateTemp(os.TempDir(), "carapace-selfupdate_*"+ext)
if err != nil {
return err
}
defer os.Remove(tmpArchive.Name())
f, err := os.Create(tmpArchive.Name())
if err != nil {
return err
}
defer f.Close()
c.Printf("downloading to %#v\n", tmpArchive.Name())
if err := c.Download(tag, asset, f); err != nil {
return err
}
// sum, err := c.Checksum(tag, asset)
// if err != nil {
// return err
// }
// TODO verify checksum
binDir, err := traverse.GoBinDir(carapace.NewContext())
if err != nil {
return err
}
if _, err := os.Stat(binDir); errors.Is(err, os.ErrNotExist) {
if err := c.confirm("create directory %#v?", binDir); err != nil {
return err
}
c.Printf("creating directory %#v\n", binDir)
if err := os.MkdirAll(binDir, os.ModePerm); err != nil {
return err
}
}
tmpBinary := filepath.Join(binDir, c.binary+".selfupdate")
if _, err := os.Stat(tmpBinary); err == nil {
if err := c.confirm("overwrite %#v?", tmpBinary); err != nil {
return err
}
}
fExecutable, err := os.Create(tmpBinary)
if err != nil {
return err
}
defer os.Remove(fExecutable.Name())
defer f.Close()
c.Printf("extracting to %#v\n", fExecutable.Name())
if err := c.extract(tmpArchive.Name(), fExecutable); err != nil {
return err
}
if err := os.Chmod(fExecutable.Name(), 0755); err != nil {
return err
}
if err := fExecutable.Close(); err != nil {
return err
}
c.Printf("executing %#v\n", fExecutable.Name()+" --version")
if err := c.verify(fExecutable.Name()); err != nil {
return err
}
target := filepath.Join(binDir, c.binary)
if _, err := os.Stat(target); err == nil {
if err := c.confirm("overwrite %#v?", target); err != nil {
return err
}
}
return c.swap(fExecutable.Name(), target)
}
func (c config) verify(executable string) error {
command := exec.Command(executable, "--version")
command.Stdout = c.progress
command.Stderr = c.progress
return command.Run()
}
func (c config) extract(source string, out io.Writer) error {
switch {
case strings.HasSuffix(source, ".tar.gz"):
command := exec.Command("tar", "--to-stdout", "-xzvf", source, c.binary)
command.Stdout = out
command.Stderr = c.progress
return command.Run()
case strings.HasSuffix(source, ".zip"):
command := exec.Command("tar", "--to-stdout", "-xvf", source, c.binary)
command.Stdout = out
command.Stderr = c.progress
return command.Run()
default:
return errors.New("invalid extension [expected: .tar.gz|.zip]")
}
}
func (c config) Download(tag, asset string, out io.Writer) error {
return c.t.Download(c.repo, tag, asset, out, c.progress)
}
func (c config) Checksum(tag, asset string) (string, error) {
r := regexp.MustCompile(`^(?P<prefix>[^_]+_[^_]+)_.*$`)
matches := r.FindStringSubmatch(asset)
if matches == nil {
return "", errors.New(`asset does not match checksum pattern`)
}
b := &bytes.Buffer{}
if err := c.t.Download(c.repo, tag, fmt.Sprintf("%v_checksums.txt", matches[1]), b, c.progress); err != nil {
return "", err
}
m := make(map[string]string)
for _, line := range strings.Split(b.String(), "\n") {
if sum, file, ok := strings.Cut(line, " "); ok {
m[file] = sum
}
}
return m[asset], nil
}