|
| 1 | +package get |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "github.com/briandowns/spinner" |
| 8 | + "github.com/spf13/cobra" |
| 9 | + |
| 10 | + "github.com/zeabur/cli/internal/cmdutil" |
| 11 | +) |
| 12 | + |
| 13 | +type Options struct { |
| 14 | + code string |
| 15 | +} |
| 16 | + |
| 17 | +func NewCmdGet(f *cmdutil.Factory) *cobra.Command { |
| 18 | + opts := Options{} |
| 19 | + |
| 20 | + cmd := &cobra.Command{ |
| 21 | + Use: "get", |
| 22 | + Short: "Get template by code", |
| 23 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 24 | + return runGet(f, opts) |
| 25 | + }, |
| 26 | + } |
| 27 | + |
| 28 | + cmd.Flags().StringVarP(&opts.code, "code", "c", "", "Template code") |
| 29 | + |
| 30 | + return cmd |
| 31 | +} |
| 32 | + |
| 33 | +func runGet(f *cmdutil.Factory, opts Options) error { |
| 34 | + if f.Interactive { |
| 35 | + return runGetInteractive(f, opts) |
| 36 | + } |
| 37 | + return runGetNonInteractive(f, opts) |
| 38 | + |
| 39 | +} |
| 40 | + |
| 41 | +func runGetInteractive(f *cmdutil.Factory, opts Options) error { |
| 42 | + code, err := f.Prompter.Input("Template Code: ", "") |
| 43 | + if err != nil { |
| 44 | + return err |
| 45 | + } |
| 46 | + |
| 47 | + opts.code = code |
| 48 | + |
| 49 | + err = getTemplate(f, opts) |
| 50 | + if err != nil { |
| 51 | + return err |
| 52 | + } |
| 53 | + |
| 54 | + return nil |
| 55 | +} |
| 56 | + |
| 57 | +func runGetNonInteractive(f *cmdutil.Factory, opts Options) error { |
| 58 | + err := paramCheck(opts) |
| 59 | + if err != nil { |
| 60 | + return err |
| 61 | + } |
| 62 | + |
| 63 | + err = getTemplate(f, opts) |
| 64 | + if err != nil { |
| 65 | + return err |
| 66 | + } |
| 67 | + |
| 68 | + return nil |
| 69 | +} |
| 70 | + |
| 71 | +func getTemplate(f *cmdutil.Factory, opts Options) error { |
| 72 | + s := spinner.New(cmdutil.SpinnerCharSet, cmdutil.SpinnerInterval, |
| 73 | + spinner.WithColor(cmdutil.SpinnerColor), |
| 74 | + spinner.WithSuffix(" Fetching template..."), |
| 75 | + ) |
| 76 | + s.Start() |
| 77 | + template, err := f.ApiClient.GetTemplate(context.Background(), opts.code) |
| 78 | + if err != nil { |
| 79 | + return err |
| 80 | + } |
| 81 | + s.Stop() |
| 82 | + |
| 83 | + if template == nil || template.Code == "" { |
| 84 | + fmt.Println("Template not found") |
| 85 | + } else { |
| 86 | + f.Printer.Table([]string{"Code", "Name", "Description"}, [][]string{{template.Code, template.Name, template.Description}}) |
| 87 | + } |
| 88 | + |
| 89 | + return nil |
| 90 | +} |
| 91 | + |
| 92 | +func paramCheck(opts Options) error { |
| 93 | + if opts.code == "" { |
| 94 | + return fmt.Errorf("template code is required") |
| 95 | + } |
| 96 | + |
| 97 | + return nil |
| 98 | +} |
0 commit comments