-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroot.go
More file actions
401 lines (333 loc) · 10.6 KB
/
root.go
File metadata and controls
401 lines (333 loc) · 10.6 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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package rootcmd
import (
"fmt"
"io"
"os"
e "errors"
"github.com/creasty/defaults"
"github.com/sdsc-ordes/quitsh/pkg/build"
"github.com/sdsc-ordes/quitsh/pkg/ci"
printcmd "github.com/sdsc-ordes/quitsh/pkg/cli/cmd/config/print"
"github.com/sdsc-ordes/quitsh/pkg/common"
"github.com/sdsc-ordes/quitsh/pkg/config"
"github.com/sdsc-ordes/quitsh/pkg/errors"
"github.com/sdsc-ordes/quitsh/pkg/exec"
fs "github.com/sdsc-ordes/quitsh/pkg/filesystem"
"github.com/sdsc-ordes/quitsh/pkg/log"
"github.com/goccy/go-yaml"
"github.com/hashicorp/go-version"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// Root arguments.
// NOTE: All fields need proper default values (here mostly empty).
type (
Args struct {
// The config YAML from which we read parameters for the CLI.
// Preset by env. var `QUITSH_CONFIG`.
Config string `yaml:"-"`
// The config YAML (user overlay).
// Preset by env. var `QUITSH_CONFIG_USER`.
ConfigUser string `yaml:"-"`
// Config key,value arguments to override nested config
// values by paths e.g. `a.b.c: {"a":3}` on the command line.
ConfigKeyValues []string `yaml:"-"`
// Working directory to switch to at startup.
// This will be used to search for components.
// This will be used to define the `RootDir` directory.
Cwd string `yaml:"cwd"`
// The root directory of quitsh.
// By default its the Git root directory resolved starting from
// `Cwd`.
RootDir string `yaml:"rootDir"`
// The log level `debug,info,warning,error`.
LogLevel string `yaml:"logLevel" default:""`
// Enable environment print on command execution errors.
EnableEnvPrint bool `yaml:"enableEnvPrint"`
// Disable any toolchain dispatch which might happen.
SkipToolchainDispatch bool `yaml:"skipToolchainDispatch"`
// If we use a global output directory
// instead of component's specific one.
GlobalOutput bool `yaml:"globalOutput"`
// Use a specific output directory (relative to root dir).
GlobalOutputDir string `yaml:"outputDir"`
// Enable running targets in parallel.
Parallel bool `yaml:"parallel"`
}
Settings struct {
Name string
Version *version.Version
Description string
}
)
// SetDefaults implements [defaults.Setter].
func (s *Args) SetDefaults() {
if s.Config == "" {
s.Config = os.Getenv(common.EnvQuitshConfig)
}
if s.ConfigUser == "" {
s.ConfigUser = os.Getenv(common.EnvQuitshConfigUser)
}
}
// SetDefaults implements [defaults.Setter].
func (s *Settings) SetDefaults() {
if s.Name == "" {
s.Name = "quitsh"
}
if s.Version == nil {
s.Version = build.GetBuildVersion()
}
desc := fmt.Sprintf(
"A script tool to support tooling in monorepos [based on quitsh version: %v].",
build.GetBuildVersion(),
) +
`
It replaces non-statically typed script languages -> Quit using 'sh'.
`
if s.Description == "" {
s.Description = desc
}
}
// New creates a new `quitsh` root command with settings `setts` and
// root arguments `rootArgs`. The full argument structure `config` is treated
// as `any` and will be used to parse the configuration files `--config`
// (`--config-user`) into before startup.
// Note: The user must default `config` with `defaults.Set`.
// WARNING: The default values here set and in any subcommand, are unimportant!
// We load the config (the ground truth) always afterwards and before
// any arguments are parsed.
// The sequence is as follows:
// - Incoming `config` is defaulted from `defaults.Setter`.
// - Unmarshal from from `--config`, `--config-user` and `--config-values`.
// - Cobra sets defaults values in command definitions:
// -> IMPORTANT: default values must be to the same pointers when
// config pointer are used, cause otherwise it will overwrite with another
// default value!
// - Cobra executes and sets CLI arguments to override stuff as a final step.
func New(setts *Settings, rootArgs *Args, config config.IConfig) (
rootCmd *cobra.Command) {
err := defaults.Set(rootArgs)
log.PanicE(err, "Could not default root arguments.")
if setts == nil {
setts = &Settings{}
}
err = defaults.Set(setts)
log.PanicE(err, "Could not default settings.")
parsedConfig, parsedConfigUser, err := parseConfigs(config)
log.PanicE(err, "Could not parse config files.")
var version bool
rootCmd = &cobra.Command{
Use: setts.Name,
Long: setts.Description,
SilenceErrors: true,
SilenceUsage: true,
PersistentPreRunE: func(_cmd *cobra.Command, _args []string) error {
applyEnvReplacement(rootArgs)
e := applyGeneralOptions(rootArgs)
if e != nil {
return e
}
if parsedConfig != "" {
log.Debug("Parsed general config.", "path", parsedConfig)
}
if parsedConfigUser != "" {
log.Debug("Parsed user config.", "path", parsedConfigUser)
}
e = applyEnvReplacementConfig(config)
if e != nil {
return e
}
e = config.Validate()
if e != nil {
return e
}
_ = printcmd.PrintConfig(config, true)
return nil
},
RunE: func(cmd *cobra.Command, _args []string) error {
return runRoot(cmd, setts, version)
},
}
addPersistendFlags(rootCmd.PersistentFlags(), rootArgs)
rootCmd.PersistentFlags().
BoolVarP(&rootArgs.Parallel,
"parallel", "P", rootArgs.Parallel, "If targets are built in parallel.")
rootCmd.Flags().
BoolVar(&version, "version", version, "Print the version.")
rootCmd.SilenceErrors = true
return rootCmd
}
func addPersistendFlags(flags *pflag.FlagSet, args *Args) {
flags.
StringVar(&args.Config, "config", args.Config,
"The global configuration file. If set to '-' then stdin is read."+
"Env. variable 'QUITSH_CONFIG' presets this.")
flags.
StringVar(&args.ConfigUser, "config-user", args.ConfigUser,
"The global user configuration file (overlay), can not exist."+
"Env. variable 'QUITSH_CONFIG_USER' presets this.")
flags.
StringArrayVarP(
&args.ConfigKeyValues,
"config-val",
"K",
args.ConfigKeyValues,
"Config key/YAML-value pairs to override nested config values, e.g. `\"a.b.c: {\\\"a\\\": 3}\"`.",
)
flags.
StringVarP(&args.Cwd,
"cwd", "C", args.Cwd,
"Set the current working directory "+
"(note: '--root-dir' = Git root dir evaluated from '--cwd').")
flags.
StringVarP(&args.RootDir,
"root-dir", "R", args.RootDir, "Set the root directory. "+
"This is used to define configured relative paths, e.g. flake path etc.")
flags.
StringVar(&args.LogLevel,
"log-level", args.LogLevel, "The log level. [debug|info|warn|error]")
flags.
BoolVar(
&args.EnableEnvPrint,
"enable-env-print",
args.EnableEnvPrint,
"If env. variables printing for failed commands should be enabled.",
)
flags.
BoolVar(&args.SkipToolchainDispatch,
"skip-toolchain-dispatch", args.SkipToolchainDispatch,
"The flag to denote that we are already inside the toolchain. "+
"Skip any invocation to any toolchain dispatcher.",
)
flags.
BoolVar(&args.GlobalOutput,
"global-output", args.GlobalOutput,
fmt.Sprintf("If a global output directory (repository root dir + '%s').", fs.OutputDir))
flags.
StringVar(
&args.GlobalOutputDir,
"global-output-dir",
args.GlobalOutputDir,
"Use this as global output directory (relative to '--root-dir', more simple: use '--global-output').",
)
}
func parseConfigs(conf config.IConfig) (parsedConfigPath, parsedUserConfigPath string, err error) {
// Parse here the --config, and --config-user and `--config-values`
// and init the config, because that needs to happen before
// cobra parses the flags and set defaults.
//
// Priorities:
// 2. Env. variables (see addPersistendFlags, default values from env.)
// 1. Config from `--config` and `--config-user` and `--config-values.`
// 0. Command line arguments.
var args Args
err = defaults.Set(&args)
log.PanicE(err, "could not default root arguments")
s := pflag.NewFlagSet("default", pflag.ContinueOnError)
addPersistendFlags(s, &args)
s.ParseErrorsWhitelist.UnknownFlags = true
err = s.Parse(os.Args)
if e.Is(err, pflag.ErrHelp) {
// WARN: any `-h` will get into an error. Noway to disable that.
// So we set the error to nil, and return.
return "", "", nil
}
applyEnvReplacement(&args)
parsedConfigPath, err = initConfig(args.RootDir, args.Config, conf, true)
if err != nil {
return
}
parsedUserConfigPath, err = initConfig(args.RootDir, args.ConfigUser, conf, false)
if err != nil {
return
}
err = config.ApplyKeyValues(args.ConfigKeyValues, conf)
if err != nil {
return
}
return
}
func initConfig(
rootDir string,
configPath string,
conf config.IConfig,
errorIfNotExists bool,
) (string, error) {
if configPath == "" {
return "", nil
}
var f io.Reader
switch configPath {
case "-":
f = os.Stdin
configPath = "[stdin]"
default:
// Traverse up until found if relative path.
configPath = fs.FindRelPathInParents(".", configPath, rootDir)
if configPath == "" {
if errorIfNotExists {
return "", errors.New("Config file '%s' does not exists in parents.", configPath)
}
return "", nil
}
ff, err := os.OpenFile(configPath, os.O_RDONLY, fs.DefaultPermissionsFile)
if err != nil {
return "", errors.New("Could not load config file '%s'", configPath)
}
defer ff.Close()
f = ff
}
decoder := yaml.NewDecoder(f, yaml.Strict())
err := decoder.Decode(conf)
if err != nil {
return configPath, errors.AddContext(err,
"could not decode config file '%s'", configPath)
}
return configPath, nil
}
func runRoot(rootCmd *cobra.Command, setts *Settings, version bool) error {
if version {
fmt.Printf( //nolint:forbidigo // Allowed as no log yet.
"%s version %v\n",
setts.Name, setts.Version,
)
return nil
}
_ = rootCmd.Help()
return errors.New("no command given")
}
func applyEnvReplacement(r *Args) {
r.RootDir = os.ExpandEnv(r.RootDir)
r.Config = os.ExpandEnv(r.Config)
r.ConfigUser = os.ExpandEnv(r.ConfigUser)
r.GlobalOutputDir = os.ExpandEnv(r.GlobalOutputDir)
}
func applyEnvReplacementConfig(c any) error {
envRep, _ := c.(config.EnvExpander)
if envRep != nil {
return envRep.ExpandEnv()
}
return nil
}
func applyGeneralOptions(r *Args) error {
if r.LogLevel != "" {
err := log.SetLevel(r.LogLevel)
if err != nil {
return errors.AddContext(err, "could not set log level to '%v'", r.LogLevel)
}
}
if r.GlobalOutput && r.GlobalOutputDir != "" {
return errors.New("either use '--global-output' or " +
"'--global-output-dir', but not both")
}
r.Cwd = fs.MakeAbsolute(r.Cwd)
log.Debug("Setting working dir.", "cwd", r.Cwd)
err := os.Chdir(r.Cwd)
if err != nil {
return errors.AddContext(err, "could not change working dir '%v'", r.Cwd)
}
// Global hack to enable env. printing
// FIXME: Setting globals is not so good!
exec.EnableEnvPrint = !ci.IsRunning() && r.EnableEnvPrint
return nil
}