-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathroot.go
More file actions
459 lines (379 loc) · 14 KB
/
Copy pathroot.go
File metadata and controls
459 lines (379 loc) · 14 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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*
Copyright © 2020 NAME HERE <EMAIL ADDRESS>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"context"
"errors"
"fmt"
"io/fs"
"log"
"os"
"strings"
"time"
"github.com/planetscale/cli/internal/cmd/agentguide"
"github.com/planetscale/cli/internal/cmd/mcp"
"github.com/planetscale/cli/internal/cmd/role"
"github.com/planetscale/cli/internal/cmd/size"
"github.com/planetscale/cli/internal/cmd/trafficcontrol"
"github.com/planetscale/cli/internal/cmd/workflow"
"github.com/fatih/color"
"github.com/planetscale/cli/internal/cmd/api"
"github.com/planetscale/cli/internal/cmd/auditlog"
"github.com/planetscale/cli/internal/cmd/auth"
"github.com/planetscale/cli/internal/cmd/backup"
"github.com/planetscale/cli/internal/cmd/branch"
"github.com/planetscale/cli/internal/cmd/connect"
"github.com/planetscale/cli/internal/cmd/database"
"github.com/planetscale/cli/internal/cmd/dataimports"
"github.com/planetscale/cli/internal/cmd/deployrequest"
"github.com/planetscale/cli/internal/cmd/keyspace"
"github.com/planetscale/cli/internal/cmd/org"
"github.com/planetscale/cli/internal/cmd/password"
"github.com/planetscale/cli/internal/cmd/ping"
"github.com/planetscale/cli/internal/cmd/region"
"github.com/planetscale/cli/internal/cmd/shell"
"github.com/planetscale/cli/internal/cmd/signup"
"github.com/planetscale/cli/internal/cmd/sql"
"github.com/planetscale/cli/internal/cmd/token"
"github.com/planetscale/cli/internal/cmd/version"
"github.com/planetscale/cli/internal/cmd/webhook"
"github.com/planetscale/cli/internal/cmdutil"
"github.com/planetscale/cli/internal/config"
"github.com/planetscale/cli/internal/printer"
"github.com/planetscale/cli/internal/update"
ps "github.com/planetscale/planetscale-go/planetscale"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
var (
cfgFile string
replacer = strings.NewReplacer("-", "_", ".", "_")
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "pscale",
Short: "A CLI for PlanetScale",
Long: `pscale is a CLI for communicating with PlanetScale's API.
Agents and automation should start with:
pscale agent-guide --format json
pscale auth check --format json`,
TraverseChildren: true,
}
// Execute executes the command and returns the exit status of the finished
// command.
func Execute(ctx context.Context, sigc chan os.Signal, signals []os.Signal, ver, commit, buildDate string) int {
var format printer.Format
var debug bool
if _, ok := os.LookupEnv("PSCALE_DISABLE_DEV_WARNING"); !ok {
if commit == "" || ver == "" || buildDate == "" {
fmt.Fprintf(os.Stderr, "!! WARNING: You are using a self-compiled binary which is not officially supported.\n!! To dismiss this warning, set PSCALE_DISABLE_DEV_WARNING=true\n\n")
}
}
if update.Enabled() {
updateCheckRes := make(chan *update.UpdateInfo, 1)
updateCheckErr := make(chan error, 1)
updateTimeout := time.After(500 * time.Millisecond)
go func() {
// note: don't close the chans to avoid
// triggering the wrong select case
ui, err := update.CheckVersion(ctx, ver)
if err != nil {
updateCheckErr <- err
} else {
updateCheckRes <- ui
}
}()
defer func() {
select {
case ui := <-updateCheckRes:
ui.PrintUpdateHint(ver)
case err := <-updateCheckErr:
fmt.Fprintf(os.Stderr, "Updater error: %v\n", err)
case <-updateTimeout:
}
}()
}
err := runCmd(ctx, ver, commit, buildDate, &format, &debug, sigc, signals)
if err == nil {
return 0
}
if cmdErr, ok := errors.AsType[*cmdutil.Error](err); ok && cmdErr.Handled {
if cmdErr.ExitCode != 0 {
return cmdErr.ExitCode
}
return cmdutil.ActionRequestedExitCode
}
if format == printer.JSON {
return cmdutil.ReportGlobalJSONError(os.Stdout, os.Stderr, err)
}
if isRootOrgFlagError(err) {
fmt.Fprintf(os.Stderr, "Error: %s\nHint: --org belongs on resource commands, not on pscale root. Example: pscale database list --org <org> --format json\n", err)
return cmdutil.FatalErrExitCode
}
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
// check if a sub command wants to return a specific exit code
if cmdErr, ok := errors.AsType[*cmdutil.Error](err); ok {
return cmdErr.ExitCode
}
return cmdutil.FatalErrExitCode
}
func isRootOrgFlagError(err error) bool {
if err == nil {
return false
}
return strings.Contains(err.Error(), "unknown flag: --org")
}
// runCmd adds all child commands to the root command, sets flags
// appropriately, and runs the root command.
func runCmd(ctx context.Context, ver, commit, buildDate string, format *printer.Format, debug *bool, sigc chan os.Signal, signals []os.Signal) error {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config",
"", "Config file (default is $HOME/.config/planetscale/pscale.yml)")
rootCmd.SilenceUsage = true
rootCmd.SilenceErrors = true
v := version.Format(ver, commit, buildDate)
rootCmd.SetVersionTemplate(v)
rootCmd.Version = v
rootCmd.Flags().Bool("version", false, "Show pscale version")
cfg, err := config.New()
if err != nil {
return err
}
rootCmd.PersistentFlags().StringVar(&cfg.BaseURL,
"api-url", ps.DefaultBaseURL, "The base URL for the PlanetScale API.")
rootCmd.PersistentFlags().StringVar(&cfg.AccessToken,
"api-token", cfg.AccessToken, "The API token to use for authenticating against the PlanetScale API.")
rootCmd.PersistentFlags().VarP(printer.NewFormatValue(printer.Human, format), "format", "f",
"Show output in a specific format. Possible values: [human, json, csv]")
if err := viper.BindPFlag("format", rootCmd.PersistentFlags().Lookup("format")); err != nil {
return err
}
rootCmd.RegisterFlagCompletionFunc("format", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"human", "json", "csv"}, cobra.ShellCompDirectiveDefault
})
rootCmd.PersistentFlags().BoolVar(debug, "debug", false, "Enable debug mode")
if err := viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug")); err != nil {
return err
}
userAgent := "pscale-cli/" + ver
headers := map[string]string{
"pscale-cli-version": ver,
}
ch := &cmdutil.Helper{
Printer: printer.NewPrinter(format),
Config: cfg,
ConfigFS: config.NewConfigFS(osFS{}),
Client: func() (*ps.Client, error) {
return cfg.NewClientFromConfig(ps.WithUserAgent(userAgent), ps.WithRequestHeaders(headers))
},
}
ch.SetDebug(debug)
// service token flags. they are hidden for now.
rootCmd.PersistentFlags().StringVar(&cfg.ServiceTokenID,
"service-token-name", "", "The Service Token name for authenticating.")
rootCmd.PersistentFlags().StringVar(&cfg.ServiceTokenID, "service-token-id", "", "The Service Token ID for authenticating.")
rootCmd.PersistentFlags().StringVar(&cfg.ServiceToken,
"service-token", "", "Service Token for authenticating.")
rootCmd.PersistentFlags().BoolVar(&color.NoColor, "no-color", false, "Disable color output")
if err := viper.BindPFlag("no-color", rootCmd.PersistentFlags().Lookup("no-color")); err != nil {
return err
}
rootCmd.PersistentFlags().MarkDeprecated("service-token-name", "use --service-token-id instead")
rootCmd.PersistentFlags().MarkHidden("service-token-name")
// We don't want to show the default value
rootCmd.PersistentFlags().Lookup("api-token").DefValue = ""
// Add command groups for better organization
rootCmd.AddGroup(&cobra.Group{ID: "database", Title: printer.Bold("MySQL & PostgreSQL database commands:")})
rootCmd.AddGroup(&cobra.Group{ID: "vitess", Title: printer.Bold("Vitess/MySQL-specific commands:")})
rootCmd.AddGroup(&cobra.Group{ID: "postgres", Title: printer.Bold("PostgreSQL-specific commands:")})
rootCmd.AddGroup(&cobra.Group{ID: "platform", Title: printer.Bold("Platform & account management:")})
loginCmd := auth.LoginCmd(ch)
loginCmd.Hidden = true
logoutCmd := auth.LogoutCmd(ch)
logoutCmd.Hidden = true
rootCmd.AddCommand(loginCmd)
rootCmd.AddCommand(logoutCmd)
// Platform & Account Management commands
agentGuideCmd := agentguide.AgentGuideCmd(ch)
agentGuideCmd.GroupID = "platform"
rootCmd.AddCommand(agentGuideCmd)
apiCmd := api.ApiCmd(ch, userAgent, headers)
apiCmd.GroupID = "platform"
rootCmd.AddCommand(apiCmd)
auditlogCmd := auditlog.AuditLogCmd(ch)
auditlogCmd.GroupID = "platform"
rootCmd.AddCommand(auditlogCmd)
authCmd := auth.AuthCmd(ch)
authCmd.GroupID = "platform"
rootCmd.AddCommand(authCmd)
completionCmd := CompletionCmd()
completionCmd.GroupID = "platform"
rootCmd.AddCommand(completionCmd)
mcpCmd := mcp.McpCmd(ch)
mcpCmd.GroupID = "database"
rootCmd.AddCommand(mcpCmd)
orgCmd := org.OrgCmd(ch)
orgCmd.GroupID = "platform"
rootCmd.AddCommand(orgCmd)
pingCmd := ping.PingCmd(ch)
pingCmd.GroupID = "platform"
rootCmd.AddCommand(pingCmd)
regionCmd := region.RegionCmd(ch)
regionCmd.GroupID = "platform"
rootCmd.AddCommand(regionCmd)
signupCmd := signup.SignupCmd(ch)
signupCmd.GroupID = "platform"
rootCmd.AddCommand(signupCmd)
sizeCmd := size.SizeCmd(ch)
sizeCmd.GroupID = "platform"
rootCmd.AddCommand(sizeCmd)
tokenCmd := token.TokenCmd(ch)
tokenCmd.GroupID = "platform"
rootCmd.AddCommand(tokenCmd)
versionCmd := version.VersionCmd(ch, ver, commit, buildDate)
versionCmd.GroupID = "platform"
rootCmd.AddCommand(versionCmd)
// Database management commands (Both databases)
backupCmd := backup.BackupCmd(ch)
backupCmd.GroupID = "database"
rootCmd.AddCommand(backupCmd)
branchCmd := branch.BranchCmd(ch)
branchCmd.GroupID = "database"
rootCmd.AddCommand(branchCmd)
databaseCmd := database.DatabaseCmd(ch)
databaseCmd.GroupID = "database"
rootCmd.AddCommand(databaseCmd)
webhookCmd := webhook.WebhookCmd(ch)
webhookCmd.GroupID = "database"
rootCmd.AddCommand(webhookCmd)
// Vitess-specific commands
connectCmd := connect.ConnectCmd(ch)
connectCmd.GroupID = "vitess"
rootCmd.AddCommand(connectCmd)
dataimportsCmd := dataimports.DataImportsCmd(ch)
dataimportsCmd.GroupID = "vitess"
rootCmd.AddCommand(dataimportsCmd)
deployRequestCmd := deployrequest.DeployRequestCmd(ch)
deployRequestCmd.GroupID = "vitess"
rootCmd.AddCommand(deployRequestCmd)
keyspaceCmd := keyspace.KeyspaceCmd(ch)
keyspaceCmd.GroupID = "vitess"
rootCmd.AddCommand(keyspaceCmd)
passwordCmd := password.PasswordCmd(ch)
passwordCmd.GroupID = "vitess"
rootCmd.AddCommand(passwordCmd)
shellCmd := shell.ShellCmd(ch, sigc, signals...)
shellCmd.GroupID = "database"
rootCmd.AddCommand(shellCmd)
sqlCmd := sql.SQLCmd(ch)
sqlCmd.GroupID = "database"
rootCmd.AddCommand(sqlCmd)
workflowCmd := workflow.WorkflowCmd(ch)
workflowCmd.GroupID = "vitess"
rootCmd.AddCommand(workflowCmd)
roleCmd := role.RoleCmd(ch)
roleCmd.GroupID = "postgres"
rootCmd.AddCommand(roleCmd)
trafficCmd := trafficcontrol.TrafficCmd(ch)
trafficCmd.GroupID = "postgres"
rootCmd.AddCommand(trafficCmd)
annotateRequiredFlags(rootCmd)
return rootCmd.ExecuteContext(ctx)
}
// annotateRequiredFlags walks the command tree and appends "(required)" to the
// usage text of every flag marked as required, so it's visible in --help.
func annotateRequiredFlags(cmd *cobra.Command) {
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if ann, ok := f.Annotations[cobra.BashCompOneRequiredFlag]; ok && len(ann) > 0 && ann[0] == "true" {
f.Usage += " (required)"
}
})
for _, child := range cmd.Commands() {
annotateRequiredFlags(child)
}
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
defaultConfigDir, err := config.ConfigDir()
if err != nil {
fmt.Println(err)
os.Exit(cmdutil.FatalErrExitCode)
}
// Order of preference for configuration files:
// (1) $HOME/.config/planetscale
viper.AddConfigPath(defaultConfigDir)
viper.SetConfigName("pscale")
viper.SetConfigType("yml")
}
viper.SetEnvPrefix("planetscale")
viper.SetEnvKeyReplacer(replacer)
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
// Only handle errors when it's something unrelated to the config file not
// existing.
fmt.Println(err)
os.Exit(cmdutil.FatalErrExitCode)
}
}
// If no configFile is passed:
// 1. Check local git repo for a config file
// 2. If not in a git repo. Check working directory for a config file
if cfgFile == "" {
if rootDir, err := config.RootGitRepoDir(); err == nil {
viper.AddConfigPath(rootDir)
viper.SetConfigName(config.ProjectConfigFile())
_ = viper.MergeInConfig()
} else if localDir, err := config.LocalDir(); err == nil {
viper.AddConfigPath(localDir)
viper.SetConfigName(config.ProjectConfigFile())
_ = viper.MergeInConfig()
}
}
postInitCommands(rootCmd.Commands())
}
// Hacky fix for getting Cobra required flags and Viper playing well together.
// See: https://github.com/spf13/viper/issues/397
func postInitCommands(commands []*cobra.Command) {
for _, cmd := range commands {
presetRequiredFlags(cmd)
if cmd.HasSubCommands() {
postInitCommands(cmd.Commands())
}
}
}
func presetRequiredFlags(cmd *cobra.Command) {
err := viper.BindPFlags(cmd.Flags())
if err != nil {
log.Fatalf("error binding flags: %v", err)
}
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if viper.IsSet(f.Name) && viper.GetString(f.Name) != "" {
err = cmd.Flags().Set(f.Name, viper.GetString(f.Name))
if err != nil {
log.Fatalf("error setting flag %s: %v", f.Name, err)
}
}
})
}
// https://github.com/golang/go/issues/44286
type osFS struct{}
func (c osFS) Open(name string) (fs.File, error) {
return os.Open(name)
}