-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathroot.go
More file actions
278 lines (242 loc) · 10.3 KB
/
root.go
File metadata and controls
278 lines (242 loc) · 10.3 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
package cmd
import (
"fmt"
"strings"
"time"
"github.com/stackitcloud/stackit-cli/internal/pkg/types"
affinityGroups "github.com/stackitcloud/stackit-cli/internal/cmd/affinity-groups"
"github.com/stackitcloud/stackit-cli/internal/cmd/auth"
"github.com/stackitcloud/stackit-cli/internal/cmd/beta"
configCmd "github.com/stackitcloud/stackit-cli/internal/cmd/config"
"github.com/stackitcloud/stackit-cli/internal/cmd/curl"
"github.com/stackitcloud/stackit-cli/internal/cmd/dns"
"github.com/stackitcloud/stackit-cli/internal/cmd/git"
"github.com/stackitcloud/stackit-cli/internal/cmd/image"
keypair "github.com/stackitcloud/stackit-cli/internal/cmd/key-pair"
"github.com/stackitcloud/stackit-cli/internal/cmd/kms"
loadbalancer "github.com/stackitcloud/stackit-cli/internal/cmd/load-balancer"
"github.com/stackitcloud/stackit-cli/internal/cmd/logme"
"github.com/stackitcloud/stackit-cli/internal/cmd/logs"
"github.com/stackitcloud/stackit-cli/internal/cmd/mariadb"
"github.com/stackitcloud/stackit-cli/internal/cmd/mongodbflex"
"github.com/stackitcloud/stackit-cli/internal/cmd/network"
networkArea "github.com/stackitcloud/stackit-cli/internal/cmd/network-area"
networkinterface "github.com/stackitcloud/stackit-cli/internal/cmd/network-interface"
objectstorage "github.com/stackitcloud/stackit-cli/internal/cmd/object-storage"
"github.com/stackitcloud/stackit-cli/internal/cmd/observability"
"github.com/stackitcloud/stackit-cli/internal/cmd/opensearch"
"github.com/stackitcloud/stackit-cli/internal/cmd/organization"
"github.com/stackitcloud/stackit-cli/internal/cmd/postgresflex"
"github.com/stackitcloud/stackit-cli/internal/cmd/project"
publicip "github.com/stackitcloud/stackit-cli/internal/cmd/public-ip"
"github.com/stackitcloud/stackit-cli/internal/cmd/quota"
"github.com/stackitcloud/stackit-cli/internal/cmd/rabbitmq"
"github.com/stackitcloud/stackit-cli/internal/cmd/redis"
secretsmanager "github.com/stackitcloud/stackit-cli/internal/cmd/secrets-manager"
securitygroup "github.com/stackitcloud/stackit-cli/internal/cmd/security-group"
"github.com/stackitcloud/stackit-cli/internal/cmd/server"
serviceaccount "github.com/stackitcloud/stackit-cli/internal/cmd/service-account"
"github.com/stackitcloud/stackit-cli/internal/cmd/ske"
"github.com/stackitcloud/stackit-cli/internal/cmd/volume"
"github.com/stackitcloud/stackit-cli/internal/pkg/args"
"github.com/stackitcloud/stackit-cli/internal/pkg/config"
"github.com/stackitcloud/stackit-cli/internal/pkg/errors"
"github.com/stackitcloud/stackit-cli/internal/pkg/flags"
"github.com/stackitcloud/stackit-cli/internal/pkg/globalflags"
"github.com/stackitcloud/stackit-cli/internal/pkg/print"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
func NewRootCmd(params *types.CmdParams) *cobra.Command {
cmd := &cobra.Command{
Use: "stackit",
Short: "Manage STACKIT resources using the command line",
Long: "Manage STACKIT resources using the command line.\nYour feedback is appreciated!",
Args: args.NoArgs,
SilenceErrors: true, // Error is beautified in a custom way before being printed
SilenceUsage: true,
DisableAutoGenTag: true,
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
p := params.Printer
globalFlags := globalflags.Parse(p, cmd)
p.Verbosity = print.Level(globalFlags.Verbosity)
p.AssumeYes = globalFlags.AssumeYes
argsString := print.BuildDebugStrFromSlice(params.Args)
p.Debug(print.DebugLevel, "arguments: %s", argsString)
configFilePath := viper.ConfigFileUsed()
p.Debug(print.DebugLevel, "configuration is persisted and read from: %s", configFilePath)
profileSet, activeProfile, configMethod, err := config.GetConfiguredProfile()
if err != nil {
return fmt.Errorf("get configured profile: %w", err)
}
p.Debug(print.DebugLevel, "read configuration profile %q via %s", profileSet, configMethod)
if activeProfile != profileSet {
if configMethod == "" {
p.Debug(print.DebugLevel, "no profile is configured in env var or profile file")
} else {
p.Debug(print.DebugLevel, "the configured profile %q does not exist: folder %q is missing", profileSet, config.GetProfileFolderPath(profileSet))
}
p.Debug(print.DebugLevel, "the %q profile will be used", activeProfile)
p.Warn("configured profile %q does not exist, the %q profile configuration will be used\n", profileSet, activeProfile)
}
p.Debug(print.DebugLevel, "active configuration profile: %s", activeProfile)
configKeys := viper.AllSettings()
configKeysStr := print.BuildDebugStrFromMap(configKeys)
p.Debug(print.DebugLevel, "configuration keys: %s", configKeysStr)
return nil
},
RunE: func(cmd *cobra.Command, _ []string) error {
p := params.Printer
if flags.FlagToBoolValue(p, cmd, "version") {
p.Outputf("STACKIT CLI\n")
parsedDate, err := time.Parse(time.RFC3339, params.Date)
if err != nil {
p.Outputf("Version: %s\n", params.CliVersion)
return nil
}
p.Outputf("Version: %s (%s)\n", params.CliVersion, parsedDate.Format(time.DateOnly))
return nil
}
return cmd.Help()
},
}
cmd.SetOut(params.Printer.StdOut)
err := configureFlags(cmd)
cobra.CheckErr(err)
addSubcommands(cmd, params)
traverseCommands(cmd, func(c *cobra.Command) {
// Cobra creates the help flag with "help for <command>" as the description
// We want to override that message by capitalizing the first letter to match the other flag descriptions
// See spf13/cobra#480
c.Flags().BoolP("help", "h", false, fmt.Sprintf("Help for %q", c.CommandPath()))
c.SetArgs(params.Args)
c.SetIn(params.Printer.StdIn)
c.SetOut(params.Printer.StdOut)
c.SetErr(params.Printer.StdErr)
c.Flags().SetOutput(params.Printer.StdErr)
})
beautifyUsageTemplate(cmd)
return cmd
}
func beautifyUsageTemplate(cmd *cobra.Command) {
cobra.AddTemplateFunc("WhiteBold", print.WhiteBold)
usageTemplate := cmd.UsageTemplate()
usageTemplate = strings.NewReplacer(
`Usage:`, `{{WhiteBold "USAGE"}}`,
`Examples:`, `{{WhiteBold "EXAMPLES"}}`,
`Aliases:`, `{{WhiteBold "ALIASES"}}`,
`Available Commands:`, `{{WhiteBold "AVAILABLE COMMANDS"}}`,
`Additional Commands:`, `{{WhiteBold "ADDITIONAL COMMANDS"}}`,
`Global Flags:`, `{{WhiteBold "GLOBAL FLAGS"}}`,
`Flags:`, `{{WhiteBold "FLAGS"}}`,
`Additional help topics:`, `{{WhiteBold "ADDITIONAL HELP TOPICS"}}`,
).Replace(usageTemplate)
cmd.SetUsageTemplate(usageTemplate)
}
func configureFlags(cmd *cobra.Command) error {
cmd.Flags().BoolP("version", "v", false, `Show "stackit" version`)
err := globalflags.Configure(cmd.PersistentFlags())
if err != nil {
return fmt.Errorf("configure global flags: %w", err)
}
return nil
}
func addSubcommands(cmd *cobra.Command, params *types.CmdParams) {
cmd.AddCommand(auth.NewCmd(params))
cmd.AddCommand(configCmd.NewCmd(params))
cmd.AddCommand(beta.NewCmd(params))
cmd.AddCommand(curl.NewCmd(params))
cmd.AddCommand(dns.NewCmd(params))
cmd.AddCommand(loadbalancer.NewCmd(params))
cmd.AddCommand(logme.NewCmd(params))
cmd.AddCommand(logs.NewCmd(params))
cmd.AddCommand(mariadb.NewCmd(params))
cmd.AddCommand(mongodbflex.NewCmd(params))
cmd.AddCommand(objectstorage.NewCmd(params))
cmd.AddCommand(observability.NewCmd(params))
cmd.AddCommand(opensearch.NewCmd(params))
cmd.AddCommand(organization.NewCmd(params))
cmd.AddCommand(postgresflex.NewCmd(params))
cmd.AddCommand(project.NewCmd(params))
cmd.AddCommand(rabbitmq.NewCmd(params))
cmd.AddCommand(redis.NewCmd(params))
cmd.AddCommand(secretsmanager.NewCmd(params))
cmd.AddCommand(serviceaccount.NewCmd(params))
cmd.AddCommand(ske.NewCmd(params))
cmd.AddCommand(server.NewCmd(params))
cmd.AddCommand(networkArea.NewCmd(params))
cmd.AddCommand(network.NewCmd(params))
cmd.AddCommand(volume.NewCmd(params))
cmd.AddCommand(networkinterface.NewCmd(params))
cmd.AddCommand(publicip.NewCmd(params))
cmd.AddCommand(securitygroup.NewCmd(params))
cmd.AddCommand(keypair.NewCmd(params))
cmd.AddCommand(image.NewCmd(params))
cmd.AddCommand(quota.NewCmd(params))
cmd.AddCommand(affinityGroups.NewCmd(params))
cmd.AddCommand(git.NewCmd(params))
cmd.AddCommand(kms.NewCmd(params))
}
// traverseCommands calls f for c and all of its children.
func traverseCommands(c *cobra.Command, f func(*cobra.Command)) {
f(c)
for _, c := range c.Commands() {
traverseCommands(c, f)
}
}
// Execute executes the RootCmd and returns true on success and false on failure.
func Execute(params *types.CmdParams) bool {
cmd := NewRootCmd(params)
p := params.Printer
err := cmd.Execute()
if err != nil {
err := beautifyUnknownAndMissingCommandsError(cmd, err, params.Args)
p.Debug(print.ErrorLevel, "execute command: %v", err)
p.Error("%s", err.Error())
return false
}
return true
}
// Returns a more user-friendly error if the input error is due to unknown/missing subcommands (issue: https://github.com/spf13/cobra/issues/706)
//
// Otherwise, returns the input error unchanged
func beautifyUnknownAndMissingCommandsError(rootCmd *cobra.Command, cmdErr error, args []string) error { // nolint:gocritic // args is a nice name despite shadowing
if !strings.HasPrefix(cmdErr.Error(), "unknown flag") {
return cmdErr
}
cmd, unparsedInputs, err := rootCmd.Traverse(args)
if err != nil {
return cmdErr
}
if len(unparsedInputs) == 0 {
// This shouldn't happen
// If we're here, Cobra was able to parse everything, thus it wouldn't raise "unknown flag" errors
return cmdErr
}
// If cmd itself has more subcommands, we assume it has no logic by itself (other than --help)
// We want the error message to state that either a cmd's subcommand is missing, or that the cmd's subcommand called is wrong
if cmd.HasSubCommands() {
if strings.HasPrefix(unparsedInputs[0], "-") {
return &errors.SubcommandMissingError{
Cmd: cmd,
}
}
return &errors.InputUnknownError{
ProvidedInput: unparsedInputs[0],
Cmd: cmd,
}
}
// If we're here, cmd doesn't have subcommands command
// If Cobra raised "unknown flag" errors, then it was while parsing cmd's flags
// To be more user-friendly, we add a usage tip
err = cmd.ParseFlags(unparsedInputs)
if err != nil {
return errors.AppendUsageTip(err, cmd)
}
// This shouldn't happen
// If we're here, Cobra was able to parse cmd's flags, thus it wouldn't raise "unknown flag" errors
return &errors.InputUnknownError{
ProvidedInput: unparsedInputs[0],
Cmd: cmd,
}
}