-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefaults_command.go
More file actions
255 lines (218 loc) · 7.87 KB
/
Copy pathdefaults_command.go
File metadata and controls
255 lines (218 loc) · 7.87 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
package naistrix
import (
"context"
"errors"
"fmt"
"io/fs"
"maps"
"os"
"path/filepath"
"slices"
"sort"
"github.com/MakeNowJust/heredoc/v2"
"github.com/nais/naistrix/input"
"github.com/spf13/viper"
)
// defaultsCommand creates the built-in defaults command for managing default flags for a user.
func defaultsCommand(commandName string, config *viper.Viper) *Command {
return &Command{
Name: commandName,
Title: "Manage default flag values.",
Description: heredoc.Docf(`
The %s command allows you to set, get, unset and list values stored in the configuration file.
Configuration values acts as defaults for various flags throughout the application.
`, commandName),
SubCommands: []*Command{
defaultsSet(config),
defaultsGet(commandName, config),
defaultsList(commandName, config),
defaultsUnset(config),
},
}
}
func defaultsSet(config *viper.Viper) *Command {
return &Command{
Name: "set",
Args: []Argument{
{Name: "key"},
{Name: "value"},
},
Title: "Set a configuration value.",
Description: "Set a configuration value in the configuration file. This value will be used as default for relevant flags throughout the application.",
AutoCompleteFunc: func(_ context.Context, args *Arguments, _ string) ([]string, string) {
settings, err := getSettingsFromConfigFile(config)
if err != nil {
return []string{}, ""
}
return slices.Collect(maps.Keys(settings)), "Choose an existing key or create a new one"
},
RunFunc: func(_ context.Context, args *Arguments, out *OutputWriter) error {
configFilePath := config.ConfigFileUsed()
dir := filepath.Dir(configFilePath)
if _, err := os.Stat(dir); errors.Is(err, fs.ErrNotExist) {
if ok, err := input.Confirm(fmt.Sprintf("The directory for the configuration file (%s) does not exist, do you want to create it?", dir)); err != nil {
return err
} else if !ok {
out.Warnln("Directory creation aborted; configuration not saved")
return nil
}
} else if err != nil {
return fmt.Errorf("unable to access directory %q for configuration file: %w", dir, err)
}
if err := ensureDirectoryExists(dir); err != nil {
return fmt.Errorf("unable to create directory %q for configuration file: %w", dir, err)
}
key := args.Get("key")
value := args.Get("value")
out.Printf("Set <info>%s</info> = <info>%s</info>\n", key, value)
v := viper.New()
v.SetConfigFile(configFilePath)
if err := v.ReadInConfig(); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("unable to read configuration file %q: %w", configFilePath, err)
}
v.Set(key, value)
if err := v.WriteConfig(); err != nil {
return fmt.Errorf("unable to save configuration file: %w", err)
}
out.Println("Configuration file updated")
return nil
},
}
}
func defaultsGet(defaultsCommandName string, config *viper.Viper) *Command {
return &Command{
Name: "get",
Title: "Get one or more configuration values.",
Description: "This command retrieves one or more configuration values from the configuration file.",
Args: []Argument{{Name: "key", Repeatable: true}},
AutoCompleteFunc: autoCompleteConfigurationKeys(config),
RunFunc: func(_ context.Context, args *Arguments, out *OutputWriter) error {
settings, err := getSettingsFromConfigFile(config)
if err != nil {
return fmt.Errorf("unable to read configuration file: %w", err)
}
for _, key := range args.GetRepeatable("key") {
value, ok := settings[key]
if !ok {
out.Printf("No such configuration key: <info>%s</info>, create the value using <info>%s set %s <value></info>\n", key, defaultsCommandName, key)
continue
}
out.Printf("<info>%s</info> = <info>%v</info>\n", key, value)
}
return nil
},
}
}
func defaultsList(defaultsCommandName string, config *viper.Viper) *Command {
return &Command{
Name: "list",
Title: "List configuration values.",
Description: "List all configuration values found in the configuration file.",
RunFunc: func(_ context.Context, _ *Arguments, out *OutputWriter) error {
settings, err := getSettingsFromConfigFile(config)
if err != nil {
return fmt.Errorf("unable to read configuration file: %w", err)
}
if len(settings) == 0 {
out.Printf("The configuration file <info>%s</info> is empty, or it does not yet exist\n", config.ConfigFileUsed())
out.Printf("Use the <info>%s set <key> <value></info> command to set configuration values\n", defaultsCommandName)
return nil
}
values := make([][]string, 0)
for k, v := range settings {
values = append(values, []string{k, fmt.Sprint(v)})
}
sort.SliceStable(values, func(i, j int) bool {
if len(values[i]) == 0 || len(values[j]) == 0 {
return false
}
return values[i][0] < values[j][0]
})
values = append([][]string{{"Key", "Value"}}, values...)
out.Printf("The following configuration values are set in <info>%s</info>:\n\n", config.ConfigFileUsed())
_ = out.Table().Render(values)
out.Printf("\nUse the <info>%[1]s set <key> <value></info> command to update or create values, or the <info>%[1]s unset <key>[, <key>]</info> command to remove values\n", defaultsCommandName)
return nil
},
}
}
func defaultsUnset(config *viper.Viper) *Command {
return &Command{
Name: "unset",
Title: "Unset one or more configuration values.",
Description: "This command removes one or more configuration values from the configuration file completely.",
Args: []Argument{{Name: "key", Repeatable: true}},
AutoCompleteFunc: autoCompleteConfigurationKeys(config),
RunFunc: func(_ context.Context, args *Arguments, out *OutputWriter) error {
settings, err := getSettingsFromConfigFile(config)
if err != nil {
return fmt.Errorf("unable to read configuration file: %w", err)
}
updated := false
for _, key := range args.GetRepeatable("key") {
value, ok := settings[key]
if !ok {
out.Printf("No such configuration key: <info>%s</info>\n", key)
continue
}
out.Printf("Unset <info>%s</info> (value: <info>%v</info>)\n", key, value)
delete(settings, key)
updated = true
}
if !updated {
out.Println("Nothing to update")
return nil
}
v := viper.New()
for key, value := range settings {
v.Set(key, value)
}
v.SetConfigFile(config.ConfigFileUsed())
if err := v.WriteConfig(); err != nil {
return fmt.Errorf("unable to save configuration file: %w", err)
}
out.Println("Configuration file updated")
return nil
},
}
}
// ensureDirectoryExists tries to create the directory that will hold the Viper configuration file.
func ensureDirectoryExists(dir string) error {
return os.MkdirAll(dir, 0o750)
}
// getSettingsFromConfigFile returns settings from a Viper configuration file as a map.
func getSettingsFromConfigFile(config *viper.Viper) (map[string]any, error) {
v := viper.New()
v.SetConfigFile(config.ConfigFileUsed())
if err := v.ReadInConfig(); errors.Is(err, os.ErrNotExist) {
return make(map[string]any), nil
} else if err != nil {
return nil, fmt.Errorf("unable to read configuration file %q: %w", config.ConfigFileUsed(), err)
}
return v.AllSettings(), nil
}
// autoCompleteConfigurationKeys returns an AutoCompleteFunc that suggests configuration keys from the given config
// file.
func autoCompleteConfigurationKeys(config *viper.Viper) AutoCompleteFunc {
return func(_ context.Context, args *Arguments, _ string) ([]string, string) {
settings, err := getSettingsFromConfigFile(config)
if err != nil {
return []string{}, ""
}
var inArgs []string
if args.Len() > 0 {
inArgs = args.GetRepeatable("key")
}
keys := make([]string, 0)
for key := range settings {
if slices.Contains(inArgs, key) {
continue
}
keys = append(keys, key)
}
if len(keys) == 0 {
return []string{}, ""
}
return keys, "Available configuration keys"
}
}