-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
update.go
310 lines (271 loc) · 8.12 KB
/
update.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
package cmd
import (
"context"
"fmt"
"os"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/nao1215/gup/internal/goutil"
"github.com/nao1215/gup/internal/notify"
"github.com/nao1215/gup/internal/print"
"github.com/spf13/cobra"
"golang.org/x/exp/slices"
"golang.org/x/sync/semaphore"
)
func newUpdateCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "update",
Short: "Update binaries installed by 'go install'",
Long: `Update binaries installed by 'go install'
If you execute '$ gup update', gup gets the package path of all commands
under $GOPATH/bin and automatically updates commands to the latest version,
using the current installed Go toolchain.`,
Run: func(cmd *cobra.Command, args []string) {
OsExit(gup(cmd, args))
},
ValidArgsFunction: completePathBinaries,
}
cmd.Flags().BoolP("dry-run", "n", false, "perform the trial update with no changes")
cmd.Flags().BoolP("notify", "N", false, "enable desktop notifications")
cmd.Flags().StringSliceP("exclude", "e", []string{}, "specify binaries which should not be updated (delimiter: ',')")
if err := cmd.RegisterFlagCompletionFunc("exclude", completePathBinaries); err != nil {
panic(err)
}
cmd.Flags().StringSliceP("main", "m", []string{}, "specify binaries which update by @main or @master (delimiter: ',')")
if err := cmd.RegisterFlagCompletionFunc("main", completePathBinaries); err != nil {
panic(err)
}
// cmd.Flags().BoolP("main-all", "M", false, "update all binaries by @main or @master (delimiter: ',')")
cmd.Flags().IntP("jobs", "j", runtime.NumCPU(), "Specify the number of CPU cores to use")
if err := cmd.RegisterFlagCompletionFunc("jobs", completeNCPUs); err != nil {
panic(err)
}
return cmd
}
// gup is main sequence.
// All errors are handled in this function.
func gup(cmd *cobra.Command, args []string) int {
if err := goutil.CanUseGoCmd(); err != nil {
print.Err(fmt.Errorf("%s: %w", "you didn't install golang", err))
return 1
}
dryRun, err := cmd.Flags().GetBool("dry-run")
if err != nil {
print.Err(fmt.Errorf("%s: %w", "can not parse command line argument (--dry-run)", err))
return 1
}
notify, err := cmd.Flags().GetBool("notify")
if err != nil {
print.Err(fmt.Errorf("%s: %w", "can not parse command line argument (--notify)", err))
return 1
}
cpus, err := cmd.Flags().GetInt("jobs")
if err != nil {
print.Err(fmt.Errorf("%s: %w", "can not parse command line argument (--jobs)", err))
return 1
}
pkgs, err := getPackageInfo()
if err != nil {
print.Err(err)
return 1
}
excludePkgList, err := cmd.Flags().GetStringSlice("exclude")
if err != nil {
print.Err(fmt.Errorf("%s: %w", "can not parse command line argument (--exclude)", err))
return 1
}
mainPkgNames, err := cmd.Flags().GetStringSlice("main")
if err != nil {
print.Err(fmt.Errorf("%s: %w", "can not parse command line argument (--main)", err))
return 1
}
pkgs = extractUserSpecifyPkg(pkgs, args)
pkgs = excludePkgs(excludePkgList, pkgs)
if len(pkgs) == 0 {
print.Err("unable to update package: no package information or no package under $GOBIN")
return 1
}
return update(pkgs, dryRun, notify, cpus, mainPkgNames)
}
func excludePkgs(excludePkgList []string, pkgs []goutil.Package) []goutil.Package {
packageList := []goutil.Package{}
for _, v := range pkgs {
if slices.Contains(excludePkgList, v.Name) {
print.Info(fmt.Sprintf("Exclude '%s' from the update target", v.Name))
continue
}
packageList = append(packageList, v)
}
return packageList
}
type updateResult struct {
pkg goutil.Package
err error
}
// update updates all packages.
// If dryRun is true, it does not update.
// If notification is true, it notifies the result of update.
func update(pkgs []goutil.Package, dryRun, notification bool, cpus int, mainPkgNames []string) int {
result := 0
countFmt := "[%" pkgDigit(pkgs) "d/%" pkgDigit(pkgs) "d]"
dryRunManager := goutil.NewGoPaths()
print.Info("update binary under $GOPATH/bin or $GOBIN")
signals := make(chan os.Signal, 1)
if dryRun {
if err := dryRunManager.StartDryRunMode(); err != nil {
print.Err(fmt.Errorf("can not change to dry run mode: %w", err))
notify.Warn("gup", "Can not change to dry run mode")
return 1
}
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP,
syscall.SIGQUIT, syscall.SIGABRT)
go catchSignal(signals, dryRunManager)
}
ch := make(chan updateResult)
weighted := semaphore.NewWeighted(int64(cpus))
updater := func(ctx context.Context, p goutil.Package, result chan updateResult) {
if err := weighted.Acquire(ctx, 1); err != nil {
r := updateResult{
pkg: p,
err: err,
}
result <- r
return
}
defer weighted.Release(1)
var err error
if p.ImportPath == "" {
err = fmt.Errorf(" %s is not installed by 'go install' (or permission incorrect)", p.Name)
} else {
if slices.Contains(mainPkgNames, p.Name) {
if err = goutil.InstallMainOrMaster(p.ImportPath); err != nil {
err = fmt.Errorf(" %s %w", p.Name, err)
}
} else {
if err = goutil.InstallLatest(p.ImportPath); err != nil {
err = fmt.Errorf(" %s %w", p.Name, err)
}
}
}
p.SetLatestVer()
r := updateResult{
pkg: p,
err: err,
}
result <- r
}
// update all package
ctx := context.Background()
for _, v := range pkgs {
go updater(ctx, v, ch)
}
// print result
for i := 0; i < len(pkgs); i {
v := <-ch
if v.err == nil {
print.Info(fmt.Sprintf(countFmt " %s (%s)",
i 1, len(pkgs), v.pkg.ImportPath, v.pkg.CurrentToLatestStr()))
} else {
result = 1
print.Err(fmt.Errorf(countFmt "%s", i 1, len(pkgs), v.err.Error()))
}
}
if dryRun {
if err := dryRunManager.EndDryRunMode(); err != nil {
print.Err(fmt.Errorf("can not change dry run mode to normal mode: %w", err))
return 1
}
close(signals)
}
desktopNotifyIfNeeded(result, notification)
return result
}
func desktopNotifyIfNeeded(result int, enable bool) {
if enable {
if result == 0 {
notify.Info("gup", "All update success")
} else {
notify.Warn("gup", "Some package can't update")
}
}
}
func catchSignal(c chan os.Signal, dryRunManager *goutil.GoPaths) {
for {
select {
case <-c:
if err := dryRunManager.EndDryRunMode(); err != nil {
print.Err(fmt.Errorf("can not change dry run mode to normal mode: %w", err))
}
return
default:
time.Sleep(1 * time.Second)
}
}
}
func pkgDigit(pkgs []goutil.Package) string {
return strconv.Itoa(len(strconv.Itoa(len(pkgs))))
}
func getBinaryPathList() ([]string, error) {
goBin, err := goutil.GoBin()
if err != nil {
return nil, fmt.Errorf("%s: %w", "can't find installed binaries", err)
}
binList, err := goutil.BinaryPathList(goBin)
if err != nil {
return nil, fmt.Errorf("%s: %w", "can't get binary-paths installed by 'go install'", err)
}
return binList, nil
}
func getPackageInfo() ([]goutil.Package, error) {
binList, err := getBinaryPathList()
if err != nil {
return nil, fmt.Errorf("%s: %w", "can't get package info", err)
}
return goutil.GetPackageInformation(binList), nil
}
func extractUserSpecifyPkg(pkgs []goutil.Package, targets []string) []goutil.Package {
result := []goutil.Package{}
tmp := []string{}
if len(targets) == 0 {
return pkgs
}
if runtime.GOOS == "windows" {
for i, target := range targets {
if strings.HasSuffix(strings.ToLower(target), ".exe") {
targets[i] = strings.TrimSuffix(strings.ToLower(target), ".exe")
}
}
}
for _, v := range pkgs {
pkg := v.Name
if runtime.GOOS == "windows" {
if strings.HasSuffix(strings.ToLower(pkg), ".exe") {
pkg = strings.TrimSuffix(strings.ToLower(pkg), ".exe")
}
}
if slices.Contains(targets, pkg) {
result = append(result, v)
tmp = append(tmp, pkg)
}
}
if len(tmp) != len(targets) {
for _, target := range targets {
if !slices.Contains(tmp, target) {
print.Warn("not found '" target "' package in $GOPATH/bin or $GOBIN")
}
}
}
return result
}
func completePathBinaries(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
binList, _ := getBinaryPathList()
for i, b := range binList {
binList[i] = filepath.Base(b)
}
return binList, cobra.ShellCompDirectiveNoFileComp
}