-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstructconf.go
224 lines (197 loc) · 5.62 KB
/
structconf.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
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) {
err := LoadAndValidate(configPointer, programName, 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 {
err := loadConfig(configPointer, programName, opts...)
if err != nil {
return err
}
return validate(configPointer)
}
type helpRequestedError struct {
helpText string
}
func (e *helpRequestedError) Error() string {
return e.helpText
}
func loadConfig(configPointer any, programName 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(), os.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(), os.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 ""
}