|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "reflect" |
| 8 | + "strings" |
| 9 | + "text/tabwriter" |
| 10 | + |
| 11 | + "github.com/spf13/pflag" |
| 12 | + |
| 13 | + "go.coder.com/cli" |
| 14 | + "go.coder.com/flog" |
| 15 | +) |
| 16 | + |
| 17 | +type usersCmd struct { |
| 18 | +} |
| 19 | + |
| 20 | +func (cmd usersCmd) Spec() cli.CommandSpec { |
| 21 | + return cli.CommandSpec{ |
| 22 | + Name: "users", |
| 23 | + Usage: "[subcommand] <flags>", |
| 24 | + Desc: "interact with user accounts", |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +func (cmd usersCmd) Run(fl *pflag.FlagSet) { |
| 29 | + exitUsage(fl) |
| 30 | +} |
| 31 | + |
| 32 | +func (cmd *usersCmd) Subcommands() []cli.Command { |
| 33 | + return []cli.Command{ |
| 34 | + &listCmd{}, |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +type listCmd struct { |
| 39 | + outputFmt string |
| 40 | +} |
| 41 | + |
| 42 | +func tabDelimited(data interface{}) string { |
| 43 | + v := reflect.ValueOf(data) |
| 44 | + s := &strings.Builder{} |
| 45 | + for i := 0; i < v.NumField(); i++ { |
| 46 | + s.WriteString(fmt.Sprintf("%s\t", v.Field(i).Interface())) |
| 47 | + } |
| 48 | + return s.String() |
| 49 | +} |
| 50 | + |
| 51 | +func (cmd *listCmd) Run(fl *pflag.FlagSet) { |
| 52 | + entClient := requireAuth() |
| 53 | + |
| 54 | + users, err := entClient.Users() |
| 55 | + if err != nil { |
| 56 | + flog.Fatal("failed to get users: %v", err) |
| 57 | + } |
| 58 | + |
| 59 | + switch cmd.outputFmt { |
| 60 | + case "human": |
| 61 | + w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0) |
| 62 | + for _, u := range users { |
| 63 | + _, err = fmt.Fprintln(w, tabDelimited(u)) |
| 64 | + if err != nil { |
| 65 | + flog.Fatal("failed to write: %v", err) |
| 66 | + } |
| 67 | + } |
| 68 | + err = w.Flush() |
| 69 | + if err != nil { |
| 70 | + flog.Fatal("failed to flush writer: %v", err) |
| 71 | + } |
| 72 | + case "json": |
| 73 | + err = json.NewEncoder(os.Stdout).Encode(users) |
| 74 | + if err != nil { |
| 75 | + flog.Fatal("failed to encode users to json: %v", err) |
| 76 | + } |
| 77 | + default: |
| 78 | + exitUsage(fl) |
| 79 | + } |
| 80 | + |
| 81 | +} |
| 82 | + |
| 83 | +func (cmd *listCmd) RegisterFlags(fl *pflag.FlagSet) { |
| 84 | + fl.StringVarP(&cmd.outputFmt, "output", "o", "human", "output format (human | json)") |
| 85 | +} |
| 86 | + |
| 87 | +func (cmd *listCmd) Spec() cli.CommandSpec { |
| 88 | + return cli.CommandSpec{ |
| 89 | + Name: "ls", |
| 90 | + Usage: "<flags>", |
| 91 | + Desc: "list all users", |
| 92 | + } |
| 93 | +} |
0 commit comments