/
update_cmd.go
205 lines (159 loc) · 4.69 KB
/
update_cmd.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
package cmd
import (
"context"
"time"
"github.com/alitto/pond"
"github.com/imdario/mergo"
art "github.com/plar/go-adaptive-radix-tree"
"github.com/pterm/pterm"
"github.com/samber/lo"
"github.com/spf13/cobra"
"github.com/zbiljic/fget/pkg/fsfind"
)
var updateCmd = &cobra.Command{
Use: "update",
Aliases: []string{"up"},
Short: "Fetch changes from a remote repository into the current branch",
Annotations: map[string]string{"group": "update"},
Args: cobra.ArbitraryArgs,
RunE: runUpdate,
}
var pullCmdFlags = &updateOptions{}
func init() {
updateCmd.Flags().BoolVar(&pullCmdFlags.DryRun, "dry-run", false, "Displays the operations that would be performed using the specified command without actually running them")
updateCmd.Flags().Uint16VarP(&pullCmdFlags.MaxWorkers, "workers", "j", poolDefaultMaxWorkers, "Set the maximum number of workers to use")
updateCmd.Flags().BoolVarP(&pullCmdFlags.NoErrors, "no-errors", "s", false, "Suppress some errors")
updateCmd.Flags().BoolVarP(&pullCmdFlags.OnlyUpdated, "only-updated", "u", false, "Print only updated projects")
updateCmd.Flags().DurationVar(&pullCmdFlags.ExecTimeout, "exec-timeout", 0, "Duration after which process should stop")
updateCmd.Flags().DurationVar(&pullCmdFlags.RetryTimeout, "retry-timeout", defaultRetryMaxElapsedTime, "Duration for retry operation")
rootCmd.AddCommand(updateCmd)
}
type updateOptions struct {
Roots []string
DryRun bool
MaxWorkers uint16
NoErrors bool
OnlyUpdated bool
ExecTimeout time.Duration
RetryTimeout time.Duration
}
func runUpdate(cmd *cobra.Command, args []string) error {
cmdName := cmd.Name()
runFn := gitRunUpdate
opts, err := parseUpdateArgs(args)
if err != nil {
return err
}
if err := mergo.Merge(&opts, pullCmdFlags); err != nil {
return err
}
retryMaxElapsedTime = opts.RetryTimeout
// for configuration
baseDir := opts.Roots[0]
config, err := loadOrCreateConfigState(baseDir, cmdName, opts.Roots...)
if err != nil {
return err
}
defer func() {
if err := finishConfigState(baseDir, cmdName, config); err != nil {
ptermErrorMessageStyle.Println(err.Error())
}
}()
if len(config.Paths) == 0 {
spinner, err := pterm.DefaultSpinner.
WithWriter(dynamicOutput).
WithRemoveWhenDone(true).
Start("finding repositories...")
if err != nil {
return err
}
repoPaths, err := fsfind.GitDirectoriesTree(opts.Roots...)
if err != nil {
return err
}
config.TotalCount = repoPaths.Size()
repoPaths.ForEach(func(node art.Node) bool {
config.Paths = append(config.Paths, string(node.Key()))
return true
})
if err := saveConfigState(baseDir, cmdName, config); err != nil {
return err
}
spinner.Stop() //nolint:errcheck
}
// make a copy
activeRepoPaths := make([]string, len(config.Paths))
copy(activeRepoPaths, config.Paths)
cleanupFn := func(repoPath string, index int, err error) error {
if err != nil {
if opts.NoErrors {
return nil
}
return err
}
// update active
activeRepoPaths = lo.Without(activeRepoPaths, repoPath)
config.Paths = activeRepoPaths
if err := saveCheckpointConfigState(baseDir, cmdName, config, index); err != nil {
ptermErrorMessageStyle.Println(err.Error())
}
return nil
}
// start
startedAt := time.Now()
startOffset := 1 + config.TotalCount - len(activeRepoPaths)
// worker pool
pool := pond.New(int(opts.MaxWorkers), poolDefaultMaxCapacity)
defer pool.StopAndWait()
ctx := cmd.Context()
if opts.ExecTimeout > 0 {
var ctxCancelFn context.CancelFunc
ctx, ctxCancelFn = context.WithTimeout(ctx, opts.ExecTimeout)
defer ctxCancelFn()
}
// task group associated to a context
group, ctx := pool.GroupContext(ctx)
for i, path := range config.Paths {
i := i + startOffset
repoPath := path
// context setup
ctx = context.WithValue(ctx, ctxKeyDryRun{}, opts.DryRun)
ctx = context.WithValue(ctx, ctxKeyOnlyUpdated{}, opts.OnlyUpdated)
task := taskUpdateFn(
ctx,
cmdName,
config,
i,
repoPath,
runFn,
cleanupFn,
)
group.Submit(task)
}
if err := group.Wait(); err != nil {
return err
}
pterm.Println()
ptermSuccessWithPrefixText(cmdName).
Printfln("took %s (total: %s)",
time.Since(startedAt).Round(time.Millisecond).String(),
time.Since(config.CreateTime).Round(time.Millisecond).String(),
)
return nil
}
func parseUpdateArgs(args []string) (updateOptions, error) {
opts := updateOptions{}
if len(args) > 0 {
for _, arg := range args {
path, err := fsfind.DirAbsPath(arg)
if err != nil {
return opts, err
}
opts.Roots = append(opts.Roots, path)
}
} else {
// fallback to current working directory
opts.Roots = append(opts.Roots, GetWd())
}
return opts, nil
}