diff --git a/NOTICE b/NOTICE index fb51e5c0914..e8d106feb43 100644 --- a/NOTICE +++ b/NOTICE @@ -115,6 +115,10 @@ charmbracelet/bubbletea - https://github.com/charmbracelet/bubbletea Copyright (c) 2020-2025 Charmbracelet, Inc License - https://github.com/charmbracelet/bubbletea/blob/main/LICENSE +charmbracelet/colorprofile - https://github.com/charmbracelet/colorprofile +Copyright (c) 2020-2024 Charmbracelet, Inc +License - https://github.com/charmbracelet/colorprofile/blob/main/LICENSE + charmbracelet/huh - https://github.com/charmbracelet/huh Copyright (c) 2023 Charmbracelet, Inc. License - https://github.com/charmbracelet/huh/blob/main/LICENSE diff --git a/cmd/air/format.go b/cmd/air/format.go index d73c2d8a620..50a59fdd100 100644 --- a/cmd/air/format.go +++ b/cmd/air/format.go @@ -13,7 +13,6 @@ import ( "github.com/databricks/cli/libs/cmdio" "github.com/databricks/databricks-sdk-go/service/jobs" - "github.com/muesli/termenv" "go.yaml.in/yaml/v3" ) @@ -36,7 +35,7 @@ func hyperlink(ctx context.Context, out io.Writer, label, url string) string { if url == "" || !cmdio.SupportsColor(ctx, out) { return label } - return termenv.Hyperlink(url, label) + return cmdio.Hyperlink(url, label) } // reformatYAMLForDisplay re-renders a training-config YAML so multi-line strings diff --git a/cmd/air/list_tui.go b/cmd/air/list_tui.go index 6798244c621..9f5e37fb3b3 100644 --- a/cmd/air/list_tui.go +++ b/cmd/air/list_tui.go @@ -62,7 +62,7 @@ func renderListText(cmd *cobra.Command, f *runFetcher, limit int, activeOnly boo _, err = io.WriteString(out, emptyListMessage(activeOnly)) return err } - _, err = io.WriteString(out, staticListTable(r, rows, color)) + _, err = io.WriteString(r.Writer(out), staticListTable(r, rows, color)) return err } @@ -75,7 +75,7 @@ func emptyListMessage(activeOnly bool) string { // staticListTable renders the whole table once, with no selection — used when // piped or non-interactive. -func staticListTable(r *lipgloss.Renderer, rows []listRow, links bool) string { +func staticListTable(r *cmdio.Renderer, rows []listRow, links bool) string { if len(rows) == 0 { return "No runs found.\n" } @@ -131,7 +131,7 @@ type listModel struct { // detailHorizontalStep is how many columns ←/→ pan the detail pane. const detailHorizontalStep = 8 -func newListModel(r *lipgloss.Renderer, f *runFetcher, rows []listRow, links bool) listModel { +func newListModel(r *cmdio.Renderer, f *runFetcher, rows []listRow, links bool) listModel { vp := viewport.New(0, 0) vp.SetHorizontalStep(detailHorizontalStep) return listModel{ diff --git a/cmd/air/list_tui_render.go b/cmd/air/list_tui_render.go index 98b75347f1e..11658422c38 100644 --- a/cmd/air/list_tui_render.go +++ b/cmd/air/list_tui_render.go @@ -5,22 +5,23 @@ import ( "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" - "github.com/muesli/termenv" + + "github.com/databricks/cli/libs/cmdio" ) // DuBois dark-first palette. Neutrals (n7..n12) carry structure; the state // colors are reserved for the Status column. -const ( - colN7 = lipgloss.Color("#69696B") // gutter / dim - colN9 = lipgloss.Color("#ABABAE") // secondary values - colN11 = lipgloss.Color("#E0E0E3") // body - colN12 = lipgloss.Color("#F1F1F4") // selected text - colOverlay = lipgloss.Color("#1F1F23") // selected-row fill - colRunID = lipgloss.Color("#B7A8E8") // run id - colGreen = lipgloss.Color("#4CD964") // success - colAmber = lipgloss.Color("#E8B84A") // running / pending - colRed = lipgloss.Color("#EB6B6B") // failed - colBlue = lipgloss.Color("#6CA8F0") // MLflow link +var ( + colN7 cmdio.Color = lipgloss.Color("#69696B") // gutter / dim + colN9 cmdio.Color = lipgloss.Color("#ABABAE") // secondary values + colN11 cmdio.Color = lipgloss.Color("#E0E0E3") // body + colN12 cmdio.Color = lipgloss.Color("#F1F1F4") // selected text + colOverlay cmdio.Color = lipgloss.Color("#1F1F23") // selected-row fill + colRunID cmdio.Color = lipgloss.Color("#B7A8E8") // run id + colGreen cmdio.Color = lipgloss.Color("#4CD964") // success + colAmber cmdio.Color = lipgloss.Color("#E8B84A") // running / pending + colRed cmdio.Color = lipgloss.Color("#EB6B6B") // failed + colBlue cmdio.Color = lipgloss.Color("#6CA8F0") // MLflow link ) // mlflowColWidth is the MLflow column's width in a wide terminal, and the width @@ -30,10 +31,10 @@ const mlflowColWidth = 22 // listStyles renders the runs table. The renderer carries the color profile, so // styles render plain under --no-color / non-tty. type listStyles struct { - r *lipgloss.Renderer + r *cmdio.Renderer } -func newListStyles(r *lipgloss.Renderer) listStyles { +func newListStyles(r *cmdio.Renderer) listStyles { return listStyles{r: r} } @@ -257,7 +258,7 @@ func (s listStyles) renderRow(cols listCols, r listRow, selected, links bool) st if selected { base = base.Background(colOverlay) } - fg := func(c lipgloss.Color) lipgloss.Color { + fg := func(c cmdio.Color) cmdio.Color { if selected { return colN12 } @@ -324,7 +325,7 @@ func listRowStatus(r listRow) string { // characters (it may come from the server, or from a cache written before this // stripping existed), truncated to width, then padded with (background-only) // spaces so columns align even when the text is styled or hyperlinked. -func (s listStyles) cell(base lipgloss.Style, text string, width int, fg lipgloss.Color, right, underline bool, link string) string { +func (s listStyles) cell(base lipgloss.Style, text string, width int, fg cmdio.Color, right, underline bool, link string) string { text = truncate(stripControl(text), width) style := base.Foreground(fg) if underline { @@ -332,7 +333,7 @@ func (s listStyles) cell(base lipgloss.Style, text string, width int, fg lipglos } rendered := style.Render(text) if link != "" { - rendered = termenv.Hyperlink(link, rendered) + rendered = cmdio.Hyperlink(link, rendered) } gap := max(width-lipgloss.Width(text), 0) padStr := base.Render(strings.Repeat(" ", gap)) @@ -370,7 +371,7 @@ func mlflowLabel(r listRow) string { } // statusColor maps an air run status word to its data color. -func statusColor(status string) lipgloss.Color { +func statusColor(status string) cmdio.Color { switch status { case "SUCCESS": return colGreen diff --git a/cmd/air/list_tui_test.go b/cmd/air/list_tui_test.go index 19806e1d1ec..e712722da00 100644 --- a/cmd/air/list_tui_test.go +++ b/cmd/air/list_tui_test.go @@ -175,9 +175,12 @@ func TestListModelEnterOpensMLflowLogs(t *testing.T) { func TestListModelView(t *testing.T) { next, _ := testListModel(t).Update(tea.WindowSizeMsg{Width: 200, Height: 24}) - out := next.(listModel).View() + raw := next.(listModel).View() - assert.NotContains(t, out, "\x1b", "Ascii profile + no links should produce no escapes") + // On lipgloss v2 styles always render full color and the program + // downsamples at write time, so check text on the stripped view. + assert.NotContains(t, raw, "\x1b]8;;", "no links should produce no hyperlinks") + out := ansi.Strip(raw) for _, want := range []string{ "Run ID", "Experiment", "Status", "Started", "Duration", "Progress", "MLflow", "User", "Accelerators", "qwen-train", "● SUCCESS", "● RUNNING", "● FAILED", @@ -193,8 +196,15 @@ func TestListModelView(t *testing.T) { func TestStaticListTable(t *testing.T) { r, _ := cmdio.NewRenderer(cmdio.MockDiscard(t.Context()), io.Discard) - out := staticListTable(r, testListRows(), false) - + raw := staticListTable(r, testListRows(), false) + assert.NotContains(t, raw, "\x1b]8;;", "no links should produce no hyperlinks") + + // Write the table as renderListText does. The table carries styling (full + // color on lipgloss v2); r.Writer strips it for this color-less target. + var b strings.Builder + _, err := io.WriteString(r.Writer(&b), raw) + require.NoError(t, err) + out := b.String() assert.NotContains(t, out, "\x1b") assert.NotContains(t, out, "▸", "static table has no selection") for _, want := range []string{"Run ID", "1", "qwen-train", "1m 14s", "qwen-run-001", "8x H100", "Accelerators"} { @@ -253,12 +263,16 @@ func TestRenderRowStripsControlCharacters(t *testing.T) { } cols := computeListCols([]listRow{row}) - out := styles.renderRow(cols, row, false, false) + raw := styles.renderRow(cols, row, false, false) + // On lipgloss v2 styles always render full color (stripped at write + // time), so check the injected sequences on the raw output only. + for _, injected := range []string{"\x1b]0;", "\x1b[2J", "\x1b[31m", "\r"} { + assert.NotContains(t, raw, injected) + } + out := r.Render(raw) assert.Contains(t, out, "experiment") assert.Contains(t, out, "user@example.com") assert.Contains(t, out, "my-run") - assert.NotContains(t, out, "\x1b") - assert.NotContains(t, out, "\r") // Stripping happens before width is measured, so the columns stay aligned. assert.Equal(t, cols.experiment, lipgloss.Width(stripControl(row.Experiment))) } diff --git a/cmd/air/logs.go b/cmd/air/logs.go index 2a6d83f2e4c..9d419754146 100644 --- a/cmd/air/logs.go +++ b/cmd/air/logs.go @@ -257,6 +257,7 @@ func fetchLogs(ctx context.Context, w *databricks.WorkspaceClient, out io.Writer // printJobRunLink leaves the run link below the streamed output, including on failure. func printJobRunLink(ctx context.Context, out io.Writer, runURL string) { renderer, colorOn := cmdio.NewRenderer(ctx, out) + out = renderer.Writer(out) p := newPalette(renderer) fmt.Fprintln(out) fmt.Fprintln(out, "View job run at: "+link(colorOn, p.blue, runURL, runURL)) diff --git a/cmd/air/render.go b/cmd/air/render.go index b8f0043d906..97a338c54da 100644 --- a/cmd/air/render.go +++ b/cmd/air/render.go @@ -16,7 +16,6 @@ import ( "github.com/databricks/databricks-sdk-go/config" "github.com/databricks/databricks-sdk-go/httpclient" "github.com/databricks/databricks-sdk-go/service/jobs" - "github.com/muesli/termenv" "go.yaml.in/yaml/v3" ) @@ -55,7 +54,7 @@ type palette struct { red lipgloss.Style // failed status } -func newPalette(r *lipgloss.Renderer) palette { +func newPalette(r *cmdio.Renderer) palette { fg := func(hex string) lipgloss.Style { return r.NewStyle().Foreground(lipgloss.Color(hex)) } return palette{ n7: fg("#6E6E70"), @@ -98,6 +97,7 @@ func renderRunText(ctx context.Context, out io.Writer, w *databricks.WorkspaceCl // emits no SGR codes; combined with the link fallback below this gives clean, // un-escaped output under --no-color / NO_COLOR / piped stdout. renderer, colorOn := cmdio.NewRenderer(ctx, out) + out = renderer.Writer(out) p := newPalette(renderer) // The list detail pane (list_detail.go) renders through here without going @@ -487,7 +487,7 @@ func link(colorOn bool, style lipgloss.Style, label, url string) string { // through lipgloss.Render instead corrupts it: lipgloss re-styles each rune // and splits the "\x1b]8;;" introducer, so the terminal can't parse the // sequence and prints it literally. - return termenv.Hyperlink(url, style.Underline(true).Render(label)) + return cmdio.Hyperlink(url, style.Underline(true).Render(label)) } // statusStyle maps a run status to its accent color: green for success, red for diff --git a/cmd/air/render_test.go b/cmd/air/render_test.go index db1af3bfb4b..b74f0cd2b5b 100644 --- a/cmd/air/render_test.go +++ b/cmd/air/render_test.go @@ -12,15 +12,16 @@ import ( "github.com/databricks/databricks-sdk-go" "github.com/databricks/databricks-sdk-go/experimental/mocks" "github.com/databricks/databricks-sdk-go/service/jobs" - "github.com/muesli/termenv" "github.com/stretchr/testify/assert" ) -// asciiPalette returns a palette whose styles emit no escape codes, so render -// output is plain text and assertions stay readable. -func asciiPalette(t *testing.T) palette { +// asciiPalette returns a palette for a color-less target and a function that +// renders styled output the way it reaches that target (no escape codes). On +// lipgloss v2 styles always render full color and are stripped at write time, +// so tests assert on what reaches the target. +func asciiPalette(t *testing.T) (palette, func(string) string) { r, _ := cmdio.NewRenderer(cmdio.MockDiscard(t.Context()), io.Discard) - return newPalette(r) + return newPalette(r), r.Render } // A local HTTP server exercises the SDK export path without a live workspace. @@ -209,9 +210,9 @@ func TestSynthConfigYAML(t *testing.T) { } func TestColorizeConfigLine(t *testing.T) { - p := asciiPalette(t) - // Under the Ascii profile colorization adds no escapes, so each line is - // preserved verbatim (indentation included) regardless of its role. + p, plain := asciiPalette(t) + // Colorization only adds styling, so each line is preserved verbatim + // (indentation included) regardless of its role. for _, line := range []string{ "experiment_name: stream-latency-test", "compute:", @@ -220,7 +221,7 @@ func TestColorizeConfigLine(t *testing.T) { "command: |", ` for i in $(seq 1 10); do echo "step $i"; done`, } { - assert.Equal(t, line, colorizeConfigLine(p, line)) + assert.Equal(t, line, plain(colorizeConfigLine(p, line))) } } @@ -233,8 +234,8 @@ func TestIsConfigKey(t *testing.T) { } func TestRenderBox(t *testing.T) { - p := asciiPalette(t) - out := renderBox(p, configBoxTitle, "experiment_name: stream-latency-test\ncompute:") + p, plain := asciiPalette(t) + out := plain(renderBox(p, configBoxTitle, "experiment_name: stream-latency-test\ncompute:")) lines := strings.Split(out, "\n") // Title sits in the top border; corners are rounded; every row is the same width. @@ -250,8 +251,8 @@ func TestRenderBox(t *testing.T) { } func TestRenderFields(t *testing.T) { - p := asciiPalette(t) - out := renderFields(p, false, runView{ + p, plain := asciiPalette(t) + out := plain(renderFields(p, false, runView{ runID: "836121283738861", dashboardURL: "https://h.test/jobs/runs/836121283738861", status: "SUCCESS", @@ -265,7 +266,7 @@ func TestRenderFields(t *testing.T) { user: "user@example.com", accelerators: "1x A10", environment: "4", - }) + })) // Labels are padded to the longest ("Accelerators"), so values align. assert.Contains(t, out, "Run ID ") @@ -283,8 +284,8 @@ func TestRenderFields(t *testing.T) { } func TestRenderFieldsStripsControlCharacters(t *testing.T) { - p := asciiPalette(t) - out := renderFields(p, false, runView{ + p, plain := asciiPalette(t) + raw := renderFields(p, false, runView{ runID: "1", status: "SUCCESS", submitted: "2026-06-03 04:17 UTC", @@ -298,6 +299,12 @@ func TestRenderFieldsStripsControlCharacters(t *testing.T) { environment: "\x1b]8;;https://attacker.test/\x07databricks_ai_v6\x1b]8;;\x07", }) + // On lipgloss v2 styles always render full color (stripped at write + // time), so check the injected sequences on the raw output only. + for _, injected := range []string{"\x1b]0;", "\x1b[2J", "\x1b[31m", "\r"} { + assert.NotContains(t, raw, injected) + } + out := plain(raw) assert.Contains(t, out, "Experiment experiment") assert.Contains(t, out, "MLflow Run runname") assert.Contains(t, out, "User user@example.com") @@ -307,12 +314,15 @@ func TestRenderFieldsStripsControlCharacters(t *testing.T) { } func TestLink(t *testing.T) { - p := asciiPalette(t) + p, plain := asciiPalette(t) // Color off: the bare label, no URL. - assert.Equal(t, "label", link(false, p.blue, "label", "https://h.test")) - assert.Equal(t, "label", link(false, p.blue, "label", "")) + assert.Equal(t, "label", plain(link(false, p.blue, "label", "https://h.test"))) + assert.Equal(t, "label", plain(link(false, p.blue, "label", ""))) // With color on, the label is wrapped in an OSC 8 hyperlink to the url. - assert.Contains(t, link(true, p.blue, "label", "https://h.test"), termenv.Hyperlink("https://h.test", "label")) + linked := link(true, p.blue, "label", "https://h.test") + assert.True(t, strings.HasPrefix(linked, "\x1b]8;;https://h.test\x1b\\"), linked) + assert.True(t, strings.HasSuffix(linked, "\x1b]8;;\x1b\\"), linked) + assert.Equal(t, "label", plain(linked)) } func TestStatusStyleSelectors(t *testing.T) { diff --git a/cmd/air/run.go b/cmd/air/run.go index df2b54c8991..fac8315e6c7 100644 --- a/cmd/air/run.go +++ b/cmd/air/run.go @@ -395,6 +395,7 @@ func handleWatchResult(out io.Writer, profile, runID string, err error) error { // degrades to plain text on non-rich terminals. func printSubmitResult(ctx context.Context, out io.Writer, runIDStr, dashboardURL string) { renderer, colorOn := cmdio.NewRenderer(ctx, out) + out = renderer.Writer(out) p := newPalette(renderer) fmt.Fprintln(out, p.green.Render("Submitted workload with Job Run ID: "+runIDStr)) @@ -409,6 +410,7 @@ const logsDividerWidth = 60 // dropped on non-rich terminals; the rule characters are always printed. func printLogsDivider(ctx context.Context, out io.Writer) { renderer, _ := cmdio.NewRenderer(ctx, out) + out = renderer.Writer(out) p := newPalette(renderer) const label = " Logs " diff --git a/cmd/selftest/tui/huh.go b/cmd/selftest/tui/huh.go index cc42e92c209..973ea1fbadb 100644 --- a/cmd/selftest/tui/huh.go +++ b/cmd/selftest/tui/huh.go @@ -5,7 +5,6 @@ import ( "strconv" "github.com/charmbracelet/huh" - "github.com/charmbracelet/lipgloss" "github.com/databricks/cli/libs/apps/prompt" "github.com/databricks/cli/libs/cmdio" "github.com/spf13/cobra" @@ -74,23 +73,12 @@ so this checks the theme, not the production prompt flows.`, } cmdio.LogString(ctx, "answer: "+answer) - r, _ := cmdio.NewRenderer(ctx, cmd.ErrOrStderr()) - cmdio.LogString(ctx, fmt.Sprintf("dark_background=%t", r.HasDarkBackground())) + cmdio.LogString(ctx, fmt.Sprintf("dark_background=%t", cmdio.HasDarkBackground())) - // The blurred button colour is an AdaptiveColor, which hides the choice - // behind one value. lipgloss resolves it with the default renderer, the - // one the theme's styles render with, so print the side it picks. + // The appkit theme picks its colours for the background detected when + // it is built, so the blurred button is the colour for that background. fg := theme.Focused.BlurredButton.GetForeground() - if adaptive, ok := fg.(lipgloss.AdaptiveColor); ok { - dark := lipgloss.HasDarkBackground() - resolved := adaptive.Light - if dark { - resolved = adaptive.Dark - } - cmdio.LogString(ctx, fmt.Sprintf("blurred_button=%s (resolved, default renderer dark_background=%t)", resolved, dark)) - } else { - cmdio.LogString(ctx, fmt.Sprintf("blurred_button=%+v (not an AdaptiveColor, not resolved)", fg)) - } + cmdio.LogString(ctx, fmt.Sprintf("blurred_button=%v (resolved, dark_background=%t)", fg, cmdio.HasDarkBackground())) return nil }, } diff --git a/cmd/selftest/tui/profile.go b/cmd/selftest/tui/profile.go index d33f98a8265..5f287597a9f 100644 --- a/cmd/selftest/tui/profile.go +++ b/cmd/selftest/tui/profile.go @@ -37,7 +37,7 @@ func newProfileCmd() *cobra.Command { } { r, color := cmdio.NewRenderer(ctx, s.out) fmt.Fprintf(w, "%s: supports_color=%t profile=%s dark_background=%t\n", - s.name, color, r.ColorProfile().Name(), r.HasDarkBackground()) + s.name, color, r.Profile(), cmdio.HasDarkBackground()) } fmt.Fprintln(w, "env:") for _, name := range profileEnvVars { diff --git a/go.mod b/go.mod index 08b5a1c0f61..0704f04fcf5 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( github.com/Masterminds/semver/v3 v3.5.0 // MIT github.com/charmbracelet/bubbles v1.0.0 // MIT github.com/charmbracelet/bubbletea v1.3.10 // MIT + github.com/charmbracelet/colorprofile v0.4.1 // MIT github.com/charmbracelet/huh v1.0.0 // MIT github.com/charmbracelet/lipgloss v1.1.0 // MIT github.com/charmbracelet/x/ansi v0.11.9 // MIT @@ -54,7 +55,6 @@ require ( github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/catppuccin/go v0.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/charmbracelet/colorprofile v0.4.1 // indirect github.com/charmbracelet/x/cellbuf v0.0.15 // indirect github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect github.com/charmbracelet/x/term v0.2.2 // indirect diff --git a/libs/apps/prompt/prompt.go b/libs/apps/prompt/prompt.go index 915bc6b4ec3..9cef046c8f7 100644 --- a/libs/apps/prompt/prompt.go +++ b/libs/apps/prompt/prompt.go @@ -28,15 +28,24 @@ const DefaultAppDescription = "A Databricks App powered by AppKit" // Brand palette — tuned for legibility on both light and dark terminals. var ( - colorRed = lipgloss.Color("#E84040") // Bright Databricks red - colorGray = lipgloss.Color("#A1A1AA") // Light gray, legible on dark backgrounds - colorYellow = lipgloss.Color("#FFAB00") // Databricks yellow / amber - colorOrange = lipgloss.Color("#FF5F40") // Databricks orange (code blocks) - colorDimmed = lipgloss.AdaptiveColor{Light: "#A1A1AA", Dark: "#52525B"} + colorRed cmdio.Color = lipgloss.Color("#E84040") // Bright Databricks red + colorGray cmdio.Color = lipgloss.Color("#A1A1AA") // Light gray, legible on dark backgrounds + colorYellow cmdio.Color = lipgloss.Color("#FFAB00") // Databricks yellow / amber + colorOrange cmdio.Color = lipgloss.Color("#FF5F40") // Databricks orange (code blocks) + + colorDimmedLight cmdio.Color = lipgloss.Color("#A1A1AA") + colorDimmedDark cmdio.Color = lipgloss.Color("#52525B") ) // AppkitTheme returns a custom theme for appkit prompts. func AppkitTheme() *huh.Theme { + return appkitTheme(cmdio.HasDarkBackground()) +} + +// appkitTheme builds the theme for a known background, matching the shape of +// huh v2's ThemeFunc. +func appkitTheme(isDark bool) *huh.Theme { + lightDark := cmdio.LightDark(isDark) t := huh.ThemeBase() t.Focused.Title = t.Focused.Title.Foreground(colorRed).Bold(true) @@ -53,7 +62,7 @@ func AppkitTheme() *huh.Theme { BorderTop(false).BorderBottom(false). BorderForeground(colorYellow) t.Focused.BlurredButton = t.Focused.BlurredButton. - Foreground(colorDimmed). + Foreground(lightDark(colorDimmedLight, colorDimmedDark)). Background(lipgloss.Color("")). Bold(false) diff --git a/libs/apps/prompt/prompt_test.go b/libs/apps/prompt/prompt_test.go index 9e77eb76aca..b9116cd621d 100644 --- a/libs/apps/prompt/prompt_test.go +++ b/libs/apps/prompt/prompt_test.go @@ -555,3 +555,8 @@ func TestListSystemAIModelServicesWithoutAccess(t *testing.T) { require.NoError(t, err) assert.Equal(t, []ListItem{{ID: browseCatalogsID, Label: "Browse other catalogs..."}}, f.Items) } + +func TestAppkitThemeDimmedButtonFollowsBackground(t *testing.T) { + assert.Equal(t, colorDimmedDark, appkitTheme(true).Focused.BlurredButton.GetForeground()) + assert.Equal(t, colorDimmedLight, appkitTheme(false).Focused.BlurredButton.GetForeground()) +} diff --git a/libs/cmdio/color.go b/libs/cmdio/color.go index 4549b31feff..60fb3a15fa0 100644 --- a/libs/cmdio/color.go +++ b/libs/cmdio/color.go @@ -3,12 +3,10 @@ package cmdio import ( "context" "fmt" - "io" "strings" "text/template" "github.com/charmbracelet/lipgloss" - "github.com/muesli/termenv" ) // SGR (Select Graphic Rendition) escapes; see @@ -140,17 +138,3 @@ func PadLeft(s string, n int) string { } return s } - -// 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. -func NewRenderer(ctx context.Context, w io.Writer) (*lipgloss.Renderer, bool) { - color := SupportsColor(ctx, w) - r := lipgloss.NewRenderer(w) - if !color { - r.SetColorProfile(termenv.Ascii) - } - return r, color -} diff --git a/libs/cmdio/color_test.go b/libs/cmdio/color_test.go index 404f0c12cdb..54cdc067c0e 100644 --- a/libs/cmdio/color_test.go +++ b/libs/cmdio/color_test.go @@ -3,11 +3,15 @@ package cmdio_test import ( "bytes" "context" + "io" + "strings" "testing" + "github.com/charmbracelet/colorprofile" + "github.com/charmbracelet/lipgloss" "github.com/databricks/cli/libs/cmdio" - "github.com/muesli/termenv" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func ttyContext(t *testing.T) context.Context { @@ -128,15 +132,40 @@ func TestPadLeft(t *testing.T) { } } -func TestNewRendererForcesAsciiWhenNoColor(t *testing.T) { +func TestNewRendererStripsWhenNoColor(t *testing.T) { ctx := noColorContext(t) - // A bytes.Buffer is never a TTY, so the renderer must fall back to Ascii and - // its styles must render without SGR escapes. - r, color := cmdio.NewRenderer(ctx, &bytes.Buffer{}) + // A bytes.Buffer is never a TTY, so output through the renderer must carry + // no escapes, whether styles render color themselves or not. + var buf bytes.Buffer + r, color := cmdio.NewRenderer(ctx, &buf) assert.False(t, color) - assert.Equal(t, termenv.Ascii, r.ColorProfile()) - assert.Equal(t, "hi", r.NewStyle().Bold(true).Render("hi")) + assert.Equal(t, colorprofile.NoTTY, r.Profile()) + assert.Equal(t, "hi", r.Render(r.NewStyle().Bold(true).Render("hi"))) + + // Strings styled outside the renderer are stripped at write time too. + n, err := io.Copy(r.Writer(&buf), strings.NewReader("\x1b[1mbold\x1b[0m "+cmdio.Hyperlink("https://h.test", "link"))) + require.NoError(t, err) + assert.Equal(t, int64(len("\x1b[1mbold\x1b[0m "+cmdio.Hyperlink("https://h.test", "link"))), n) + assert.Equal(t, "bold link", buf.String()) +} + +func TestLightDark(t *testing.T) { + light, dark := lipgloss.Color("#ffffff"), lipgloss.Color("#000000") + assert.Equal(t, dark, cmdio.LightDark(true)(light, dark)) + assert.Equal(t, light, cmdio.LightDark(false)(light, dark)) +} + +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, colorprofile.Ascii, r.Profile()) } func TestRenderFuncMap(t *testing.T) { diff --git a/libs/cmdio/conpty_windows_test.go b/libs/cmdio/conpty_windows_test.go index 614f06fce9d..ced88b4a9c0 100644 --- a/libs/cmdio/conpty_windows_test.go +++ b/libs/cmdio/conpty_windows_test.go @@ -5,6 +5,8 @@ import ( "os" "testing" + "github.com/charmbracelet/colorprofile" + "github.com/charmbracelet/lipgloss" "github.com/databricks/cli/libs/env" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -74,3 +76,26 @@ 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, colorprofile.ANSI, r.Profile()) + 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, colorprofile.Ascii, r.Profile()) +} diff --git a/libs/cmdio/lipgloss.go b/libs/cmdio/lipgloss.go new file mode 100644 index 00000000000..5930b951573 --- /dev/null +++ b/libs/cmdio/lipgloss.go @@ -0,0 +1,142 @@ +package cmdio + +import ( + "context" + "io" + "strings" + "sync" + + "github.com/charmbracelet/colorprofile" + "github.com/charmbracelet/lipgloss" + "github.com/muesli/termenv" +) + +// This file owns how cmdio colors styled output: which color profile a writer +// gets (NewRenderer), stripping or downsampling at write time (Renderer.Writer +// and Renderer.Render), and the Color, LightDark and Hyperlink helpers whose +// lipgloss counterparts change shape in v2. Callers still use lipgloss.Style +// and lipgloss.Width directly. +// +// Callers write styled strings through Renderer.Writer because that is where +// lipgloss v2 applies the profile: v2 styles always emit full-color SGR. + +// Color is a color value accepted by lipgloss styles: lipgloss.TerminalColor +// on v1, image/color.Color on v2. Palettes and signatures use it instead of the +// concrete lipgloss.Color string type, which v2 turns into a function. +type Color = lipgloss.TerminalColor + +// Renderer carries the color profile for output written to a specific writer. +type Renderer struct { + lg *lipgloss.Renderer + profile colorprofile.Profile +} + +// NewRenderer returns a renderer targeting w, along with whether w supports +// color. The 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), styles minted from the renderer emit no SGR escapes and +// output written through Writer has all escape sequences stripped; +// - when w is an MSYS2 pty pipe (no ConPTY; see conpty.go), which cmdio +// treats as a terminal but termenv can't recognize, the profile 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. +func NewRenderer(ctx context.Context, w io.Writer) (*Renderer, bool) { + lg := lipgloss.NewRenderer(w) + if !SupportsColor(ctx, w) { + lg.SetColorProfile(termenv.Ascii) + return &Renderer{lg: lg, profile: colorprofile.NoTTY}, false + } + if isMSYSPipe(w) && lg.ColorProfile() == termenv.Ascii && !termenv.EnvNoColor() { + lg.SetColorProfile(termenv.ANSI) + } + return &Renderer{lg: lg, profile: colorprofileFromTermenv(lg.ColorProfile())}, true +} + +// NewStyle returns a style whose colors are rendered for this renderer. +func (r *Renderer) NewStyle() lipgloss.Style { + return r.lg.NewStyle() +} + +// Profile returns the color profile output is downsampled to. +func (r *Renderer) Profile() colorprofile.Profile { + return r.profile +} + +// Writer wraps w so styled strings written to it match the renderer's profile. +// When color is off it strips every escape sequence. When color is on it +// passes output through unchanged: on v1, styles minted from this renderer +// already render at its profile. (On v2 the writer always downsamples.) +// +// Stripping works per Write call, as colorprofile.Writer does, so an escape +// sequence split across two writes leaks its tail. Write whole styled strings. +func (r *Renderer) Writer(w io.Writer) io.Writer { + if r.profile != colorprofile.NoTTY { + return w + } + return &profileWriter{w: &colorprofile.Writer{Forward: w, Profile: r.profile}} +} + +// Render downsamples an already-styled string to the renderer's profile. +func (r *Renderer) Render(s string) string { + var b strings.Builder + _, _ = r.Writer(&b).Write([]byte(s)) + return b.String() +} + +// LightDark returns a function picking the light or dark variant of a color, +// mirroring lipgloss v2's LightDark. +func LightDark(isDark bool) func(light, dark Color) Color { + return func(light, dark Color) Color { + if isDark { + return dark + } + return light + } +} + +// HasDarkBackground reports whether the process's terminal has a dark +// background, queried at most once. It defaults to true when the terminal +// can't be queried. +var HasDarkBackground = sync.OnceValue(lipgloss.HasDarkBackground) + +// Hyperlink wraps label in an OSC 8 terminal hyperlink to url. Callers decide +// whether the target supports it; output written through a color-less +// Renderer.Writer has the escape stripped. +func Hyperlink(url, label string) string { + const osc8, st = "\x1b]8;;", "\x1b\\" + return osc8 + url + st + label + osc8 + st +} + +// colorprofileFromTermenv maps the termenv profile lipgloss v1 renders with to +// the colorprofile profile Renderer.Profile reports. +func colorprofileFromTermenv(p termenv.Profile) colorprofile.Profile { + switch p { + case termenv.TrueColor: + return colorprofile.TrueColor + case termenv.ANSI256: + return colorprofile.ANSI256 + case termenv.ANSI: + return colorprofile.ANSI + default: + return colorprofile.Ascii + } +} + +// profileWriter reports the caller's byte count on success. colorprofile.Writer +// returns the length of the rewritten output, which io.Copy and friends would +// treat as a short write whenever escapes were stripped. +type profileWriter struct { + w io.Writer +} + +func (p *profileWriter) Write(b []byte) (int, error) { + if _, err := p.w.Write(b); err != nil { + return 0, err + } + return len(b), nil +} diff --git a/libs/cmdio/lipgloss_test.go b/libs/cmdio/lipgloss_test.go new file mode 100644 index 00000000000..bf51feaa714 --- /dev/null +++ b/libs/cmdio/lipgloss_test.go @@ -0,0 +1,19 @@ +package cmdio + +import ( + "strings" + "testing" + + "github.com/charmbracelet/colorprofile" + "github.com/stretchr/testify/assert" +) + +func TestWriterPassesThroughWhenColorOn(t *testing.T) { + r := &Renderer{profile: colorprofile.ANSI} + styled := "\x1b[38;2;143;179;220mlabel\x1b[m " + Hyperlink("https://h.test", "docs") + + var b strings.Builder + _, err := r.Writer(&b).Write([]byte(styled)) + assert.NoError(t, err) + assert.Equal(t, styled, b.String()) +} diff --git a/libs/gorules/rule_lipgloss.go b/libs/gorules/rule_lipgloss.go new file mode 100644 index 00000000000..3c647412a66 --- /dev/null +++ b/libs/gorules/rule_lipgloss.go @@ -0,0 +1,27 @@ +package gorules + +import "github.com/quasilyte/go-ruleguard/dsl" + +// NoLipglossNewRenderer steers renderer construction through cmdio.NewRenderer, +// which decides color and its depth for the target writer +// (libs/cmdio/lipgloss.go). A bare lipgloss.NewRenderer bypasses that gate and +// reads color from process env, so it is only allowed inside libs/cmdio itself. +func NoLipglossNewRenderer(m dsl.Matcher) { + m.Match(`lipgloss.NewRenderer($*_)`). + Where(!m.File().PkgPath.Matches(`libs/cmdio$`)). + Report(`Do not call lipgloss.NewRenderer directly; use cmdio.NewRenderer(ctx, w) so color handling stays centralized`) +} + +// NoLipglossAdaptiveColor keeps light/dark selection explicit; lipgloss v2 +// removes AdaptiveColor. +func NoLipglossAdaptiveColor(m dsl.Matcher) { + m.Match(`lipgloss.AdaptiveColor{$*_}`). + Report(`Do not use lipgloss.AdaptiveColor; select the variant with cmdio.LightDark(isDark)`) +} + +// NoTermenvHyperlink routes OSC 8 links through cmdio.Hyperlink; lipgloss v2 +// no longer depends on termenv. +func NoTermenvHyperlink(m dsl.Matcher) { + m.Match(`termenv.Hyperlink($*_)`). + Report(`Do not use termenv.Hyperlink; use cmdio.Hyperlink`) +} diff --git a/libs/gorules/rule_lipgloss_renderer.go b/libs/gorules/rule_lipgloss_renderer.go deleted file mode 100644 index 7b50992fe4e..00000000000 --- a/libs/gorules/rule_lipgloss_renderer.go +++ /dev/null @@ -1,13 +0,0 @@ -package gorules - -import "github.com/quasilyte/go-ruleguard/dsl" - -// NoLipglossNewRenderer steers renderer construction through cmdio.NewRenderer, -// which forces the Ascii profile when the target writer has no color. A bare -// lipgloss.NewRenderer bypasses that gate and reads color from process env, so -// it is only allowed inside libs/cmdio itself (where the wrapper lives). -func NoLipglossNewRenderer(m dsl.Matcher) { - m.Match(`lipgloss.NewRenderer($*_)`). - Where(!m.File().PkgPath.Matches(`libs/cmdio$`)). - Report(`Do not call lipgloss.NewRenderer directly; use cmdio.NewRenderer(ctx, w) so color handling stays centralized`) -}