-
Notifications
You must be signed in to change notification settings - Fork 52
/
show.go
102 lines (83 loc) · 2.53 KB
/
show.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
package database
import (
"fmt"
"github.com/planetscale/cli/internal/cmdutil"
"github.com/planetscale/cli/internal/printer"
"github.com/planetscale/planetscale-go/planetscale"
"github.com/pkg/browser"
"github.com/spf13/cobra"
)
func ShowCmd(ch *cmdutil.Helper) *cobra.Command {
cmd := &cobra.Command{
Use: "show <database>",
Short: "Retrieve information about a database",
Args: cmdutil.RequiredArgs("database"),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
client, err := ch.Client()
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
org := ch.Config.Organization // --org flag
if org == "" {
cfg, err := ch.ConfigFS.DefaultConfig()
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
org = cfg.Organization
}
databases, err := client.Databases.List(cmd.Context(), &planetscale.ListDatabasesRequest{
Organization: org,
})
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
candidates := make([]string, 0, len(databases))
for _, db := range databases {
candidates = append(candidates, db.Name)
}
return candidates, cobra.ShellCompDirectiveNoFileComp
},
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
name := args[0]
web, err := cmd.Flags().GetBool("web")
if err != nil {
return err
}
if web {
ch.Printer.Println("🌐 Redirecting you to your database in your web browser.")
err := browser.OpenURL(fmt.Sprintf("%s/%s/%s", cmdutil.ApplicationURL, ch.Config.Organization, name))
if err != nil {
return err
}
return nil
}
client, err := ch.Client()
if err != nil {
return err
}
end := ch.Printer.PrintProgress(fmt.Sprintf("Fetching database %s...", printer.BoldBlue(name)))
defer end()
database, err := client.Databases.Get(ctx, &planetscale.GetDatabaseRequest{
Organization: ch.Config.Organization,
Database: name,
})
if err != nil {
switch cmdutil.ErrCode(err) {
case planetscale.ErrNotFound:
return fmt.Errorf("database %s does not exist in organization %s",
printer.BoldBlue(name), printer.BoldBlue(ch.Config.Organization))
default:
return cmdutil.HandleError(err)
}
}
end()
return ch.Printer.PrintResource(toDatabase(database))
},
}
cmd.Flags().BoolP("web", "w", false, "Open in your web browser")
return cmd
}