|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "os" |
| 6 | + |
| 7 | + "cdr.dev/coder-cli/coder-sdk" |
| 8 | + "cdr.dev/coder-cli/pkg/clog" |
| 9 | + "cdr.dev/coder-cli/pkg/tablewriter" |
| 10 | + "github.com/spf13/cobra" |
| 11 | + "golang.org/x/xerrors" |
| 12 | +) |
| 13 | + |
| 14 | +func imgsCmd() *cobra.Command { |
| 15 | + var user string |
| 16 | + |
| 17 | + cmd := &cobra.Command{ |
| 18 | + Use: "images", |
| 19 | + Short: "Manage Coder images", |
| 20 | + Long: "Manage existing images and/or import new ones.", |
| 21 | + } |
| 22 | + |
| 23 | + cmd.PersistentFlags().StringVar(&user, "user", coder.Me, "Specifies the user by email") |
| 24 | + cmd.AddCommand(lsImgsCommand(&user)) |
| 25 | + return cmd |
| 26 | +} |
| 27 | + |
| 28 | +func lsImgsCommand(user *string) *cobra.Command { |
| 29 | + var ( |
| 30 | + orgName string |
| 31 | + outputFmt string |
| 32 | + ) |
| 33 | + |
| 34 | + cmd := &cobra.Command{ |
| 35 | + Use: "ls", |
| 36 | + Short: "list all images available to the active user", |
| 37 | + Long: "List all Coder images available to the active user.", |
| 38 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 39 | + ctx := cmd.Context() |
| 40 | + |
| 41 | + client, err := newClient(ctx) |
| 42 | + if err != nil { |
| 43 | + return err |
| 44 | + } |
| 45 | + |
| 46 | + imgs, err := getImgs(ctx, client, |
| 47 | + getImgsConf{ |
| 48 | + email: *user, |
| 49 | + orgName: orgName, |
| 50 | + }, |
| 51 | + ) |
| 52 | + |
| 53 | + if err != nil { |
| 54 | + return err |
| 55 | + } |
| 56 | + |
| 57 | + if len(imgs) < 1 { |
| 58 | + clog.LogInfo("no images found") |
| 59 | + imgs = []coder.Image{} // ensures that json output still marshals |
| 60 | + } |
| 61 | + |
| 62 | + switch outputFmt { |
| 63 | + case jsonOutput: |
| 64 | + enc := json.NewEncoder(os.Stdout) |
| 65 | + // pretty print the json |
| 66 | + enc.SetIndent("", "\t") |
| 67 | + |
| 68 | + if err := enc.Encode(imgs); err != nil { |
| 69 | + return xerrors.Errorf("write images as JSON: %w", err) |
| 70 | + } |
| 71 | + return nil |
| 72 | + case humanOutput: |
| 73 | + err = tablewriter.WriteTable(len(imgs), func(i int) interface{} { |
| 74 | + return imgs[i] |
| 75 | + }) |
| 76 | + if err != nil { |
| 77 | + return xerrors.Errorf("write table: %w", err) |
| 78 | + } |
| 79 | + return nil |
| 80 | + default: |
| 81 | + return xerrors.Errorf("%q is not a supported value for --output", outputFmt) |
| 82 | + } |
| 83 | + }, |
| 84 | + } |
| 85 | + cmd.Flags().StringVar(&orgName, "org", "", "organization name") |
| 86 | + cmd.Flags().StringVar(&outputFmt, "output", humanOutput, "human | json") |
| 87 | + return cmd |
| 88 | +} |
0 commit comments