Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
11 changes: 9 additions & 2 deletions libs/cmdio/capabilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,23 @@ type Capabilities struct {

// newCapabilities detects terminal capabilities from context and I/O streams.
func newCapabilities(ctx context.Context, in io.Reader, out, err io.Writer) Capabilities {
noColor, dumb := colorFromEnv(ctx)
return Capabilities{
stdinIsTTY: isTTY(in),
stdoutIsTTY: isTTY(out),
stderrIsTTY: isTTY(err),
noColor: env.Get(ctx, "NO_COLOR") != "",
dumb: env.Get(ctx, "TERM") == "dumb",
noColor: noColor,
dumb: dumb,
stdinIsMSYSPipe: isMSYSPipe(in),
}
}

// colorFromEnv reads the color preferences from ctx: whether NO_COLOR is set,
// and whether TERM is "dumb". They are reported separately, see Capabilities.
func colorFromEnv(ctx context.Context) (noColor, dumb bool) {
return env.Get(ctx, "NO_COLOR") != "", env.Get(ctx, "TERM") == "dumb"
}

// SupportsInteractive returns true if stderr can show output that redraws
// in place (spinners, prompts). NO_COLOR does not affect this; it only
// removes color from that output.
Expand Down
119 changes: 119 additions & 0 deletions libs/cmdio/cmdiotest/pin_color_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package cmdiotest_test

import (
"context"
"fmt"
"sync"
"testing"

"github.com/databricks/cli/libs/cmdio"
"github.com/databricks/cli/libs/cmdio/cmdiotest/termtest"
"github.com/stretchr/testify/require"
)

// TestColorPin_Swatch pins, for each environment of the color matrix, the
// color helpers and a renderer-minted style, and whether the renderer reports
// color for the screen. The color capability comes from the environment, as in
// a real command.
//
// Two limits. The screen is a pipe, so the renderer always reports no color
// here; a real-terminal renderer (depth, profile names) is not pinned. And
// cmdio reads only NO_COLOR and TERM=dumb, so the environments other than
// no-color and term-dumb produce identical goldens. That is deliberate: it
// fails if cmdio starts reading a variable that a row sets (TERM, CI,
// CLICOLOR, COLORTERM or NO_COLOR).
func TestColorPin_Swatch(t *testing.T) {
t.Parallel()
for _, ce := range colorEnvs() {
t.Run(ce.name, func(t *testing.T) {
t.Parallel()
tm := termtest.RunWith(t, termtest.Options{Env: ce.env, ColorFromEnv: true, MapNewline: true}, func(ctx context.Context) (struct{}, error) {
_, screen := termtest.Streams(ctx)
r, color := cmdio.NewRenderer(ctx, screen)
cmdio.LogString(ctx, fmt.Sprintf("renderer color: %t", color))
cmdio.LogString(ctx, "helpers: "+cmdio.Red(ctx, "red")+" "+cmdio.Green(ctx, "green")+" "+cmdio.Blue(ctx, "blue")+" "+
cmdio.HiBlack(ctx, "hiblack")+" "+cmdio.HiBlue(ctx, "hiblue")+" "+cmdio.Bold(ctx, "bold")+" "+cmdio.Faint(ctx, "faint"))
cmdio.LogString(ctx, "renderer: "+r.NewStyle().Bold(true).Render("bold")+" "+r.NewStyle().Reverse(true).Render("reverse"))
return struct{}{}, nil
})
_, err := tm.Result()
require.NoError(t, err)
tm.GoldenStyled("01-swatch")
})
}
}

// TestColorPin_Select pins the styled screen of a select prompt for each
// environment of the color matrix.
func TestColorPin_Select(t *testing.T) {
t.Parallel()
for _, ce := range colorEnvs() {
t.Run(ce.name, func(t *testing.T) {
t.Parallel()
tm := termtest.RunWith(t, termtest.Options{Env: ce.env, ColorFromEnv: true}, func(ctx context.Context) (string, error) {
return cmdio.SelectOrdered(ctx, pinItems(), "Pick an item")
})
if !tm.WaitForOrExit("gamma") {
_, err := tm.Result()
termtest.GoldenText(t, "01-not-shown", fmt.Sprintf("err: %v", err))
return
}
tm.GoldenStyled("01-initial")
tm.Type(termtest.KeyEnter)
_, err := tm.Result()
require.NoError(t, err)
})
}
}

// TestColorPin_Prompt pins the styled screen of a text prompt for each
// environment of the color matrix.
func TestColorPin_Prompt(t *testing.T) {
t.Parallel()
for _, ce := range colorEnvs() {
t.Run(ce.name, func(t *testing.T) {
t.Parallel()
tm := termtest.RunWith(t, termtest.Options{Env: ce.env, ColorFromEnv: true}, func(ctx context.Context) (string, error) {
return cmdio.RunPrompt(ctx, cmdio.PromptOptions{Label: "Workspace name"})
})
if !tm.WaitForOrExit("Workspace name") {
_, err := tm.Result()
termtest.GoldenText(t, "01-not-shown", fmt.Sprintf("err: %v", err))
return
}
typeKeys(tm, "dev")
tm.GoldenStyled("01-typed")
tm.Type(termtest.KeyEnter)
_, err := tm.Result()
require.NoError(t, err)
})
}
}

// TestColorPin_Spinner pins the styled screen of a running spinner for each
// environment of the color matrix. Only TERM=dumb gets no spinner; NO_COLOR
// keeps it, uncolored.
func TestColorPin_Spinner(t *testing.T) {
t.Parallel()
for _, ce := range colorEnvs() {
t.Run(ce.name, func(t *testing.T) {
t.Parallel()
stop := make(chan struct{})
stopOnce := sync.OnceFunc(func() { close(stop) })
t.Cleanup(stopOnce)
tm := termtest.RunWith(t, termtest.Options{Env: ce.env, ColorFromEnv: true, MapNewline: true, Normalize: blankSpinnerFrames}, func(ctx context.Context) (struct{}, error) {
sp := cmdio.NewSpinner(ctx)
sp.Update("Working")
cmdio.LogString(ctx, "spinner started")
<-stop
sp.Close()
return struct{}{}, nil
})
tm.WaitFor("spinner started")
tm.GoldenStyled("01-running")
stopOnce()
_, err := tm.Result()
require.NoError(t, err)
})
}
}
123 changes: 123 additions & 0 deletions libs/cmdio/cmdiotest/pin_helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package cmdiotest_test

import (
"fmt"
"maps"
"strings"
"testing"

"github.com/databricks/cli/libs/cmdio"
"github.com/databricks/cli/libs/cmdio/cmdiotest/termtest"
)

// The pin tests record what the interactive components do today, including
// behavior that is accidental, so that a change of the TUI libraries shows
// up as golden diffs. They pin; they don't judge.

// spinnerFrames are the braille frames cmdio's spinners cycle through.
const spinnerFrames = "⣾⣽⣻⢿⡿⣟⣯⣷"

// blankSpinnerFrames replaces every spinner frame with "*", so a golden of a
// running spinner doesn't depend on which frame was on screen.
func blankSpinnerFrames(s string) string {
return strings.Map(func(r rune) rune {
if strings.ContainsRune(spinnerFrames, r) {
return '*'
}
return r
}, s)
}

// countSpinnerFrames returns how many distinct spinner frames appear in s.
func countSpinnerFrames(s string) int {
seen := map[rune]bool{}
for _, r := range s {
if strings.ContainsRune(spinnerFrames, r) {
seen[r] = true
}
}
return len(seen)
}

// colorEnv is one environment of the color matrix. cmdio itself reads only
// NO_COLOR and TERM. The map also sets CI, CLICOLOR, CLICOLOR_FORCE, COLORTERM
// and TERM_PROGRAM, so the TUI libraries see a fixed environment (an empty
// value reads as unset). TestColorPin_Swatch explains why the rows are kept.
type colorEnv struct {
name string
env map[string]string
}

func colorEnvs() []colorEnv {
base := map[string]string{
"TERM": "xterm-256color",
"COLORTERM": "",
"NO_COLOR": "",
"CLICOLOR": "",
"CLICOLOR_FORCE": "",
"CI": "",
"TERM_PROGRAM": "",
}
with := func(overrides map[string]string) map[string]string {
m := maps.Clone(base)
maps.Copy(m, overrides)
return m
}
return []colorEnv{
{"term-unset", with(map[string]string{"TERM": ""})},
{"term-xterm-256color", with(nil)},
{"term-screen", with(map[string]string{"TERM": "screen"})},
{"term-vt100", with(map[string]string{"TERM": "vt100"})},
{"term-dumb", with(map[string]string{"TERM": "dumb"})},
{"ci", with(map[string]string{"CI": "1"})},
{"clicolor-0", with(map[string]string{"CLICOLOR": "0"})},
{"no-color", with(map[string]string{"NO_COLOR": "1"})},
{"tmux-truecolor", with(map[string]string{"TERM": "tmux-256color", "COLORTERM": "truecolor"})},
{"colorterm-yes", with(map[string]string{"COLORTERM": "yes"})},
}
}

// colorEnvNamed returns the environment of the color matrix called name.
func colorEnvNamed(name string) map[string]string {
for _, ce := range colorEnvs() {
if ce.name == name {
return ce.env
}
}
panic("no color env " + name)
}

// pinItems is the item list the select pins use.
func pinItems() []cmdio.Tuple {
return []cmdio.Tuple{
{Name: "alpha", Id: "id-01"},
{Name: "beta", Id: "id-02"},
{Name: "gamma", Id: "id-03"},
}
}

// failWithRaw fails the test with msg and the raw output, so a missed wait
// shows what the program actually wrote.
func failWithRaw[T any](t *testing.T, tm *termtest.Term[T], format string, args ...any) {
t.Helper()
t.Fatalf("%s\n--- raw output ---\n%q", fmt.Sprintf(format, args...), tm.Raw())
}

// quoted renders bytes as one escaped Go string, so goldens of raw
// input or output stay readable.
func quoted(b []byte) string {
if len(b) == 0 {
return "(none)"
}
return fmt.Sprintf("%q", b)
}

// typeKeys writes each key as its own read: it waits for the program to
// settle after every write, so two keys never reach it as one burst. Use
// [termtest.Term.TypeBurst] to test a burst on purpose.
func typeKeys[T any](tm *termtest.Term[T], keys ...string) {
for _, k := range keys {
tm.Type(k)
tm.Settle()
}
}
Loading
Loading