-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcli.go
More file actions
380 lines (310 loc) · 8.02 KB
/
cli.go
File metadata and controls
380 lines (310 loc) · 8.02 KB
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
package cli
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/lets-cli/lets/internal/cmd"
"github.com/lets-cli/lets/internal/config"
"github.com/lets-cli/lets/internal/env"
"github.com/lets-cli/lets/internal/executor"
"github.com/lets-cli/lets/internal/logging"
"github.com/lets-cli/lets/internal/set"
"github.com/lets-cli/lets/internal/upgrade"
"github.com/lets-cli/lets/internal/upgrade/registry"
"github.com/lets-cli/lets/internal/workdir"
"github.com/mattn/go-isatty"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
const updateCheckTimeout = 3 * time.Second
type updateCheckResult struct {
notifier *upgrade.UpdateNotifier
notice *upgrade.UpdateNotice
}
func Main(version string, buildDate string) int {
ctx := getContext()
configDir := os.Getenv("LETS_CONFIG_DIR")
logging.InitLogging(os.Stdout, os.Stderr)
rootCmd := cmd.CreateRootCommand(version, buildDate)
rootCmd.InitDefaultHelpFlag()
rootCmd.InitDefaultVersionFlag()
reinitCompletionCmd := cmd.InitCompletionCmd(rootCmd, nil)
cmd.InitSelfCmd(rootCmd, version)
rootCmd.InitDefaultHelpCmd()
command, args, err := rootCmd.Traverse(os.Args[1:])
if err != nil {
log.Errorf("traverse commands error: %s", err)
return getExitCode(err, 1)
}
rootFlags, err := parseRootFlags(args)
if err != nil {
log.Errorf("parse flags error: %s", err)
return 1
}
if rootFlags.version {
if err := cmd.PrintVersionMessage(rootCmd); err != nil {
log.Errorf("print version error: %s", err)
return 1
}
return 0
}
debugLevel := env.SetDebugLevel(rootFlags.debug)
if debugLevel > 0 {
log.SetLevel(log.DebugLevel)
}
if rootFlags.config == "" {
rootFlags.config = os.Getenv("LETS_CONFIG")
}
cfg, err := config.Load(rootFlags.config, configDir, version)
if err != nil {
if failOnConfigError(rootCmd, command, rootFlags) {
log.Errorf("config error: %s", err)
return 1
}
}
if cfg != nil {
reinitCompletionCmd(cfg)
cmd.InitSubCommands(rootCmd, cfg, rootFlags.all, os.Stdout)
}
if rootFlags.init {
wd, err := os.Getwd()
if err == nil {
err = workdir.InitLetsFile(wd, version)
}
if err != nil {
log.Errorf("can not create lets.yaml: %s", err)
return 1
}
return 0
}
if rootFlags.upgrade {
upgrader, err := upgrade.NewBinaryUpgrader(registry.NewGithubRegistry(), version)
if err == nil {
err = upgrader.Upgrade(ctx)
}
if err != nil {
log.Errorf("can not self-upgrade binary: %s", err)
return 1
}
return 0
}
showUsage := rootFlags.help || (command.Name() == "help" && len(args) == 0) || (len(os.Args) == 1)
if showUsage {
if err := cmd.PrintRootHelpMessage(rootCmd); err != nil {
log.Errorf("print help error: %s", err)
return 1
}
return 0
}
updateCh, cancelUpdateCheck := maybeStartUpdateCheck(ctx, version, command)
defer cancelUpdateCheck()
if err := rootCmd.ExecuteContext(ctx); err != nil {
var depErr *executor.DependencyError
if errors.As(err, &depErr) {
executor.PrintDependencyTree(depErr, os.Stderr)
log.Errorf("%s", depErr.FailureMessage())
return getExitCode(err, 1)
}
log.Errorf("%s", err.Error())
return getExitCode(err, 1)
}
printUpdateNotice(updateCh)
return 0
}
// getContext returns context and kicks of a goroutine
// which waits for SIGINT, SIGTERM and cancels global context.
//
// Note that since we setting stdin to command we run, that command
// will receive SIGINT, SIGTERM at the same time as we here,
// so command's process can begin finishing earlier than cancel will say it to.
func getContext() context.Context {
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
go func() {
sig := <-ch
log.Printf("signal received: %s", sig)
cancel()
}()
return ctx
}
func getExitCode(err error, defaultCode int) int {
var exitCoder interface{ ExitCode() int }
if errors.As(err, &exitCoder) {
return exitCoder.ExitCode()
}
return defaultCode
}
// do not fail on config error if it is help (-h, --help), --init, completion, or lets self.
func failOnConfigError(root *cobra.Command, current *cobra.Command, rootFlags *flags) bool {
return (root.Flags().NFlag() == 0 && !allowsMissingConfig(current)) && !rootFlags.help && !rootFlags.init
}
func allowsMissingConfig(current *cobra.Command) bool {
if current == nil {
return false
}
switch current.Name() {
case "completion", "help":
return true
}
for cmd := current; cmd != nil; cmd = cmd.Parent() {
parent := cmd.Parent()
if cmd.Name() == "self" && parent != nil && parent.Name() == "lets" {
return true
}
}
return false
}
func maybeStartUpdateCheck(
ctx context.Context,
version string,
command *cobra.Command,
) (<-chan updateCheckResult, context.CancelFunc) {
if !shouldCheckForUpdate(command.Name(), isInteractiveStderr()) {
return nil, func() {}
}
log.Debugf("start update check")
notifier, err := upgrade.NewUpdateNotifier(registry.NewGithubRegistry())
if err != nil {
return nil, func() {}
}
ch := make(chan updateCheckResult, 1)
checkCtx, cancel := context.WithTimeout(ctx, updateCheckTimeout)
go func() {
notice, err := notifier.Check(checkCtx, version)
if err != nil {
upgrade.LogUpdateCheckError(err)
}
log.Debugf("update check done")
ch <- updateCheckResult{
notifier: notifier,
notice: notice,
}
}()
return ch, cancel
}
func printUpdateNotice(updateCh <-chan updateCheckResult) {
if updateCh == nil {
return
}
select {
case result := <-updateCh:
if result.notice == nil {
return
}
if _, err := fmt.Fprintln(os.Stderr, result.notice.Message()); err != nil {
return
}
if err := result.notifier.MarkNotified(result.notice); err != nil {
upgrade.LogUpdateCheckError(err)
}
default:
}
}
func shouldCheckForUpdate(commandName string, interactive bool) bool {
if !interactive || os.Getenv("CI") != "" || os.Getenv("LETS_CHECK_UPDATE") != "" {
return false
}
switch commandName {
case "completion", "help", "lsp", "self":
return false
default:
return true
}
}
func isInteractiveStderr() bool {
fd := os.Stderr.Fd()
return isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd)
}
type flags struct {
config string
debug int
help bool
version bool
all bool
init bool
upgrade bool
}
// We can not parse --config and --debug flags using cobra.Command.ParseFlags
//
// until we read config and initialize all subcommands.
// Otherwise root command will parse all flags gready.
//
// For example in 'lets --config lets.my.yaml mysubcommand --config=myconfig'
//
// cobra will parse all --config flags, but take only latest
//
// --config=myconfig, and this is wrong.
func parseRootFlags(args []string) (*flags, error) {
f := &flags{}
// if first arg is not a flag, then it is subcommand
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
return f, nil
}
visited := set.NewSet[string]()
isFlagVisited := func(name string) bool {
if visited.Contains(name) {
return true
}
visited.Add(name)
return false
}
idx := 0
for idx < len(args) {
arg := args[idx]
if !strings.HasPrefix(arg, "-") {
// stop if arg is not a flag, it is probably a subcommand
break
}
name, value, found := strings.Cut(arg, "=")
switch name {
case "--config", "-c":
if !isFlagVisited("config") {
if found {
if value == "" {
return nil, errors.New("--config must be set to value")
}
f.config = value
} else if len(args[idx:]) > 0 {
f.config = args[idx+1]
idx += 2
continue
}
}
case "--debug", "-d", "-dd":
if !isFlagVisited("debug") {
f.debug = 1
if arg == "-dd" {
f.debug = 2
}
}
case "--help", "-h":
if !isFlagVisited("help") {
f.help = true
}
case "--version", "-v":
if !isFlagVisited("version") {
f.version = true
}
case "--all":
if !isFlagVisited("all") {
f.all = true
}
case "--init":
if !isFlagVisited("init") {
f.init = true
}
case "--upgrade":
if !isFlagVisited("upgrade") {
f.upgrade = true
}
}
idx += 1 //nolint:revive,golint
}
return f, nil
}