Files
Nick Vigilante 0efb574355 feat(cli/cliui): add TextFormatFunc and OutputFormatter.WriteLine helpers (#30508)
Adds two small helpers to `cli/cliui/output.go` so commands that add
`-o/--output` don't repeat the same boilerplate, as suggested in
https://github.com/coder/coder/pull/30152#issuecomment-6043360441 by
@jeremyruppel.

- `TextFormatFunc[T]` wraps `ChangeFormatterData(TextFormat(), ...)`
with the type assertion and "expected X, got Y" error, so a command only
supplies its render function.
- `(*OutputFormatter).WriteLine` formats data and writes it to an
`io.Writer` with a trailing newline, replacing the `Format` + `Fprintln`
block.

No existing callers change in this PR. These PRs are stacked on it and
use the helpers:

- #30135 `coder tokens create`
- #30139 `coder ai-gateway keys create`
- #30145 `coder organizations members edit-roles`
- #30152 `coder provisioner keys create`

Migrating the existing callers on `main` (for example
`cli/organization.go`, `enterprise/cli/workspaceproxy.go`) is left for a
follow-up, since some of them print with `Fprint` rather than `Fprintln`
and need care to keep output identical.

Refs CLI-56

<details>
<summary>Decision log</summary>

- A global `-o` flag on the root command was ruled out because `coder
config-ssh` already uses `-o` for `--ssh-option`.
- The "one-time secret plus metadata" response structs in #30135 and
#30152 stay local to each command, since they embed different SDK types
and a shared helper would save little.
- `WriteLine` uses `Fprintln` to match the four stacked PRs and most
existing callers.
It was renamed from `Write` during review so the trailing newline is
visible at call sites and the method is not confused with `io.Writer`.

</details>

> [!NOTE]
> This PR was generated by Coder Agents on behalf of @nickvigilante.
2026-10-08 19:41:31 +00:00

228 lines
5.2 KiB
Go

package cliui_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/serpent"
)
type format struct {
id string
attachOptionsFn func(opts *serpent.OptionSet)
formatFn func(ctx context.Context, data any) (string, error)
}
var _ cliui.OutputFormat = &format{}
func (f *format) ID() string {
return f.id
}
func (f *format) AttachOptions(opts *serpent.OptionSet) {
if f.attachOptionsFn != nil {
f.attachOptionsFn(opts)
}
}
func (f *format) Format(ctx context.Context, data any) (string, error) {
if f.formatFn != nil {
return f.formatFn(ctx, data)
}
return "", nil
}
func Test_OutputFormatter(t *testing.T) {
t.Parallel()
t.Run("RequiresTwoFormatters", func(t *testing.T) {
t.Parallel()
require.Panics(t, func() {
cliui.NewOutputFormatter()
})
require.Panics(t, func() {
cliui.NewOutputFormatter(cliui.JSONFormat())
})
require.NotPanics(t, func() {
cliui.NewOutputFormatter(cliui.JSONFormat(), cliui.TextFormat())
})
})
t.Run("NoMissingFormatID", func(t *testing.T) {
t.Parallel()
require.Panics(t, func() {
cliui.NewOutputFormatter(
cliui.JSONFormat(),
&format{id: ""},
)
})
})
t.Run("NoDuplicateFormats", func(t *testing.T) {
t.Parallel()
require.Panics(t, func() {
cliui.NewOutputFormatter(
cliui.JSONFormat(),
cliui.JSONFormat(),
)
})
})
t.Run("OK", func(t *testing.T) {
t.Parallel()
var called atomic.Int64
f := cliui.NewOutputFormatter(
cliui.JSONFormat(),
&format{
id: "foo",
attachOptionsFn: func(opts *serpent.OptionSet) {
opts.Add(serpent.Option{
Name: "foo",
Flag: "foo",
FlagShorthand: "f",
Value: serpent.DiscardValue,
Description: "foo flag 1234",
})
},
formatFn: func(_ context.Context, _ any) (string, error) {
called.Add(1)
return "foo", nil
},
},
)
cmd := &serpent.Command{}
f.AttachOptions(&cmd.Options)
fs := cmd.Options.FlagSet()
selected := cmd.Options.ByFlag("output")
require.NotNil(t, selected)
require.Equal(t, "json", selected.Value.String())
usage := fs.FlagUsages()
require.Contains(t, usage, "Output format.")
require.Contains(t, usage, "foo flag 1234")
ctx := context.Background()
data := []string{"hi", "dean", "was", "here"}
out, err := f.Format(ctx, data)
require.NoError(t, err)
var got []string
require.NoError(t, json.Unmarshal([]byte(out), &got))
require.Equal(t, data, got)
require.EqualValues(t, 0, called.Load())
require.NoError(t, fs.Set("output", "foo"))
out, err = f.Format(ctx, data)
require.NoError(t, err)
require.Equal(t, "foo", out)
require.EqualValues(t, 1, called.Load())
require.Error(t, fs.Set("output", "bar"))
out, err = f.Format(ctx, data)
require.NoError(t, err)
require.Equal(t, "foo", out)
require.EqualValues(t, 2, called.Load())
})
t.Run("WriteLine", func(t *testing.T) {
t.Parallel()
f := cliui.NewOutputFormatter(cliui.TextFormat(), cliui.JSONFormat())
cmd := &serpent.Command{}
f.AttachOptions(&cmd.Options)
var buf bytes.Buffer
require.NoError(t, f.WriteLine(context.Background(), &buf, "hello"))
require.Equal(t, "hello\n", buf.String())
require.NoError(t, cmd.Options.FlagSet().Set("output", "json"))
buf.Reset()
require.NoError(t, f.WriteLine(context.Background(), &buf, "hello"))
require.Equal(t, "\"hello\"\n", buf.String())
require.NoError(t, cmd.Options.FlagSet().Set("output", "text"))
buf.Reset()
require.NoError(t, f.WriteLine(context.Background(), &buf, ""))
require.Equal(t, "\n", buf.String())
})
t.Run("WriteLineFormatError", func(t *testing.T) {
t.Parallel()
f := cliui.NewOutputFormatter(
cliui.TextFormatFunc(func(int) (string, error) { return "unreachable", nil }),
cliui.JSONFormat(),
)
cmd := &serpent.Command{}
f.AttachOptions(&cmd.Options)
var buf bytes.Buffer
require.Error(t, f.WriteLine(context.Background(), &buf, "not an int"))
require.Empty(t, buf.String())
})
}
func Test_TextFormatFunc(t *testing.T) {
t.Parallel()
type item struct {
Name string `json:"name"`
}
f := cliui.TextFormatFunc(func(i item) (string, error) {
return strings.ToUpper(i.Name), nil
})
require.Equal(t, "text", f.ID())
t.Run("OK", func(t *testing.T) {
t.Parallel()
out, err := f.Format(context.Background(), item{Name: "coder"})
require.NoError(t, err)
require.Equal(t, "CODER", out)
})
t.Run("WrongType", func(t *testing.T) {
t.Parallel()
_, err := f.Format(context.Background(), "coder")
require.ErrorContains(t, err, "expected cliui_test.item, got string")
})
t.Run("WrongTypeInterface", func(t *testing.T) {
t.Parallel()
stringer := cliui.TextFormatFunc(func(s fmt.Stringer) (string, error) {
return s.String(), nil
})
_, err := stringer.Format(context.Background(), 42)
require.ErrorContains(t, err, "expected fmt.Stringer, got int")
})
t.Run("FuncError", func(t *testing.T) {
t.Parallel()
failing := cliui.TextFormatFunc(func(item) (string, error) {
return "", assert.AnError
})
_, err := failing.Format(context.Background(), item{})
require.ErrorIs(t, err, assert.AnError)
})
}