-
Notifications
You must be signed in to change notification settings - Fork 21
/
config.go
300 lines (256 loc) · 9.28 KB
/
config.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
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
// Copyright 2022 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package command
import (
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
configlib "github.com/vmware-tanzu/tanzu-plugin-runtime/config"
"github.com/vmware-tanzu/tanzu-plugin-runtime/plugin"
"github.com/vmware-tanzu/tanzu-cli/pkg/cli"
"github.com/vmware-tanzu/tanzu-cli/pkg/pluginsupplier"
"github.com/vmware-tanzu/tanzu-plugin-runtime/log"
)
// ConfigLiterals used with set/unset commands
const (
ConfigLiteralFeatures = "features"
ConfigLiteralEnv = "env"
)
func init() {
configCmd.SetUsageFunc(cli.SubCmdUsageFunc)
configCmd.AddCommand(
getConfigCmd,
initConfigCmd,
setConfigCmd,
unsetConfigCmd,
newEULACmd(),
newCertCmd(),
)
}
var unattended bool
var configCmd = &cobra.Command{
Use: "config",
Short: "Configuration for the CLI",
Annotations: map[string]string{
"group": string(plugin.SystemCmdGroup),
},
}
var getConfigCmd = &cobra.Command{
Use: "get",
Short: "Get the current configuration",
ValidArgsFunction: noMoreCompletions,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := configlib.GetClientConfig()
if err != nil {
return err
}
// Print the entire config
b, err := yaml.Marshal(&cfg)
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), strings.TrimSpace(string(b)))
warningForShadowedEnvVars(cmd.ErrOrStderr())
return nil
},
}
// Check if any of the variables of the config file are shadowed by
// a variable defined in the shell. If so, warn the user.
func warningForShadowedEnvVars(writer io.Writer) {
varsInConfig := configlib.GetEnvConfigurations()
varNames := make([]string, 0, len(varsInConfig))
for k := range varsInConfig {
varNames = append(varNames, k)
}
sort.Strings(varNames)
first := true
for _, name := range varNames {
configValue := varsInConfig[name]
envValue := os.Getenv(name)
if envValue != configValue {
if first {
first = false
fmt.Fprintln(writer, "\nNote: The following variables set in the current shell take precedence over the ones of the same name set in the tanzu config:")
}
if envValue == "" {
envValue = "''"
}
fmt.Fprintf(writer, " - %s: %s\n", name, envValue)
}
}
}
var setConfigCmd = &cobra.Command{
Use: "set PATH <value>",
Short: "Set config values at the given PATH",
Long: "Set config values at the given PATH. Supported PATH values: [features.global.<feature>, features.<plugin>.<feature>, env.<variable>]",
ValidArgsFunction: completeSetConfig,
Example: `
# Sets a custom CA cert for a proxy that requires it
tanzu config set env.PROXY_CA_CERT b329baa034afn3.....
# Enables a specific plugin feature
tanzu config set features.management-cluster.custom_nameservers true
# Enables a general CLI feature
tanzu config set features.global.abcd true`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 2 {
return errors.Errorf("both PATH and <value> are required")
}
if len(args) > 2 {
return errors.Errorf("only PATH and <value> are allowed")
}
err := setConfiguration(args[0], args[1])
if err != nil {
return err
}
return nil
},
}
// setConfiguration sets the key-value pair for the given path
func setConfiguration(pathParam, value string) error {
// parse the param
paramArray := strings.Split(pathParam, ".")
if len(paramArray) < 2 {
return errors.New("unable to parse config path parameter into parts [" + pathParam + "] (was expecting 'features.<plugin>.<feature>' or 'env.<env_variable>')")
}
configLiteral := paramArray[0]
switch configLiteral {
case ConfigLiteralFeatures:
if len(paramArray) != 3 {
return errors.New("unable to parse config path parameter into three parts [" + strings.Join(paramArray, ".") + "] (was expecting 'features.<plugin>.<feature>'")
}
if value != "true" && value != "false" { //nolint:goconst
return errors.New("invalid value provided only boolean true or false are accepted")
}
return configlib.SetFeature(paramArray[1], paramArray[2], value)
case ConfigLiteralEnv:
if len(paramArray) != 2 {
return errors.New("unable to parse config path parameter into two parts [" + strings.Join(paramArray, ".") + "] (was expecting 'env.<variable>'")
}
return configlib.SetEnv(paramArray[1], value)
default:
return errors.New("unsupported config path parameter [" + configLiteral + "] (was expecting 'features.<plugin>.<feature>' or 'env.<env_variable>')")
}
}
var initConfigCmd = &cobra.Command{
Use: "init",
Short: "Initialize config with defaults",
Long: "Initialize config with defaults including plugin specific defaults such as default feature flags for all active and installed plugins",
ValidArgsFunction: noMoreCompletions,
RunE: func(cmd *cobra.Command, args []string) error {
plugins, err := pluginsupplier.GetInstalledPlugins()
if err != nil {
return err
}
// Add the default featureflags for active plugins based on the currentContext
// Plugins that are installed but are not active plugin will not be processed here
// and defaultFeatureFlags will not be configured for those plugins
for _, desc := range plugins {
err := configlib.ConfigureFeatureFlags(desc.DefaultFeatureFlags, configlib.SkipIfExists())
if err != nil {
return err
}
}
log.Success("successfully initialized the config")
return nil
},
}
var unsetConfigCmd = &cobra.Command{
Use: "unset PATH",
Short: "Unset config values at the given PATH",
Long: "Unset config values at the given PATH. Supported PATH values: [features.global.<feature>, features.<plugin>.<feature>, env.<variable>]",
ValidArgsFunction: completeUnsetConfig,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.Errorf("PATH is required")
}
if len(args) > 1 {
return errors.Errorf("only PATH is allowed")
}
return unsetConfiguration(args[0])
},
}
// unsetConfiguration unsets the key-value pair for the given path and removes it
func unsetConfiguration(pathParam string) error {
// parse the param
paramArray := strings.Split(pathParam, ".")
if len(paramArray) < 2 {
return errors.New("unable to parse config path parameter into parts [" + pathParam + "] (was expecting 'features.<plugin>.<feature>' or 'env.<env_variable>')")
}
configLiteral := paramArray[0]
switch configLiteral {
case ConfigLiteralFeatures:
return unsetFeatures(paramArray)
case ConfigLiteralEnv:
return unsetEnvs(paramArray)
default:
return errors.New("unsupported config path parameter [" + configLiteral + "] (was expecting 'features.<plugin>.<feature>' or 'env.<env_variable>')")
}
}
func unsetFeatures(paramArray []string) error {
if len(paramArray) != 3 {
return errors.New("unable to parse config path parameter into three parts [" + strings.Join(paramArray, ".") + "] (was expecting 'features.<plugin>.<feature>'")
}
pluginName := paramArray[1]
featureName := paramArray[2]
return configlib.DeleteFeature(pluginName, featureName)
}
func unsetEnvs(paramArray []string) error {
if len(paramArray) != 2 {
return errors.New("unable to parse config path parameter into two parts [" + strings.Join(paramArray, ".") + "] (was expecting 'env.<env_variable>'")
}
envVariable := paramArray[1]
return configlib.DeleteEnv(envVariable)
}
// ====================================
// Shell completion functions
// ====================================
func completeSetConfig(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) {
if len(args) > 1 {
return activeHelpNoMoreArgs(nil), cobra.ShellCompDirectiveNoFileComp
}
if len(args) == 1 {
return cobra.AppendActiveHelp(nil, "You must provide a value as a second argument"),
cobra.ShellCompDirectiveNoFileComp
}
comps := cobra.AppendActiveHelp(nil, "You can modify the below entries, or provide a new one")
comps = append(comps, completionGetEnvAndFeatures()...)
return comps, cobra.ShellCompDirectiveNoFileComp
}
func completeUnsetConfig(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) {
if len(args) > 0 {
return activeHelpNoMoreArgs(nil), cobra.ShellCompDirectiveNoFileComp
}
return completionGetEnvAndFeatures(), cobra.ShellCompDirectiveNoFileComp
}
func completionGetEnvAndFeatures() []string {
// Complete all available env.<var> and features.<...> immediately
// instead of first completing "env." and "features.".
// This allows doing fuzzy matching with zsh and fish such as:
// "tanzu config unset ADD<TAB>" and directly getting the completion
// "env.TANZU_CLI_ADDITIONAL_PLUGIN_DISCOVERY_IMAGES_TEST_ONLY"
var comps []string
if envVars, err := configlib.GetAllEnvs(); err == nil {
for name, value := range envVars {
comps = append(comps, fmt.Sprintf("%s.%s\tValue: %q", ConfigLiteralEnv, name, value))
}
}
// Retrieve client config node
featureFlags, err := configlib.GetAllFeatureFlags()
if err != nil {
return comps
}
for pluginKey, features := range featureFlags {
for name, value := range features {
comps = append(comps, fmt.Sprintf("%s.%s.%s\tValue: %q", ConfigLiteralFeatures, pluginKey, name, value))
}
}
// Sort to allow for testing
sort.Strings(comps)
return comps
}