-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructconf.go
More file actions
324 lines (272 loc) · 8.37 KB
/
structconf.go
File metadata and controls
324 lines (272 loc) · 8.37 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
package structconf
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"strings"
"github.com/urfave/cli/v3"
)
type options struct {
version string
description string
longDescription string
enableShellCompletion bool
loadConfigFlagName string
}
type Option func(opts *options)
func WithVersion(version string) Option {
return func(opts *options) {
opts.version = version
}
}
func WithDescription(description string) Option {
return func(opts *options) {
opts.description = description
}
}
func WithLongDescription(usage string) Option {
return func(opts *options) {
opts.longDescription = usage
}
}
func WithShellCompletions() Option {
return func(opts *options) {
opts.enableShellCompletion = true
}
}
func WithDefaultLoadConfigFlag() Option {
return WithLoadConfigFlag("load-config")
}
func WithLoadConfigFlag(flagName string) Option {
return func(opts *options) {
opts.loadConfigFlagName = flagName
}
}
// MustLoadAndValidate is like LoadAndValidate, but if it fails, it prints the error to stderr and exits
// with a non-zero exit code.
func MustLoadAndValidate(configPointer any, programName string, opts ...Option) {
MustLoadAndValidateArgs(configPointer, programName, os.Args, opts...)
}
// MustLoadAndValidateArgs is like LoadAndValidateArgs, but if it fails, it prints the error to stderr and exits
// with a non-zero exit code.
func MustLoadAndValidateArgs(configPointer any, programName string, args []string, opts ...Option) {
err := LoadAndValidateArgs(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)
}
}
// LoadAndValidate loads the given config struct and validates it.
//
// It loads the config from the following sources in the given order:
// 1. command line flags
// 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 validates the loaded config, using the validate tag in config fields - if it fails, it returns an error.
// The returned error is suitable to be printed to the user.
func LoadAndValidate(configPointer any, programName string, opts ...Option) error {
return LoadAndValidateArgs(configPointer, programName, os.Args, opts...)
}
// LoadAndValidateArgs is like LoadAndValidate, but allows explicitly providing the CLI args.
func LoadAndValidateArgs(configPointer any, programName string, args []string, opts ...Option) error {
err := loadConfigWithArgs(configPointer, programName, args, opts...)
if err != nil {
return err
}
return validate(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, env vars and default values,
// then validated 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 ...Option) (*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 to the command and wraps the command's Action so that config
// loading and validation are run before the existing Action.
//
// The WithLoadConfigFlag option is not currently supported for BindCommand/NewCommand.
func BindCommand(command *cli.Command, configPointer any, opts ...Option) error {
cfg := &options{}
for _, opt := range opts {
opt(cfg)
}
if cfg.loadConfigFlagName != "" {
return errors.New("WithLoadConfigFlag is not supported for BindCommand/NewCommand; use LoadAndValidate for top-level commands")
}
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
if cfg.enableShellCompletion {
command.EnableShellCompletion = true
}
if cfg.version != "" {
command.Version = cfg.version
}
if cfg.longDescription != "" {
command.Description = cfg.longDescription
}
if cfg.description != "" {
command.Usage = cfg.description
}
wrappedAction := command.Action
command.Action = func(ctx context.Context, cmd *cli.Command) error {
config.Apply(cmd)
if err := validate(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 loadConfigWithArgs(configPointer any, programName string, args []string, opts ...Option) error {
cfg := &options{}
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,
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 nil
}
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 ""
}