Skip to content
This repository was archived by the owner on Aug 30, 2024. It is now read-only.

Migrate to cobra #86

Merged
merged 10 commits into from
Aug 10, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add table output to envs ls
  • Loading branch information
cmoog committed Aug 4, 2020
commit 9b1173e57587eb85de0b3ebc3990c9b160f4689c
2 changes: 1 addition & 1 deletion ci/integration/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func TestCoderCLI(t *testing.T) {
headlessLogin(ctx, t, c)

c.Run(ctx, "coder envs").Assert(t,
tcli.Success(),
tcli.Error(),
)

c.Run(ctx, "coder envs ls").Assert(t,
Expand Down
30 changes: 26 additions & 4 deletions cmd/coder/envs.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
package main

import (
"fmt"
"encoding/json"
"os"

"cdr.dev/coder-cli/internal/x/xtabwriter"
"github.com/urfave/cli"

"go.coder.com/flog"
)

func makeEnvsCommand() cli.Command {
var outputFmt string
return cli.Command{
Name: "envs",
Usage: "Interact with Coder environments",
Description: "Perform operations on the Coder environments owned by the active user.",
Action: exitHelp,
Subcommands: []cli.Command{
{
Name: "ls",
Expand All @@ -21,11 +27,27 @@ func makeEnvsCommand() cli.Command {
entClient := requireAuth()
envs := getEnvs(entClient)

for _, env := range envs {
fmt.Println(env.Name)
switch outputFmt {
case "human":
err := xtabwriter.WriteTable(len(envs), func(i int) interface{} {
return envs[i]
})
requireSuccess(err, "failed to write table: %v", err)
case "json":
err := json.NewEncoder(os.Stdout).Encode(envs)
requireSuccess(err, "failed to write json: %v", err)
default:
flog.Fatal("unknown --output value %q", outputFmt)
}
},
Flags: nil,
Flags: []cli.Flag{
cli.StringFlag{
Name: "output",
Usage: "json | human",
Value: "human",
Destination: &outputFmt,
},
},
},
},
}
Expand Down
5 changes: 5 additions & 0 deletions cmd/coder/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ func main() {
flog.Fatal("command %q not found", s)
}
app.Email = "support@coder.com"
app.Action = exitHelp

app.Commands = []cli.Command{
makeLoginCmd(),
Expand All @@ -64,3 +65,7 @@ func requireSuccess(err error, msg string, args ...interface{}) {
flog.Fatal(msg, args...)
}
}

func exitHelp(c *cli.Context) {
cli.ShowCommandHelpAndExit(c, c.Command.FullName(), 1)
}
5 changes: 3 additions & 2 deletions cmd/coder/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ func makeSecretsCmd() cli.Command {
Name: "secrets",
Usage: "Interact with Coder Secrets",
Description: "Interact with secrets objects owned by the active user.",
Action: exitHelp,
Subcommands: []cli.Command{
{
Name: "ls",
Expand All @@ -30,7 +31,7 @@ func makeSecretsCmd() cli.Command {
Name: "rm",
Usage: "Remove one or more secrets by name",
ArgsUsage: "[...secret_name]",
Action: removeSecret,
Action: removeSecrets,
},
{
Name: "view",
Expand Down Expand Up @@ -171,7 +172,7 @@ func viewSecret(c *cli.Context) {
requireSuccess(err, "failed to write: %v", err)
}

func removeSecret(c *cli.Context) {
func removeSecrets(c *cli.Context) {
var (
client = requireAuth()
names = append([]string{c.Args().First()}, c.Args().Tail()...)
Expand Down
23 changes: 8 additions & 15 deletions cmd/coder/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"encoding/json"
"fmt"
"os"

"cdr.dev/coder-cli/internal/x/xtabwriter"
Expand All @@ -14,8 +13,9 @@ import (
func makeUsersCmd() cli.Command {
var output string
return cli.Command{
Name: "users",
Usage: "Interact with Coder user accounts",
Name: "users",
Usage: "Interact with Coder user accounts",
Action: exitHelp,
Subcommands: []cli.Command{
{
Name: "ls",
Expand All @@ -24,7 +24,7 @@ func makeUsersCmd() cli.Command {
Flags: []cli.Flag{
cli.StringFlag{
Name: "output",
Usage: "(json | human)",
Usage: "json | human",
Value: "human",
Destination: &output,
},
Expand All @@ -43,17 +43,10 @@ func listUsers(outputFmt *string) func(c *cli.Context) {

switch *outputFmt {
case "human":
w := xtabwriter.NewWriter()
if len(users) > 0 {
_, err = fmt.Fprintln(w, xtabwriter.StructFieldNames(users[0]))
requireSuccess(err, "failed to write: %v", err)
}
for _, u := range users {
_, err = fmt.Fprintln(w, xtabwriter.StructValues(u))
requireSuccess(err, "failed to write: %v", err)
}
err = w.Flush()
requireSuccess(err, "failed to flush writer: %v", err)
err := xtabwriter.WriteTable(len(users), func(i int) interface{} {
return users[i]
})
requireSuccess(err, "failed to write table: %v", err)
case "json":
err = json.NewEncoder(os.Stdout).Encode(users)
requireSuccess(err, "failed to encode users to json: %v", err)
Expand Down
24 changes: 22 additions & 2 deletions internal/entclient/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,33 @@ import (
"context"
"time"

"cdr.dev/coder-cli/internal/x/xjson"
"nhooyr.io/websocket"
)

// Environment describes a Coder environment
type Environment struct {
Name string `json:"name"`
ID string `json:"id"`
ID string `json:"id" tab:"-"`
Name string `json:"name"`
ImageID string `json:"image_id" tab:"-"`
ImageTag string `json:"image_tag"`
OrganizationID string `json:"organization_id" tab:"-"`
UserID string `json:"user_id" tab:"-"`
LastBuiltAt time.Time `json:"last_built_at" tab:"-"`
CPUCores float32 `json:"cpu_cores"`
MemoryGB int `json:"memory_gb"`
DiskGB int `json:"disk_gb"`
GPUs int `json:"gpus"`
Updating bool `json:"updating"`
RebuildMessages []struct {
Text string `json:"text"`
Required bool `json:"required"`
} `json:"rebuild_messages" tab:"-"`
CreatedAt time.Time `json:"created_at" tab:"-"`
UpdatedAt time.Time `json:"updated_at" tab:"-"`
LastOpenedAt time.Time `json:"last_opened_at" tab:"-"`
LastConnectionAt time.Time `json:"last_connection_at" tab:"-"`
AutoOffThreshold xjson.Duration `json:"auto_off_threshold" tab:"-"`
}

// Envs gets the list of environments owned by the authenticated user
Expand Down
33 changes: 33 additions & 0 deletions internal/x/xjson/duration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package xjson

import (
"encoding/json"
"strconv"
"time"
)

// Duration is a time.Duration that marshals to millisecond precision.
// Most javascript applications expect durations to be in milliseconds.
type Duration time.Duration

// MarshalJSON marshals the duration to millisecond precision.
func (d Duration) MarshalJSON() ([]byte, error) {
du := time.Duration(d)
return json.Marshal(du.Milliseconds())
}

// UnmarshalJSON unmarshals a millisecond-precision integer to
// a time.Duration.
func (d *Duration) UnmarshalJSON(b []byte) error {
i, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return err
}

*d = Duration(time.Duration(i) * time.Millisecond)
return nil
}

func (d Duration) String() string {
return time.Duration(d).String()
}
28 changes: 27 additions & 1 deletion internal/x/xtabwriter/tabwriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func StructValues(data interface{}) string {
if shouldHideField(v.Type().Field(i)) {
continue
}
s.WriteString(fmt.Sprintf("%s\t", v.Field(i).Interface()))
s.WriteString(fmt.Sprintf("%v\t", v.Field(i).Interface()))
}
return s.String()
}
Expand All @@ -46,6 +46,32 @@ func StructFieldNames(data interface{}) string {
return s.String()
}

// WriteTable writes the given list elements to stdout in a human readable
// tabular format. Headers abide by the `tab` struct tag.
//
// `tab:"-"` omits the field and no tag defaults to the Go identifier.
func WriteTable(length int, each func(i int) interface{}) error {
if length < 1 {
return nil
}
w := NewWriter()
defer w.Flush()
for ix := 0; ix < length; ix++ {
item := each(ix)
if ix == 0 {
_, err := fmt.Fprintln(w, StructFieldNames(item))
if err != nil {
return err
}
}
_, err := fmt.Fprintln(w, StructValues(item))
if err != nil {
return err
}
}
return nil
}

func shouldHideField(f reflect.StructField) bool {
return f.Tag.Get(structFieldTagKey) == "-"
}