From 3976f851323880f3f2cd092c679197d62f8cc327 Mon Sep 17 00:00:00 2001 From: Pieter Noordhuis Date: Mon, 16 Nov 2026 18:14:16 +0100 Subject: [PATCH 1/6] cmdio: make NO_COLOR only affect color Capabilities folded NO_COLOR and TERM=dumb into one "color" flag and built SupportsInteractive (and so prompts, spinners and the pager) on top of it. A user with NO_COLOR=1 on a real terminal got no spinners and every prompt failed with "expected to have ...". NO_COLOR is a color preference only (https://no-color.org); TERM=dumb is what rules out redrawing output. - Split the flag into noColor and dumb. SupportsInteractive is now stderr TTY && !dumb; color checks use both. - Add SupportsStderrColor next to SupportsStdoutColor and use it for prompt rendering: color helpers in select templates and the text prompt pass through uncolored with color off, while bold, faint, italic and underline still apply (allowed by NO_COLOR). - NewRenderer follows cmdio's color decision in both directions. It already forced Ascii when color is off; it now raises an Ascii probe to ANSI when cmdio says the writer supports color (MSYS2 pty pipes, which termenv can't recognize), so the spinner matches the rest of the output. Verified with the termtesting harness: NO_COLOR=1 select works in iTerm2, Git Bash and PowerShell; the spinner is colored on an MSYS2 pipe. Co-authored-by: Isaac --- .nextchanges/cli/no-color-keeps-prompts.md | 1 + libs/cmdio/capabilities.go | 31 ++- libs/cmdio/capabilities_test.go | 233 ++++++--------------- libs/cmdio/color.go | 20 +- libs/cmdio/color_test.go | 12 ++ libs/cmdio/conpty_test.go | 2 +- libs/cmdio/io.go | 1 - libs/cmdio/io_test.go | 4 +- libs/cmdio/prompt.go | 20 +- libs/cmdio/prompt_test.go | 17 ++ libs/cmdio/render_test.go | 4 +- libs/cmdio/select.go | 56 +++-- libs/cmdio/select_test.go | 24 +++ libs/cmdio/testing.go | 5 +- 14 files changed, 209 insertions(+), 221 deletions(-) create mode 100644 .nextchanges/cli/no-color-keeps-prompts.md create mode 100644 libs/cmdio/prompt_test.go create mode 100644 libs/cmdio/select_test.go diff --git a/.nextchanges/cli/no-color-keeps-prompts.md b/.nextchanges/cli/no-color-keeps-prompts.md new file mode 100644 index 00000000000..bc1c55d5fc8 --- /dev/null +++ b/.nextchanges/cli/no-color-keeps-prompts.md @@ -0,0 +1 @@ +* `NO_COLOR` now only removes color: prompts, spinners and pagers stay available (uncolored) instead of being disabled. ([#7700](https://github.com/databricks/cli/pull/7700)) diff --git a/libs/cmdio/capabilities.go b/libs/cmdio/capabilities.go index 1569354f445..2cafdc6c9ee 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 and spinners 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..707e32ad3eb 100644 --- a/libs/cmdio/capabilities_test.go +++ b/libs/cmdio/capabilities_test.go @@ -4,35 +4,35 @@ import ( "io" "testing" + "github.com/databricks/cli/libs/env" "github.com/stretchr/testify/assert" ) +func TestNewCapabilities_Env(t *testing.T) { + ctx := t.Context() + 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 { @@ -43,82 +43,25 @@ func TestCapabilities_SupportsInteractive(t *testing.T) { } func TestCapabilities_SupportsPrompt(t *testing.T) { + tty := Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true} + with := func(f func(*Capabilities)) Capabilities { + c := tty + f(&c) + return c + } tests := []struct { name string 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", tty, true}, + {"MSYS2 pipe stdin blocks prompts", with(func(c *Capabilities) { c.stdinIsMSYSPipe = true }), false}, + {"stdin not TTY", with(func(c *Capabilities) { c.stdinIsTTY = false }), false}, + {"stdout not TTY (prompts write to stderr, so this is OK)", with(func(c *Capabilities) { c.stdoutIsTTY = false }), true}, + {"stderr not TTY", with(func(c *Capabilities) { c.stderrIsTTY = false }), false}, + {"NO_COLOR still prompts", with(func(c *Capabilities) { c.noColor = true }), true}, + {"TERM=dumb", with(func(c *Capabilities) { c.dumb = true }), false}, + {"no TTY support at all", Capabilities{}, false}, } for _, tt := range tests { @@ -135,101 +78,47 @@ 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) { - result := tt.caps.SupportsColor(tt.writer) - assert.Equal(t, tt.expected, result) + assert.Equal(t, tt.expected, tt.caps.SupportsColor(tt.writer)) }) } } +func TestCapabilities_SupportsStreamColor(t *testing.T) { + c := Capabilities{stdoutIsTTY: true, stderrIsTTY: true} + assert.True(t, c.SupportsStdoutColor()) + assert.True(t, c.SupportsStderrColor()) + + c.noColor = true + assert.False(t, c.SupportsStdoutColor()) + assert.False(t, c.SupportsStderrColor()) + + c = Capabilities{stdoutIsTTY: true} + assert.True(t, c.SupportsStdoutColor()) + assert.False(t, c.SupportsStderrColor()) +} + func TestCapabilities_InteractiveMode(t *testing.T) { tests := []struct { name string 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/color.go b/libs/cmdio/color.go index 4549b31feff..b2ef83d06d8 100644 --- a/libs/cmdio/color.go +++ b/libs/cmdio/color.go @@ -142,15 +142,25 @@ func PadLeft(s string, n int) string { } // NewRenderer returns a lipgloss renderer targeting w, along with whether w -// supports color. When it does not (NO_COLOR, TERM=dumb, or w is piped or -// redirected) the renderer is forced to the Ascii profile so every Style it -// mints emits no SGR escapes. Callers still write rendered strings to w -// themselves; the renderer only carries the color profile. +// supports color. cmdio's decision wins in both directions, so lipgloss +// output agrees with the rest of cmdio's output: +// - when w doesn't support color (NO_COLOR, TERM=dumb, or w is piped or +// redirected) the renderer is forced to the Ascii profile so every Style +// it mints emits no SGR escapes; +// - when it does but termenv's own probe found nothing (an MSYS2 pty pipe +// without ConPTY, which termenv can't see is a terminal; see conpty.go), +// the renderer is raised to basic ANSI. +// +// Callers still write rendered strings to w themselves; the renderer only +// carries the color profile. func NewRenderer(ctx context.Context, w io.Writer) (*lipgloss.Renderer, bool) { color := SupportsColor(ctx, w) r := lipgloss.NewRenderer(w) - if !color { + switch { + case !color: r.SetColorProfile(termenv.Ascii) + case r.ColorProfile() == termenv.Ascii: + r.SetColorProfile(termenv.ANSI) } return r, color } diff --git a/libs/cmdio/color_test.go b/libs/cmdio/color_test.go index 404f0c12cdb..a3fc012925d 100644 --- a/libs/cmdio/color_test.go +++ b/libs/cmdio/color_test.go @@ -5,6 +5,7 @@ import ( "context" "testing" + "github.com/charmbracelet/lipgloss" "github.com/databricks/cli/libs/cmdio" "github.com/muesli/termenv" "github.com/stretchr/testify/assert" @@ -139,6 +140,17 @@ func TestNewRendererForcesAsciiWhenNoColor(t *testing.T) { assert.Equal(t, "hi", r.NewStyle().Bold(true).Render("hi")) } +func TestNewRendererRaisesAsciiWhenColor(t *testing.T) { + ctx := ttyContext(t) + + // termenv can't detect a FakeTTY (like an MSYS2 pty pipe), but cmdio says + // it supports color, so the renderer must still emit color. + r, color := cmdio.NewRenderer(ctx, cmdio.FakeTTY(&bytes.Buffer{})) + assert.True(t, color) + assert.Equal(t, termenv.ANSI, r.ColorProfile()) + assert.NotEqual(t, "hi", r.NewStyle().Foreground(lipgloss.Color("10")).Render("hi")) +} + func TestRenderFuncMap(t *testing.T) { ctx := ttyContext(t) fm := cmdio.RenderFuncMap(ctx) 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..895078ab89e 100644 --- a/libs/cmdio/io.go +++ b/libs/cmdio/io.go @@ -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..90eb2817bf7 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, @@ -95,6 +97,14 @@ func newPromptModel(opts PromptOptions) *promptModel { } } +// paint returns the color code, or "" with color off. +func (m *promptModel) paint(code string) string { + if !m.color { + return "" + } + return code +} + func (m *promptModel) value() string { return string(m.runes) } @@ -104,12 +114,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 + m.paint(ansiGreen) + glyphValid + ansiReset } if !m.touched { return glyphBlank } - return ansiBold + ansiRed + glyphInvalid + ansiReset + return ansiBold + m.paint(ansiRed) + glyphInvalid + ansiReset } func (m *promptModel) Init() tea.Cmd { return nil } @@ -246,7 +256,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" + m.paint(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..358c52690ca --- /dev/null +++ b/libs/cmdio/prompt_test.go @@ -0,0 +1,17 @@ +package cmdio + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +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) +} 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..0a9cbbe1a3d 100644 --- a/libs/cmdio/select.go +++ b/libs/cmdio/select.go @@ -37,21 +37,30 @@ 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 { + c := func(code string) func(any) string { + if !color { + return func(v any) string { return fmt.Sprint(v) } + } + return promptANSI(code) + } + return template.FuncMap{ + "bold": promptANSI(ansiBold), + "faint": promptANSI(ansiFaint), + "italic": promptANSI(ansiItalic), + "underline": promptANSI(ansiUnderline), + "red": c(ansiRed), + "green": c(ansiGreen), + "yellow": c(ansiYellow), + "blue": c(ansiBlue), + "magenta": c(ansiMagenta), + "cyan": c(ansiCyan), + } } func promptANSI(prefix string) func(any) string { @@ -105,7 +114,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 +182,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 +228,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..138c4311878 --- /dev/null +++ b/libs/cmdio/select_test.go @@ -0,0 +1,24 @@ +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) +} 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, From 14dd2df31344f59d32da096c7a8077d10d7ca6fe Mon Sep 17 00:00:00 2001 From: Pieter Noordhuis Date: Mon, 16 Nov 2026 21:00:51 +0100 Subject: [PATCH 2/6] cmdio: address review of NO_COLOR change - NewRenderer raises Ascii to ANSI only for MSYS2 pty pipes, so termenv's other reasons for Ascii on a terminal (CLICOLOR=0, CI) are respected again. Covered by a Windows test on a real MSYS2 pipe and a test that a non-MSYS writer keeps termenv's profile. - Fix IsInputTTY and HasTerminal doc comments for the new semantics. - Test that the pager stays available under NO_COLOR. - Changelog: be precise about which interactive features stay, and note that a NO_COLOR terminal now counts as interactive (update notice, user agent). Co-authored-by: Isaac --- .nextchanges/cli/no-color-keeps-prompts.md | 2 +- libs/cmdio/capabilities_test.go | 17 +++++++++++++++++ libs/cmdio/color.go | 9 +++++---- libs/cmdio/color_test.go | 12 ++++++------ libs/cmdio/conpty_windows_test.go | 13 +++++++++++++ libs/cmdio/io.go | 6 +++--- 6 files changed, 45 insertions(+), 14 deletions(-) diff --git a/.nextchanges/cli/no-color-keeps-prompts.md b/.nextchanges/cli/no-color-keeps-prompts.md index bc1c55d5fc8..d3334afa8cc 100644 --- a/.nextchanges/cli/no-color-keeps-prompts.md +++ b/.nextchanges/cli/no-color-keeps-prompts.md @@ -1 +1 @@ -* `NO_COLOR` now only removes color: prompts, spinners and pagers stay available (uncolored) instead of being disabled. ([#7700](https://github.com/databricks/cli/pull/7700)) +* `NO_COLOR` now only removes color: prompts, spinners and the pager for list output stay available (uncolored) instead of being disabled, and a terminal with `NO_COLOR` set counts as interactive (for example for the update notice and the user agent). ([#7700](https://github.com/databricks/cli/pull/7700)) diff --git a/libs/cmdio/capabilities_test.go b/libs/cmdio/capabilities_test.go index 707e32ad3eb..1e75eae2184 100644 --- a/libs/cmdio/capabilities_test.go +++ b/libs/cmdio/capabilities_test.go @@ -71,6 +71,23 @@ func TestCapabilities_SupportsPrompt(t *testing.T) { } } +func TestCapabilities_SupportsPager(t *testing.T) { + tty := Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true} + assert.True(t, tty.SupportsPager()) + + c := tty + c.noColor = true + assert.True(t, c.SupportsPager(), "NO_COLOR keeps the pager (uncolored)") + + c = tty + c.dumb = true + assert.False(t, c.SupportsPager(), "TERM=dumb can't redraw") + + c = tty + c.stdoutIsTTY = false + assert.False(t, c.SupportsPager(), "stdout redirected") +} + func TestCapabilities_SupportsColor(t *testing.T) { tests := []struct { name string diff --git a/libs/cmdio/color.go b/libs/cmdio/color.go index b2ef83d06d8..57b339b10d0 100644 --- a/libs/cmdio/color.go +++ b/libs/cmdio/color.go @@ -147,9 +147,10 @@ func PadLeft(s string, n int) string { // - when w doesn't support color (NO_COLOR, TERM=dumb, or w is piped or // redirected) the renderer is forced to the Ascii profile so every Style // it mints emits no SGR escapes; -// - when it does but termenv's own probe found nothing (an MSYS2 pty pipe -// without ConPTY, which termenv can't see is a terminal; see conpty.go), -// the renderer is raised to basic ANSI. +// - when w is an MSYS2 pty pipe (no ConPTY; see conpty.go), which cmdio +// treats as a terminal but termenv can't recognize, the renderer is +// raised from Ascii to basic ANSI. Other reasons termenv picks Ascii on +// a terminal (CLICOLOR=0, CI) are left alone. // // Callers still write rendered strings to w themselves; the renderer only // carries the color profile. @@ -159,7 +160,7 @@ func NewRenderer(ctx context.Context, w io.Writer) (*lipgloss.Renderer, bool) { switch { case !color: r.SetColorProfile(termenv.Ascii) - case r.ColorProfile() == termenv.Ascii: + case isMSYSPipe(w) && r.ColorProfile() == termenv.Ascii: r.SetColorProfile(termenv.ANSI) } return r, color diff --git a/libs/cmdio/color_test.go b/libs/cmdio/color_test.go index a3fc012925d..4774852b507 100644 --- a/libs/cmdio/color_test.go +++ b/libs/cmdio/color_test.go @@ -5,7 +5,6 @@ import ( "context" "testing" - "github.com/charmbracelet/lipgloss" "github.com/databricks/cli/libs/cmdio" "github.com/muesli/termenv" "github.com/stretchr/testify/assert" @@ -140,15 +139,16 @@ func TestNewRendererForcesAsciiWhenNoColor(t *testing.T) { assert.Equal(t, "hi", r.NewStyle().Bold(true).Render("hi")) } -func TestNewRendererRaisesAsciiWhenColor(t *testing.T) { +func TestNewRendererKeepsTermenvProfile(t *testing.T) { ctx := ttyContext(t) - // termenv can't detect a FakeTTY (like an MSYS2 pty pipe), but cmdio says - // it supports color, so the renderer must still emit color. + // cmdio says a FakeTTY supports color, but it isn't an MSYS2 pty pipe, so + // termenv's own decision (Ascii: it can't see a terminal) stands. The same + // holds for CLICOLOR=0 or CI on a real terminal. The MSYS2 pipe case is + // covered in conpty_windows_test.go. r, color := cmdio.NewRenderer(ctx, cmdio.FakeTTY(&bytes.Buffer{})) assert.True(t, color) - assert.Equal(t, termenv.ANSI, r.ColorProfile()) - assert.NotEqual(t, "hi", r.NewStyle().Foreground(lipgloss.Color("10")).Render("hi")) + assert.Equal(t, termenv.Ascii, r.ColorProfile()) } func TestRenderFuncMap(t *testing.T) { diff --git a/libs/cmdio/conpty_windows_test.go b/libs/cmdio/conpty_windows_test.go index 614f06fce9d..f16b12b72f1 100644 --- a/libs/cmdio/conpty_windows_test.go +++ b/libs/cmdio/conpty_windows_test.go @@ -5,7 +5,9 @@ import ( "os" "testing" + "github.com/charmbracelet/lipgloss" "github.com/databricks/cli/libs/env" + "github.com/muesli/termenv" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/sys/windows" @@ -74,3 +76,14 @@ func TestNewCapabilitiesMSYSPipeStdin(t *testing.T) { assert.False(t, c.stdinIsMSYSPipe) assert.True(t, c.SupportsPrompt()) } + +func TestNewRendererRaisesMSYSPipeToANSI(t *testing.T) { + // termenv can't recognize an MSYS2 pty pipe as a terminal, but cmdio + // does, so the renderer must still emit color there. + f := openNamedPipe(t, fmt.Sprintf("msys-%016x-pty0-to-master", os.Getpid()+1)) + ctx := InContext(t.Context(), &cmdIO{capabilities: Capabilities{stderrIsTTY: true}}) + r, color := NewRenderer(ctx, f) + assert.True(t, color) + assert.Equal(t, termenv.ANSI, r.ColorProfile()) + assert.NotEqual(t, "hi", r.NewStyle().Foreground(lipgloss.Color("10")).Render("hi")) +} diff --git a/libs/cmdio/io.go b/libs/cmdio/io.go index 895078ab89e..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 From fb6f7d2bf565dec3f2e6d22bf07a5efbf89ff66f Mon Sep 17 00:00:00 2001 From: Pieter Noordhuis Date: Mon, 16 Nov 2026 21:17:50 +0100 Subject: [PATCH 3/6] cmdio: address second review of NO_COLOR change - NewRenderer's raise on MSYS2 pipes honors CLICOLOR=0 (termenv.EnvNoColor); document that termenv's CI guess is not honored there. Windows test for the CLICOLOR case. - Share one colorCode helper between the select templates and the text prompt instead of two ways to drop color codes. Co-authored-by: Isaac --- libs/cmdio/color.go | 10 +++++++--- libs/cmdio/conpty_windows_test.go | 8 ++++++++ libs/cmdio/prompt.go | 14 +++---------- libs/cmdio/select.go | 33 ++++++++++++++++++++----------- 4 files changed, 39 insertions(+), 26 deletions(-) diff --git a/libs/cmdio/color.go b/libs/cmdio/color.go index 57b339b10d0..8728c748d6a 100644 --- a/libs/cmdio/color.go +++ b/libs/cmdio/color.go @@ -149,8 +149,12 @@ func PadLeft(s string, n int) string { // it mints emits no SGR escapes; // - when w is an MSYS2 pty pipe (no ConPTY; see conpty.go), which cmdio // treats as a terminal but termenv can't recognize, the renderer is -// raised from Ascii to basic ANSI. Other reasons termenv picks Ascii on -// a terminal (CLICOLOR=0, CI) are left alone. +// raised from Ascii to basic ANSI unless CLICOLOR=0 asks for no color +// (termenv.EnvNoColor). termenv's CI check is not honored there: it only +// guesses that CI output isn't a terminal, and this one is. +// +// On every other writer termenv's profile stands, including Ascii for +// CLICOLOR=0 or CI on a terminal. // // Callers still write rendered strings to w themselves; the renderer only // carries the color profile. @@ -160,7 +164,7 @@ func NewRenderer(ctx context.Context, w io.Writer) (*lipgloss.Renderer, bool) { switch { case !color: r.SetColorProfile(termenv.Ascii) - case isMSYSPipe(w) && r.ColorProfile() == termenv.Ascii: + case isMSYSPipe(w) && r.ColorProfile() == termenv.Ascii && !termenv.EnvNoColor(): r.SetColorProfile(termenv.ANSI) } return r, color diff --git a/libs/cmdio/conpty_windows_test.go b/libs/cmdio/conpty_windows_test.go index f16b12b72f1..46444e64c0d 100644 --- a/libs/cmdio/conpty_windows_test.go +++ b/libs/cmdio/conpty_windows_test.go @@ -87,3 +87,11 @@ func TestNewRendererRaisesMSYSPipeToANSI(t *testing.T) { assert.Equal(t, termenv.ANSI, r.ColorProfile()) assert.NotEqual(t, "hi", r.NewStyle().Foreground(lipgloss.Color("10")).Render("hi")) } + +func TestNewRendererMSYSPipeHonorsCLICOLOR(t *testing.T) { + t.Setenv("CLICOLOR", "0") + f := openNamedPipe(t, fmt.Sprintf("msys-%016x-pty1-to-master", os.Getpid()+3)) + ctx := InContext(t.Context(), &cmdIO{capabilities: Capabilities{stderrIsTTY: true}}) + r, _ := NewRenderer(ctx, f) + assert.Equal(t, termenv.Ascii, r.ColorProfile()) +} diff --git a/libs/cmdio/prompt.go b/libs/cmdio/prompt.go index 90eb2817bf7..513fc76b997 100644 --- a/libs/cmdio/prompt.go +++ b/libs/cmdio/prompt.go @@ -97,14 +97,6 @@ func newPromptModel(opts PromptOptions, color bool) *promptModel { } } -// paint returns the color code, or "" with color off. -func (m *promptModel) paint(code string) string { - if !m.color { - return "" - } - return code -} - func (m *promptModel) value() string { return string(m.runes) } @@ -114,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 + m.paint(ansiGreen) + glyphValid + ansiReset + return ansiBold + colorCode(m.color, ansiGreen) + glyphValid + ansiReset } if !m.touched { return glyphBlank } - return ansiBold + m.paint(ansiRed) + glyphInvalid + ansiReset + return ansiBold + colorCode(m.color, ansiRed) + glyphInvalid + ansiReset } func (m *promptModel) Init() tea.Cmd { return nil } @@ -256,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" + m.paint(ansiRed) + ">> " + m.submitErr.Error() + ansiReset + line += "\n" + colorCode(m.color, ansiRed) + ">> " + m.submitErr.Error() + ansiReset } return line } diff --git a/libs/cmdio/select.go b/libs/cmdio/select.go index 0a9cbbe1a3d..469e293f561 100644 --- a/libs/cmdio/select.go +++ b/libs/cmdio/select.go @@ -43,32 +43,41 @@ const ( // (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 { - c := func(code string) func(any) string { - if !color { - return func(v any) string { return fmt.Sprint(v) } - } - return promptANSI(code) - } return template.FuncMap{ "bold": promptANSI(ansiBold), "faint": promptANSI(ansiFaint), "italic": promptANSI(ansiItalic), "underline": promptANSI(ansiUnderline), - "red": c(ansiRed), - "green": c(ansiGreen), - "yellow": c(ansiYellow), - "blue": c(ansiBlue), - "magenta": c(ansiMagenta), - "cyan": c(ansiCyan), + "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. From c99396f1303cba11e4b9b7dfa8eb9d488b86bde9 Mon Sep 17 00:00:00 2001 From: Pieter Noordhuis Date: Mon, 16 Nov 2026 21:28:16 +0100 Subject: [PATCH 4/6] cmdio: address third review of NO_COLOR change - Test NO_COLOR end to end through RunSelect and RunPrompt: no color codes, emphasis kept. - NewRenderer doc: cmdio adjusts termenv's profile in two specific cases rather than always winning. - Fix SupportsStderrColor doc; changelog wording. Co-authored-by: Isaac --- .nextchanges/cli/no-color-keeps-prompts.md | 2 +- libs/cmdio/capabilities.go | 4 +-- libs/cmdio/color.go | 4 +-- libs/cmdio/prompt_test.go | 36 ++++++++++++++++++++++ libs/cmdio/select_test.go | 17 ++++++++++ 5 files changed, 58 insertions(+), 5 deletions(-) diff --git a/.nextchanges/cli/no-color-keeps-prompts.md b/.nextchanges/cli/no-color-keeps-prompts.md index d3334afa8cc..1ce363bdf44 100644 --- a/.nextchanges/cli/no-color-keeps-prompts.md +++ b/.nextchanges/cli/no-color-keeps-prompts.md @@ -1 +1 @@ -* `NO_COLOR` now only removes color: prompts, spinners and the pager for list output stay available (uncolored) instead of being disabled, and a terminal with `NO_COLOR` set counts as interactive (for example for the update notice and the user agent). ([#7700](https://github.com/databricks/cli/pull/7700)) +* `NO_COLOR` now only removes color: prompts, spinners and the pager for list output are now available (uncolored) instead of being disabled, and a terminal with `NO_COLOR` set counts as interactive (for example for the update notice and the user agent). ([#7700](https://github.com/databricks/cli/pull/7700)) diff --git a/libs/cmdio/capabilities.go b/libs/cmdio/capabilities.go index 2cafdc6c9ee..f48c72a006a 100644 --- a/libs/cmdio/capabilities.go +++ b/libs/cmdio/capabilities.go @@ -70,8 +70,8 @@ func (c Capabilities) SupportsStdoutColor() bool { return c.stdoutIsTTY && c.colorAllowed() } -// SupportsStderrColor is the stderr counterpart of SupportsStdoutColor; -// prompts and spinners render to stderr. +// SupportsStderrColor is the stderr counterpart of SupportsStdoutColor. +// Prompts use it; they render to stderr. func (c Capabilities) SupportsStderrColor() bool { return c.stderrIsTTY && c.colorAllowed() } diff --git a/libs/cmdio/color.go b/libs/cmdio/color.go index 8728c748d6a..012795869ff 100644 --- a/libs/cmdio/color.go +++ b/libs/cmdio/color.go @@ -142,8 +142,8 @@ func PadLeft(s string, n int) string { } // NewRenderer returns a lipgloss renderer targeting w, along with whether w -// supports color. cmdio's decision wins in both directions, so lipgloss -// output agrees with the rest of cmdio's output: +// supports color. The renderer's profile starts from termenv's probe of w and +// is adjusted where cmdio knows better: // - when w doesn't support color (NO_COLOR, TERM=dumb, or w is piped or // redirected) the renderer is forced to the Ascii profile so every Style // it mints emits no SGR escapes; diff --git a/libs/cmdio/prompt_test.go b/libs/cmdio/prompt_test.go index 358c52690ca..55151157cce 100644 --- a/libs/cmdio/prompt_test.go +++ b/libs/cmdio/prompt_test.go @@ -1,9 +1,13 @@ package cmdio import ( + "bytes" + "io" "testing" + "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPromptModelNoColor(t *testing.T) { @@ -15,3 +19,35 @@ func TestPromptModelNoColor(t *testing.T) { assert.NotContains(t, v, ansiGreen) assert.Contains(t, v, ansiBold) } + +// runWithKeys runs fn against a fully interactive test cmdIO and types keys +// once it is running. It returns what was rendered to stderr. +func runWithKeys(t *testing.T, noColor bool, keys string, fn func(c *cmdIO) error) string { + t.Helper() + in, w := io.Pipe() + var out bytes.Buffer + c := NewTestIO(in, io.Discard, &out) + c.capabilities.noColor = noColor + + go func() { + time.Sleep(200 * 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, "x\r", run), ansiGreen) + + out := runWithKeys(t, true, "x\r", run) + assert.NotContains(t, out, ansiGreen) + assert.Contains(t, out, ansiBold) +} diff --git a/libs/cmdio/select_test.go b/libs/cmdio/select_test.go index 138c4311878..ce34943d587 100644 --- a/libs/cmdio/select_test.go +++ b/libs/cmdio/select_test.go @@ -22,3 +22,20 @@ func TestSelectModelNoColor(t *testing.T) { 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, "\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, "\r", run) + assert.NotContains(t, out, ansiBlue) + assert.Contains(t, out, ansiBold) + assert.Contains(t, out, ansiUnderline) +} From edc13ce0b5d7297832ab1f3567305db177e4967e Mon Sep 17 00:00:00 2001 From: Pieter Noordhuis Date: Mon, 16 Nov 2026 21:37:58 +0100 Subject: [PATCH 5/6] cmdio: address fourth review of NO_COLOR change - Tests no longer read NO_COLOR/TERM from the developer's shell. - Changelog: shorter, and accurate about what NO_COLOR no longer disables. Co-authored-by: Isaac --- .nextchanges/cli/no-color-keeps-prompts.md | 2 +- libs/cmdio/capabilities_test.go | 3 ++- libs/cmdio/conpty_windows_test.go | 4 ++++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.nextchanges/cli/no-color-keeps-prompts.md b/.nextchanges/cli/no-color-keeps-prompts.md index 1ce363bdf44..42df4828c96 100644 --- a/.nextchanges/cli/no-color-keeps-prompts.md +++ b/.nextchanges/cli/no-color-keeps-prompts.md @@ -1 +1 @@ -* `NO_COLOR` now only removes color: prompts, spinners and the pager for list output are now available (uncolored) instead of being disabled, and a terminal with `NO_COLOR` set counts as interactive (for example for the update notice and the user agent). ([#7700](https://github.com/databricks/cli/pull/7700)) +* `NO_COLOR` no longer disables prompts, spinners or the pager for list commands; they run without color. ([#7700](https://github.com/databricks/cli/pull/7700)) diff --git a/libs/cmdio/capabilities_test.go b/libs/cmdio/capabilities_test.go index 1e75eae2184..16f1c415c69 100644 --- a/libs/cmdio/capabilities_test.go +++ b/libs/cmdio/capabilities_test.go @@ -9,7 +9,8 @@ import ( ) func TestNewCapabilities_Env(t *testing.T) { - ctx := t.Context() + // 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) diff --git a/libs/cmdio/conpty_windows_test.go b/libs/cmdio/conpty_windows_test.go index 46444e64c0d..41a943c5d2e 100644 --- a/libs/cmdio/conpty_windows_test.go +++ b/libs/cmdio/conpty_windows_test.go @@ -78,6 +78,8 @@ func TestNewCapabilitiesMSYSPipeStdin(t *testing.T) { } func TestNewRendererRaisesMSYSPipeToANSI(t *testing.T) { + // termenv reads NO_COLOR from the process environment. + t.Setenv("NO_COLOR", "") // termenv can't recognize an MSYS2 pty pipe as a terminal, but cmdio // does, so the renderer must still emit color there. f := openNamedPipe(t, fmt.Sprintf("msys-%016x-pty0-to-master", os.Getpid()+1)) @@ -89,6 +91,8 @@ func TestNewRendererRaisesMSYSPipeToANSI(t *testing.T) { } func TestNewRendererMSYSPipeHonorsCLICOLOR(t *testing.T) { + // termenv reads NO_COLOR from the process environment. + t.Setenv("NO_COLOR", "") t.Setenv("CLICOLOR", "0") f := openNamedPipe(t, fmt.Sprintf("msys-%016x-pty1-to-master", os.Getpid()+3)) ctx := InContext(t.Context(), &cmdIO{capabilities: Capabilities{stderrIsTTY: true}}) From 6487b5c96cc557a9a525878485b100c47c2f7a5a Mon Sep 17 00:00:00 2001 From: Pieter Noordhuis Date: Tue, 17 Nov 2026 13:02:16 +0100 Subject: [PATCH 6/6] cmdio: address review of NO_COLOR change - Keep the static table in experimental postgres query when color is off: the table viewer marks the cursor and search matches with color only. - Drop the MSYS2 pty pipe renderer change; it is unrelated to NO_COLOR and will be handled separately. - Wait for the first frame before typing in the prompt and select tests instead of sleeping. - Narrow the changelog to the list pager and make the capability tests table-driven. Co-authored-by: Isaac --- .nextchanges/cli/no-color-keeps-prompts.md | 2 +- experimental/postgres/cmd/query.go | 6 +- libs/cmdio/capabilities_test.go | 73 +++++++++++----------- libs/cmdio/color.go | 25 ++------ libs/cmdio/color_test.go | 12 ---- libs/cmdio/conpty_windows_test.go | 25 -------- libs/cmdio/prompt_test.go | 35 ++++++++--- libs/cmdio/select_test.go | 4 +- 8 files changed, 78 insertions(+), 104 deletions(-) diff --git a/.nextchanges/cli/no-color-keeps-prompts.md b/.nextchanges/cli/no-color-keeps-prompts.md index 42df4828c96..c6871334721 100644 --- a/.nextchanges/cli/no-color-keeps-prompts.md +++ b/.nextchanges/cli/no-color-keeps-prompts.md @@ -1 +1 @@ -* `NO_COLOR` no longer disables prompts, spinners or the pager for list commands; they run without color. ([#7700](https://github.com/databricks/cli/pull/7700)) +* `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_test.go b/libs/cmdio/capabilities_test.go index 16f1c415c69..63a8226d86e 100644 --- a/libs/cmdio/capabilities_test.go +++ b/libs/cmdio/capabilities_test.go @@ -44,24 +44,18 @@ func TestCapabilities_SupportsInteractive(t *testing.T) { } func TestCapabilities_SupportsPrompt(t *testing.T) { - tty := Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true} - with := func(f func(*Capabilities)) Capabilities { - c := tty - f(&c) - return c - } tests := []struct { name string caps Capabilities expected bool }{ - {"full TTY support", tty, true}, - {"MSYS2 pipe stdin blocks prompts", with(func(c *Capabilities) { c.stdinIsMSYSPipe = true }), false}, - {"stdin not TTY", with(func(c *Capabilities) { c.stdinIsTTY = false }), false}, - {"stdout not TTY (prompts write to stderr, so this is OK)", with(func(c *Capabilities) { c.stdoutIsTTY = false }), true}, - {"stderr not TTY", with(func(c *Capabilities) { c.stderrIsTTY = false }), false}, - {"NO_COLOR still prompts", with(func(c *Capabilities) { c.noColor = true }), true}, - {"TERM=dumb", with(func(c *Capabilities) { c.dumb = true }), 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}, } @@ -73,20 +67,22 @@ func TestCapabilities_SupportsPrompt(t *testing.T) { } func TestCapabilities_SupportsPager(t *testing.T) { - tty := Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true} - assert.True(t, tty.SupportsPager()) - - c := tty - c.noColor = true - assert.True(t, c.SupportsPager(), "NO_COLOR keeps the pager (uncolored)") - - c = tty - c.dumb = true - assert.False(t, c.SupportsPager(), "TERM=dumb can't redraw") + 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}, + } - c = tty - c.stdoutIsTTY = false - assert.False(t, c.SupportsPager(), "stdout redirected") + 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) { @@ -111,17 +107,22 @@ func TestCapabilities_SupportsColor(t *testing.T) { } func TestCapabilities_SupportsStreamColor(t *testing.T) { - c := Capabilities{stdoutIsTTY: true, stderrIsTTY: true} - assert.True(t, c.SupportsStdoutColor()) - assert.True(t, c.SupportsStderrColor()) - - c.noColor = true - assert.False(t, c.SupportsStdoutColor()) - assert.False(t, c.SupportsStderrColor()) + 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}, + } - c = Capabilities{stdoutIsTTY: true} - assert.True(t, c.SupportsStdoutColor()) - assert.False(t, c.SupportsStderrColor()) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.stdout, tt.caps.SupportsStdoutColor()) + assert.Equal(t, tt.stderr, tt.caps.SupportsStderrColor()) + }) + } } func TestCapabilities_InteractiveMode(t *testing.T) { diff --git a/libs/cmdio/color.go b/libs/cmdio/color.go index 012795869ff..4549b31feff 100644 --- a/libs/cmdio/color.go +++ b/libs/cmdio/color.go @@ -142,30 +142,15 @@ func PadLeft(s string, n int) string { } // NewRenderer returns a lipgloss renderer targeting w, along with whether w -// supports color. The renderer's profile starts from termenv's probe of w and -// is adjusted where cmdio knows better: -// - when w doesn't support color (NO_COLOR, TERM=dumb, or w is piped or -// redirected) the renderer is forced to the Ascii profile so every Style -// it mints emits no SGR escapes; -// - when w is an MSYS2 pty pipe (no ConPTY; see conpty.go), which cmdio -// treats as a terminal but termenv can't recognize, the renderer is -// raised from Ascii to basic ANSI unless CLICOLOR=0 asks for no color -// (termenv.EnvNoColor). termenv's CI check is not honored there: it only -// guesses that CI output isn't a terminal, and this one is. -// -// On every other writer termenv's profile stands, including Ascii for -// CLICOLOR=0 or CI on a terminal. -// -// Callers still write rendered strings to w themselves; the renderer only -// carries the color profile. +// supports color. When it does not (NO_COLOR, TERM=dumb, or w is piped or +// redirected) the renderer is forced to the Ascii profile so every Style it +// mints emits no SGR escapes. Callers still write rendered strings to w +// themselves; the renderer only carries the color profile. func NewRenderer(ctx context.Context, w io.Writer) (*lipgloss.Renderer, bool) { color := SupportsColor(ctx, w) r := lipgloss.NewRenderer(w) - switch { - case !color: + if !color { r.SetColorProfile(termenv.Ascii) - case isMSYSPipe(w) && r.ColorProfile() == termenv.Ascii && !termenv.EnvNoColor(): - r.SetColorProfile(termenv.ANSI) } return r, color } diff --git a/libs/cmdio/color_test.go b/libs/cmdio/color_test.go index 4774852b507..404f0c12cdb 100644 --- a/libs/cmdio/color_test.go +++ b/libs/cmdio/color_test.go @@ -139,18 +139,6 @@ func TestNewRendererForcesAsciiWhenNoColor(t *testing.T) { assert.Equal(t, "hi", r.NewStyle().Bold(true).Render("hi")) } -func TestNewRendererKeepsTermenvProfile(t *testing.T) { - ctx := ttyContext(t) - - // cmdio says a FakeTTY supports color, but it isn't an MSYS2 pty pipe, so - // termenv's own decision (Ascii: it can't see a terminal) stands. The same - // holds for CLICOLOR=0 or CI on a real terminal. The MSYS2 pipe case is - // covered in conpty_windows_test.go. - r, color := cmdio.NewRenderer(ctx, cmdio.FakeTTY(&bytes.Buffer{})) - assert.True(t, color) - assert.Equal(t, termenv.Ascii, r.ColorProfile()) -} - func TestRenderFuncMap(t *testing.T) { ctx := ttyContext(t) fm := cmdio.RenderFuncMap(ctx) diff --git a/libs/cmdio/conpty_windows_test.go b/libs/cmdio/conpty_windows_test.go index 41a943c5d2e..614f06fce9d 100644 --- a/libs/cmdio/conpty_windows_test.go +++ b/libs/cmdio/conpty_windows_test.go @@ -5,9 +5,7 @@ import ( "os" "testing" - "github.com/charmbracelet/lipgloss" "github.com/databricks/cli/libs/env" - "github.com/muesli/termenv" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/sys/windows" @@ -76,26 +74,3 @@ func TestNewCapabilitiesMSYSPipeStdin(t *testing.T) { assert.False(t, c.stdinIsMSYSPipe) assert.True(t, c.SupportsPrompt()) } - -func TestNewRendererRaisesMSYSPipeToANSI(t *testing.T) { - // termenv reads NO_COLOR from the process environment. - t.Setenv("NO_COLOR", "") - // termenv can't recognize an MSYS2 pty pipe as a terminal, but cmdio - // does, so the renderer must still emit color there. - f := openNamedPipe(t, fmt.Sprintf("msys-%016x-pty0-to-master", os.Getpid()+1)) - ctx := InContext(t.Context(), &cmdIO{capabilities: Capabilities{stderrIsTTY: true}}) - r, color := NewRenderer(ctx, f) - assert.True(t, color) - assert.Equal(t, termenv.ANSI, r.ColorProfile()) - assert.NotEqual(t, "hi", r.NewStyle().Foreground(lipgloss.Color("10")).Render("hi")) -} - -func TestNewRendererMSYSPipeHonorsCLICOLOR(t *testing.T) { - // termenv reads NO_COLOR from the process environment. - t.Setenv("NO_COLOR", "") - t.Setenv("CLICOLOR", "0") - f := openNamedPipe(t, fmt.Sprintf("msys-%016x-pty1-to-master", os.Getpid()+3)) - ctx := InContext(t.Context(), &cmdIO{capabilities: Capabilities{stderrIsTTY: true}}) - r, _ := NewRenderer(ctx, f) - assert.Equal(t, termenv.Ascii, r.ColorProfile()) -} diff --git a/libs/cmdio/prompt_test.go b/libs/cmdio/prompt_test.go index 55151157cce..49aba4d680b 100644 --- a/libs/cmdio/prompt_test.go +++ b/libs/cmdio/prompt_test.go @@ -3,6 +3,8 @@ package cmdio import ( "bytes" "io" + "strings" + "sync" "testing" "time" @@ -20,17 +22,36 @@ func TestPromptModelNoColor(t *testing.T) { 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 it is running. It returns what was rendered to stderr. -func runWithKeys(t *testing.T, noColor bool, keys string, fn func(c *cmdIO) error) string { +// 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() - var out bytes.Buffer - c := NewTestIO(in, io.Discard, &out) + out := &syncBuffer{} + c := NewTestIO(in, io.Discard, out) c.capabilities.noColor = noColor go func() { - time.Sleep(200 * time.Millisecond) + 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)) @@ -45,9 +66,9 @@ func TestRunPromptNoColor(t *testing.T) { return err } - assert.Contains(t, runWithKeys(t, false, "x\r", run), ansiGreen) + assert.Contains(t, runWithKeys(t, false, "Name", "x\r", run), ansiGreen) - out := runWithKeys(t, true, "x\r", run) + out := runWithKeys(t, true, "Name", "x\r", run) assert.NotContains(t, out, ansiGreen) assert.Contains(t, out, ansiBold) } diff --git a/libs/cmdio/select_test.go b/libs/cmdio/select_test.go index ce34943d587..de19d2dbcae 100644 --- a/libs/cmdio/select_test.go +++ b/libs/cmdio/select_test.go @@ -30,11 +30,11 @@ func TestRunSelectNoColor(t *testing.T) { return err } - assert.Contains(t, runWithKeys(t, false, "\r", run), ansiBlue) + 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, "\r", run) + out := runWithKeys(t, true, "Pick", "\r", run) assert.NotContains(t, out, ansiBlue) assert.Contains(t, out, ansiBold) assert.Contains(t, out, ansiUnderline)