-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
252 lines (213 loc) · 5.49 KB
/
main.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
package main
import (
"context"
"errors"
"os"
"os/signal"
"strings"
"syscall"
"github.com/lets-cli/lets/cmd"
"github.com/lets-cli/lets/config"
"github.com/lets-cli/lets/env"
"github.com/lets-cli/lets/executor"
"github.com/lets-cli/lets/logging"
"github.com/lets-cli/lets/set"
"github.com/lets-cli/lets/upgrade"
"github.com/lets-cli/lets/upgrade/registry"
"github.com/lets-cli/lets/workdir"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var version = "0.0.0-dev"
func main() {
ctx := getContext()
configDir := os.Getenv("LETS_CONFIG_DIR")
logging.InitLogging(os.Stdout, os.Stderr)
rootCmd := cmd.CreateRootCommand(version)
rootCmd.InitDefaultHelpFlag()
rootCmd.InitDefaultVersionFlag()
reinitCompletionCmd := cmd.InitCompletionCmd(rootCmd, nil)
rootCmd.InitDefaultHelpCmd()
command, args, err := rootCmd.Traverse(os.Args[1:])
if err != nil {
log.Errorf("lets: traverse commands error: %s", err)
os.Exit(1)
}
rootFlags, err := parseRootFlags(args)
if err != nil {
log.Errorf("lets: parse flags error: %s", err)
os.Exit(1)
}
if rootFlags.version {
if err := cmd.PrintVersionMessage(rootCmd); err != nil {
log.Errorf("lets: print version error: %s", err)
os.Exit(1)
}
os.Exit(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("lets: config error: %s", err)
os.Exit(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("lets: can not create lets.yaml: %s", err)
os.Exit(1)
}
os.Exit(0)
}
if rootFlags.upgrade {
upgrader, err := upgrade.NewBinaryUpgrader(registry.NewGithubRegistry(ctx), version)
if err == nil {
err = upgrader.Upgrade()
}
if err != nil {
log.Errorf("lets: can not self-upgrade binary: %s", err)
os.Exit(1)
}
os.Exit(0)
}
showUsage := rootFlags.help || (command.Name() == "help" && len(args) == 0)
if showUsage {
if err := cmd.PrintHelpMessage(rootCmd); err != nil {
log.Errorf("lets: print help error: %s", err)
os.Exit(1)
}
os.Exit(0)
}
if err := rootCmd.ExecuteContext(ctx); err != nil {
log.Error(err.Error())
exitCode := 1
if e, ok := err.(*executor.ExecuteError); ok { //nolint:errorlint
exitCode = e.ExitCode()
}
os.Exit(exitCode)
}
}
// 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("lets: signal received: %s", sig)
cancel()
}()
return ctx
}
// do not fail on config error in it is help (-h, --help) or --init or completion command
func failOnConfigError(root *cobra.Command, current *cobra.Command, rootFlags *flags) bool {
rootCommands := set.NewSet("completion", "help")
return (root.Flags().NFlag() == 0 && !rootCommands.Contains(current.Name())) && !rootFlags.help && !rootFlags.init
}
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
}