-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructconf.go
More file actions
341 lines (286 loc) · 8.75 KB
/
structconf.go
File metadata and controls
341 lines (286 loc) · 8.75 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
package structconf
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"strings"
"github.com/urfave/cli/v3"
)
type ConfigValidator func(cmd *cli.Command, configPointer any) error
type cliOptions struct {
version string
description string
longDescription string
loadConfigFlagName string
enableShellCompletion bool
commandOptions commandOptions
}
type commandOptions struct {
validator ConfigValidator
}
type (
Option func(opts *cliOptions)
CommandOption func(opts *commandOptions)
)
func WithVersion(version string) Option {
return func(opts *cliOptions) {
opts.version = version
}
}
func WithDescription(description string) Option {
return func(opts *cliOptions) {
opts.description = description
}
}
func WithLongDescription(usage string) Option {
return func(opts *cliOptions) {
opts.longDescription = usage
}
}
func WithShellCompletions() Option {
return func(opts *cliOptions) {
opts.enableShellCompletion = true
}
}
func WithDefaultLoadConfigFlag() Option {
return WithLoadConfigFlag("load-config")
}
func WithLoadConfigFlag(flagName string) Option {
return func(opts *cliOptions) {
opts.loadConfigFlagName = flagName
}
}
func WithValidator(validator ConfigValidator) Option {
return func(opts *cliOptions) {
opts.commandOptions.validator = validator
}
}
func WithCommandValidator(validator ConfigValidator) CommandOption {
return func(opts *commandOptions) {
opts.validator = validator
}
}
func WithDisableValidation() Option {
return func(opts *cliOptions) {
opts.commandOptions.validator = func(cmd *cli.Command, configPointer any) error { return nil }
}
}
func WithDisableCommandValidation() CommandOption {
return func(opts *commandOptions) {
opts.validator = func(cmd *cli.Command, configPointer any) error { return nil }
}
}
// MustLoad is like Load, but if it fails, it prints the error to stderr and exits
// with a non-zero exit code.
func MustLoad(configPointer any, programName string, opts ...Option) {
MustLoadArgs(configPointer, programName, os.Args, opts...)
}
// MustLoadArgs is like LoadArgs, but if it fails, it prints the error to stderr and exits
// with a non-zero exit code.
func MustLoadArgs(configPointer any, programName string, args []string, opts ...Option) {
err := LoadArgs(configPointer, programName, args, opts...)
if err != nil {
helpRequested := &helpRequestedError{}
if errors.As(err, &helpRequested) {
fmt.Println(helpRequested.helpText) //nolint:forbidigo
os.Exit(0) // no error, since we requested help
}
_, printErr := fmt.Fprintln(os.Stderr, err.Error())
if printErr != nil {
fmt.Println(err.Error()) //nolint:forbidigo // we couldn't print to stderr, so let's print to stdout instead
}
os.Exit(1)
}
}
// Load loads the given config struct.
//
// It loads the config from the following sources in the given order:
// 1. command line flags and arguments
// 2. config files (if the config struct satisfies the loadConfigFromTOMLFiles interface by embedding LoadTOMLConfig)
// 3. environment variables
// 4. default values defined in the field tags
//
// It then runs the configured validator, which uses the validate tag in config fields by default.
// The returned error is suitable to be printed to the user.
func Load(configPointer any, programName string, opts ...Option) error {
return LoadArgs(configPointer, programName, os.Args, opts...)
}
// LoadArgs is like Load, but allows explicitly providing the CLI args.
func LoadArgs(configPointer any, programName string, args []string, opts ...Option) error {
cfg := &cliOptions{
commandOptions: commandOptions{
validator: validate, // default validator
},
}
for _, opt := range opts {
opt(cfg)
}
tomlSources := make([]cli.MapSource, 0)
var loadConfigFlag cli.Flag
if cfg.loadConfigFlagName != "" {
loadConfigFlag = &cli.StringSliceFlag{
Name: cfg.loadConfigFlagName,
Usage: "Load configuration from TOML files",
}
config, err := NewStructConfigurator(configPointer, nil)
if err != nil {
return err
}
flags := config.Flags()
flags = append(flags, loadConfigFlag)
if duplicate := firstDuplicateFlagName(flags); duplicate != "" {
return fmt.Errorf("got duplicate flag name: %s", duplicate)
}
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
cmd := cli.Command{
Name: programName,
Version: cfg.version,
Writer: stdout,
ErrWriter: stderr,
Description: cfg.longDescription,
Usage: cfg.description,
EnableShellCompletion: cfg.enableShellCompletion,
Flags: flags,
Action: func(ctx context.Context, cmd *cli.Command) error {
tomlFiles := cmd.StringSlice(cfg.loadConfigFlagName)
for _, file := range tomlFiles {
source, err := NewTomlFileSource("toml", file)
if err != nil {
return err
}
tomlSources = append(tomlSources, source)
}
return nil
},
}
err = cmd.Run(context.Background(), args)
if err != nil {
if stdout.Len() > 0 {
return errors.New(err.Error() + "\n\n" + stdout.String())
}
return err
}
if stdout.Len() > 0 { // help was requested -> return an error so that we can exit
return &helpRequestedError{
helpText: stdout.String(),
}
}
}
config, err := NewStructConfigurator(configPointer, tomlSources)
if err != nil {
return err
}
flags := config.Flags()
if loadConfigFlag != nil {
flags = append(flags, loadConfigFlag)
}
if duplicate := firstDuplicateFlagName(flags); duplicate != "" {
return fmt.Errorf("duplicate flag: --%s", duplicate)
}
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
cmd := &cli.Command{
Name: programName,
Version: cfg.version,
Writer: stdout,
ErrWriter: stderr,
Description: cfg.longDescription,
Usage: cfg.description,
EnableShellCompletion: cfg.enableShellCompletion,
Flags: flags,
Arguments: config.Arguments(),
Action: func(ctx context.Context, cmd *cli.Command) error {
config.Apply(cmd)
return nil
},
}
err = cmd.Run(context.Background(), args)
if err != nil {
if stdout.Len() > 0 {
return errors.New(strings.TrimSpace(err.Error() + "\n\n" + stdout.String()))
}
return err
}
if stdout.Len() > 0 { // help was requested -> return an error so that we can exit
return &helpRequestedError{
helpText: strings.TrimSpace(stdout.String()),
}
}
return cfg.commandOptions.validator(cmd, configPointer)
}
// NewCommand creates a urfave/cli command and binds the given config struct to it.
//
// When the command is executed, the config is loaded from flags, arguments, env vars and default values,
// then the configured validator is run before the optional action is executed.
//
// The WithLoadConfigFlag option is not currently supported for BindCommand/NewCommand.
func NewCommand(configPointer any, commandName string, action cli.ActionFunc, opts ...CommandOption) (*cli.Command, error) {
cmd := &cli.Command{
Name: commandName,
Action: action,
}
err := BindCommand(cmd, configPointer, opts...)
if err != nil {
return nil, err
}
return cmd, nil
}
// BindCommand binds the given config struct to an existing urfave/cli command.
//
// It appends reflected flags and arguments to the command and wraps the command's Action so that config
// loading and the configured validator are run before the existing Action.
//
// The WithLoadConfigFlag option is not currently supported for BindCommand/NewCommand.
func BindCommand(command *cli.Command, configPointer any, opts ...CommandOption) error {
cfg := &commandOptions{
validator: validate, // default validator
}
for _, opt := range opts {
opt(cfg)
}
config, err := NewStructConfigurator(configPointer, nil)
if err != nil {
return err
}
flags := append([]cli.Flag{}, command.Flags...)
flags = append(flags, config.Flags()...)
if duplicate := firstDuplicateFlagName(flags); duplicate != "" {
return fmt.Errorf("duplicate flag: --%s", duplicate)
}
command.Flags = flags
command.Arguments = append(command.Arguments, config.Arguments()...)
wrappedAction := command.Action
command.Action = func(ctx context.Context, cmd *cli.Command) error {
config.Apply(cmd)
if err := cfg.validator(command, configPointer); err != nil {
return err
}
if wrappedAction == nil {
return nil
}
return wrappedAction(ctx, cmd)
}
return nil
}
type helpRequestedError struct {
helpText string
}
func (e *helpRequestedError) Error() string {
return e.helpText
}
func firstDuplicateFlagName(flags []cli.Flag) string {
seen := make(map[string]bool)
for _, flag := range flags {
for _, name := range flag.Names() {
isDuplicate, ok := seen[name]
if ok && isDuplicate {
return name
}
seen[name] = true
}
}
return ""
}