diff --git a/.nextchanges/cli/no-color-keeps-prompts.md b/.nextchanges/cli/no-color-keeps-prompts.md new file mode 100644 index 00000000000..c6871334721 --- /dev/null +++ b/.nextchanges/cli/no-color-keeps-prompts.md @@ -0,0 +1 @@ +* `NO_COLOR` no longer disables prompts, spinners or the list pager; they run without color. ([#7700](https://github.com/databricks/cli/pull/7700)) diff --git a/experimental/postgres/cmd/query.go b/experimental/postgres/cmd/query.go index 53684423f52..ed89caf02fc 100644 --- a/experimental/postgres/cmd/query.go +++ b/experimental/postgres/cmd/query.go @@ -212,7 +212,11 @@ func runQuery(ctx context.Context, cmd *cobra.Command, args []string, f queryFla // Promote-to-interactive only when stdout is a prompt-capable TTY so // a pipe falls back to the static table rather than launching a TUI // into a dead writer. - sink := newSinkInteractive(format, out, stderr, stdoutTTY && cmdio.IsPromptSupported(ctx)) + // The table viewer marks the cursor row and search matches with color + // only, so it needs color as well as a prompt-capable terminal (like + // the aitools query viewer and air list). + interactive := stdoutTTY && cmdio.IsPromptSupported(ctx) && cmdio.SupportsColor(ctx, out) + sink := newSinkInteractive(format, out, stderr, interactive) stmtCtx, stmtCancel := withStatementTimeout(signalCtx, f.timeout) err := executeOne(stmtCtx, conn, units[0].SQL, sink) stmtCancel() diff --git a/libs/cmdio/capabilities.go b/libs/cmdio/capabilities.go index 1569354f445..f48c72a006a 100644 --- a/libs/cmdio/capabilities.go +++ b/libs/cmdio/capabilities.go @@ -19,8 +19,11 @@ type Capabilities struct { // keystrokes from it, so prompts and pagers are disabled there. stdinIsMSYSPipe bool - // Environment flags - color bool // Color output is enabled (NO_COLOR not set and TERM not dumb) + // Environment flags. They are independent on purpose: NO_COLOR is a + // color preference only (https://no-color.org), while TERM=dumb means + // the terminal can't move the cursor, which rules out redrawing output. + noColor bool // NO_COLOR is set + dumb bool // TERM=dumb } // newCapabilities detects terminal capabilities from context and I/O streams. @@ -29,14 +32,22 @@ func newCapabilities(ctx context.Context, in io.Reader, out, err io.Writer) Capa stdinIsTTY: isTTY(in), stdoutIsTTY: isTTY(out), stderrIsTTY: isTTY(err), - color: env.Get(ctx, "NO_COLOR") == "" && env.Get(ctx, "TERM") != "dumb", + noColor: env.Get(ctx, "NO_COLOR") != "", + dumb: env.Get(ctx, "TERM") == "dumb", stdinIsMSYSPipe: isMSYSPipe(in), } } -// SupportsInteractive returns true if terminal supports interactive features (colors, spinners). +// 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. func (c Capabilities) SupportsInteractive() bool { - return c.stderrIsTTY && c.color + return c.stderrIsTTY && !c.dumb +} + +// colorAllowed reports whether the environment permits color at all. +func (c Capabilities) colorAllowed() bool { + return !c.noColor && !c.dumb } // SupportsPrompt returns true if terminal supports user prompting. @@ -49,14 +60,20 @@ func (c Capabilities) SupportsPrompt() bool { // SupportsColor returns true if the given writer supports colored output. // This checks both TTY status and environment variables (NO_COLOR, TERM=dumb). func (c Capabilities) SupportsColor(w io.Writer) bool { - return isTTY(w) && c.color + return isTTY(w) && c.colorAllowed() } // SupportsStdoutColor returns true if stdout supports colored output. // Use this when emitting colored bytes to a writer that wraps stdout (e.g. // a buffered flusher) where SupportsColor's isTTY check would be misled. func (c Capabilities) SupportsStdoutColor() bool { - return c.stdoutIsTTY && c.color + return c.stdoutIsTTY && c.colorAllowed() +} + +// SupportsStderrColor is the stderr counterpart of SupportsStdoutColor. +// Prompts use it; they render to stderr. +func (c Capabilities) SupportsStderrColor() bool { + return c.stderrIsTTY && c.colorAllowed() } // SupportsPager returns true when we can drive an interactive pager. diff --git a/libs/cmdio/capabilities_test.go b/libs/cmdio/capabilities_test.go index aafc84931cd..63a8226d86e 100644 --- a/libs/cmdio/capabilities_test.go +++ b/libs/cmdio/capabilities_test.go @@ -4,35 +4,36 @@ import ( "io" "testing" + "github.com/databricks/cli/libs/env" "github.com/stretchr/testify/assert" ) +func TestNewCapabilities_Env(t *testing.T) { + // Pin both variables so the developer's shell can't leak in. + ctx := env.Set(env.Set(t.Context(), "NO_COLOR", ""), "TERM", "") + c := newCapabilities(ctx, nil, nil, nil) + assert.False(t, c.noColor) + assert.False(t, c.dumb) + + c = newCapabilities(env.Set(ctx, "NO_COLOR", "1"), nil, nil, nil) + assert.True(t, c.noColor) + assert.False(t, c.dumb) + + c = newCapabilities(env.Set(ctx, "TERM", "dumb"), nil, nil, nil) + assert.False(t, c.noColor) + assert.True(t, c.dumb) +} + func TestCapabilities_SupportsInteractive(t *testing.T) { tests := []struct { name string caps Capabilities expected bool }{ - { - name: "normal terminal", - caps: Capabilities{stderrIsTTY: true, color: true}, - expected: true, - }, - { - name: "NO_COLOR set", - caps: Capabilities{stderrIsTTY: true, color: false}, - expected: false, - }, - { - name: "stderr not TTY", - caps: Capabilities{stderrIsTTY: false, color: true}, - expected: false, - }, - { - name: "both NO_COLOR and no TTY", - caps: Capabilities{stderrIsTTY: false, color: false}, - expected: false, - }, + {"normal terminal", Capabilities{stderrIsTTY: true}, true}, + {"NO_COLOR only removes color", Capabilities{stderrIsTTY: true, noColor: true}, true}, + {"TERM=dumb can't redraw", Capabilities{stderrIsTTY: true, dumb: true}, false}, + {"stderr not TTY", Capabilities{stderrIsTTY: false}, false}, } for _, tt := range tests { @@ -48,77 +49,14 @@ func TestCapabilities_SupportsPrompt(t *testing.T) { caps Capabilities expected bool }{ - { - name: "full TTY support", - caps: Capabilities{ - stdinIsTTY: true, - stdoutIsTTY: true, - stderrIsTTY: true, - color: true, - }, - expected: true, - }, - { - name: "MSYS2 pipe stdin blocks prompts", - caps: Capabilities{ - stdinIsTTY: true, - stdoutIsTTY: true, - stderrIsTTY: true, - color: true, - stdinIsMSYSPipe: true, - }, - expected: false, - }, - { - name: "stdin not TTY", - caps: Capabilities{ - stdinIsTTY: false, - stdoutIsTTY: true, - stderrIsTTY: true, - color: true, - }, - expected: false, - }, - { - name: "stdout not TTY (prompts write to stderr, so this is OK)", - caps: Capabilities{ - stdinIsTTY: true, - stdoutIsTTY: false, - stderrIsTTY: true, - color: true, - }, - expected: true, - }, - { - name: "stderr not TTY", - caps: Capabilities{ - stdinIsTTY: true, - stdoutIsTTY: true, - stderrIsTTY: false, - color: true, - }, - expected: false, - }, - { - name: "NO_COLOR set", - caps: Capabilities{ - stdinIsTTY: true, - stdoutIsTTY: true, - stderrIsTTY: true, - color: false, - }, - expected: false, - }, - { - name: "no TTY support at all", - caps: Capabilities{ - stdinIsTTY: false, - stdoutIsTTY: false, - stderrIsTTY: false, - color: true, - }, - expected: false, - }, + {"full TTY support", Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true}, true}, + {"MSYS2 pipe stdin blocks prompts", Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true, stdinIsMSYSPipe: true}, false}, + {"stdin not TTY", Capabilities{stdoutIsTTY: true, stderrIsTTY: true}, false}, + {"stdout not TTY (prompts write to stderr, so this is OK)", Capabilities{stdinIsTTY: true, stderrIsTTY: true}, true}, + {"stderr not TTY", Capabilities{stdinIsTTY: true, stdoutIsTTY: true}, false}, + {"NO_COLOR still prompts", Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true, noColor: true}, true}, + {"TERM=dumb", Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true, dumb: true}, false}, + {"no TTY support at all", Capabilities{}, false}, } for _, tt := range tests { @@ -128,6 +66,25 @@ func TestCapabilities_SupportsPrompt(t *testing.T) { } } +func TestCapabilities_SupportsPager(t *testing.T) { + tests := []struct { + name string + caps Capabilities + expected bool + }{ + {"full TTY support", Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true}, true}, + {"NO_COLOR keeps the pager (uncolored)", Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true, noColor: true}, true}, + {"TERM=dumb can't redraw", Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true, dumb: true}, false}, + {"stdout redirected", Capabilities{stdinIsTTY: true, stderrIsTTY: true}, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expected, tt.caps.SupportsPager()) + }) + } +} + func TestCapabilities_SupportsColor(t *testing.T) { tests := []struct { name string @@ -135,36 +92,35 @@ func TestCapabilities_SupportsColor(t *testing.T) { writer io.Writer expected bool }{ - { - name: "TTY with no env restrictions", - caps: Capabilities{color: true}, - writer: FakeTTY(io.Discard), - expected: true, - }, - { - name: "TTY with NO_COLOR set", - caps: Capabilities{color: false}, - writer: FakeTTY(io.Discard), - expected: false, - }, - { - name: "non-TTY writer", - caps: Capabilities{color: true}, - writer: io.Discard, - expected: false, - }, - { - name: "non-TTY with NO_COLOR", - caps: Capabilities{color: false}, - writer: io.Discard, - expected: false, - }, + {"TTY with no env restrictions", Capabilities{}, FakeTTY(io.Discard), true}, + {"TTY with NO_COLOR set", Capabilities{noColor: true}, FakeTTY(io.Discard), false}, + {"TTY with TERM=dumb", Capabilities{dumb: true}, FakeTTY(io.Discard), false}, + {"non-TTY writer", Capabilities{}, io.Discard, false}, + {"non-TTY with NO_COLOR", Capabilities{noColor: true}, io.Discard, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expected, tt.caps.SupportsColor(tt.writer)) + }) + } +} + +func TestCapabilities_SupportsStreamColor(t *testing.T) { + tests := []struct { + name string + caps Capabilities + stdout, stderr bool + }{ + {"both TTYs", Capabilities{stdoutIsTTY: true, stderrIsTTY: true}, true, true}, + {"NO_COLOR", Capabilities{stdoutIsTTY: true, stderrIsTTY: true, noColor: true}, false, false}, + {"only stdout TTY", Capabilities{stdoutIsTTY: true}, true, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result := tt.caps.SupportsColor(tt.writer) - assert.Equal(t, tt.expected, result) + assert.Equal(t, tt.stdout, tt.caps.SupportsStdoutColor()) + assert.Equal(t, tt.stderr, tt.caps.SupportsStderrColor()) }) } } @@ -175,61 +131,13 @@ func TestCapabilities_InteractiveMode(t *testing.T) { caps Capabilities expected InteractiveMode }{ - { - name: "full interactive - all TTYs, color, console stdin", - caps: Capabilities{ - stdinIsTTY: true, - stderrIsTTY: true, - color: true, - }, - expected: InteractiveModeFull, - }, - { - name: "output only - stdin not TTY", - caps: Capabilities{ - stdinIsTTY: false, - stderrIsTTY: true, - color: true, - }, - expected: InteractiveModeOutputOnly, - }, - { - name: "output only - MSYS2 pipe stdin", - caps: Capabilities{ - stdinIsTTY: true, - stderrIsTTY: true, - color: true, - stdinIsMSYSPipe: true, - }, - expected: InteractiveModeOutputOnly, - }, - { - name: "none - stderr not TTY", - caps: Capabilities{ - stdinIsTTY: true, - stderrIsTTY: false, - color: true, - }, - expected: InteractiveModeNone, - }, - { - name: "none - NO_COLOR set", - caps: Capabilities{ - stdinIsTTY: true, - stderrIsTTY: true, - color: false, - }, - expected: InteractiveModeNone, - }, - { - name: "none - no TTY support at all", - caps: Capabilities{ - stdinIsTTY: false, - stderrIsTTY: false, - color: false, - }, - expected: InteractiveModeNone, - }, + {"full interactive", Capabilities{stdinIsTTY: true, stderrIsTTY: true}, InteractiveModeFull}, + {"full interactive with NO_COLOR", Capabilities{stdinIsTTY: true, stderrIsTTY: true, noColor: true}, InteractiveModeFull}, + {"output only - stdin not TTY", Capabilities{stdinIsTTY: false, stderrIsTTY: true}, InteractiveModeOutputOnly}, + {"output only - MSYS2 pipe stdin", Capabilities{stdinIsTTY: true, stderrIsTTY: true, stdinIsMSYSPipe: true}, InteractiveModeOutputOnly}, + {"none - stderr not TTY", Capabilities{stdinIsTTY: true, stderrIsTTY: false}, InteractiveModeNone}, + {"none - TERM=dumb", Capabilities{stdinIsTTY: true, stderrIsTTY: true, dumb: true}, InteractiveModeNone}, + {"none - no TTY support at all", Capabilities{}, InteractiveModeNone}, } for _, tt := range tests { diff --git a/libs/cmdio/conpty_test.go b/libs/cmdio/conpty_test.go index 06d8d61ba67..b20e0debb8f 100644 --- a/libs/cmdio/conpty_test.go +++ b/libs/cmdio/conpty_test.go @@ -44,7 +44,7 @@ func TestIsMSYSPipeAnonymousPipe(t *testing.T) { func TestMSYSPipeBlocksPromptsOnly(t *testing.T) { // An MSYS2 pty pipe counts as a TTY for output and line input, but not // for prompts and pagers, which need raw keystrokes. - c := Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true, color: true, stdinIsMSYSPipe: true} + c := Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true, stdinIsMSYSPipe: true} assert.True(t, c.SupportsInteractive()) assert.True(t, c.SupportsColor(FakeTTY(&bytes.Buffer{}))) assert.False(t, c.SupportsPrompt()) diff --git a/libs/cmdio/io.go b/libs/cmdio/io.go index 5e4486db0c2..5a0385d664a 100644 --- a/libs/cmdio/io.go +++ b/libs/cmdio/io.go @@ -85,8 +85,8 @@ func IsPromptSupported(ctx context.Context) bool { // IsInputTTY reports whether stdin is a terminal, so that a user can type // input into the command. Unlike IsPromptSupported, it does not depend on -// stderr, NO_COLOR or TERM=dumb, which only matter for rendering prompts, and -// it accepts MSYS2 pty pipes, which carry line input but not keystrokes. +// stderr or TERM=dumb, which only matter for rendering prompts, and it accepts +// MSYS2 pty pipes, which carry line input but not keystrokes. func IsInputTTY(ctx context.Context) bool { c := fromContext(ctx) return c.capabilities.stdinIsTTY @@ -102,7 +102,7 @@ func IsPagerSupported(ctx context.Context) bool { } // HasTerminal reports whether stdin, stdout or stderr is a terminal. Unlike -// GetInteractiveMode it ignores colour preferences (NO_COLOR, TERM=dumb). +// GetInteractiveMode it ignores TERM=dumb. func HasTerminal(ctx context.Context) bool { c := fromContext(ctx) return c.capabilities.stdinIsTTY || c.capabilities.stdoutIsTTY || c.capabilities.stderrIsTTY @@ -173,7 +173,6 @@ func MockDiscard(ctx context.Context) context.Context { stdinIsTTY: false, stdoutIsTTY: false, stderrIsTTY: false, - color: false, }, outputFormat: flags.OutputText, in: io.NopCloser(strings.NewReader("")), diff --git a/libs/cmdio/io_test.go b/libs/cmdio/io_test.go index c573e78ccce..b926dec3cd7 100644 --- a/libs/cmdio/io_test.go +++ b/libs/cmdio/io_test.go @@ -42,13 +42,13 @@ func TestAcquireTeaProgramWaitsForRelease(t *testing.T) { } func TestIsInputTTY(t *testing.T) { - // Prompts are not supported without stderr as a terminal and with color, + // Prompts are not supported without stderr as a terminal, // but a user can still type into stdin. ctx := InContext(t.Context(), &cmdIO{capabilities: Capabilities{stdinIsTTY: true}}) assert.True(t, IsInputTTY(ctx)) assert.False(t, IsPromptSupported(ctx)) - ctx = InContext(t.Context(), &cmdIO{capabilities: Capabilities{stderrIsTTY: true, color: true}}) + ctx = InContext(t.Context(), &cmdIO{capabilities: Capabilities{stderrIsTTY: true}}) assert.False(t, IsInputTTY(ctx)) } diff --git a/libs/cmdio/prompt.go b/libs/cmdio/prompt.go index 4469465e972..513fc76b997 100644 --- a/libs/cmdio/prompt.go +++ b/libs/cmdio/prompt.go @@ -48,7 +48,7 @@ func RunPrompt(ctx context.Context, opts PromptOptions) (string, error) { if !c.capabilities.SupportsPrompt() { return "", fmt.Errorf("expected to have %s", opts.Label) } - return c.runPromptModel(newPromptModel(opts)) + return c.runPromptModel(newPromptModel(opts, c.capabilities.SupportsStderrColor())) } // Secret prompts the user for a value while masking input with '*' and @@ -63,6 +63,7 @@ func Secret(ctx context.Context, label string) (string, error) { } type promptModel struct { + color bool // emit color codes (bold etc. apply regardless) label string mask rune hideEntered bool @@ -86,8 +87,9 @@ type promptModel struct { submitErr error } -func newPromptModel(opts PromptOptions) *promptModel { +func newPromptModel(opts PromptOptions, color bool) *promptModel { return &promptModel{ + color: color, label: opts.Label, mask: opts.Mask, hideEntered: opts.HideEntered, @@ -104,12 +106,12 @@ func (m *promptModel) value() string { // blank before that. func (m *promptModel) glyph() string { if m.validate == nil || m.validate(m.value()) == nil { - return ansiBold + ansiGreen + glyphValid + ansiReset + return ansiBold + colorCode(m.color, ansiGreen) + glyphValid + ansiReset } if !m.touched { return glyphBlank } - return ansiBold + ansiRed + glyphInvalid + ansiReset + return ansiBold + colorCode(m.color, ansiRed) + glyphInvalid + ansiReset } func (m *promptModel) Init() tea.Cmd { return nil } @@ -246,7 +248,7 @@ func (m *promptModel) View() string { if m.submitErr != nil { // Validation error line captured at the failed Enter; cleared on // the next edit. - line += "\n" + ansiRed + ">> " + m.submitErr.Error() + ansiReset + line += "\n" + colorCode(m.color, ansiRed) + ">> " + m.submitErr.Error() + ansiReset } return line } diff --git a/libs/cmdio/prompt_test.go b/libs/cmdio/prompt_test.go new file mode 100644 index 00000000000..49aba4d680b --- /dev/null +++ b/libs/cmdio/prompt_test.go @@ -0,0 +1,74 @@ +package cmdio + +import ( + "bytes" + "io" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPromptModelNoColor(t *testing.T) { + m := newPromptModel(PromptOptions{Label: "Name"}, true) + assert.Contains(t, m.View(), ansiGreen) + + m = newPromptModel(PromptOptions{Label: "Name"}, false) + v := m.View() + assert.NotContains(t, v, ansiGreen) + assert.Contains(t, v, ansiBold) +} + +// syncBuffer is a bytes.Buffer that is safe to read while bubbletea writes. +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// runWithKeys runs fn against a fully interactive test cmdIO and types keys +// once the first frame containing label is on screen, so assertions about +// that frame don't depend on timing. It returns what was rendered to stderr. +func runWithKeys(t *testing.T, noColor bool, label, keys string, fn func(c *cmdIO) error) string { + t.Helper() + in, w := io.Pipe() + out := &syncBuffer{} + c := NewTestIO(in, io.Discard, out) + c.capabilities.noColor = noColor + + go func() { + assert.Eventually(t, func() bool { return strings.Contains(out.String(), label) }, 5*time.Second, 10*time.Millisecond) + _, _ = w.Write([]byte(keys)) + }() + require.NoError(t, fn(c)) + _ = w.Close() + return out.String() +} + +func TestRunPromptNoColor(t *testing.T) { + run := func(c *cmdIO) error { + v, err := RunPrompt(InContext(t.Context(), c), PromptOptions{Label: "Name"}) + assert.Equal(t, "x", v) + return err + } + + assert.Contains(t, runWithKeys(t, false, "Name", "x\r", run), ansiGreen) + + out := runWithKeys(t, true, "Name", "x\r", run) + assert.NotContains(t, out, ansiGreen) + assert.Contains(t, out, ansiBold) +} diff --git a/libs/cmdio/render_test.go b/libs/cmdio/render_test.go index dc8eec6dd2d..e336a061f65 100644 --- a/libs/cmdio/render_test.go +++ b/libs/cmdio/render_test.go @@ -192,7 +192,7 @@ func TestRenderJSONColorGate(t *testing.T) { t.Run(tt.name, func(t *testing.T) { out := &bytes.Buffer{} c := &cmdIO{ - capabilities: Capabilities{stdoutIsTTY: tt.stdoutIsTTY, color: tt.color}, + capabilities: Capabilities{stdoutIsTTY: tt.stdoutIsTTY, noColor: !tt.color}, outputFormat: flags.OutputJSON, out: out, err: out, @@ -241,7 +241,7 @@ func TestRenderJSONBytesColorGate(t *testing.T) { t.Run(tt.name, func(t *testing.T) { out := &bytes.Buffer{} c := &cmdIO{ - capabilities: Capabilities{stdoutIsTTY: tt.stdoutIsTTY, color: tt.color}, + capabilities: Capabilities{stdoutIsTTY: tt.stdoutIsTTY, noColor: !tt.color}, out: out, err: out, } diff --git a/libs/cmdio/select.go b/libs/cmdio/select.go index 2d481139bae..469e293f561 100644 --- a/libs/cmdio/select.go +++ b/libs/cmdio/select.go @@ -37,29 +37,47 @@ const ( helpTextSearch = helpTextBase + " and / toggles search" ) -// promptFuncMap is the pipeline-form template.FuncMap used by select-prompt -// templates (`{{ . | bold }}`). It always emits SGR codes; color.go's -// RenderFuncMap is printf-style and gates colors on ctx so the two cannot -// share an implementation. -var promptFuncMap = template.FuncMap{ - "bold": promptANSI(ansiBold), - "faint": promptANSI(ansiFaint), - "italic": promptANSI(ansiItalic), - "underline": promptANSI(ansiUnderline), - "red": promptANSI(ansiRed), - "green": promptANSI(ansiGreen), - "yellow": promptANSI(ansiYellow), - "blue": promptANSI(ansiBlue), - "magenta": promptANSI(ansiMagenta), - "cyan": promptANSI(ansiCyan), +// promptFuncMap returns the pipeline-form template.FuncMap used by +// select-prompt templates (`{{ . | bold }}`). color.go's RenderFuncMap is +// printf-style, so the two cannot share an implementation. With color off +// (NO_COLOR) the color helpers pass text through unchanged; bold, faint, +// italic and underline are not colors and always apply. +func promptFuncMap(color bool) template.FuncMap { + return template.FuncMap{ + "bold": promptANSI(ansiBold), + "faint": promptANSI(ansiFaint), + "italic": promptANSI(ansiItalic), + "underline": promptANSI(ansiUnderline), + "red": promptANSI(colorCode(color, ansiRed)), + "green": promptANSI(colorCode(color, ansiGreen)), + "yellow": promptANSI(colorCode(color, ansiYellow)), + "blue": promptANSI(colorCode(color, ansiBlue)), + "magenta": promptANSI(colorCode(color, ansiMagenta)), + "cyan": promptANSI(colorCode(color, ansiCyan)), + } } +// promptANSI wraps a value in an SGR code. An empty code (a color with color +// off) passes the value through unchanged. func promptANSI(prefix string) func(any) string { + if prefix == "" { + return func(v any) string { return fmt.Sprint(v) } + } return func(v any) string { return prefix + fmt.Sprint(v) + ansiReset } } +// colorCode returns code, or "" with color off. Prompts use it for colors +// only: bold, faint, italic and underline are not colors, so NO_COLOR keeps +// them. +func colorCode(color bool, code string) string { + if !color { + return "" + } + return code +} + // SelectOptions configures an interactive single-choice picker shown by // [RunSelect]. Template strings use text/template syntax and have access // to the fields of the items in Items. @@ -105,7 +123,7 @@ func RunSelect(ctx context.Context, opts SelectOptions) (int, error) { if !c.capabilities.SupportsPrompt() { return 0, fmt.Errorf("expected to have %s", opts.Label) } - m, err := newSelectModel(opts) + m, err := newSelectModel(opts, c.capabilities.SupportsStderrColor()) if err != nil { return 0, err } @@ -173,24 +191,25 @@ type selectModel struct { cancelled bool } -func newSelectModel(opts SelectOptions) (*selectModel, error) { +func newSelectModel(opts SelectOptions, color bool) (*selectModel, error) { items, err := normalizeItems(opts.Items) if err != nil { return nil, err } - labelTpl, err := parsePromptTemplate("label", defaultIfEmpty(opts.LabelTemplate, defaultLabelTemplate)) + funcs := promptFuncMap(color) + labelTpl, err := parsePromptTemplate(funcs, "label", defaultIfEmpty(opts.LabelTemplate, defaultLabelTemplate)) if err != nil { return nil, err } - activeTpl, err := parsePromptTemplate("active", defaultIfEmpty(opts.Active, defaultActiveTemplate)) + activeTpl, err := parsePromptTemplate(funcs, "active", defaultIfEmpty(opts.Active, defaultActiveTemplate)) if err != nil { return nil, err } - inactiveTpl, err := parsePromptTemplate("inactive", defaultIfEmpty(opts.Inactive, defaultInactiveTemplate)) + inactiveTpl, err := parsePromptTemplate(funcs, "inactive", defaultIfEmpty(opts.Inactive, defaultInactiveTemplate)) if err != nil { return nil, err } - selectedTpl, err := parsePromptTemplate("selected", defaultIfEmpty(opts.Selected, defaultSelectedTemplate)) + selectedTpl, err := parsePromptTemplate(funcs, "selected", defaultIfEmpty(opts.Selected, defaultSelectedTemplate)) if err != nil { return nil, err } @@ -218,8 +237,8 @@ func defaultIfEmpty(s, fallback string) string { return s } -func parsePromptTemplate(name, src string) (*template.Template, error) { - t, err := template.New(name).Funcs(promptFuncMap).Parse(src) +func parsePromptTemplate(funcs template.FuncMap, name, src string) (*template.Template, error) { + t, err := template.New(name).Funcs(funcs).Parse(src) if err != nil { return nil, fmt.Errorf("parse %s template: %w", name, err) } diff --git a/libs/cmdio/select_test.go b/libs/cmdio/select_test.go new file mode 100644 index 00000000000..de19d2dbcae --- /dev/null +++ b/libs/cmdio/select_test.go @@ -0,0 +1,41 @@ +package cmdio + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSelectModelNoColor(t *testing.T) { + opts := SelectOptions{Label: "Pick", Items: []Tuple{{"a", "1"}}} + + m, err := newSelectModel(opts, true) + require.NoError(t, err) + assert.Contains(t, m.View(), ansiBlue) + + // NO_COLOR drops the blue "?" but keeps bold/underline on the cursor row. + m, err = newSelectModel(opts, false) + require.NoError(t, err) + v := m.View() + assert.NotContains(t, v, ansiBlue) + assert.Contains(t, v, ansiBold) + assert.Contains(t, v, ansiUnderline) +} + +func TestRunSelectNoColor(t *testing.T) { + opts := SelectOptions{Label: "Pick", Items: []Tuple{{"a", "1"}, {"b", "2"}}} + run := func(c *cmdIO) error { + _, err := RunSelect(InContext(t.Context(), c), opts) + return err + } + + assert.Contains(t, runWithKeys(t, false, "Pick", "\r", run), ansiBlue) + + // NO_COLOR: the prompt still runs, without the blue "?", but the cursor + // row keeps its bold and underline. + out := runWithKeys(t, true, "Pick", "\r", run) + assert.NotContains(t, out, ansiBlue) + assert.Contains(t, out, ansiBold) + assert.Contains(t, out, ansiUnderline) +} diff --git a/libs/cmdio/testing.go b/libs/cmdio/testing.go index bb8f7cc6202..c1141f7d1e3 100644 --- a/libs/cmdio/testing.go +++ b/libs/cmdio/testing.go @@ -30,7 +30,6 @@ func NewTestIO(in io.Reader, out, err io.Writer) *cmdIO { stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true, - color: true, }, outputFormat: flags.OutputText, in: in, @@ -74,8 +73,8 @@ func SetupTest(ctx context.Context, opts TestOptions) (context.Context, *Test) { capabilities: Capabilities{ stdinIsTTY: opts.PromptSupported, stdoutIsTTY: opts.PromptSupported, - stderrIsTTY: true, - color: opts.PromptSupported, + stderrIsTTY: opts.PromptSupported, + noColor: !opts.PromptSupported, }, in: rin, out: wout,