feat(cli): add formatting options to coder whoami (#19970)

This addresses a long-standing gripe of mine: to get your logged in
username you would have to do
```bash
coder whoami | awk '{print $9}'
```

This allows you to do:

```
coder whoami -o json | jq -r '.username'
```

or

```
coder whoami -f table -c username
```
This commit is contained in:
Cian Johnston
2025-09-26 09:33:27 +01:00
committed by GitHub
parent f2904726a5
commit 930bbaf035
3 changed files with 58 additions and 4 deletions
+8 -1
View File
@@ -1,9 +1,16 @@
coder v0.0.0-devel
USAGE:
coder whoami
coder whoami [flags]
Fetch authenticated user info for Coder deployment
OPTIONS:
-c, --column [URL|Username] (default: url,username)
Columns to display in table output.
-o, --output text|json|table (default: text)
Output format.
———
Run `coder --help` for a list of global options.
+29 -2
View File
@@ -9,7 +9,25 @@ import (
"github.com/coder/serpent"
)
type whoamiRow struct {
URL string `json:"url" table:"URL,default_sort"`
Username string `json:"username" table:"Username"`
}
func (r whoamiRow) String() string {
return fmt.Sprintf(
Caret+"Coder is running at %s, You're authenticated as %s !\n",
pretty.Sprint(cliui.DefaultStyles.Keyword, r.URL),
pretty.Sprint(cliui.DefaultStyles.Keyword, r.Username),
)
}
func (r *RootCmd) whoami() *serpent.Command {
formatter := cliui.NewOutputFormatter(
cliui.TextFormat(),
cliui.JSONFormat(),
cliui.TableFormat([]whoamiRow{}, []string{"url", "username"}),
)
cmd := &serpent.Command{
Annotations: workspaceCommand,
Use: "whoami",
@@ -28,14 +46,23 @@ func (r *RootCmd) whoami() *serpent.Command {
resp, err := client.User(ctx, codersdk.Me)
// Get Coder instance url
clientURL := client.URL
if err != nil {
return err
}
_, _ = fmt.Fprintf(inv.Stdout, Caret+"Coder is running at %s, You're authenticated as %s !\n", pretty.Sprint(cliui.DefaultStyles.Keyword, clientURL), pretty.Sprint(cliui.DefaultStyles.Keyword, resp.Username))
out, err := formatter.Format(ctx, []whoamiRow{
{
URL: clientURL.String(),
Username: resp.Username,
},
})
if err != nil {
return err
}
_, err = inv.Stdout.Write([]byte(out))
return err
},
}
formatter.AttachOptions(&cmd.Options)
return cmd
}
+21 -1
View File
@@ -6,5 +6,25 @@ Fetch authenticated user info for Coder deployment
## Usage
```console
coder whoami
coder whoami [flags]
```
## Options
### -c, --column
| | |
|---------|------------------------------|
| Type | <code>[URL\|Username]</code> |
| Default | <code>url,username</code> |
Columns to display in table output.
### -o, --output
| | |
|---------|--------------------------------|
| Type | <code>text\|json\|table</code> |
| Default | <code>text</code> |
Output format.