diff --git a/.nextchanges/cli/kitty-keyboard.md b/.nextchanges/cli/kitty-keyboard.md new file mode 100644 index 00000000000..80b0ed98468 --- /dev/null +++ b/.nextchanges/cli/kitty-keyboard.md @@ -0,0 +1 @@ +* Interactive prompts, selection lists and the pager enable the kitty keyboard protocol and modifyOtherKeys in terminals that support them, and restore the previous keyboard mode on exit. ([#7742](https://github.com/databricks/cli/pull/7742)) diff --git a/.nextchanges/cli/shift-enter.md b/.nextchanges/cli/shift-enter.md new file mode 100644 index 00000000000..f436f5fa077 --- /dev/null +++ b/.nextchanges/cli/shift-enter.md @@ -0,0 +1 @@ +* Shift+Enter submits prompts and selection lists in terminals that report it separately (Ghostty, kitty, WezTerm). ([#7742](https://github.com/databricks/cli/pull/7742)) diff --git a/.nextchanges/cli/terminal-replies.md b/.nextchanges/cli/terminal-replies.md new file mode 100644 index 00000000000..cfd3c11b2e8 --- /dev/null +++ b/.nextchanges/cli/terminal-replies.md @@ -0,0 +1 @@ +* Prompts and selection lists that exit before the terminal answers its startup queries no longer leave the answers, such as `^[[?2026;2$y`, at the shell prompt. ([#7742](https://github.com/databricks/cli/pull/7742)) diff --git a/cmd/air/list_detail_test.go b/cmd/air/list_detail_test.go index b53d492bc6c..8337938c0fc 100644 --- a/cmd/air/list_detail_test.go +++ b/cmd/air/list_detail_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/charmbracelet/lipgloss" + "charm.land/lipgloss/v2" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/databricks-sdk-go/service/jobs" "github.com/stretchr/testify/assert" diff --git a/cmd/air/list_tui.go b/cmd/air/list_tui.go index cdcb0cf1595..8e7a15f7eae 100644 --- a/cmd/air/list_tui.go +++ b/cmd/air/list_tui.go @@ -6,12 +6,13 @@ import ( "strconv" "strings" - "github.com/charmbracelet/bubbles/viewport" - tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" + "charm.land/bubbles/v2/viewport" + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" "github.com/databricks/cli/libs/browser" "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/teainput" "github.com/spf13/cobra" ) @@ -40,11 +41,13 @@ func renderListText(cmd *cobra.Command, f *runFetcher, limit int, activeOnly boo _, err := io.WriteString(out, emptyListMessage(activeOnly)) return err } - _, err = tea.NewProgram( + _, err = cmdio.NewTeaProgram( newListModel(r, f, first, color), + cmd.InOrStdin(), tea.WithContext(ctx), tea.WithInput(cmd.InOrStdin()), tea.WithOutput(out), + tea.WithColorProfile(r.Profile()), ).Run() if err != nil { return err @@ -132,7 +135,7 @@ type listModel struct { const detailHorizontalStep = 8 func newListModel(r *cmdio.Renderer, f *runFetcher, rows []listRow, links bool) listModel { - vp := viewport.New(0, 0) + vp := viewport.New() vp.SetHorizontalStep(detailHorizontalStep) return listModel{ rows: rows, @@ -195,8 +198,8 @@ func (m listModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.height = msg.Height m.width = msg.Width m.cols = layoutListCols(m.rows, m.width) - m.viewport.Width = msg.Width - m.viewport.Height = max(msg.Height-3, 1) + m.viewport.SetWidth(msg.Width) + m.viewport.SetHeight(max(msg.Height-3, 1)) m.viewport.SetContent(m.wrappedDetail()) m.offset = m.clampedOffset() return m.maybeFetch() @@ -238,10 +241,10 @@ func (m listModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.viewport.SetXOffset(0) return m, nil - case tea.KeyMsg: + case tea.KeyPressMsg: // Detail pane key handling. if m.mode == modeDetail { - switch msg.String() { + switch teainput.KeyName(msg) { case "esc", "q": m.mode = modeList return m, nil @@ -256,7 +259,7 @@ func (m listModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } // List pane key handling. - switch msg.String() { + switch teainput.KeyName(msg) { case "q", "ctrl+c": return m, tea.Quit case "esc": @@ -320,7 +323,7 @@ func (m listModel) wrappedDetail() string { if strings.IndexAny(plain, "╭│╰") == 0 || strings.Contains(plain, "://") { continue } - lines[i] = ansi.Wrap(line, m.viewport.Width, "") + lines[i] = ansi.Wrap(line, m.viewport.Width(), "") } return strings.Join(lines, "\n") } @@ -335,7 +338,7 @@ func (m listModel) clampedOffset() int { return max(offset, 0) } -func (m listModel) View() string { return m.render() } +func (m listModel) View() tea.View { return tea.NewView(m.render()) } func (m listModel) render() string { if m.mode == modeDetail { diff --git a/cmd/air/list_tui_render.go b/cmd/air/list_tui_render.go index 11658422c38..03a50516074 100644 --- a/cmd/air/list_tui_render.go +++ b/cmd/air/list_tui_render.go @@ -3,7 +3,7 @@ package aircmd import ( "strings" - "github.com/charmbracelet/lipgloss" + "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" "github.com/databricks/cli/libs/cmdio" diff --git a/cmd/air/list_tui_test.go b/cmd/air/list_tui_test.go index e712722da00..a47cab19b1c 100644 --- a/cmd/air/list_tui_test.go +++ b/cmd/air/list_tui_test.go @@ -8,10 +8,11 @@ import ( "strings" "testing" - tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/teainput" "github.com/databricks/cli/libs/env" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -34,7 +35,7 @@ func testListModel(t *testing.T) listModel { func key(t *testing.T, m listModel, s string) listModel { t.Helper() - next, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)}) + next, _ := m.Update(teainput.Type(s)) return next.(listModel) } @@ -92,17 +93,17 @@ func TestListModelPaging(t *testing.T) { m = next.(listModel) require.Equal(t, 4, m.visibleCount()) - page := func(k tea.KeyType) { - n, _ := m.Update(tea.KeyMsg{Type: k}) + page := func(name string) { + n, _ := m.Update(teainput.Press(name)) m = n.(listModel) } - page(tea.KeyRight) + page("right") assert.Equal(t, 4, m.cursor) - page(tea.KeyEnd) + page("end") assert.Equal(t, 9, m.cursor) - page(tea.KeyLeft) + page("left") assert.Equal(t, 5, m.cursor) - page(tea.KeyHome) + page("home") assert.Equal(t, 0, m.cursor) } @@ -153,7 +154,7 @@ func TestListModelMoreRowsEmptyKeepsPaging(t *testing.T) { func TestListModelQuit(t *testing.T) { m := testListModel(t) - _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("q")}) + _, cmd := m.Update(teainput.Press("q")) require.NotNil(t, cmd) assert.Equal(t, tea.QuitMsg{}, cmd()) } @@ -165,7 +166,7 @@ func TestListModelEnterOpensMLflowLogs(t *testing.T) { f := &runFetcher{ctx: ctx, w: newTestWorkspaceClient(t, "https://x.test")} m := newListModel(r, f, testListRows(), false) - _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + _, cmd := m.Update(teainput.Press("enter")) require.NotNil(t, cmd) cmd() @@ -175,7 +176,7 @@ func TestListModelEnterOpensMLflowLogs(t *testing.T) { func TestListModelView(t *testing.T) { next, _ := testListModel(t).Update(tea.WindowSizeMsg{Width: 200, Height: 24}) - raw := next.(listModel).View() + raw := next.(listModel).render() // On lipgloss v2 styles always render full color and the program // downsamples at write time, so check text on the stripped view. @@ -283,7 +284,7 @@ func TestListModelInfoKeyOpensDetail(t *testing.T) { m := newListModel(r, f, testListRows(), false) // `i` opens the detail pane in a loading state and dispatches a fetch (not run here). - next, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("i")}) + next, cmd := m.Update(teainput.Press("i")) m = next.(listModel) assert.Equal(t, modeDetail, m.mode) assert.True(t, m.detailLoading) @@ -299,7 +300,7 @@ func detailLoadingModel(t *testing.T) listModel { m := newListModel(r, f, testListRows(), false) next, _ := m.Update(tea.WindowSizeMsg{Width: 80, Height: 24}) m = next.(listModel) - next, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("i")}) + next, _ = m.Update(teainput.Press("i")) m = next.(listModel) require.Equal(t, modeDetail, m.mode) require.True(t, m.detailLoading) @@ -314,16 +315,16 @@ func TestListModelDetailPaneAndBack(t *testing.T) { m = next.(listModel) require.Equal(t, modeDetail, m.mode) assert.False(t, m.detailLoading) - view := m.View() + view := m.render() assert.Contains(t, view, "Run Details") assert.Contains(t, view, "hello from the detail pane") assert.Contains(t, view, "esc back") // esc returns to the list. - next, _ = m.Update(tea.KeyMsg{Type: tea.KeyEsc}) + next, _ = m.Update(teainput.Press("esc")) m = next.(listModel) assert.Equal(t, modeList, m.mode) - assert.Contains(t, m.View(), "Run ID") + assert.Contains(t, m.render(), "Run ID") } func TestListModelDetailPaneWrapsLongLines(t *testing.T) { @@ -333,7 +334,7 @@ func TestListModelDetailPaneWrapsLongLines(t *testing.T) { next, _ := m.Update(detailMsg{title: "Run Details", body: reason}) m = next.(listModel) - assert.Contains(t, m.View(), "ENDOFREASON", "the end of a long line must be visible, not clipped at the pane edge") + assert.Contains(t, m.render(), "ENDOFREASON", "the end of a long line must be visible, not clipped at the pane edge") // A narrower terminal re-wraps the same text. next, _ = m.Update(tea.WindowSizeMsg{Width: 30, Height: 24}) @@ -357,7 +358,7 @@ func TestListModelDetailPaneKeepsBoxRowsAndURLsWhole(t *testing.T) { assert.Equal(t, 2, m.viewport.TotalLineCount(), "box rows and URLs must not wrap") // ←/→ pans to the clipped end instead. - next, _ = m.Update(tea.KeyMsg{Type: tea.KeyRight}) + next, _ = m.Update(teainput.Press("right")) m = next.(listModel) assert.Positive(t, m.viewport.HorizontalScrollPercent()) } @@ -366,7 +367,7 @@ func TestListModelDetailLateMsgDropped(t *testing.T) { m := detailLoadingModel(t) // User escapes back to the list before the fetch resolves. - next, _ := m.Update(tea.KeyMsg{Type: tea.KeyEsc}) + next, _ := m.Update(teainput.Press("esc")) m = next.(listModel) require.Equal(t, modeList, m.mode) @@ -374,7 +375,7 @@ func TestListModelDetailLateMsgDropped(t *testing.T) { next, _ = m.Update(detailMsg{title: "Run Details", body: "late result"}) m = next.(listModel) assert.Equal(t, modeList, m.mode) - assert.NotContains(t, m.View(), "late result") + assert.NotContains(t, m.render(), "late result") } func TestTruncateFitsDisplayWidth(t *testing.T) { @@ -481,16 +482,17 @@ func TestListModelFitsTerminalWidth(t *testing.T) { next, _ := m.Update(tea.WindowSizeMsg{Width: 160, Height: 30}) m = next.(listModel) - lines := strings.Split(strings.TrimRight(m.View(), "\n"), "\n") + lines := strings.Split(strings.TrimRight(m.render(), "\n"), "\n") require.Len(t, lines, 3) // header, one row, hint for _, line := range lines[:2] { assert.LessOrEqual(t, ansi.StringWidth(line), 160) } assert.Contains(t, lines[0], "Accelerators") assert.Contains(t, lines[1], "8x H100") - // Experiment keeps its end, User its start. - assert.Contains(t, lines[1], " …tart/qwen-finetune-lora ") - assert.Contains(t, lines[1], " someone.with.a.long.nam… ") + // Experiment keeps its end, User its start. The row is styled, so match the text. + plain := ansi.Strip(lines[1]) + assert.Contains(t, plain, " …tart/qwen-finetune-lora ") + assert.Contains(t, plain, " someone.with.a.long.nam… ") // A lazily loaded page is laid out against the same width. next, _ = m.Update(moreRowsMsg{rows: rows[1:]}) @@ -509,7 +511,7 @@ func TestStaticListTableIgnoresTerminalWidth(t *testing.T) { lines := strings.Split(staticListTable(r, wideListRows(), false), "\n") assert.Equal(t, computeListCols(wideListRows()).tableWidth(), ansi.StringWidth(lines[0])) // The one-shot table still cuts a long Experiment at its end. - assert.Contains(t, lines[1], " /Users/someone.longname@example.com… ") + assert.Contains(t, ansi.Strip(lines[1]), " /Users/someone.longname@example.com… ") } func TestLayoutListCols(t *testing.T) { @@ -688,7 +690,7 @@ func TestRenderHidesColumns(t *testing.T) { assert.NotContains(t, row, "8x H100") assert.NotContains(t, row, "runs/04c41514fbb0", "a hidden MLflow column carries no hyperlink") } - assert.True(t, strings.HasPrefix(styles.renderRow(cols, rows[0], true, false), "▸")) + assert.True(t, strings.HasPrefix(ansi.Strip(styles.renderRow(cols, rows[0], true, false)), "▸")) } func TestListModelNarrowTerminalHidesColumns(t *testing.T) { @@ -699,7 +701,7 @@ func TestListModelNarrowTerminalHidesColumns(t *testing.T) { view := func(width int) []string { next, _ := m.Update(tea.WindowSizeMsg{Width: width, Height: 30}) m = next.(listModel) - lines := strings.Split(strings.TrimRight(m.View(), "\n"), "\n") + lines := strings.Split(strings.TrimRight(m.render(), "\n"), "\n") require.Len(t, lines, 4) // header, two rows, hint for _, line := range lines { assert.LessOrEqual(t, ansi.StringWidth(line), width, line) @@ -732,11 +734,11 @@ func TestListModelHintNamesHiddenColumnsWithFullLegend(t *testing.T) { m := newListModel(r, f, fullLabelListRows(), false) next, _ := m.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) m = next.(listModel) - lines := strings.Split(strings.TrimRight(m.View(), "\n"), "\n") + lines := strings.Split(strings.TrimRight(m.render(), "\n"), "\n") require.Len(t, lines, 4) assert.NotContains(t, lines[0], "Accelerators") assert.Contains(t, lines[0], "MLflow") - assert.Equal(t, hintLegend+" · row 1/2 · hidden: Accelerators", lines[3]) + assert.Equal(t, hintLegend+" · row 1/2 · hidden: Accelerators", ansi.Strip(lines[3])) assert.LessOrEqual(t, ansi.StringWidth(lines[3]), 120) } @@ -762,7 +764,7 @@ func TestListModelHintFitsNarrowTerminal(t *testing.T) { m.loadErr = errors.New("boom") } m.cursor = len(rows) - 1 - hint := m.renderHint() + hint := ansi.Strip(m.renderHint()) assert.LessOrEqual(t, ansi.StringWidth(hint), width, hint) // The row counter and paging state come first, so they survive // every step down. @@ -781,13 +783,13 @@ func TestListModelHintFitsNarrowTerminal(t *testing.T) { idle, loading := m, m idle.loading, idle.loadErr = false, nil loading.loading, loading.loadErr = true, nil - loadingHint := loading.renderHint() + loadingHint := ansi.Strip(loading.renderHint()) if strings.HasSuffix(loadingHint, "…") || strings.HasSuffix(hint, "…") { assert.Less(t, width, 48, hint) return } assert.True(t, strings.Contains(hint, "hidden: ") || strings.Contains(hint, "columns hidden"), hint) - assert.Equal(t, idle.renderHint(), strings.Replace(loadingHint, " (loading…)", "", 1)) + assert.Equal(t, ansi.Strip(idle.renderHint()), strings.Replace(loadingHint, " (loading…)", "", 1)) }) } } @@ -805,7 +807,7 @@ func TestListModelRelayoutsLoadedPageInNarrowTerminal(t *testing.T) { next, _ = m.Update(moreRowsMsg{rows: rows[:1]}) m = next.(listModel) assert.Equal(t, []string{"User", "Accelerators"}, m.cols.hiddenNames()) - for line := range strings.SplitSeq(strings.TrimRight(m.View(), "\n"), "\n") { + for line := range strings.SplitSeq(strings.TrimRight(m.render(), "\n"), "\n") { assert.LessOrEqual(t, ansi.StringWidth(line), 100, line) } } @@ -821,7 +823,7 @@ func TestListModelEnterOpensMLflowLogsWhenColumnHidden(t *testing.T) { m = next.(listModel) require.False(t, m.cols.shown(columnMLflow)) - _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + _, cmd := m.Update(teainput.Press("enter")) require.NotNil(t, cmd) cmd() assert.Contains(t, stderr.String(), "https://h/ml/experiments/E/runs/04c41514fbb0/logs") diff --git a/cmd/air/mlflow_test.go b/cmd/air/mlflow_test.go index 6edc209537a..419a00d28b3 100644 --- a/cmd/air/mlflow_test.go +++ b/cmd/air/mlflow_test.go @@ -5,7 +5,7 @@ import ( "net/http/httptest" "testing" - "github.com/charmbracelet/lipgloss" + "charm.land/lipgloss/v2" "github.com/databricks/databricks-sdk-go" "github.com/databricks/databricks-sdk-go/service/jobs" "github.com/stretchr/testify/assert" diff --git a/cmd/air/render.go b/cmd/air/render.go index 97a338c54da..5fc667d95bb 100644 --- a/cmd/air/render.go +++ b/cmd/air/render.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - "github.com/charmbracelet/lipgloss" + "charm.land/lipgloss/v2" "github.com/databricks/cli/libs/auth" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/databricks-sdk-go" diff --git a/cmd/air/render_test.go b/cmd/air/render_test.go index b74f0cd2b5b..11806c55a5e 100644 --- a/cmd/air/render_test.go +++ b/cmd/air/render_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/charmbracelet/lipgloss" + "charm.land/lipgloss/v2" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/databricks-sdk-go" "github.com/databricks/databricks-sdk-go/experimental/mocks" diff --git a/cmd/aitools/categorize.go b/cmd/aitools/categorize.go index aab075edb07..7fe5023c76d 100644 --- a/cmd/aitools/categorize.go +++ b/cmd/aitools/categorize.go @@ -9,7 +9,7 @@ import ( "os" "syscall" - "github.com/charmbracelet/huh" + "charm.land/huh/v2" "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/clicompat" "github.com/databricks/cli/libs/telemetry/protos" diff --git a/cmd/aitools/categorize_test.go b/cmd/aitools/categorize_test.go index cc79f24c6bd..3ab9e105632 100644 --- a/cmd/aitools/categorize_test.go +++ b/cmd/aitools/categorize_test.go @@ -18,7 +18,7 @@ import ( "testing" "time" - "github.com/charmbracelet/huh" + "charm.land/huh/v2" "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/clicompat" "github.com/databricks/cli/libs/telemetry/protos" diff --git a/cmd/aitools/funnel.go b/cmd/aitools/funnel.go index 00f0eadef30..7fc53b9eab1 100644 --- a/cmd/aitools/funnel.go +++ b/cmd/aitools/funnel.go @@ -5,7 +5,7 @@ import ( "errors" "slices" - "github.com/charmbracelet/huh" + "charm.land/huh/v2" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/cmdio" diff --git a/cmd/aitools/funnel_test.go b/cmd/aitools/funnel_test.go index dcbfe086135..d087956fe90 100644 --- a/cmd/aitools/funnel_test.go +++ b/cmd/aitools/funnel_test.go @@ -15,7 +15,7 @@ import ( "testing" "time" - "github.com/charmbracelet/huh" + "charm.land/huh/v2" "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/internal/testutil" "github.com/databricks/cli/libs/aitools/agents" diff --git a/cmd/aitools/install.go b/cmd/aitools/install.go index 62e6f43e2b8..540e8a51bcb 100644 --- a/cmd/aitools/install.go +++ b/cmd/aitools/install.go @@ -8,7 +8,7 @@ import ( "runtime" "strings" - "github.com/charmbracelet/huh" + "charm.land/huh/v2" "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/installer" @@ -509,7 +509,7 @@ func agentStateLabel(s agents.DisplayState) string { } } -func defaultPromptAgentSelection(_ context.Context, scope string, choices []agentChoice) ([]*agents.Agent, error) { +func defaultPromptAgentSelection(ctx context.Context, scope string, choices []agentChoice) ([]*agents.Agent, error) { options := make([]huh.Option[string], 0, len(choices)) byName := make(map[string]*agents.Agent, len(choices)) for _, c := range choices { @@ -518,12 +518,11 @@ func defaultPromptAgentSelection(_ context.Context, scope string, choices []agen } var selected []string - err := huh.NewMultiSelect[string](). + err := cmdio.RunHuhField(ctx, huh.NewMultiSelect[string](). Title(agentPickerTitle(scope)). Description("space to toggle, enter to install"). Options(options...). - Value(&selected). - Run() + Value(&selected)) if err != nil { return nil, promptError(err) } diff --git a/cmd/aitools/install_test.go b/cmd/aitools/install_test.go index c24b8cc9b3c..15e51bf17ce 100644 --- a/cmd/aitools/install_test.go +++ b/cmd/aitools/install_test.go @@ -16,7 +16,7 @@ import ( "runtime" "testing" - "github.com/charmbracelet/huh" + "charm.land/huh/v2" "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/installer" diff --git a/cmd/aitools/recovery_test.go b/cmd/aitools/recovery_test.go index 9bc9c95f1d9..163ed7949d1 100644 --- a/cmd/aitools/recovery_test.go +++ b/cmd/aitools/recovery_test.go @@ -15,7 +15,7 @@ import ( "syscall" "testing" - "github.com/charmbracelet/huh" + "charm.land/huh/v2" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/clicompat" diff --git a/cmd/aitools/scope.go b/cmd/aitools/scope.go index 20f5545f542..c0de9c14b5f 100644 --- a/cmd/aitools/scope.go +++ b/cmd/aitools/scope.go @@ -7,7 +7,7 @@ import ( "os" "path/filepath" - "github.com/charmbracelet/huh" + "charm.land/huh/v2" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/cmdio" @@ -86,14 +86,13 @@ func defaultPromptScopeSelection(ctx context.Context) (string, error) { projectLabel := "Project (" + projectPath + "/)\n Checked into the repo, shared with everyone on the project." var scope string - err = huh.NewSelect[string](). + err = cmdio.RunHuhField(ctx, huh.NewSelect[string](). Title("Where should skills be installed?"). Options( huh.NewOption(globalLabel, installer.ScopeGlobal), huh.NewOption(projectLabel, installer.ScopeProject), ). - Value(&scope). - Run() + Value(&scope)) if err != nil { return "", promptError(err) } @@ -363,15 +362,14 @@ func defaultPromptUpdateScopeSelection(ctx context.Context) ([]string, error) { bothLabel := "Both global and project" var scope string - err = huh.NewSelect[string](). + err = cmdio.RunHuhField(ctx, huh.NewSelect[string](). Title("Which installation should be updated?"). Options( huh.NewOption(globalLabel, installer.ScopeGlobal), huh.NewOption(projectLabel, installer.ScopeProject), huh.NewOption(bothLabel, scopeBoth), ). - Value(&scope). - Run() + Value(&scope)) if err != nil { return nil, promptError(err) } @@ -399,14 +397,13 @@ func defaultPromptUninstallScopeSelection(ctx context.Context) (string, error) { projectLabel := "Project (" + projectPath + "/)" var scope string - err = huh.NewSelect[string](). + err = cmdio.RunHuhField(ctx, huh.NewSelect[string](). Title("Which installation should be uninstalled?"). Options( huh.NewOption(globalLabel, installer.ScopeGlobal), huh.NewOption(projectLabel, installer.ScopeProject), ). - Value(&scope). - Run() + Value(&scope)) if err != nil { return "", promptError(err) } diff --git a/cmd/apps/init.go b/cmd/apps/init.go index ad69d79bd19..7b4fa30e430 100644 --- a/cmd/apps/init.go +++ b/cmd/apps/init.go @@ -15,7 +15,7 @@ import ( "strings" "text/template" - "github.com/charmbracelet/huh" + "charm.land/huh/v2" "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/installer" @@ -450,7 +450,7 @@ func findMissingBindingValues(resources []manifest.Resource, values, authModes m // promptForBindingValue asks for a value of a binding field and stores it in values. func promptForBindingValue(ctx context.Context, mv missingBindingValue, values map[string]string) error { var value string - err := huh.NewInput(). + err := cmdio.RunHuhField(ctx, huh.NewInput(). Title(fmt.Sprintf("%s %s", mv.resource.Alias, mv.field)). Description(fmt.Sprintf("Needed by the %s binding in databricks.yml", mv.yamlKey)). Value(&value). @@ -460,8 +460,7 @@ func promptForBindingValue(ctx context.Context, mv missingBindingValue, values m } return nil }). - WithTheme(prompt.AppkitTheme()). - Run() + WithTheme(prompt.AppkitTheme())) if err != nil { return err } @@ -582,14 +581,13 @@ func promptForPluginsAndDeps(ctx context.Context, m *manifest.Manifest, preSelec } var selected []string - err := huh.NewMultiSelect[string](). + err := cmdio.RunHuhField(ctx, huh.NewMultiSelect[string](). Title("Select features"). Description("space to toggle, enter to confirm"). Options(options...). Value(&selected). Height(8). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return nil, err } @@ -650,12 +648,11 @@ func promptForPluginsAndDeps(ctx context.Context, m *manifest.Manifest, preSelec // Step 4: Description config.Description = prompt.DefaultAppDescription - err := huh.NewInput(). + err := cmdio.RunHuhField(ctx, huh.NewInput(). Title("Description"). Placeholder(prompt.DefaultAppDescription). Value(&config.Description). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return nil, err } @@ -692,7 +689,7 @@ func promptForAuthModes(ctx context.Context, resources []manifest.Resource, them const mixed = "mixed" appMode := generator.AuthModeSP - err := huh.NewSelect[string](). + err := cmdio.RunHuhField(ctx, huh.NewSelect[string](). Title("How should the app access resources?"). Options( huh.NewOption("Service principal", generator.AuthModeSP), @@ -700,8 +697,7 @@ func promptForAuthModes(ctx context.Context, resources []manifest.Resource, them huh.NewOption("Mixed (choose per resource)", mixed), ). Value(&appMode). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return nil, err } @@ -711,7 +707,7 @@ func promptForAuthModes(ctx context.Context, resources []manifest.Resource, them mode := appMode if appMode == mixed { mode = generator.AuthModeSP - err := huh.NewSelect[string](). + err := cmdio.RunHuhField(ctx, huh.NewSelect[string](). Title(fmt.Sprintf("How should the app access %s?", r.Alias)). Options( huh.NewOption("On behalf of user", generator.AuthModeOBO), @@ -719,8 +715,7 @@ func promptForAuthModes(ctx context.Context, resources []manifest.Resource, them huh.NewOption("Both", generator.AuthModeBoth), ). Value(&mode). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return nil, err } @@ -755,12 +750,11 @@ func promptForResource(ctx context.Context, r manifest.Resource, theme prompt.Th if fn, ok := prompt.GetPromptFunc(r.Type); ok { if !required { var configure bool - err := huh.NewConfirm(). + err := cmdio.RunHuhField(ctx, huh.NewConfirm(). Title(fmt.Sprintf("Configure %s?", r.Alias)). - Description(r.Description + " (optional)"). + Description(r.Description+" (optional)"). Value(&configure). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return nil, err } @@ -793,7 +787,7 @@ func promptForResource(ctx context.Context, r manifest.Resource, theme prompt.Th }) } - if err := input.WithTheme(theme).Run(); err != nil { + if err := cmdio.RunHuhField(ctx, input.WithTheme(theme)); err != nil { return nil, err } diff --git a/cmd/fs/upload_progress.go b/cmd/fs/upload_progress.go index a186fb5fa76..6030d87a1d6 100644 --- a/cmd/fs/upload_progress.go +++ b/cmd/fs/upload_progress.go @@ -7,7 +7,7 @@ import ( "sync" "time" - "github.com/charmbracelet/lipgloss" + "charm.land/lipgloss/v2" "github.com/databricks/cli/libs/cmdio" files "github.com/databricks/sdk-go/files/v2" diff --git a/cmd/fs/upload_progress_test.go b/cmd/fs/upload_progress_test.go index 2786cf0fd40..cbd8dbe5f6b 100644 --- a/cmd/fs/upload_progress_test.go +++ b/cmd/fs/upload_progress_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/charmbracelet/lipgloss" + "charm.land/lipgloss/v2" ) func TestRenderBarWidth(t *testing.T) { diff --git a/cmd/selftest/tui/colors.go b/cmd/selftest/tui/colors.go index 3415dbf0ce3..66babf8402b 100644 --- a/cmd/selftest/tui/colors.go +++ b/cmd/selftest/tui/colors.go @@ -7,7 +7,7 @@ import ( "strconv" "strings" - "github.com/charmbracelet/lipgloss" + "charm.land/lipgloss/v2" "github.com/databricks/cli/libs/cmdio" "github.com/spf13/cobra" ) diff --git a/cmd/selftest/tui/huh.go b/cmd/selftest/tui/huh.go index 84235ceca4a..a443b946c18 100644 --- a/cmd/selftest/tui/huh.go +++ b/cmd/selftest/tui/huh.go @@ -2,10 +2,11 @@ package tui import ( "fmt" + "os" "strconv" - "github.com/charmbracelet/huh" - "github.com/charmbracelet/lipgloss" + "charm.land/huh/v2" + "charm.land/lipgloss/v2" "github.com/databricks/cli/libs/apps/prompt" "github.com/databricks/cli/libs/cmdio" "github.com/spf13/cobra" @@ -57,7 +58,7 @@ so this checks the theme, not the production prompt flows.`, group = huh.NewMultiSelect[string]().Title("Pick items").Options(options...).Value(&picked) } - if err := huh.NewForm(huh.NewGroup(group)).WithTheme(theme).Run(); err != nil { + if err := cmdio.RunHuhForm(ctx, huh.NewForm(huh.NewGroup(group)).WithTheme(theme)); err != nil { return err } @@ -74,22 +75,14 @@ so this checks the theme, not the production prompt flows.`, } cmdio.LogString(ctx, "answer: "+answer) - 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. - fg := theme.Focused.BlurredButton.GetForeground() - if adaptive, ok := fg.(lipgloss.AdaptiveColor); ok { - dark := cmdio.HasDarkBackground() - resolved := adaptive.Light - if dark { - resolved = adaptive.Dark - } - cmdio.LogString(ctx, fmt.Sprintf("blurred_button=%s (resolved, dark_background=%t)", resolved, dark)) - } else { - cmdio.LogString(ctx, fmt.Sprintf("blurred_button=%+v (not an AdaptiveColor, not resolved)", fg)) - } + // The appkit theme is a huh.ThemeFunc, so its colours depend on the + // background, queried once here for the probe. The blurred button is + // the colour the theme picks for that background. + dark := lipgloss.HasDarkBackground(os.Stdin, os.Stdout) + cmdio.LogString(ctx, fmt.Sprintf("dark_background=%t", dark)) + fg := theme.Theme(dark).Focused.BlurredButton.GetForeground() + r, g, b, _ := fg.RGBA() + cmdio.LogString(ctx, fmt.Sprintf("blurred_button=#%02x%02x%02x (resolved, dark_background=%t)", r>>8, g>>8, b>>8, dark)) return nil }, } diff --git a/cmd/selftest/tui/keys.go b/cmd/selftest/tui/keys.go index 4ff18a28519..d18ce6bba18 100644 --- a/cmd/selftest/tui/keys.go +++ b/cmd/selftest/tui/keys.go @@ -8,8 +8,9 @@ import ( "os" "time" - tea "github.com/charmbracelet/bubbletea" + tea "charm.land/bubbletea/v2" "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/teainput" "github.com/spf13/cobra" "golang.org/x/term" ) @@ -30,14 +31,12 @@ type keysModel struct { func (m *keysModel) Init() tea.Cmd { return nil } func (m *keysModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { - key, ok := msg.(tea.KeyMsg) + ev, ok := teainput.Decode(msg) if !ok { return m, nil } - line := fmt.Sprintf("key=%q type=%d runes=%q alt=%t paste=%t", - key.String(), key.Type, string(key.Runes), key.Alt, key.Paste) - fmt.Fprint(m.out, line+m.eol) - if key.Type == tea.KeyCtrlC { + fmt.Fprint(m.out, describeKey(msg, ev)+m.eol) + if ev.Key == "ctrl+c" { m.ctrlC++ if m.ctrlC >= keysExitCtrlC { return m, tea.Quit @@ -46,7 +45,17 @@ func (m *keysModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } -func (m *keysModel) View() string { return "" } +func (m *keysModel) View() tea.View { return tea.NewView("") } + +// describeKey prints the message bubbletea delivered next to the event the +// models see, so a decoding difference shows on the same line. +func describeKey(msg tea.Msg, ev teainput.Event) string { + if k, ok := msg.(tea.KeyPressMsg); ok { + return fmt.Sprintf("key=%q code=%U mod=%d text=%q decoded=%q text=%q", + k.String(), k.Code, k.Mod, k.Text, ev.Key, ev.Text) + } + return fmt.Sprintf("paste text=%q decoded=%q", ev.Text, ev.Key) +} func newKeysCmd() *cobra.Command { var ( diff --git a/cmd/selftest/tui/profile.go b/cmd/selftest/tui/profile.go index 5f287597a9f..633b5ff801a 100644 --- a/cmd/selftest/tui/profile.go +++ b/cmd/selftest/tui/profile.go @@ -3,7 +3,9 @@ package tui import ( "fmt" "io" + "os" + "charm.land/lipgloss/v2" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/env" "github.com/spf13/cobra" @@ -37,7 +39,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.Profile(), cmdio.HasDarkBackground()) + s.name, color, r.Profile(), lipgloss.HasDarkBackground(os.Stdin, os.Stdout)) } fmt.Fprintln(w, "env:") for _, name := range profileEnvVars { diff --git a/go.mod b/go.mod index 0704f04fcf5..c2665ddd7f4 100644 --- a/go.mod +++ b/go.mod @@ -5,14 +5,14 @@ go 1.27.0 toolchain go1.27.4 require ( + charm.land/bubbles/v2 v2.2.1 // MIT + charm.land/bubbletea/v2 v2.1.1 // MIT + charm.land/huh/v2 v2.0.3 // MIT + charm.land/lipgloss/v2 v2.1.0 // MIT dario.cat/mergo v1.0.2 // BSD-3-Clause github.com/BurntSushi/toml v1.6.0 // MIT 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/colorprofile v0.4.3 // MIT github.com/charmbracelet/x/ansi v0.11.9 // MIT github.com/databricks/databricks-sdk-go v0.200.0 // Apache-2.0 github.com/databricks/sdk-go/auth v0.2.0 // Apache-2.0 @@ -55,14 +55,16 @@ 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/x/cellbuf v0.0.15 // indirect + github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect + github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/charmbracelet/x/termios v0.1.1 // indirect + github.com/charmbracelet/x/windows v0.2.2 // indirect github.com/clipperhouse/displaywidth v0.11.0 // indirect github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/danieljoos/wincred v1.2.3 // indirect github.com/dustin/go-humanize v1.0.1 // indirect - github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect @@ -78,15 +80,13 @@ require ( github.com/klauspost/compress v1.20.3 // indirect github.com/kr/text v0.2.0 // indirect github.com/lucasb-eyer/go-colorful v1.4.1 // indirect - github.com/mattn/go-localereader v0.0.1 // indirect github.com/mattn/go-runewidth v0.0.31 // indirect github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect - github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect github.com/muesli/cancelreader v0.2.2 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/stretchr/objx v0.5.3 // indirect - github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + github.com/xo/terminfo v1.0.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect go.opentelemetry.io/otel v1.47.0 // indirect diff --git a/go.sum b/go.sum index 78540bfb6db..d410ed57bf5 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,11 @@ +charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU= +charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc= +charm.land/bubbletea/v2 v2.1.1 h1:S1S9l37pCZGrj1JexBcr9x4Nr3MVeM42InqCYM/tDpU= +charm.land/bubbletea/v2 v2.1.1/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU= +charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU= +charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc= +charm.land/lipgloss/v2 v2.1.0 h1:RLCNLhSQST+NPOmvUSbRWZ3UFOXsf3ZXFmJ5E/2tHEU= +charm.land/lipgloss/v2 v2.1.0/go.mod h1:wwfOgrNqUA9yjL8nmG6BIO0qQnmkEgJ8ISptbme83gI= cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM= cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= @@ -16,40 +24,36 @@ github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= -github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY= -github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl8ZBcNLgcbrw8E= +github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o= +github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w= github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY= github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc= -github.com/charmbracelet/bubbles v1.0.0/go.mod h1:9d/Zd5GdnauMI5ivUIVisuEm3ave1XwXtD1ckyV6r3E= -github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= -github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= -github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk= -github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk= -github.com/charmbracelet/huh v1.0.0 h1:wOnedH8G4qzJbmhftTqrpppyqHakl/zbbNdXIWJyIxw= -github.com/charmbracelet/huh v1.0.0/go.mod h1:5YVc+SlZ1IhQALxRPpkGwwEKftN/+OlJlnJYlDRFqN4= -github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= -github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= +github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= +github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= +github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 h1:hISLzUbwcvJbGoNR6A3L/TpguRRnACBmZOee8LcHLJw= +github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio= github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM= github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= -github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI= -github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q= -github.com/charmbracelet/x/conpty v0.1.0 h1:4zc8KaIcbiL4mghEON8D72agYtSeIgq8FSThSPQIb+U= -github.com/charmbracelet/x/conpty v0.1.0/go.mod h1:rMFsDJoDwVmiYM10aD4bH2XiRgwI7NYJtQgl5yskjEQ= +github.com/charmbracelet/x/conpty v0.1.1 h1:s1bUxjoi7EpqiXysVtC+a8RrvPPNcNvAjfi4jxsAuEs= +github.com/charmbracelet/x/conpty v0.1.1/go.mod h1:OmtR77VODEFbiTzGE9G1XiRJAga6011PIm4u5fTNZpk= github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA= github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0= -github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ= -github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= +github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA= +github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I= +github.com/charmbracelet/x/exp/ordered v0.1.0 h1:55/qLwjIh0gL0Vni+QAWk7T/qRVP6sBf+2agPBgnOFE= +github.com/charmbracelet/x/exp/ordered v0.1.0/go.mod h1:5UHwmG+is5THxMyCJHNPCn2/ecI07aKNrW+LcResjJ8= github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4= github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ= github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY= github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo= -github.com/charmbracelet/x/xpty v0.1.2 h1:Pqmu4TEJ8KeA9uSkISKMU3f+C1F6OGBn8ABuGlqCbtI= -github.com/charmbracelet/x/xpty v0.1.2/go.mod h1:XK2Z0id5rtLWcpeNiMYBccNNBrP2IJnzHI0Lq13Xzq4= +github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM= +github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k= +github.com/charmbracelet/x/xpty v0.1.3 h1:eGSitii4suhzrISYH50ZfufV3v085BXQwIytcOdFSsw= +github.com/charmbracelet/x/xpty v0.1.3/go.mod h1:poPYpWuLDBFCKmKLDnhBp51ATa0ooD8FhypRwEFtH3Y= github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= @@ -74,8 +78,6 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= -github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -128,14 +130,10 @@ github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBql github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= -github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= -github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= github.com/mattn/go-runewidth v0.0.31 h1:1oCV4ReTlosDBc6rYRw5cL8S/4y8iv5oRl4SJ5IBgwo= github.com/mattn/go-runewidth v0.0.31/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8= github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4= github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE= -github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= -github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= @@ -178,8 +176,8 @@ github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWD github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/tailscale/hujson v0.0.0-20250605163823-992244df8c5a h1:a6TNDN9CgG+cYjaeN8l2mc4kSz2iMiCDQxPEyltUV/I= github.com/tailscale/hujson v0.0.0-20250605163823-992244df8c5a/go.mod h1:EbW0wDK/qEUYI0A5bqq0C2kF8JTQwWONmGDBbzsxxHo= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY= +github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs= github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= @@ -215,7 +213,6 @@ golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= -golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= diff --git a/internal/build/notice_test.go b/internal/build/notice_test.go index abe1d39287d..c56dbe68d5e 100644 --- a/internal/build/notice_test.go +++ b/internal/build/notice_test.go @@ -17,6 +17,11 @@ var moduleToGitHub = map[string]string{ "gopkg.in/ini.v1": "go-ini/ini", "go.yaml.in/yaml/v3": "yaml/go-yaml", "dario.cat/mergo": "darccio/mergo", + + "charm.land/bubbles/v2": "charmbracelet/bubbles", + "charm.land/bubbletea/v2": "charmbracelet/bubbletea", + "charm.land/huh/v2": "charmbracelet/huh", + "charm.land/lipgloss/v2": "charmbracelet/lipgloss", } // Modules excluded from NOTICE requirements (Databricks-owned). diff --git a/libs/apps/prompt/prompt.go b/libs/apps/prompt/prompt.go index 411bba7747c..35b90e7800e 100644 --- a/libs/apps/prompt/prompt.go +++ b/libs/apps/prompt/prompt.go @@ -11,8 +11,8 @@ import ( "strconv" "strings" - "github.com/charmbracelet/huh" - "github.com/charmbracelet/lipgloss" + "charm.land/huh/v2" + "charm.land/lipgloss/v2" "github.com/databricks/cli/libs/apps/manifest" "github.com/databricks/cli/libs/cmdctx" "github.com/databricks/cli/libs/cmdio" @@ -38,18 +38,18 @@ var ( ) // Theme is the huh theme handed to appkit prompt forms and fields. -type Theme = *huh.Theme +type Theme = huh.Theme // AppkitTheme returns a custom theme for appkit prompts. func AppkitTheme() Theme { - return appkitStyles(cmdio.HasDarkBackground()) + return huh.ThemeFunc(appkitStyles) } // appkitStyles builds the appkit styles on top of huh's base theme for a known -// background, matching the shape of huh v2's ThemeFunc. -func appkitStyles(isDark bool) *huh.Theme { +// background. +func appkitStyles(isDark bool) *huh.Styles { lightDark := cmdio.LightDark(isDark) - t := huh.ThemeBase() + t := huh.ThemeBase(isDark) t.Focused.Title = t.Focused.Title.Foreground(colorRed).Bold(true) t.Focused.Description = t.Focused.Description.Foreground(colorGray) @@ -309,7 +309,7 @@ func PromptForProjectName(ctx context.Context, outputDir string) (string, error) theme := AppkitTheme() var name string - err := huh.NewInput(). + err := cmdio.RunHuhField(ctx, huh.NewInput(). Title("App name"). Description("lowercase letters, numbers, hyphens (max 26 chars)"). Placeholder("my-app"). @@ -317,8 +317,7 @@ func PromptForProjectName(ctx context.Context, outputDir string) (string, error) Validate(func(s string) error { return validateProjectNameForPrompt(s, outputDir) }). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return "", err } @@ -340,15 +339,14 @@ func PromptScaffoldLocation(ctx context.Context, basename string) (bool, error) ) choice := locSubdir - err := huh.NewSelect[string](). + err := cmdio.RunHuhField(ctx, huh.NewSelect[string](). Title("Where should we create the app?"). Options( huh.NewOption("Create a new subdirectory", locSubdir), huh.NewOption(fmt.Sprintf("Use the current directory (%q)", basename), locCurrent), ). Value(&choice). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return false, err } @@ -366,12 +364,11 @@ func PromptForDeployAndRun(ctx context.Context) (deploy bool, runMode RunMode, e theme := AppkitTheme() // Deploy after creation? - err = huh.NewConfirm(). + err = cmdio.RunHuhField(ctx, huh.NewConfirm(). Title("Deploy after creation?"). Description("Run 'databricks apps deploy' after setup"). Value(&deploy). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return false, RunModeNone, err } @@ -392,13 +389,12 @@ func PromptForDeployAndRun(ctx context.Context) (deploy bool, runMode RunMode, e // Run the app? runModeStr := string(RunModeNone) - err = huh.NewSelect[string](). + err = cmdio.RunHuhField(ctx, huh.NewSelect[string](). Title("Run the app after creation?"). Description("Choose how to start the development server"). Options(runOptions...). Value(&runModeStr). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return false, RunModeNone, err } @@ -436,14 +432,13 @@ func promptFromListWithLabel(ctx context.Context, title, emptyMessage string, it labels[it.ID] = it.Label } var selected string - err := huh.NewSelect[string](). + err := cmdio.RunHuhField(ctx, huh.NewSelect[string](). Title(title). Description(fmt.Sprintf("%d available — / to filter", len(items))). Options(options...). Value(&selected). Height(8). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return "", "", err } @@ -502,13 +497,12 @@ func getFetcherByKey(ctx context.Context, cacheKey, spinnerMsg string, fallbackC func promptManualInput(ctx context.Context, title string, prefetchedLabels []string) (string, error) { theme := AppkitTheme() var value string - err := huh.NewInput(). + err := cmdio.RunHuhField(ctx, huh.NewInput(). Title(title). Placeholder("Type a name or ID"). Suggestions(prefetchedLabels). Value(&value). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return "", err } @@ -559,14 +553,13 @@ func promptFromPagedFetcher(ctx context.Context, title, emptyMessage string, fet } var selected string - err := huh.NewSelect[string](). + err := cmdio.RunHuhField(ctx, huh.NewSelect[string](). Title(title). Description(desc). Options(options...). Value(&selected). Height(8). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return "", "", err } @@ -1219,14 +1212,13 @@ func PromptForAppSelection(ctx context.Context, title string) (string, error) { } var selected string - err = huh.NewSelect[string](). + err = cmdio.RunHuhField(ctx, huh.NewSelect[string](). Title(title). Description(fmt.Sprintf("%d apps found — / to filter", len(existingApps))). Options(options...). Value(&selected). Height(8). - WithTheme(theme). - Run() + WithTheme(theme)) if err != nil { return "", err } diff --git a/libs/cmdio/cmdiotest/pin_queries_test.go b/libs/cmdio/cmdiotest/pin_queries_test.go index b1ae51b8b55..99ef0e2dada 100644 --- a/libs/cmdio/cmdiotest/pin_queries_test.go +++ b/libs/cmdio/cmdiotest/pin_queries_test.go @@ -42,6 +42,28 @@ func TestQueriesPin_PromptQuitBeforeReplies(t *testing.T) { termtest.GoldenText(t, "03-leftover", quoted(leftover)) } +// TestQueriesPin_PromptQuitBeforeRepliesTTY is TestQueriesPin_PromptQuitBeforeReplies +// with stdin posing as a terminal. NewTeaProgram installs the reply guard only +// on a terminal, so this is the path a user gets: the quit waits for the +// cursor report, and no reply is left for the shell. +func TestQueriesPin_PromptQuitBeforeRepliesTTY(t *testing.T) { + t.Parallel() + skipLeftoverOnWindows(t) + tm := termtest.RunWith(t, termtest.Options{Responder: slowTerminal, CaptureLeftover: true, StdinTTY: true}, func(ctx context.Context) (string, error) { + return cmdio.RunPrompt(ctx, cmdio.PromptOptions{Label: "Value"}) + }) + tm.WaitFor("Value") + typeKeys(tm, "ab") + tm.Type(termtest.KeyEnter) + pinPromptResult(t, tm, "01-result") + tm.GoldenQueries("02-queries") + leftover, err := tm.Leftover() + if err != nil { + t.Fatal(err) + } + termtest.GoldenText(t, "03-leftover", quoted(leftover)) +} + // TestQueriesPin_SelectQuitBeforeReplies is the select counterpart of // TestQueriesPin_PromptQuitBeforeReplies. func TestQueriesPin_SelectQuitBeforeReplies(t *testing.T) { diff --git a/libs/cmdio/cmdiotest/prompt_shift_enter_test.go b/libs/cmdio/cmdiotest/prompt_shift_enter_test.go new file mode 100644 index 00000000000..42865585fd5 --- /dev/null +++ b/libs/cmdio/cmdiotest/prompt_shift_enter_test.go @@ -0,0 +1,45 @@ +package cmdiotest_test + +import ( + "testing" + + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/cmdiotest/termtest" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Terminals with the kitty keyboard protocol or modifyOtherKeys enabled send +// Shift+Enter as its own key; prompt and select must still submit on it. +func TestPrompt_ShiftEnterSubmits(t *testing.T) { + for name, seq := range map[string]string{ + "kitty": "\x1b[13;2u", + "modifyOtherKeys": "\x1b[27;2;13~", + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + tm := termtest.NewPrompt(t, cmdio.PromptOptions{Label: "Name"}) + tm.WaitFor("Name") + tm.Type("ab") + tm.WaitFor("ab") + tm.Type(seq) + v, err := tm.Result() + require.NoError(t, err, "raw output: %q", tm.Raw()) + assert.Equal(t, "ab", v) + }) + } +} + +func TestSelect_ShiftEnterSubmits(t *testing.T) { + t.Parallel() + tm := termtest.NewSelectOrdered(t, []cmdio.Tuple{ + {Name: "alpha", Id: "a"}, + {Name: "beta", Id: "b"}, + }, "Pick") + tm.WaitFor("alpha") + tm.Type(termtest.KeyDown) + tm.Type("\x1b[13;2u") + v, err := tm.Result() + require.NoError(t, err, "raw output: %q", tm.Raw()) + assert.Equal(t, "b", v) +} diff --git a/libs/cmdio/cmdiotest/termtest/termtest.go b/libs/cmdio/cmdiotest/termtest/termtest.go index 8cf2443e3dc..acdadb10a5d 100644 --- a/libs/cmdio/cmdiotest/termtest/termtest.go +++ b/libs/cmdio/cmdiotest/termtest/termtest.go @@ -211,6 +211,11 @@ type Options struct { // cooked mode shows plain lines written to it (cmdio.LogString output). MapNewline bool + // StdinTTY makes stdin look like a terminal to cmdio, so the paths that + // need one run, such as NewTeaProgram's wait for the terminal's replies + // before quitting. Input still comes from the pipe. + StdinTTY bool + // ScreenRows, when positive, replaces the emulator's height of // [cmdio.TestTerminalHeight] rows. The emulator does not scroll, so // programs that print more lines than that (the pager draining several @@ -347,7 +352,11 @@ func RunWith[T any](t *testing.T, opts Options, fn func(ctx context.Context) (T, } else { stdout = io.Discard } - cio := cmdio.NewTestIOWithOptions(ctx, inR, stdout, screen, cmdio.TestIOOptions{ + var in io.Reader = inR + if opts.StdinTTY { + in = cmdio.FakeTTYReader(inR) + } + cio := cmdio.NewTestIOWithOptions(ctx, in, stdout, screen, cmdio.TestIOOptions{ HeaderTemplate: opts.HeaderTemplate, Template: opts.Template, ColorFromEnv: opts.ColorFromEnv, diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBracketedPasteWithNewline/01-after-paste.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBracketedPasteWithNewline/01-after-paste.golden index 749db6320e6..37374b516a0 100644 --- a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBracketedPasteWithNewline/01-after-paste.golden +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBracketedPasteWithNewline/01-after-paste.golden @@ -1,2 +1,2 @@ - +✔ Value: a b█ diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/01-after-shift-enter.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/01-after-shift-enter.golden index e9385f6a7fa..b5c85773a48 100644 --- a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/01-after-shift-enter.golden +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/01-after-shift-enter.golden @@ -1 +1 @@ -✔ Value: xyz█ +Value: xy diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/02-result.golden index 1b113f0f236..a77c89c1488 100644 --- a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/02-result.golden +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/02-result.golden @@ -1,2 +1,2 @@ -value: "xyz" +value: "xy" err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/01-after-shift-enter.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/01-after-shift-enter.golden index e9385f6a7fa..b5c85773a48 100644 --- a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/01-after-shift-enter.golden +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/01-after-shift-enter.golden @@ -1 +1 @@ -✔ Value: xyz█ +Value: xy diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/02-result.golden index 1b113f0f236..a77c89c1488 100644 --- a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/02-result.golden +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/02-result.golden @@ -1,2 +1,2 @@ -value: "xyz" +value: "xy" err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_kitty/01-after-shift-enter.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_kitty/01-after-shift-enter.golden index b5462b0e045..8b137891791 100644 --- a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_kitty/01-after-shift-enter.golden +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_kitty/01-after-shift-enter.golden @@ -1,5 +1 @@ -Search: █ -? Pick one: - alpha - beta (id-02) - gamma + diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_modifyOtherKeys/01-after-shift-enter.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_modifyOtherKeys/01-after-shift-enter.golden index b5462b0e045..8b137891791 100644 --- a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_modifyOtherKeys/01-after-shift-enter.golden +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_modifyOtherKeys/01-after-shift-enter.golden @@ -1,5 +1 @@ -Search: █ -? Pick one: - alpha - beta (id-02) - gamma + diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_ctrl-c/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_ctrl-c/01-modes.modes.golden index 29572cb66d7..d4913120490 100644 --- a/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_ctrl-c/01-modes.modes.golden +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_ctrl-c/01-modes.modes.golden @@ -1,9 +1,10 @@ -- changes -- ?25 reset ?2004 set -?2004 reset +modifyOtherKeys 2 +kitty-keyboard push 1 +modifyOtherKeys 0 +kitty-keyboard pop 1 ?25 set -?1002 reset -?1003 reset -?1006 reset +?2004 reset -- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_enter-drains/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_enter-drains/01-modes.modes.golden index 29572cb66d7..d4913120490 100644 --- a/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_enter-drains/01-modes.modes.golden +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_enter-drains/01-modes.modes.golden @@ -1,9 +1,10 @@ -- changes -- ?25 reset ?2004 set -?2004 reset +modifyOtherKeys 2 +kitty-keyboard push 1 +modifyOtherKeys 0 +kitty-keyboard pop 1 ?25 set -?1002 reset -?1003 reset -?1006 reset +?2004 reset -- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_ctrl-c/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_ctrl-c/01-modes.modes.golden index 29572cb66d7..d4913120490 100644 --- a/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_ctrl-c/01-modes.modes.golden +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_ctrl-c/01-modes.modes.golden @@ -1,9 +1,10 @@ -- changes -- ?25 reset ?2004 set -?2004 reset +modifyOtherKeys 2 +kitty-keyboard push 1 +modifyOtherKeys 0 +kitty-keyboard pop 1 ?25 set -?1002 reset -?1003 reset -?1006 reset +?2004 reset -- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_enter/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_enter/01-modes.modes.golden index 29572cb66d7..d4913120490 100644 --- a/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_enter/01-modes.modes.golden +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_enter/01-modes.modes.golden @@ -1,9 +1,10 @@ -- changes -- ?25 reset ?2004 set -?2004 reset +modifyOtherKeys 2 +kitty-keyboard push 1 +modifyOtherKeys 0 +kitty-keyboard pop 1 ?25 set -?1002 reset -?1003 reset -?1006 reset +?2004 reset -- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_ctrl-c/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_ctrl-c/01-modes.modes.golden index 4fa7141e5dc..d4913120490 100644 --- a/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_ctrl-c/01-modes.modes.golden +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_ctrl-c/01-modes.modes.golden @@ -1,10 +1,10 @@ -- changes -- ?25 reset ?2004 set -?25 reset -?2004 reset +modifyOtherKeys 2 +kitty-keyboard push 1 +modifyOtherKeys 0 +kitty-keyboard pop 1 ?25 set -?1002 reset -?1003 reset -?1006 reset +?2004 reset -- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_enter/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_enter/01-modes.modes.golden index 4fa7141e5dc..d4913120490 100644 --- a/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_enter/01-modes.modes.golden +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_enter/01-modes.modes.golden @@ -1,10 +1,10 @@ -- changes -- ?25 reset ?2004 set -?25 reset -?2004 reset +modifyOtherKeys 2 +kitty-keyboard push 1 +modifyOtherKeys 0 +kitty-keyboard pop 1 ?25 set -?1002 reset -?1003 reset -?1006 reset +?2004 reset -- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Spinner/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Spinner/01-modes.modes.golden index 29572cb66d7..ca350bae4bb 100644 --- a/libs/cmdio/cmdiotest/testdata/TestModesPin_Spinner/01-modes.modes.golden +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Spinner/01-modes.modes.golden @@ -1,9 +1,6 @@ -- changes -- ?25 reset ?2004 set -?2004 reset ?25 set -?1002 reset -?1003 reset -?1006 reset +?2004 reset -- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/02-queries.queries.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/02-queries.queries.golden index 8b137891791..5615dd803f9 100644 --- a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/02-queries.queries.golden +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/02-queries.queries.golden @@ -1 +1,3 @@ - +DECRQM ?2026 +DECRQM ?2027 +kitty-keyboard-flags diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/03-leftover.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/03-leftover.golden index 870cc2bdd10..e8a5b28b4f2 100644 --- a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/03-leftover.golden +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/03-leftover.golden @@ -1 +1 @@ -(none) +"\x1b[?2026;2$y\x1b[?2027;2$y\x1b[?0u" diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeRepliesTTY/01-result.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeRepliesTTY/01-result.golden new file mode 100644 index 00000000000..679aaf570a0 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeRepliesTTY/01-result.golden @@ -0,0 +1,2 @@ +value: "ab" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeRepliesTTY/02-queries.queries.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeRepliesTTY/02-queries.queries.golden new file mode 100644 index 00000000000..9df1ae30272 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeRepliesTTY/02-queries.queries.golden @@ -0,0 +1,4 @@ +DECRQM ?2026 +DECRQM ?2027 +kitty-keyboard-flags +CPR diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeRepliesTTY/03-leftover.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeRepliesTTY/03-leftover.golden new file mode 100644 index 00000000000..870cc2bdd10 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeRepliesTTY/03-leftover.golden @@ -0,0 +1 @@ +(none) diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/03-queries.queries.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/03-queries.queries.golden index 8b137891791..5615dd803f9 100644 --- a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/03-queries.queries.golden +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/03-queries.queries.golden @@ -1 +1,3 @@ - +DECRQM ?2026 +DECRQM ?2027 +kitty-keyboard-flags diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/01-after-reply.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/01-after-reply.golden index f3193c834b9..b479798fc86 100644 --- a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/01-after-reply.golden +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/01-after-reply.golden @@ -1 +1 @@ -✔ Value: ab11;rgb:0000/0000/0000█ +✔ Value: ab█ diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/02-result.golden index 52037450272..679aaf570a0 100644 --- a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/02-result.golden +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/02-result.golden @@ -1,2 +1,2 @@ -value: "ab11;rgb:0000/0000/0000" +value: "ab" err: diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/01-queries.queries.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/01-queries.queries.golden index 8b137891791..5615dd803f9 100644 --- a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/01-queries.queries.golden +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/01-queries.queries.golden @@ -1 +1,3 @@ - +DECRQM ?2026 +DECRQM ?2027 +kitty-keyboard-flags diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/02-leftover.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/02-leftover.golden index 870cc2bdd10..e8a5b28b4f2 100644 --- a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/02-leftover.golden +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/02-leftover.golden @@ -1 +1 @@ -(none) +"\x1b[?2026;2$y\x1b[?2027;2$y\x1b[?0u" diff --git a/libs/cmdio/color.go b/libs/cmdio/color.go index 60fb3a15fa0..bc85ecc59e6 100644 --- a/libs/cmdio/color.go +++ b/libs/cmdio/color.go @@ -6,7 +6,7 @@ import ( "strings" "text/template" - "github.com/charmbracelet/lipgloss" + "charm.land/lipgloss/v2" ) // SGR (Select Graphic Rendition) escapes; see diff --git a/libs/cmdio/color_test.go b/libs/cmdio/color_test.go index 54cdc067c0e..e1bc96af255 100644 --- a/libs/cmdio/color_test.go +++ b/libs/cmdio/color_test.go @@ -7,8 +7,8 @@ import ( "strings" "testing" + "charm.land/lipgloss/v2" "github.com/charmbracelet/colorprofile" - "github.com/charmbracelet/lipgloss" "github.com/databricks/cli/libs/cmdio" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/libs/cmdio/conpty_windows_test.go b/libs/cmdio/conpty_windows_test.go index ced88b4a9c0..ec97c998a92 100644 --- a/libs/cmdio/conpty_windows_test.go +++ b/libs/cmdio/conpty_windows_test.go @@ -5,8 +5,8 @@ import ( "os" "testing" + "charm.land/lipgloss/v2" "github.com/charmbracelet/colorprofile" - "github.com/charmbracelet/lipgloss" "github.com/databricks/cli/libs/env" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -87,7 +87,7 @@ func TestNewRendererRaisesMSYSPipeToANSI(t *testing.T) { 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")) + assert.NotEqual(t, "hi", r.Render(r.NewStyle().Foreground(lipgloss.Color("10")).Render("hi"))) } func TestNewRendererMSYSPipeHonorsCLICOLOR(t *testing.T) { diff --git a/libs/cmdio/huh.go b/libs/cmdio/huh.go new file mode 100644 index 00000000000..f44bdb78427 --- /dev/null +++ b/libs/cmdio/huh.go @@ -0,0 +1,41 @@ +package cmdio + +import ( + "context" + "io" + "os" + + tea "charm.land/bubbletea/v2" + "charm.land/huh/v2" +) + +// RunHuhField runs one huh field the way field.Run does, but with the program +// options cmdio's prompts use: the context's input and stderr, and the color +// profile of stderr, so a form matches the other TUIs. huh's WithProgramOptions +// replaces its own defaults, which is why the input and output are passed too. +// +// The reply guard is not installed. It has to inject a message when the +// terminal's answer times out, and a huh program's Send is not reachable from +// a program filter, so a missed answer would hang the quit. +func RunHuhField(ctx context.Context, field huh.Field) error { + return RunHuhForm(ctx, huh.NewForm(huh.NewGroup(field)).WithShowHelp(false)) +} + +// RunHuhForm runs form with the program options described on [RunHuhField]. +func RunHuhForm(ctx context.Context, form *huh.Form) error { + return form.WithProgramOptions(huhProgramOptions(ctx)...).Run() +} + +func huhProgramOptions(ctx context.Context) []tea.ProgramOption { + c, _ := ctx.Value(cmdIOKey).(*cmdIO) + var in io.Reader = os.Stdin + var errW io.Writer = os.Stderr + if c != nil { + in, errW = c.in, c.err + } + return []tea.ProgramOption{ + tea.WithInput(in), + tea.WithOutput(errW), + tea.WithColorProfile(teaColorProfile(SupportsColor(ctx, errW), errW)), + } +} diff --git a/libs/cmdio/io.go b/libs/cmdio/io.go index da88f2ecf73..6e7d4fda2b0 100644 --- a/libs/cmdio/io.go +++ b/libs/cmdio/io.go @@ -7,7 +7,7 @@ import ( "strings" "sync" - tea "github.com/charmbracelet/bubbletea" + tea "charm.land/bubbletea/v2" "github.com/databricks/cli/libs/flags" ) @@ -18,19 +18,22 @@ var errCtrlC = errors.New("^C") // runTUI runs a tea.Program through cmdIO's tea program slot so spinners and // pagers can't fight a prompt for the terminal. Blocks until the model quits. func (c *cmdIO) runTUI(m tea.Model) (tea.Model, error) { - p := tea.NewProgram(m, + opts := []tea.ProgramOption{ tea.WithInput(c.in), tea.WithOutput(c.err), + tea.WithColorProfile(teaColorProfile(c.capabilities.SupportsStderrColor(), c.err)), // Ctrl+C is delivered as a key event so the model can return errCtrlC. tea.WithoutSignalHandler(), - ) - c.acquireTeaProgram(p) - defer c.releaseTeaProgram() + } // NewTestIO sets a synthetic window size because bubbletea's auto-detect - // doesn't fire on pipe-backed streams. Nil in production. + // doesn't fire on pipe-backed streams. Nil in production. It must be set + // up front: Run renders the first frame before any sent message arrives. if c.teaWindowSize != nil { - go p.Send(*c.teaWindowSize) + opts = append(opts, tea.WithWindowSize(c.teaWindowSize.Width, c.teaWindowSize.Height)) } + p := NewTeaProgram(m, c.in, opts...) + c.acquireTeaProgram(p) + defer c.releaseTeaProgram() return p.Run() } diff --git a/libs/cmdio/lipgloss.go b/libs/cmdio/lipgloss.go index 5930b951573..a7dad336695 100644 --- a/libs/cmdio/lipgloss.go +++ b/libs/cmdio/lipgloss.go @@ -2,64 +2,119 @@ package cmdio import ( "context" + "image/color" "io" + "os" "strings" - "sync" + "charm.land/lipgloss/v2" "github.com/charmbracelet/colorprofile" - "github.com/charmbracelet/lipgloss" + "github.com/mattn/go-isatty" "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. +// and Renderer.Render), and the Color, LightDark and Hyperlink helpers. +// 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. +// the profile is applied: lipgloss v2 styles always emit full-color SGR. +// Bubble Tea programs get a profile via tea.WithColorProfile (see +// teaprogram.go). -// 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 +// Color is a color value accepted by lipgloss styles. Any image/color.Color +// works; lipgloss.Color returns one. +type Color = color.Color // 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. +// color. When it does not (NO_COLOR, TERM=dumb, or w is piped or redirected) +// output written through Writer has all escape sequences stripped. Otherwise +// the profile is the one lipgloss v1 rendered with; see colorDepth. 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 + return &Renderer{profile: colorprofile.NoTTY}, false + } + return &Renderer{profile: colorDepth(w)}, true +} + +// colorDepth returns the color depth for a writer cmdio already decided +// supports color. lipgloss v2 no longer picks one, and colorprofile's rules +// differ from termenv's (it ignores CLICOLOR=0 and CI, and maps tmux and +// COLORTERM=yes differently), so cmdio keeps asking termenv, which lipgloss v1 +// used, to keep colors where they were: +// - termenv's profile for w, read from the process environment. That is +// Ascii for CLICOLOR=0 or CI unless CLICOLOR_FORCE is set, and Ascii when +// termenv can't see a terminal, e.g. TERM unset on Linux and macOS; +// - raised from Ascii 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, unless CLICOLOR=0 asks for no color. termenv's CI check is +// not honored there: it only guesses that CI output isn't a terminal, +// and this one is. +func colorDepth(w io.Writer) colorprofile.Profile { + return colorDepthFor(termenvEnviron{os.Environ()}, isTermenvTTY(w), isMSYSPipe(w)) +} + +// colorDepthFor is colorDepth for an environment and the two facts it needs +// about the writer, so tests can vary them. +func colorDepthFor(environ termenv.Environ, tty, msysPipe bool) colorprofile.Profile { + // termenv's terminal check treats CI as "not a terminal" (termenv + // v0.16.0 termenv.go:32). WithTTY skips that check, so apply it here. + if environ.Getenv("CI") != "" { + tty = false } - if isMSYSPipe(w) && lg.ColorProfile() == termenv.Ascii && !termenv.EnvNoColor() { - lg.SetColorProfile(termenv.ANSI) + o := termenv.NewOutput(io.Discard, termenv.WithEnvironment(environ), termenv.WithTTY(tty)) + p := colorprofileFromTermenv(o.EnvColorProfile()) + if msysPipe && p == colorprofile.Ascii && !o.EnvNoColor() { + return colorprofile.ANSI } - return &Renderer{lg: lg, profile: colorprofileFromTermenv(lg.ColorProfile())}, true + return p +} + +// isTermenvTTY reports whether termenv considers w a terminal: only an +// *os.File for which isatty says so. MSYS2 pty pipes and fakes are not. +func isTermenvTTY(w io.Writer) bool { + f, ok := w.(*os.File) + return ok && isatty.IsTerminal(f.Fd()) //nolint:forbidigo // mirrors termenv's own check } -// NewStyle returns a style whose colors are rendered for this renderer. +// termenvEnviron adapts a KEY=VALUE list to termenv.Environ. +type termenvEnviron struct{ vars []string } + +func (e termenvEnviron) Environ() []string { return e.vars } + +func (e termenvEnviron) Getenv(key string) string { + for _, kv := range e.vars { + if k, v, ok := strings.Cut(kv, "="); ok && k == key { + return v + } + } + return "" +} + +// colorprofileFromTermenv maps a termenv profile to the colorprofile one +// lipgloss v2 and Bubble Tea use. +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 + } +} + +// NewStyle returns a style to be written through this renderer's Writer. func (r *Renderer) NewStyle() lipgloss.Style { - return r.lg.NewStyle() + return lipgloss.NewStyle() } // Profile returns the color profile output is downsampled to. @@ -67,17 +122,12 @@ 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.) +// Writer wraps w so styled strings written to it are downsampled to the +// renderer's profile; when color is off it strips every escape sequence. // -// Stripping works per Write call, as colorprofile.Writer does, so an escape +// Downsampling 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}} } @@ -88,22 +138,13 @@ func (r *Renderer) Render(s string) string { return b.String() } -// LightDark returns a function picking the light or dark variant of a color, -// mirroring lipgloss v2's LightDark. +// LightDark returns a function picking the light or dark variant of a color. +// It is lipgloss.LightDark; callers go through cmdio so palettes don't depend +// on the lipgloss major version. func LightDark(isDark bool) func(light, dark Color) Color { - return func(light, dark Color) Color { - if isDark { - return dark - } - return light - } + return lipgloss.LightDark(isDark) } -// 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. @@ -112,21 +153,6 @@ func Hyperlink(url, label string) string { 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. diff --git a/libs/cmdio/lipgloss_test.go b/libs/cmdio/lipgloss_test.go index bf51feaa714..84df12ad3b7 100644 --- a/libs/cmdio/lipgloss_test.go +++ b/libs/cmdio/lipgloss_test.go @@ -1,6 +1,7 @@ package cmdio import ( + "runtime" "strings" "testing" @@ -8,12 +9,61 @@ import ( "github.com/stretchr/testify/assert" ) -func TestWriterPassesThroughWhenColorOn(t *testing.T) { +// These mirror what NewRenderer decided on lipgloss v1, where termenv picked +// the profile (see TestNewRendererKeepsTermenvProfile and the MSYS2 cases in +// conpty_windows_test.go). +func TestColorDepth(t *testing.T) { + cases := []struct { + name string + env []string + tty bool + msysPipe bool + want colorprofile.Profile + }{ + {"not a terminal", []string{"TERM=xterm-256color"}, false, false, colorprofile.Ascii}, + {"16-color terminal", []string{"TERM=xterm"}, true, false, colorprofile.ANSI}, + {"256-color terminal", []string{"TERM=xterm-256color"}, true, false, colorprofile.ANSI256}, + {"COLORTERM upgrades to truecolor", []string{"TERM=xterm-256color", "COLORTERM=truecolor"}, true, false, colorprofile.TrueColor}, + {"COLORTERM=yes is 256 colors", []string{"TERM=xterm", "COLORTERM=yes"}, true, false, colorprofile.ANSI256}, + {"tmux keeps truecolor", []string{"TERM=screen-256color", "COLORTERM=truecolor", "TERM_PROGRAM=tmux"}, true, false, colorprofile.TrueColor}, + {"screen is 256 colors", []string{"TERM=screen-256color", "COLORTERM=truecolor"}, true, false, colorprofile.ANSI256}, + {"TERM unset", nil, true, false, colorprofile.Ascii}, + {"CLICOLOR=0", []string{"TERM=xterm-256color", "CLICOLOR=0"}, true, false, colorprofile.Ascii}, + {"CLICOLOR=0 with CLICOLOR_FORCE", []string{"TERM=xterm-256color", "CLICOLOR=0", "CLICOLOR_FORCE=1"}, true, false, colorprofile.ANSI256}, + {"CLICOLOR_FORCE=0 doesn't force", []string{"TERM=xterm-256color", "CLICOLOR=0", "CLICOLOR_FORCE=0"}, true, false, colorprofile.Ascii}, + {"CI", []string{"TERM=xterm-256color", "CI=1"}, true, false, colorprofile.Ascii}, + {"CI with CLICOLOR_FORCE", []string{"TERM=xterm-256color", "CI=1", "CLICOLOR_FORCE=1"}, true, false, colorprofile.ANSI}, + {"CI unset", []string{"TERM=xterm-256color", "CI="}, true, false, colorprofile.ANSI256}, + {"MSYS2 pty pipe is raised to ANSI", []string{"TERM=xterm"}, false, true, colorprofile.ANSI}, + {"MSYS2 pty pipe ignores CI", []string{"TERM=xterm", "CI=1"}, false, true, colorprofile.ANSI}, + {"MSYS2 pty pipe honors CLICOLOR=0", []string{"TERM=xterm", "CLICOLOR=0"}, false, true, colorprofile.Ascii}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if c.tty && runtime.GOOS == "windows" { + t.Skip("termenv ignores TERM and COLORTERM on Windows") + } + assert.Equal(t, c.want, colorDepthFor(termenvEnviron{c.env}, c.tty, c.msysPipe)) + }) + } +} + +func TestTeaColorProfile(t *testing.T) { + // Bubble Tea downsamples a program's whole view; template color helpers + // emit basic ANSI whenever the stream supports color, so that is the floor. + assert.GreaterOrEqual(t, teaColorProfile(true, &strings.Builder{}), colorprofile.ANSI) + // Without color, bold and the other attributes stay. + assert.Equal(t, colorprofile.Ascii, teaColorProfile(false, &strings.Builder{})) +} + +func TestWriterDownsamplesToProfile(t *testing.T) { r := &Renderer{profile: colorprofile.ANSI} - styled := "\x1b[38;2;143;179;220mlabel\x1b[m " + Hyperlink("https://h.test", "docs") + link := Hyperlink("https://h.test", "docs") + styled := "\x1b[38;2;143;179;220mlabel\x1b[m " + link var b strings.Builder _, err := r.Writer(&b).Write([]byte(styled)) assert.NoError(t, err) - assert.Equal(t, styled, b.String()) + // Truecolor SGR becomes the nearest 16-color code; the hyperlink survives. + assert.Equal(t, "\x1b[94mlabel\x1b[m "+link, b.String()) } diff --git a/libs/cmdio/paged_template.go b/libs/cmdio/paged_template.go index c922c079143..9307bffd24a 100644 --- a/libs/cmdio/paged_template.go +++ b/libs/cmdio/paged_template.go @@ -9,7 +9,7 @@ import ( "text/template" "unicode/utf8" - tea "github.com/charmbracelet/bubbletea" + tea "charm.land/bubbletea/v2" "github.com/databricks/databricks-sdk-go/listing" ) @@ -104,14 +104,20 @@ func renderIteratorPagedTemplateCore[T any]( headerStr: headerTemplate, } m := newPagerModel(ctx, out, iter, pager, pageSize, limitFromContext(ctx)) - p := tea.NewProgram( - m, + teaOpts := []tea.ProgramOption{ tea.WithInput(in), tea.WithOutput(out), + tea.WithColorProfile(teaColorProfile(SupportsColor(ctx, out), out)), // Match spinner: let SIGINT reach the process rather than the TUI // so Ctrl+C also interrupts a stalled iterator fetch. tea.WithoutSignalHandler(), - ) + } + // NewTestIO's synthetic window size, at the height that keeps v1's fallback + // page size of 50 rows; nil in production. + if c, ok := ctx.Value(cmdIOKey).(*cmdIO); ok && c.teaWindowSize != nil { + teaOpts = append(teaOpts, tea.WithWindowSize(c.teaWindowSize.Width, pagerFallbackPageSize+pagerViewOverhead)) + } + p := NewTeaProgram(m, in, teaOpts...) // Unlike cmdio.NewSpinner, the pager doesn't need to acquire/release // through cmdIO: p.Run is blocking and tea restores the terminal on // its own before returning, so there's no other tea.Program that could diff --git a/libs/cmdio/paged_template_test.go b/libs/cmdio/paged_template_test.go index 03a5fc1c9d5..0531792ee8c 100644 --- a/libs/cmdio/paged_template_test.go +++ b/libs/cmdio/paged_template_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" + "github.com/charmbracelet/x/ansi" "github.com/databricks/cli/libs/flags" "github.com/databricks/databricks-sdk-go/listing" "github.com/stretchr/testify/assert" @@ -67,7 +68,7 @@ func pagedOutput( func countContentLines(s string) int { count := 0 for line := range strings.SplitSeq(s, "\n") { - trimmed := strings.TrimSpace(line) + trimmed := strings.TrimSpace(ansi.Strip(line)) if trimmed == "" || strings.Contains(trimmed, pagerPromptText) { continue } @@ -199,7 +200,7 @@ func assertSameContentLines(t *testing.T, want, got string) { func nonEmptyLines(s string) []string { var out []string for l := range strings.SplitSeq(s, "\n") { - t := strings.TrimRight(l, " \r\t") + t := strings.TrimRight(ansi.Strip(l), " \r\t") if t == "" { continue } diff --git a/libs/cmdio/pager.go b/libs/cmdio/pager.go index 4f6c48b91f2..547bc37a474 100644 --- a/libs/cmdio/pager.go +++ b/libs/cmdio/pager.go @@ -6,9 +6,9 @@ import ( "strings" "time" - bubblespinner "github.com/charmbracelet/bubbles/spinner" - tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" + bubblespinner "charm.land/bubbles/v2/spinner" + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" "github.com/databricks/cli/libs/cmdio/teainput" "github.com/databricks/databricks-sdk-go/listing" ) @@ -38,6 +38,9 @@ type pagerModel[T any] struct { iter listing.Iterator[T] pager *templatePager spinner bubblespinner.Model + // spinnerRenderer renders the spinner's style to the profile lipgloss v1 + // used, which the program's profile (see teaColorProfile) may exceed. + spinnerRenderer *Renderer // fetch is bound at construction with the caller's context captured // so we don't have to stash ctx on the struct (tea.Cmd has no ctx // parameter of its own). It takes the paging state as arguments and @@ -72,10 +75,11 @@ func newPagerModel[T any]( m := &pagerModel[T]{ iter: iter, pager: pager, - spinner: newPagerSpinner(ctx, out), + spinner: newPagerSpinner(), pageSize: pageSize, limit: limit, } + m.spinnerRenderer, _ = NewRenderer(ctx, out) m.fetch = func(pageSize, limit, total int) tea.Cmd { return func() tea.Msg { return m.doFetch(ctx, pageSize, limit, total) } } @@ -84,14 +88,13 @@ func newPagerModel[T any]( // newPagerSpinner builds a spinner matching the one the cmdio package's // NewSpinner uses, so interactive feedback looks the same everywhere. -func newPagerSpinner(ctx context.Context, out io.Writer) bubblespinner.Model { +func newPagerSpinner() bubblespinner.Model { s := bubblespinner.New() s.Spinner = bubblespinner.Spinner{ Frames: []string{"⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"}, FPS: time.Second / 5, } - r, _ := NewRenderer(ctx, out) - s.Style = r.NewStyle().Foreground(lipgloss.Color("10")) + s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("10")) return s } @@ -226,14 +229,14 @@ func (m *pagerModel[T]) startDrain() tea.Cmd { return m.fetch(m.pageSize, m.limit, m.total) } -func (m *pagerModel[T]) View() string { return m.render() } +func (m *pagerModel[T]) View() tea.View { return tea.NewView(m.render()) } func (m *pagerModel[T]) render() string { switch { case m.iterDone || m.err != nil: return "" case m.fetching: - return m.spinner.View() + " " + pagerLoadingText + return m.spinnerRenderer.Render(m.spinner.View()) + " " + pagerLoadingText case m.drainAll || !m.hasPrinted: return "" default: diff --git a/libs/cmdio/pager_test.go b/libs/cmdio/pager_test.go index 503172e7176..911136e456b 100644 --- a/libs/cmdio/pager_test.go +++ b/libs/cmdio/pager_test.go @@ -7,7 +7,8 @@ import ( "testing" "text/template" - tea "github.com/charmbracelet/bubbletea" + tea "charm.land/bubbletea/v2" + "github.com/databricks/cli/libs/cmdio/teainput" "github.com/databricks/databricks-sdk-go/listing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -135,7 +136,7 @@ func TestPagerModelBatchPromptsWhenMore(t *testing.T) { assert.False(t, m.iterDone) assert.True(t, m.hasPrinted) assert.False(t, m.drainAll) - assert.Equal(t, pagerPromptText, m.View()) + assert.Equal(t, pagerPromptText, m.render()) assert.Contains(t, printedText(t, runCmd(t, cmd)), "1\n2") } @@ -161,10 +162,10 @@ func TestPagerModelBatchErrorTerminates(t *testing.T) { func TestPagerModelSpaceFetchesNext(t *testing.T) { cases := []struct { name string - key tea.KeyMsg + key tea.Msg }{ - {"KeySpace", tea.KeyMsg{Type: tea.KeySpace}}, - {"KeyRunes space", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{' '}}}, + {"KeySpace", teainput.Press("space")}, + {"KeyRunes space", teainput.Type(" ")}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -180,9 +181,9 @@ func TestPagerModelSpaceFetchesNext(t *testing.T) { func TestPagerModelEnterSetsDrainAll(t *testing.T) { m := newTestPager(t, &numberIterator{n: 100}, 5) m.hasPrinted = true - _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + _, cmd := m.Update(teainput.Press("enter")) assert.True(t, m.drainAll) - assert.NotContains(t, m.View(), pagerPromptText, "no prompt while draining") + assert.NotContains(t, m.render(), pagerPromptText, "no prompt while draining") _, ok := runCmd(t, cmd).(batchMsg) assert.True(t, ok, "enter should fire a fetch") } @@ -191,7 +192,7 @@ func TestPagerModelEnterIsNoOpWhileAlreadyDraining(t *testing.T) { m := newTestPager(t, &numberIterator{n: 100}, 5) m.hasPrinted = true m.drainAll = true - _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + _, cmd := m.Update(teainput.Press("enter")) assert.Nil(t, cmd, "re-entering drain shouldn't stack another fetch") } @@ -200,7 +201,7 @@ func TestPagerModelSpaceIgnoredDuringFetch(t *testing.T) { // fetch: doing so would run the iterator from two goroutines at once. m := newTestPager(t, &numberIterator{n: 100}, 5) m.fetching = true - _, cmd := m.Update(tea.KeyMsg{Type: tea.KeySpace}) + _, cmd := m.Update(teainput.Press("space")) assert.Nil(t, cmd, "SPACE while fetching must not dispatch another fetch") } @@ -209,7 +210,7 @@ func TestPagerModelEnterDuringFetchDefersFetch(t *testing.T) { // fetch; the pending batchMsg will chain one when it arrives. m := newTestPager(t, &numberIterator{n: 100}, 5) m.fetching = true - _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + _, cmd := m.Update(teainput.Press("enter")) assert.True(t, m.drainAll) assert.Nil(t, cmd, "ENTER during fetch must defer to batchMsg chaining") } @@ -217,12 +218,12 @@ func TestPagerModelEnterDuringFetchDefersFetch(t *testing.T) { func TestPagerModelQuitKeys(t *testing.T) { cases := []struct { name string - key tea.KeyMsg + key tea.Msg }{ - {"q", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'q'}}}, - {"Q", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'Q'}}}, - {"esc", tea.KeyMsg{Type: tea.KeyEsc}}, - {"ctrl+c", tea.KeyMsg{Type: tea.KeyCtrlC}}, + {"q", teainput.Press("q")}, + {"Q", teainput.Press("Q")}, + {"esc", teainput.Press("esc")}, + {"ctrl+c", teainput.Press("ctrl+c")}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -236,10 +237,10 @@ func TestPagerModelQuitKeys(t *testing.T) { } func TestPagerModelQuitKeysInterruptDrain(t *testing.T) { - for _, key := range []tea.KeyMsg{ - {Type: tea.KeyRunes, Runes: []rune{'q'}}, - {Type: tea.KeyEsc}, - {Type: tea.KeyCtrlC}, + for _, key := range []tea.Msg{ + teainput.Press("q"), + teainput.Press("esc"), + teainput.Press("ctrl+c"), } { m := newTestPager(t, &numberIterator{n: 100}, 5) m.hasPrinted = true @@ -253,20 +254,20 @@ func TestPagerModelQuitKeysInterruptDrain(t *testing.T) { func TestPagerModelIgnoresKeysAfterDone(t *testing.T) { m := newTestPager(t, &numberIterator{n: 0}, 5) m.iterDone = true - _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyCtrlC}) + _, cmd := m.Update(teainput.Press("ctrl+c")) assert.Nil(t, cmd, "keys after completion should be no-ops") } func TestPagerModelViewHiddenUntilFirstBatch(t *testing.T) { m := newTestPager(t, &numberIterator{n: 10}, 5) - assert.Empty(t, m.View(), "prompt must not flash before any output is rendered") + assert.Empty(t, m.render(), "prompt must not flash before any output is rendered") } func TestPagerModelViewShowsSpinnerWhileFetching(t *testing.T) { m := newTestPager(t, &numberIterator{n: 100}, 5) m.fetching = true - assert.Contains(t, m.View(), pagerLoadingText) - assert.NotContains(t, m.View(), pagerPromptText) + assert.Contains(t, m.render(), pagerLoadingText) + assert.NotContains(t, m.render(), pagerPromptText) } func TestPagerModelWindowSizeResizesPage(t *testing.T) { diff --git a/libs/cmdio/prompt.go b/libs/cmdio/prompt.go index 6f309db2601..4ae4bc4db1c 100644 --- a/libs/cmdio/prompt.go +++ b/libs/cmdio/prompt.go @@ -6,7 +6,7 @@ import ( "io" "strings" - tea "github.com/charmbracelet/bubbletea" + tea "charm.land/bubbletea/v2" "github.com/databricks/cli/libs/cmdio/teainput" ) @@ -200,7 +200,7 @@ func (m *promptModel) insert(typed []rune) { m.submitErr = nil } -func (m *promptModel) View() string { return m.render() } +func (m *promptModel) View() tea.View { return tea.NewView(m.render()) } func (m *promptModel) render() string { // HideEntered: empty final frame so the masked value isn't left in diff --git a/libs/cmdio/prompt_test.go b/libs/cmdio/prompt_test.go index 49aba4d680b..4f5510a0590 100644 --- a/libs/cmdio/prompt_test.go +++ b/libs/cmdio/prompt_test.go @@ -3,6 +3,8 @@ package cmdio import ( "bytes" "io" + "regexp" + "slices" "strings" "sync" "testing" @@ -14,10 +16,10 @@ import ( func TestPromptModelNoColor(t *testing.T) { m := newPromptModel(PromptOptions{Label: "Name"}, true) - assert.Contains(t, m.View(), ansiGreen) + assert.Contains(t, m.render(), ansiGreen) m = newPromptModel(PromptOptions{Label: "Name"}, false) - v := m.View() + v := m.render() assert.NotContains(t, v, ansiGreen) assert.Contains(t, v, ansiBold) } @@ -66,9 +68,24 @@ func TestRunPromptNoColor(t *testing.T) { return err } - assert.Contains(t, runWithKeys(t, false, "Name", "x\r", run), ansiGreen) + assert.True(t, hasSGR(runWithKeys(t, false, "Name", "x\r", run), ansiGreen)) out := runWithKeys(t, true, "Name", "x\r", run) - assert.NotContains(t, out, ansiGreen) - assert.Contains(t, out, ansiBold) + assert.False(t, hasSGR(out, ansiGreen)) + assert.True(t, hasSGR(out, ansiBold)) +} + +var sgrSequence = regexp.MustCompile(`\x1b\[([0-9;]*)m`) + +// hasSGR reports whether out sets the attribute of the single-parameter SGR +// sequence want, e.g. "\x1b[32m". Bubble Tea v2 re-encodes what a view +// writes, merging parameters ("\x1b[32;1m"), so the bytes don't survive. +func hasSGR(out, want string) bool { + code := sgrSequence.FindStringSubmatch(want)[1] + for _, m := range sgrSequence.FindAllStringSubmatch(out, -1) { + if slices.Contains(strings.Split(m[1], ";"), code) { + return true + } + } + return false } diff --git a/libs/cmdio/select.go b/libs/cmdio/select.go index 47dd423b393..c493699c4a8 100644 --- a/libs/cmdio/select.go +++ b/libs/cmdio/select.go @@ -9,7 +9,7 @@ import ( "text/template" "unicode/utf8" - tea "github.com/charmbracelet/bubbletea" + tea "charm.land/bubbletea/v2" "github.com/databricks/cli/libs/cmdio/teainput" ) @@ -246,7 +246,8 @@ func parsePromptTemplate(funcs template.FuncMap, name, src string) (*template.Te return t, nil } -func (m *selectModel) Init() tea.Cmd { return tea.HideCursor } +// Init is a no-op: Bubble Tea hides the cursor while a program runs. +func (m *selectModel) Init() tea.Cmd { return nil } func (m *selectModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { in, ok := teainput.Decode(msg) @@ -359,7 +360,7 @@ func (m *selectModel) appendFilter(s string) { m.recomputeMatches() } -func (m *selectModel) View() string { return m.render() } +func (m *selectModel) View() tea.View { return tea.NewView(m.render()) } func (m *selectModel) render() string { var b strings.Builder diff --git a/libs/cmdio/select_test.go b/libs/cmdio/select_test.go index 61e9477cf08..d34d768812e 100644 --- a/libs/cmdio/select_test.go +++ b/libs/cmdio/select_test.go @@ -14,12 +14,12 @@ func TestSelectModelNoColor(t *testing.T) { m, err := newSelectModel(opts, true) require.NoError(t, err) - assert.Contains(t, m.View(), ansiBlue) + assert.Contains(t, m.render(), 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() + v := m.render() assert.NotContains(t, v, ansiBlue) assert.Contains(t, v, ansiBold) assert.Contains(t, v, ansiUnderline) @@ -32,14 +32,14 @@ func TestRunSelectNoColor(t *testing.T) { return err } - assert.Contains(t, runWithKeys(t, false, "Pick", "\r", run), ansiBlue) + assert.True(t, hasSGR(runWithKeys(t, false, "Pick", "\r", run), ansiBlue)) // NO_COLOR: the prompt still runs, without the blue "?", but the cursor // row keeps its bold and underline. out := runWithKeys(t, true, "Pick", "\r", run) - assert.NotContains(t, out, ansiBlue) - assert.Contains(t, out, ansiBold) - assert.Contains(t, out, ansiUnderline) + assert.False(t, hasSGR(out, ansiBlue)) + assert.True(t, hasSGR(out, ansiBold)) + assert.True(t, hasSGR(out, ansiUnderline)) } // A paste is text, not keys: outside search it neither moves the cursor nor diff --git a/libs/cmdio/spinner.go b/libs/cmdio/spinner.go index 195f42f65bc..e00c1a913ff 100644 --- a/libs/cmdio/spinner.go +++ b/libs/cmdio/spinner.go @@ -7,14 +7,17 @@ import ( "sync" "time" - bubblespinner "github.com/charmbracelet/bubbles/spinner" - tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" + bubblespinner "charm.land/bubbles/v2/spinner" + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" ) // spinnerModel is the Bubble Tea model for the spinner. type spinnerModel struct { - spinner bubblespinner.Model + spinner bubblespinner.Model + // glyph renders the spinner's own style to the profile lipgloss v1 used, + // which the program's profile (see teaColorProfile) may exceed. + glyph *Renderer suffix string quitting bool startTime time.Time // non-zero when elapsed time display is enabled @@ -50,6 +53,7 @@ func newSpinnerModel(ctx context.Context, w io.Writer, opts ...SpinnerOption) sp m := spinnerModel{ spinner: s, + glyph: r, } for _, opt := range opts { opt(&m) @@ -81,7 +85,7 @@ func (m spinnerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } } -func (m spinnerModel) View() string { return m.render() } +func (m spinnerModel) View() tea.View { return tea.NewView(m.render()) } func (m spinnerModel) render() string { if m.quitting { @@ -93,7 +97,7 @@ func (m spinnerModel) render() string { elapsed := time.Since(m.startTime) result += fmt.Sprintf("%02d:%02d ", int(elapsed.Minutes()), int(elapsed.Seconds())%60) } - result += m.spinner.View() + result += m.glyph.Render(m.spinner.View()) if m.suffix != "" { result += " " + m.suffix } @@ -153,15 +157,21 @@ func (c *cmdIO) NewSpinner(ctx context.Context, opts ...SpinnerOption) *spinner // Create model and program m := newSpinnerModel(ctx, c.err, opts...) - p := tea.NewProgram( - m, + teaOpts := []tea.ProgramOption{ tea.WithInput(nil), tea.WithOutput(c.err), + tea.WithColorProfile(teaColorProfile(c.capabilities.SupportsStderrColor(), c.err)), // Note: We don't let tea capture signals to match current behavior. // This allows Ctrl-C to immediately terminate instead of being captured by Bubble Tea. tea.WithoutSignalHandler(), - ) + } + // NewTestIO's synthetic window size; nil in production. It is set up front + // because Run renders the first frame before a sent message lands. + if c.teaWindowSize != nil { + teaOpts = append(teaOpts, tea.WithWindowSize(c.teaWindowSize.Width, c.teaWindowSize.Height)) + } + p := tea.NewProgram(m, teaOpts...) // Acquire program slot (queues if another program is running) c.acquireTeaProgram(p) diff --git a/libs/cmdio/spinner_test.go b/libs/cmdio/spinner_test.go index 203e9235878..51128bc304f 100644 --- a/libs/cmdio/spinner_test.go +++ b/libs/cmdio/spinner_test.go @@ -1,12 +1,14 @@ package cmdio import ( + "bytes" "context" "io" "sync" "testing" "time" + "github.com/charmbracelet/colorprofile" "github.com/stretchr/testify/assert" ) @@ -43,7 +45,7 @@ func TestSpinnerModelViewActive(t *testing.T) { m := newSpinnerModel(MockDiscard(t.Context()), io.Discard) m.suffix = "loading" - view := m.View() + view := m.render() assert.NotEmpty(t, view) assert.Contains(t, view, "loading") @@ -53,7 +55,7 @@ func TestSpinnerModelViewQuitting(t *testing.T) { m := newSpinnerModel(MockDiscard(t.Context()), io.Discard) m.quitting = true - view := m.View() + view := m.render() assert.Empty(t, view) } @@ -149,3 +151,13 @@ func TestSpinnerStructConcurrentClose(t *testing.T) { // Additional Close should still be safe sp.Close() } + +func TestSpinnerGlyphFollowsRenderer(t *testing.T) { + // lipgloss v2 styles always emit color; the glyph must still follow the + // renderer's profile, which is NoTTY for a writer without color. + m := newSpinnerModel(MockDiscard(t.Context()), &bytes.Buffer{}) + assert.NotContains(t, m.render(), "\x1b") + + m.glyph = &Renderer{profile: colorprofile.ANSI} + assert.Contains(t, m.render(), "\x1b[92m") +} diff --git a/libs/cmdio/teainput/press.go b/libs/cmdio/teainput/press.go index aedd2e2c4e3..a2d22d5d159 100644 --- a/libs/cmdio/teainput/press.go +++ b/libs/cmdio/teainput/press.go @@ -2,48 +2,79 @@ package teainput import ( "strings" + "unicode/utf8" - tea "github.com/charmbracelet/bubbletea" + tea "charm.land/bubbletea/v2" ) -// v1KeyTypes maps the keystroke names used by [Event.Key] to v1 key types. -var v1KeyTypes = func() map[string]tea.KeyType { - m := map[string]tea.KeyType{} - // v1 key types are control codes (0..127) and negative special keys. - for k := tea.KeyType(-128); k < 128; k++ { - if name := k.String(); name != "" && name != " " { - m[name] = k - } - } - m["space"] = tea.KeySpace - return m -}() +// namedKeys maps the non-printable keystroke names used by [Event.Key] to key +// codes. +var namedKeys = map[string]rune{ + "enter": tea.KeyEnter, + "tab": tea.KeyTab, + "backspace": tea.KeyBackspace, + "esc": tea.KeyEscape, + "space": tea.KeySpace, + "delete": tea.KeyDelete, + "insert": tea.KeyInsert, + "up": tea.KeyUp, + "down": tea.KeyDown, + "left": tea.KeyLeft, + "right": tea.KeyRight, + "home": tea.KeyHome, + "end": tea.KeyEnd, + "pgup": tea.KeyPgUp, + "pgdown": tea.KeyPgDown, +} + +var modifierPrefixes = []struct { + prefix string + mod tea.KeyMod +}{ + {"ctrl+", tea.ModCtrl}, + {"alt+", tea.ModAlt}, + {"shift+", tea.ModShift}, +} // Press builds the message for a key press, named like [Event.Key] // (e.g. "enter", "ctrl+c", "alt+backspace", "space", "q"). It exists so model // tests don't construct version-specific key messages. func Press(key string) tea.Msg { - alt := false - if rest, ok := strings.CutPrefix(key, "alt+"); ok && rest != "" { - alt, key = true, rest + var mod tea.KeyMod + for _, p := range modifierPrefixes { + if rest, ok := strings.CutPrefix(key, p.prefix); ok && rest != "" { + mod |= p.mod + key = rest + } } - if t, ok := v1KeyTypes[key]; ok { - msg := tea.KeyMsg{Type: t, Alt: alt} - if t == tea.KeySpace { - msg.Runes = []rune{' '} + + if code, ok := namedKeys[key]; ok { + k := tea.Key{Code: code, Mod: mod} + if code == tea.KeySpace && mod == 0 { + k.Text = " " } - return msg + return tea.KeyPressMsg(k) } - return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(key), Alt: alt} + + r, _ := utf8.DecodeRuneInString(key) + k := tea.Key{Code: r, Mod: mod} + if mod&^tea.ModShift == 0 { + k.Text = key + } + return tea.KeyPressMsg(k) } // Type builds the message for typing text as a single event, like a burst of // fast typing. func Type(text string) tea.Msg { - return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(text)} + r, _ := utf8.DecodeRuneInString(text) + if utf8.RuneCountInString(text) > 1 { + r = tea.KeyExtended + } + return tea.KeyPressMsg(tea.Key{Code: r, Text: text}) } // Paste builds the message for a bracketed paste of text. func Paste(text string) tea.Msg { - return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(text), Paste: true} + return tea.PasteMsg{Content: text} } diff --git a/libs/cmdio/teainput/teainput.go b/libs/cmdio/teainput/teainput.go index ef65f45905d..4f6f5c4e8cd 100644 --- a/libs/cmdio/teainput/teainput.go +++ b/libs/cmdio/teainput/teainput.go @@ -4,23 +4,25 @@ // The shape follows Bubble Tea v2: keys are matched by their keystroke name // ("enter", "ctrl+c", "space", "alt+backspace", "a") and printable input is // carried as text, with bracketed paste as a separate event. Models written -// against [Event] don't depend on the version-specific key API, so moving to -// v2 only changes this package. +// against [Event] don't depend on the version-specific key API, so a future +// Bubble Tea change only touches this package. package teainput import ( - tea "github.com/charmbracelet/bubbletea" + "unicode/utf8" + + tea "charm.land/bubbletea/v2" ) // Event is a decoded key press or paste. type Event struct { // Key is the keystroke name, e.g. "enter", "ctrl+c", "space", // "alt+backspace" or "a". It is empty when the message carries only text, - // which is a paste, or several runes that arrived in one read. + // which is a paste or several runes that arrived in one read. Key string // Text is the printable text the event inserts. It is empty for - // non-printable keys and for Alt-modified runes. + // non-printable keys and for Alt- or Ctrl-modified keys. Text string // Paste is set when Text came from a bracketed paste. @@ -33,47 +35,48 @@ type Event struct { // Alt stays in the name, so Alt+Enter is "alt+enter" and no model matches it // unless it names it. Alt+rune and Alt+space carry no text. func Decode(msg tea.Msg) (Event, bool) { - k, ok := msg.(tea.KeyMsg) - if !ok { - return Event{}, false - } - if k.Paste { - return Event{Text: string(k.Runes), Paste: true}, true + switch m := msg.(type) { + case tea.PasteMsg: + return Event{Text: m.Content, Paste: true}, true + case tea.KeyPressMsg: + return decodeKey(m), true } + return Event{}, false +} - switch k.Type { //nolint:exhaustive // only runes, space, backspace and tab carry Alt or text - case tea.KeyRunes: - if k.Alt { - if len(k.Runes) == 1 { - return Event{Key: "alt+" + string(k.Runes)}, true - } - return Event{}, true - } - // One rune is a key press. Several runes in one read are typed text - // (or a paste without brackets) and get no key name, so a burst that - // spells a key name, like "enter", is text and not that key. - if len(k.Runes) == 1 { - return printable(string(k.Runes)), true - } - return Event{Text: string(k.Runes)}, true - case tea.KeySpace: - if k.Alt { - return Event{Key: "alt+space"}, true - } - return printable(" "), true - case tea.KeyBackspace, tea.KeyTab: - if k.Alt { - return Event{Key: k.String()}, true - } +func decodeKey(m tea.KeyPressMsg) Event { + if m.Mod.Contains(tea.ModAlt) || m.Mod.Contains(tea.ModCtrl) { + return Event{Key: KeyName(m)} + } + if m.Text == "" { + return Event{Key: KeyName(m)} } - return Event{Key: k.String()}, true + // One rune is a key press. Several runes in one read are typed text (or a + // paste without brackets) and get no key name, so a burst that spells a key + // name, like "enter", is text and not that key. + if utf8.RuneCountInString(m.Text) > 1 { + return Event{Text: m.Text} + } + if m.Text == " " { + return Event{Key: "space", Text: m.Text} + } + return Event{Key: m.Text, Text: m.Text} } -// printable is the event for one typed rune: its key name is the rune, or -// "space" for a space. -func printable(s string) Event { - if s == " " { - return Event{Key: "space", Text: s} +// KeyName returns the keystroke name models match on, for models that switch +// on [tea.KeyPressMsg] directly instead of going through [Decode]. +// +// Shift+Enter is reported as "enter". Bubble Tea v2 enables the kitty keyboard +// protocol and modifyOtherKeys, so terminals that support them (Ghostty, +// kitty, WezTerm) send Shift+Enter as a distinct key; without those protocols +// it arrives as a plain CR, which is how users of these prompts know it. +func KeyName(m tea.KeyPressMsg) string { + name := m.String() + if m.Mod.Contains(tea.ModAlt) || m.Mod.Contains(tea.ModCtrl) { + name = m.Keystroke() + } + if name == "shift+enter" { + return "enter" } - return Event{Key: s, Text: s} + return name } diff --git a/libs/cmdio/teainput/teainput_test.go b/libs/cmdio/teainput/teainput_test.go index 39284725943..d491129db7e 100644 --- a/libs/cmdio/teainput/teainput_test.go +++ b/libs/cmdio/teainput/teainput_test.go @@ -3,46 +3,45 @@ package teainput import ( "testing" - tea "github.com/charmbracelet/bubbletea" + tea "charm.land/bubbletea/v2" "github.com/stretchr/testify/assert" ) +func key(k tea.Key) tea.Msg { return tea.KeyPressMsg(k) } + func TestDecode(t *testing.T) { cases := []struct { name string msg tea.Msg want Event }{ - {"rune", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("a")}, Event{Key: "a", Text: "a"}}, - {"alt rune", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("f"), Alt: true}, Event{Key: "alt+f"}}, - {"alt runes", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("fb"), Alt: true}, Event{}}, - {"space", tea.KeyMsg{Type: tea.KeySpace, Runes: []rune(" ")}, Event{Key: "space", Text: " "}}, - {"space as rune", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(" ")}, Event{Key: "space", Text: " "}}, - {"alt space", tea.KeyMsg{Type: tea.KeySpace, Runes: []rune(" "), Alt: true}, Event{Key: "alt+space"}}, - {"enter", tea.KeyMsg{Type: tea.KeyEnter}, Event{Key: "enter"}}, - {"ctrl+j", tea.KeyMsg{Type: tea.KeyCtrlJ}, Event{Key: "ctrl+j"}}, - {"ctrl+c", tea.KeyMsg{Type: tea.KeyCtrlC}, Event{Key: "ctrl+c"}}, - {"ctrl+h", tea.KeyMsg{Type: tea.KeyCtrlH}, Event{Key: "ctrl+h"}}, - {"backspace", tea.KeyMsg{Type: tea.KeyBackspace}, Event{Key: "backspace"}}, - {"alt backspace", tea.KeyMsg{Type: tea.KeyBackspace, Alt: true}, Event{Key: "alt+backspace"}}, - {"esc", tea.KeyMsg{Type: tea.KeyEsc}, Event{Key: "esc"}}, - {"tab", tea.KeyMsg{Type: tea.KeyTab}, Event{Key: "tab"}}, - {"alt tab", tea.KeyMsg{Type: tea.KeyTab, Alt: true}, Event{Key: "alt+tab"}}, - {"shift+tab", tea.KeyMsg{Type: tea.KeyShiftTab}, Event{Key: "shift+tab"}}, - {"delete", tea.KeyMsg{Type: tea.KeyDelete}, Event{Key: "delete"}}, - {"up", tea.KeyMsg{Type: tea.KeyUp}, Event{Key: "up"}}, - {"alt enter", tea.KeyMsg{Type: tea.KeyEnter, Alt: true}, Event{Key: "alt+enter"}}, - {"alt ctrl+c", tea.KeyMsg{Type: tea.KeyCtrlC, Alt: true}, Event{Key: "alt+ctrl+c"}}, - {"alt left", tea.KeyMsg{Type: tea.KeyLeft, Alt: true}, Event{Key: "alt+left"}}, + {"rune", key(tea.Key{Code: 'a', Text: "a"}), Event{Key: "a", Text: "a"}}, + {"shifted rune", key(tea.Key{Code: 'q', ShiftedCode: 'Q', Mod: tea.ModShift, Text: "Q"}), Event{Key: "Q", Text: "Q"}}, + {"alt rune", key(tea.Key{Code: 'f', Mod: tea.ModAlt}), Event{Key: "alt+f"}}, + {"space", key(tea.Key{Code: tea.KeySpace, Text: " "}), Event{Key: "space", Text: " "}}, + {"alt space", key(tea.Key{Code: tea.KeySpace, Mod: tea.ModAlt}), Event{Key: "alt+space"}}, + {"enter", key(tea.Key{Code: tea.KeyEnter}), Event{Key: "enter"}}, + {"shift+enter", key(tea.Key{Code: tea.KeyEnter, Mod: tea.ModShift}), Event{Key: "enter"}}, + {"alt enter", key(tea.Key{Code: tea.KeyEnter, Mod: tea.ModAlt}), Event{Key: "alt+enter"}}, + {"ctrl+enter", key(tea.Key{Code: tea.KeyEnter, Mod: tea.ModCtrl}), Event{Key: "ctrl+enter"}}, + {"ctrl+j", key(tea.Key{Code: 'j', Mod: tea.ModCtrl}), Event{Key: "ctrl+j"}}, + {"ctrl+c", key(tea.Key{Code: 'c', Mod: tea.ModCtrl}), Event{Key: "ctrl+c"}}, + {"backspace", key(tea.Key{Code: tea.KeyBackspace}), Event{Key: "backspace"}}, + {"alt backspace", key(tea.Key{Code: tea.KeyBackspace, Mod: tea.ModAlt}), Event{Key: "alt+backspace"}}, + {"esc", key(tea.Key{Code: tea.KeyEscape}), Event{Key: "esc"}}, + {"tab", key(tea.Key{Code: tea.KeyTab}), Event{Key: "tab"}}, + {"shift+tab", key(tea.Key{Code: tea.KeyTab, Mod: tea.ModShift}), Event{Key: "shift+tab"}}, + {"delete", key(tea.Key{Code: tea.KeyDelete}), Event{Key: "delete"}}, + {"up", key(tea.Key{Code: tea.KeyUp}), Event{Key: "up"}}, // Several runes in one read are text. They carry no key name, so a burst // that spells a key name is typed, not pressed. - {"burst", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("jk")}, Event{Text: "jk"}}, - {"burst enter", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("enter")}, Event{Text: "enter"}}, - {"burst down", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("down")}, Event{Text: "down"}}, - {"burst ctrl+c", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("ctrl+c")}, Event{Text: "ctrl+c"}}, - {"paste", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("a b"), Paste: true}, Event{Text: "a b", Paste: true}}, - {"paste enter", tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("enter"), Paste: true}, Event{Text: "enter", Paste: true}}, - {"empty paste", tea.KeyMsg{Type: tea.KeyRunes, Paste: true}, Event{Paste: true}}, + {"burst", key(tea.Key{Code: tea.KeyExtended, Text: "jk"}), Event{Text: "jk"}}, + {"burst enter", key(tea.Key{Code: tea.KeyExtended, Text: "enter"}), Event{Text: "enter"}}, + {"burst down", key(tea.Key{Code: tea.KeyExtended, Text: "down"}), Event{Text: "down"}}, + {"burst ctrl+c", key(tea.Key{Code: tea.KeyExtended, Text: "ctrl+c"}), Event{Text: "ctrl+c"}}, + {"paste", tea.PasteMsg{Content: "a b"}, Event{Text: "a b", Paste: true}}, + {"paste enter", tea.PasteMsg{Content: "enter"}, Event{Text: "enter", Paste: true}}, + {"empty paste", tea.PasteMsg{}, Event{Paste: true}}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -57,14 +56,14 @@ func TestDecode(t *testing.T) { } func TestPressRoundTrips(t *testing.T) { - for _, key := range []string{ - "enter", "alt+enter", "ctrl+c", "alt+ctrl+c", "ctrl+j", "ctrl+h", "backspace", "alt+backspace", - "esc", "tab", "alt+tab", "shift+tab", "delete", "up", "down", "left", "right", - "space", "alt+space", "q", "Q", "alt+f", "ctrl+n", "ctrl+p", + for _, name := range []string{ + "enter", "ctrl+c", "ctrl+j", "ctrl+h", "backspace", "alt+backspace", + "esc", "tab", "shift+tab", "delete", "up", "down", "left", "right", + "space", "alt+space", "q", "alt+f", "ctrl+n", "ctrl+p", } { - ev, ok := Decode(Press(key)) + ev, ok := Decode(Press(name)) assert.True(t, ok) - assert.Equal(t, key, ev.Key) + assert.Equal(t, name, ev.Key) } ev, _ := Decode(Type("abc")) diff --git a/libs/cmdio/teaprogram.go b/libs/cmdio/teaprogram.go new file mode 100644 index 00000000000..13c091dbd55 --- /dev/null +++ b/libs/cmdio/teaprogram.go @@ -0,0 +1,111 @@ +package cmdio + +import ( + "io" + "os" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/colorprofile" +) + +// replyWait bounds how long a quitting program waits for the terminal to +// answer. The wait is normally one round trip: milliseconds locally, longer +// over SSH. Practically every terminal answers a cursor position request, so +// the bound only applies to one that doesn't; it is long enough to cover a +// slow link, where a short bound would let the answers leak after all. +const replyWait = 2 * time.Second + +// NewTeaProgram returns a Bubble Tea program for a TUI that reads keystrokes +// from in (os.Stdin when nil). When in is a terminal, quitting is deferred +// until the terminal has answered the queries Bubble Tea sent at startup. +// +// Bubble Tea v2 queries terminals that read input for synchronized output and +// unicode support (DECRQM 2026 and 2027, tea.go:1141) and for kitty keyboard +// flags (cursed_renderer.go:447). It doesn't wait for the answers, so when a +// program quits first (Enter or Ctrl+C right away, or a slow SSH link) they +// arrive after the terminal is handed back and land at the shell prompt as +// text like ^[[?2026;2$y. +func NewTeaProgram(m tea.Model, in io.Reader, opts ...tea.ProgramOption) *tea.Program { + if in == nil { + in = os.Stdin + } + if !isTTY(in) { + return tea.NewProgram(m, opts...) + } + return newGuardedProgram(m, opts...) +} + +func newGuardedProgram(m tea.Model, opts ...tea.ProgramOption) *tea.Program { + g := &replyGuard{wait: replyWait} + p := tea.NewProgram(m, append(opts, tea.WithFilter(g.filter))...) + g.send = p.Send + return p +} + +// replyGuard defers a program's quit until the terminal has answered a +// cursor position request sent at quit time. Terminals answer in order, so +// that answer arriving means every earlier query has been answered and read +// by the program too. Every terminal answers a cursor position request +// (CPR), unlike the startup queries themselves. +// +// Keystrokes typed while waiting are discarded: the model has already quit. +type replyGuard struct { + wait time.Duration + send func(tea.Msg) + + // Only the program's event loop calls filter, so these need no lock. + waiting bool + released bool + quit tea.Msg +} + +// replyGuardTimeout ends the wait when the terminal doesn't answer. +type replyGuardTimeout struct{} + +func (g *replyGuard) filter(_ tea.Model, msg tea.Msg) tea.Msg { + switch msg.(type) { + case tea.QuitMsg, tea.InterruptMsg: + if g.released { + return msg + } + if !g.waiting { + g.waiting = true + g.quit = msg + go g.send(tea.RequestCursorPosition()) + time.AfterFunc(g.wait, func() { g.send(replyGuardTimeout{}) }) + } + return nil + case tea.CursorPositionMsg, replyGuardTimeout: + if g.waiting && !g.released { + g.released = true + go g.send(g.quit) + return nil + } + if _, ok := msg.(replyGuardTimeout); ok { + return nil + } + case tea.KeyPressMsg, tea.KeyReleaseMsg, tea.PasteMsg: + if g.waiting { + return nil + } + } + return msg +} + +// teaColorProfile returns the color profile for a program writing to w whose +// view mixes cmdio's template color helpers (raw 16-color SGR, gated on +// whether w supports color, passed as color) with lipgloss styles already +// rendered through a Renderer. +// +// Bubble Tea v1 passed both through as written. v2 downsamples the whole view +// to the program's profile, so the profile must not drop what v1 showed: +// basic ANSI at least when w supports color, so helper colors survive even +// where lipgloss styles render without color (e.g. TERM unset). Without color +// it is Ascii, not NoTTY, so bold, faint, italic and underline still apply. +func teaColorProfile(color bool, w io.Writer) colorprofile.Profile { + if !color { + return colorprofile.Ascii + } + return max(colorDepth(w), colorprofile.ANSI) +} diff --git a/libs/cmdio/teaprogram_test.go b/libs/cmdio/teaprogram_test.go new file mode 100644 index 00000000000..5a88aae9985 --- /dev/null +++ b/libs/cmdio/teaprogram_test.go @@ -0,0 +1,203 @@ +package cmdio + +import ( + "bytes" + "os" + "strings" + "sync" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestReplyGuardDefersQuitUntilCursorReport(t *testing.T) { + var mu sync.Mutex + var sent []tea.Msg + g := &replyGuard{wait: time.Hour, send: func(m tea.Msg) { + mu.Lock() + defer mu.Unlock() + sent = append(sent, m) + }} + sentMsgs := func() []tea.Msg { + mu.Lock() + defer mu.Unlock() + return append([]tea.Msg(nil), sent...) + } + + assert.Nil(t, g.filter(nil, tea.QuitMsg{}), "the first quit is held") + require.Eventually(t, func() bool { return len(sentMsgs()) == 1 }, time.Second, time.Millisecond) + assert.Equal(t, tea.RequestCursorPosition(), sentMsgs()[0]) + + assert.Nil(t, g.filter(nil, tea.QuitMsg{}), "a second quit while waiting is dropped") + assert.Nil(t, g.filter(nil, tea.KeyPressMsg{Code: 'a', Text: "a"}), "keys typed after quitting are dropped") + assert.NotNil(t, g.filter(nil, tea.WindowSizeMsg{}), "other messages still reach the program") + + assert.Nil(t, g.filter(nil, tea.CursorPositionMsg{}), "the report is consumed") + require.Eventually(t, func() bool { return len(sentMsgs()) == 2 }, time.Second, time.Millisecond) + assert.Equal(t, tea.QuitMsg{}, sentMsgs()[1]) + assert.Equal(t, tea.QuitMsg{}, g.filter(nil, tea.QuitMsg{}), "the resent quit goes through") +} + +func TestReplyGuardQuitsWhenTerminalDoesNotAnswer(t *testing.T) { + quit := make(chan tea.Msg, 4) + g := &replyGuard{wait: time.Millisecond} + g.send = func(m tea.Msg) { + if m == (replyGuardTimeout{}) { + m = g.filter(nil, m) + } + if m != nil { + quit <- m + } + } + assert.Nil(t, g.filter(nil, tea.InterruptMsg{})) + // The cursor position request, then the held interrupt after the timeout. + assert.Equal(t, tea.RequestCursorPosition(), <-quit) + assert.Equal(t, tea.InterruptMsg{}, <-quit) +} + +type quitOnKeyModel struct{} + +func (quitOnKeyModel) Init() tea.Cmd { return nil } + +func (m quitOnKeyModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + if _, ok := msg.(tea.KeyPressMsg); ok { + return m, tea.Quit + } + return m, nil +} + +func (quitOnKeyModel) View() tea.View { return tea.NewView("x") } + +// fakeTerminal answers the queries a program writes to it, in order, starting +// only after delay, like a terminal at the end of a slow link. +type fakeTerminal struct { + mu sync.Mutex + seen string + queries int + replies chan string + wrote chan struct{} +} + +var fakeTerminalReplies = []struct{ query, reply string }{ + {"\x1b[?2026$p", "\x1b[?2026;2$y"}, + {"\x1b[?2027$p", "\x1b[?2027;2$y"}, + {"\x1b[?u", "\x1b[?0u"}, + {"\x1b[6n", "\x1b[1;1R"}, +} + +func newFakeTerminal(in *os.File, delay time.Duration) *fakeTerminal { + f := &fakeTerminal{replies: make(chan string, 16), wrote: make(chan struct{}, 16)} + go func() { + time.Sleep(delay) + for r := range f.replies { + _, _ = in.WriteString(r) + f.wrote <- struct{}{} + } + }() + return f +} + +// Write answers queries in the order the program wrote them, including one +// split across two writes. +func (f *fakeTerminal) Write(b []byte) (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.seen += string(b) + for { + reply, end := "", -1 + for _, q := range fakeTerminalReplies { + if i := strings.Index(f.seen, q.query); i >= 0 && (end < 0 || i+len(q.query) < end) { + reply, end = q.reply, i+len(q.query) + } + } + if end < 0 { + return len(b), nil + } + f.seen = f.seen[end:] + f.queries++ + f.replies <- reply + } +} + +func (f *fakeTerminal) queriesSeen() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.queries +} + +// runQuitImmediately runs a program that quits on the first key, typed right +// away, against a terminal that answers queries late. build makes the program +// from the options. It returns what was left unread on the program's input. +func runQuitImmediately(t *testing.T, build func(in *os.File, opts ...tea.ProgramOption) *tea.Program) string { + inR, inW, err := os.Pipe() + require.NoError(t, err) + t.Cleanup(func() { inR.Close(); inW.Close() }) + term := newFakeTerminal(inW, 100*time.Millisecond) + + opts := []tea.ProgramOption{ + tea.WithInput(inR), + tea.WithOutput(term), + tea.WithEnvironment([]string{"TERM=xterm-256color"}), + tea.WithWindowSize(80, 24), + tea.WithoutSignalHandler(), + } + p := build(inR, opts...) + go func() { _, _ = inW.WriteString("q") }() + _, err = p.Run() + require.NoError(t, err) + + // Wait for the terminal to have answered every query it saw. + queries := term.queriesSeen() + require.Positive(t, queries, "the program sent no queries") + for range queries { + select { + case <-term.wrote: + case <-time.After(5 * time.Second): + t.Fatal("fake terminal did not answer") + } + } + + // Bubble Tea puts the pipe in blocking mode, so read deadlines don't + // work: read up to a marker written after everything else instead. + _, err = inW.WriteString("\x00") + require.NoError(t, err) + var left []byte + buf := make([]byte, 64) + for !bytes.HasSuffix(left, []byte{0}) { + n, err := inR.Read(buf) + require.NoError(t, err) + left = append(left, buf[:n]...) + } + return string(bytes.TrimSuffix(left, []byte{0})) +} + +func TestGuardedProgramConsumesLateReplies(t *testing.T) { + // Without the guard the late answers are left for whoever reads next, + // which is the user's shell. + // Whether the kitty query went out depends on whether the first frame + // was rendered before quitting. + unguarded := func(in *os.File, opts ...tea.ProgramOption) *tea.Program { + return tea.NewProgram(quitOnKeyModel{}, opts...) + } + assert.Contains(t, runQuitImmediately(t, unguarded), "\x1b[?2026;2$y\x1b[?2027;2$y") + guarded := func(_ *os.File, opts ...tea.ProgramOption) *tea.Program { + return newGuardedProgram(quitOnKeyModel{}, opts...) + } + assert.Empty(t, runQuitImmediately(t, guarded)) +} + +// TestNewTeaProgramGuardsTerminalInput runs the constructor the prompts use, +// with stdin posing as a terminal, so NewTeaProgram installs the guard. The +// quit waits for the terminal's cursor report, which arrives about 100 ms in, +// well inside replyWait, so the bound is not what ends the wait. +func TestNewTeaProgramGuardsTerminalInput(t *testing.T) { + start := time.Now() + left := runQuitImmediately(t, func(in *os.File, opts ...tea.ProgramOption) *tea.Program { + return NewTeaProgram(quitOnKeyModel{}, FakeTTYReader(in), opts...) + }) + assert.Empty(t, left) + assert.Less(t, time.Since(start), replyWait) +} diff --git a/libs/cmdio/testing.go b/libs/cmdio/testing.go index 76a65420797..4c1064c6af2 100644 --- a/libs/cmdio/testing.go +++ b/libs/cmdio/testing.go @@ -6,7 +6,7 @@ import ( "context" "io" - tea "github.com/charmbracelet/bubbletea" + tea "charm.land/bubbletea/v2" "github.com/databricks/cli/libs/flags" ) diff --git a/libs/gorules/rule_lipgloss.go b/libs/gorules/rule_lipgloss.go deleted file mode 100644 index 3c647412a66..00000000000 --- a/libs/gorules/rule_lipgloss.go +++ /dev/null @@ -1,27 +0,0 @@ -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/tableview/tableview.go b/libs/tableview/tableview.go index f1b266f7cc3..68450a3f7df 100644 --- a/libs/tableview/tableview.go +++ b/libs/tableview/tableview.go @@ -8,9 +8,9 @@ import ( "strings" "text/tabwriter" - "github.com/charmbracelet/bubbles/viewport" - tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" + "charm.land/bubbles/v2/viewport" + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" "github.com/databricks/cli/libs/cmdio/teainput" "github.com/databricks/cli/libs/cmdio" @@ -60,14 +60,14 @@ func RunWithOptions(ctx context.Context, w io.Writer, columns []string, rows [][ searchStyle: r.NewStyle().Foreground(lipgloss.Color("229")), } - teaOpts := []tea.ProgramOption{tea.WithOutput(w)} + teaOpts := []tea.ProgramOption{tea.WithOutput(w), tea.WithColorProfile(r.Profile())} if opts.Input != nil { teaOpts = append(teaOpts, tea.WithInput(opts.Input)) } - p := tea.NewProgram(m, teaOpts...) if opts.Width > 0 && opts.Height > 0 { - go p.Send(tea.WindowSizeMsg{Width: opts.Width, Height: opts.Height}) + teaOpts = append(teaOpts, tea.WithWindowSize(opts.Width, opts.Height)) } + p := cmdio.NewTeaProgram(m, opts.Input, teaOpts...) _, err := p.Run() return err } @@ -211,13 +211,13 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // Reserve room for the sticky header above the viewport. height := msg.Height - fh - len(m.header) if !m.ready { - m.viewport = viewport.New(msg.Width, height) + m.viewport = viewport.New(viewport.WithWidth(msg.Width), viewport.WithHeight(height)) m.viewport.SetHorizontalStep(horizontalScrollStep) m.viewport.SetContent(m.renderContent()) m.ready = true } else { - m.viewport.Width = msg.Width - m.viewport.Height = height + m.viewport.SetWidth(msg.Width) + m.viewport.SetHeight(height) } return m, nil } @@ -243,7 +243,7 @@ func (m model) updateNormal(msg tea.Msg, key string) (tea.Model, tea.Cmd) { case "/": m.searching = true m.searchInput = "" - m.viewport.Height-- + m.viewport.SetHeight(m.viewport.Height() - 1) return m, nil case "n": if len(m.matchLines) > 0 { @@ -268,10 +268,10 @@ func (m model) updateNormal(msg tea.Msg, key string) (tea.Model, tea.Cmd) { m.moveCursor(1) return m, nil case "pgup", "b": - m.moveCursor(-m.viewport.Height) + m.moveCursor(-m.viewport.Height()) return m, nil case "pgdown", "f", "space": - m.moveCursor(m.viewport.Height) + m.moveCursor(m.viewport.Height()) return m, nil case "g": m.cursor = 0 @@ -302,12 +302,12 @@ func (m *model) moveCursor(delta int) { // scrollToCursor ensures the cursor line is visible in the viewport. func (m *model) scrollToCursor() { - top := m.viewport.YOffset - bottom := top + m.viewport.Height - 1 + top := m.viewport.YOffset() + bottom := top + m.viewport.Height() - 1 if m.cursor < top { m.viewport.SetYOffset(m.cursor) } else if m.cursor > bottom { - m.viewport.SetYOffset(m.cursor - m.viewport.Height + 1) + m.viewport.SetYOffset(m.cursor - m.viewport.Height() + 1) } } @@ -318,7 +318,7 @@ func (m model) updateSearch(in teainput.Event) (tea.Model, tea.Cmd) { m.searchQuery = m.searchInput m.matchLines = findMatches(m.lines, m.searchQuery) m.matchIdx = 0 - m.viewport.Height++ + m.viewport.SetHeight(m.viewport.Height() + 1) // Move cursor to first match and re-render. if len(m.matchLines) > 0 { m.cursor = m.matchLines[0] @@ -331,7 +331,7 @@ func (m model) updateSearch(in teainput.Event) (tea.Model, tea.Cmd) { case "esc", "ctrl+c": m.searching = false m.searchInput = "" - m.viewport.Height++ + m.viewport.SetHeight(m.viewport.Height() + 1) return m, nil case "backspace": if len(m.searchInput) > 0 { @@ -345,7 +345,7 @@ func (m model) updateSearch(in teainput.Event) (tea.Model, tea.Cmd) { } } -func (m model) View() string { return m.render() } +func (m model) View() tea.View { return tea.NewView(m.render()) } func (m model) render() string { if !m.ready { diff --git a/libs/tableview/tableview_test.go b/libs/tableview/tableview_test.go index 7d542a365b9..00b55949f36 100644 --- a/libs/tableview/tableview_test.go +++ b/libs/tableview/tableview_test.go @@ -4,7 +4,7 @@ import ( "strings" "testing" - "github.com/charmbracelet/bubbles/viewport" + "charm.land/bubbles/v2/viewport" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -81,7 +81,7 @@ func readyModel(columns []string, rows [][]string, viewportHeight int) model { header: all[:headerLines], lines: all[headerLines:], } - m.viewport = viewport.New(80, viewportHeight) + m.viewport = viewport.New(viewport.WithWidth(80), viewport.WithHeight(viewportHeight)) m.viewport.SetContent(m.renderContent()) m.ready = true return m @@ -97,7 +97,7 @@ func TestViewKeepsHeaderAboveScrollableContent(t *testing.T) { // the column header off-screen and never bring it back. m.viewport.SetYOffset(1) - out := m.View() + out := m.render() headerIdx := strings.Index(out, "id") carolIdx := strings.Index(out, "carol") require.NotEqual(t, -1, headerIdx, "View output must contain the column header")