diff --git a/cmd/selftest/tui/colors.go b/cmd/selftest/tui/colors.go index 9afc6fd693f..3415dbf0ce3 100644 --- a/cmd/selftest/tui/colors.go +++ b/cmd/selftest/tui/colors.go @@ -1,25 +1,88 @@ package tui import ( + "context" + "fmt" + "io" + "strconv" + "strings" + + "github.com/charmbracelet/lipgloss" "github.com/databricks/cli/libs/cmdio" "github.com/spf13/cobra" ) +// swatchCount is the number of blocks per depth row in --lipgloss output. +const swatchCount = 32 + func newColorsCmd() *cobra.Command { - return &cobra.Command{ + var ( + stream string + swatches bool + ) + cmd := &cobra.Command{ Use: "colors", Short: "Print colored text to verify color support", + Long: `Print colored text to verify color support. + +The named colors are rendered with cmdio helpers, which check stdout for color +support regardless of --stream. --lipgloss adds truecolor and 256-color swatches +rendered through cmdio.NewRenderer for the chosen stream, so depth differences +are visible.`, + Args: cobra.NoArgs, + PreRunE: func(cmd *cobra.Command, args []string) error { + switch stream { + case "", "stdout", "stderr": + return nil + default: + return fmt.Errorf("--stream must be stdout or stderr, got %q", stream) + } + }, RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() + w := cmd.ErrOrStderr() + if stream == "stdout" { + w = cmd.OutOrStdout() + } + swatch := "the quick brown fox jumps over the lazy dog" - cmdio.LogString(ctx, "red: "+cmdio.Red(ctx, swatch)) - cmdio.LogString(ctx, "green: "+cmdio.Green(ctx, swatch)) - cmdio.LogString(ctx, "yellow: "+cmdio.Yellow(ctx, swatch)) - cmdio.LogString(ctx, "blue: "+cmdio.Blue(ctx, swatch)) - cmdio.LogString(ctx, "cyan: "+cmdio.Cyan(ctx, swatch)) - cmdio.LogString(ctx, "hiblack: "+cmdio.HiBlack(ctx, swatch)) - cmdio.LogString(ctx, "hiblue: "+cmdio.HiBlue(ctx, swatch)) + writeLine(ctx, stream, w, "red: "+cmdio.Red(ctx, swatch)) + writeLine(ctx, stream, w, "green: "+cmdio.Green(ctx, swatch)) + writeLine(ctx, stream, w, "yellow: "+cmdio.Yellow(ctx, swatch)) + writeLine(ctx, stream, w, "blue: "+cmdio.Blue(ctx, swatch)) + writeLine(ctx, stream, w, "cyan: "+cmdio.Cyan(ctx, swatch)) + writeLine(ctx, stream, w, "hiblack: "+cmdio.HiBlack(ctx, swatch)) + writeLine(ctx, stream, w, "hiblue: "+cmdio.HiBlue(ctx, swatch)) + + if !swatches { + return nil + } + r, _ := cmdio.NewRenderer(ctx, w) + truecolor := make([]string, 0, swatchCount) + ansi256 := make([]string, 0, swatchCount) + for i := range swatchCount { + v := i * 255 / (swatchCount - 1) + hex := fmt.Sprintf("#%02x%02x%02x", v, 0, 255-v) + truecolor = append(truecolor, r.NewStyle().Background(lipgloss.Color(hex)).Render(" ")) + index := 16 + i*7 + ansi256 = append(ansi256, r.NewStyle().Background(lipgloss.Color(strconv.Itoa(index))).Render(" ")) + } + writeLine(ctx, stream, w, "truecolor: "+strings.Join(truecolor, "")) + writeLine(ctx, stream, w, "256-color: "+strings.Join(ansi256, "")) return nil }, } + cmd.Flags().StringVar(&stream, "stream", "", "write output to stdout or stderr (default: stderr)") + cmd.Flags().BoolVar(&swatches, "lipgloss", false, "also print truecolor and 256-color swatches") + return cmd +} + +// writeLine sends lines without --stream through cmdio.LogString, so the default +// output and its stderr routing are unchanged. +func writeLine(ctx context.Context, stream string, w io.Writer, s string) { + if stream == "" { + cmdio.LogString(ctx, s) + return + } + fmt.Fprintln(w, s) } diff --git a/cmd/selftest/tui/huh.go b/cmd/selftest/tui/huh.go new file mode 100644 index 00000000000..cc42e92c209 --- /dev/null +++ b/cmd/selftest/tui/huh.go @@ -0,0 +1,99 @@ +package tui + +import ( + "fmt" + "strconv" + + "github.com/charmbracelet/huh" + "github.com/charmbracelet/lipgloss" + "github.com/databricks/cli/libs/apps/prompt" + "github.com/databricks/cli/libs/cmdio" + "github.com/spf13/cobra" +) + +func newHuhCmd() *cobra.Command { + var field string + cmd := &cobra.Command{ + Use: "huh", + Short: "Run one huh form field with the appkit theme", + Long: `Run one huh form field with the appkit theme and print the answer. + +The field is built here, not by a libs/apps/prompt helper: those helpers each +set their own title, options and validation. Only prompt.AppkitTheme is shared, +so this checks the theme, not the production prompt flows.`, + Args: cobra.NoArgs, + PreRunE: func(cmd *cobra.Command, args []string) error { + switch field { + case "input", "select", "confirm", "multiselect": + return nil + default: + return fmt.Errorf("--field must be one of input, select, confirm, multiselect, got %q", field) + } + }, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() + theme := prompt.AppkitTheme() + features := databricksFeatures[:5] + options := make([]huh.Option[string], 0, len(features)) + for _, name := range features { + options = append(options, huh.NewOption(name, name)) + } + + var ( + text string + choice string + yes bool + picked []string + group huh.Field + ) + switch field { + case "input": + group = huh.NewInput().Title("Enter a value").Value(&text) + case "select": + group = huh.NewSelect[string]().Title("Pick an item").Options(options...).Value(&choice) + case "confirm": + group = huh.NewConfirm().Title("Continue?").Value(&yes) + case "multiselect": + group = huh.NewMultiSelect[string]().Title("Pick items").Options(options...).Value(&picked) + } + + if err := huh.NewForm(huh.NewGroup(group)).WithTheme(theme).Run(); err != nil { + return err + } + + var answer string + switch field { + case "input": + answer = text + case "select": + answer = choice + case "confirm": + answer = strconv.FormatBool(yes) + case "multiselect": + answer = fmt.Sprint(picked) + } + cmdio.LogString(ctx, "answer: "+answer) + + r, _ := cmdio.NewRenderer(ctx, cmd.ErrOrStderr()) + cmdio.LogString(ctx, fmt.Sprintf("dark_background=%t", r.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 := lipgloss.HasDarkBackground() + resolved := adaptive.Light + if dark { + resolved = adaptive.Dark + } + cmdio.LogString(ctx, fmt.Sprintf("blurred_button=%s (resolved, default renderer dark_background=%t)", resolved, dark)) + } else { + cmdio.LogString(ctx, fmt.Sprintf("blurred_button=%+v (not an AdaptiveColor, not resolved)", fg)) + } + return nil + }, + } + cmd.Flags().StringVar(&field, "field", "input", "field type: input, select, confirm or multiselect") + return cmd +} diff --git a/cmd/selftest/tui/keys.go b/cmd/selftest/tui/keys.go new file mode 100644 index 00000000000..4ff18a28519 --- /dev/null +++ b/cmd/selftest/tui/keys.go @@ -0,0 +1,176 @@ +package tui + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/databricks/cli/libs/cmdio" + "github.com/spf13/cobra" + "golang.org/x/term" +) + +// keysExitCtrlC is the number of Ctrl+C presses that end the keys program. +// A single press is recorded like any other key so it can be inspected. +const keysExitCtrlC = 2 + +// keysModel prints one line per key message. It draws nothing itself so the +// output stays a plain log of decoded input. Lines are written directly from +// Update: tea.Println runs its commands concurrently, so the order is not kept. +type keysModel struct { + out io.Writer + eol string + ctrlC int +} + +func (m *keysModel) Init() tea.Cmd { return nil } + +func (m *keysModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + key, ok := msg.(tea.KeyMsg) + 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 { + m.ctrlC++ + if m.ctrlC >= keysExitCtrlC { + return m, tea.Quit + } + } + return m, nil +} + +func (m *keysModel) View() string { return "" } + +func newKeysCmd() *cobra.Command { + var ( + raw bool + timeout time.Duration + ) + cmd := &cobra.Command{ + Use: "keys", + Short: "Print each key message bubbletea decodes from stdin", + Long: `Print one line per key message that bubbletea decodes from stdin. + +Uses the same tea.Program options as cmdio's prompts, so the output shows how +this terminal encodes Esc, Alt+x, Shift+Enter, Ctrl+H vs Backspace, AltGr and +bracketed paste. Exits on two Ctrl+C presses or after --timeout. + +With --raw, bubbletea is bypassed: when stdin is a terminal it is put in raw +mode, and each chunk of bytes read is printed as hex and quoted text.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() + in := cmd.InOrStdin() + out := cmd.ErrOrStderr() + if raw { + return runRawKeys(ctx, in, out, timeout) + } + // Mirrors cmdio's runTUI options. cmdio does not expose a way to run a + // custom model, so keep these in sync with libs/cmdio/io.go. + // Raw mode clears OPOST, so "\n" would not return the carriage. + eol := "\n" + if _, ok := rawInputFile(ctx, in); ok { + eol = "\r\n" + } + p := tea.NewProgram(&keysModel{out: out, eol: eol}, + tea.WithInput(in), + tea.WithOutput(out), + tea.WithoutSignalHandler(), + ) + if timeout > 0 { + timer := time.AfterFunc(timeout, p.Quit) + defer timer.Stop() + } + _, err := p.Run() + return err + }, + } + cmd.Flags().BoolVar(&raw, "raw", false, "bypass bubbletea and print the raw bytes read from stdin") + cmd.Flags().DurationVar(&timeout, "timeout", 0, "exit after this duration (0 waits for Ctrl+C)") + cmd.PreRunE = func(cmd *cobra.Command, args []string) error { + if timeout < 0 { + return fmt.Errorf("--timeout must not be negative, got %s", timeout) + } + return nil + } + return cmd +} + +// rawInputFile returns stdin as a file when it is a terminal. bubbletea and the +// --raw path put that file in raw mode, which is why output needs "\r\n". +func rawInputFile(ctx context.Context, in io.Reader) (*os.File, bool) { + f, ok := in.(*os.File) + return f, ok && cmdio.IsInputTTY(ctx) +} + +// runRawKeys reads stdin in raw mode without bubbletea. After an early return +// the reader goroutine can be blocked on Read or on sending a chunk; the +// process exits once the command finishes, so it does not need to be joined. +func runRawKeys(ctx context.Context, in io.Reader, out io.Writer, timeout time.Duration) error { + // Raw mode clears OPOST, so "\n" would not return the carriage. Print + // "\r\n" in that case so each line starts at column 0. + eol := "\n" + if f, ok := rawInputFile(ctx, in); ok { + state, err := term.MakeRaw(int(f.Fd())) + if err != nil { + return err + } + defer func() { _ = term.Restore(int(f.Fd()), state) }() + eol = "\r\n" + } + + chunks := make(chan []byte) + readErr := make(chan error, 1) + go func() { + buf := make([]byte, 256) + for { + n, err := in.Read(buf) + if n > 0 { + chunk := make([]byte, n) + copy(chunk, buf[:n]) + chunks <- chunk + } + if err != nil { + readErr <- err + return + } + } + }() + + var timeoutC <-chan time.Time + if timeout > 0 { + timer := time.NewTimer(timeout) + defer timer.Stop() + timeoutC = timer.C + } + + ctrlC := 0 + for { + select { + case chunk := <-chunks: + fmt.Fprintf(out, "raw bytes=% x text=%q%s", chunk, string(chunk), eol) + for _, b := range chunk { + if b == 0x03 { + ctrlC++ + } + } + if ctrlC >= keysExitCtrlC { + return nil + } + case err := <-readErr: + if errors.Is(err, io.EOF) { + return nil + } + return err + case <-timeoutC: + return nil + } + } +} diff --git a/cmd/selftest/tui/keys_test.go b/cmd/selftest/tui/keys_test.go new file mode 100644 index 00000000000..9dbb2ffdc70 --- /dev/null +++ b/cmd/selftest/tui/keys_test.go @@ -0,0 +1,26 @@ +package tui + +import ( + "bytes" + "testing" + + "github.com/databricks/cli/libs/cmdio" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRunRawKeysPrintsChunksAndExitsOnDoubleCtrlC(t *testing.T) { + var out bytes.Buffer + ctx := cmdio.MockDiscard(t.Context()) + err := runRawKeys(ctx, bytes.NewReader([]byte("a\x03\x03b")), &out, 0) + require.NoError(t, err) + assert.Equal(t, "raw bytes=61 03 03 62 text=\"a\\x03\\x03b\"\n", out.String()) +} + +func TestRunRawKeysReturnsOnEOF(t *testing.T) { + var out bytes.Buffer + ctx := cmdio.MockDiscard(t.Context()) + err := runRawKeys(ctx, bytes.NewReader([]byte("hi")), &out, 0) + require.NoError(t, err) + assert.Equal(t, "raw bytes=68 69 text=\"hi\"\n", out.String()) +} diff --git a/cmd/selftest/tui/pager.go b/cmd/selftest/tui/pager.go new file mode 100644 index 00000000000..c0bc07df330 --- /dev/null +++ b/cmd/selftest/tui/pager.go @@ -0,0 +1,130 @@ +package tui + +import ( + "context" + "fmt" + "time" + + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/databricks-sdk-go/listing" + "github.com/spf13/cobra" +) + +// pagerDefaultHeader matches the header that real list commands render. +var pagerDefaultHeader = cmdio.Heredoc(` + {{header "Name"}} {{header "State"}}`) + +// pagerRowTemplate matches the row template used by real list commands. +var pagerRowTemplate = cmdio.Heredoc(` + {{range .}}{{.Name|green}} {{.State}} + {{end}}`) + +type pagerRow struct { + Name string + State string +} + +// pagerFakeIterator yields synthetic rows. It implements listing.Iterator so +// the production RenderIterator decides between paged and non-paged output. +type pagerFakeIterator struct { + rows []pagerRow + next int + failAfter int // -1 disables the injected error + delayFirst time.Duration + delay time.Duration +} + +var _ listing.Iterator[pagerRow] = (*pagerFakeIterator)(nil) + +func (it *pagerFakeIterator) HasNext(context.Context) bool { + if it.failAfter >= 0 && it.next == it.failAfter { + // Report more items so the caller reaches Next and sees the error. + return true + } + return it.next < len(it.rows) +} + +func (it *pagerFakeIterator) Next(ctx context.Context) (pagerRow, error) { + delay := it.delay + if it.next == 0 { + delay = it.delayFirst + } + if delay > 0 { + select { + case <-ctx.Done(): + return pagerRow{}, ctx.Err() + case <-time.After(delay): + } + } + if it.failAfter >= 0 && it.next == it.failAfter { + return pagerRow{}, fmt.Errorf("injected iterator error after %d rows", it.failAfter) + } + row := it.rows[it.next] + it.next++ + return row, nil +} + +var pagerStates = []string{"RUNNING", "TERMINATED", "PENDING"} + +func newPagerCmd() *cobra.Command { + var ( + items int + header string + delayFirst time.Duration + delay time.Duration + failAfter int + ) + cmd := &cobra.Command{ + Use: "pager", + Short: "cmdio.RenderIterator over synthetic rows (paged only when fully interactive)", + Args: func(cmd *cobra.Command, args []string) error { + // cobra runs Args before PersistentPreRunE, which is where cmdio reads + // these annotations, so the --header flag is applied here. + cmd.Annotations["headerTemplate"] = cmdio.Heredoc(fmt.Sprintf(` + {{header %q}} {{header "State"}}`, header)) + return cobra.NoArgs(cmd, args) + }, + PreRunE: func(cmd *cobra.Command, args []string) error { + if items < 0 { + return fmt.Errorf("--items must be non-negative, got %d", items) + } + if delayFirst < 0 || delay < 0 { + return fmt.Errorf("--delay and --delay-first must not be negative, got %s and %s", delay, delayFirst) + } + if failAfter < -1 { + return fmt.Errorf("--fail-after must be -1 or greater, got %d", failAfter) + } + return nil + }, + RunE: func(cmd *cobra.Command, args []string) error { + it := &pagerFakeIterator{ + rows: buildPagerRows(items), + failAfter: failAfter, + delayFirst: delayFirst, + delay: delay, + } + return cmdio.RenderIterator(cmd.Context(), it) + }, + Annotations: map[string]string{ + "headerTemplate": pagerDefaultHeader, + "template": pagerRowTemplate, + }, + } + cmd.Flags().IntVar(&items, "items", 50, "number of rows to yield") + cmd.Flags().StringVar(&header, "header", "Name", "text for the Name column header") + cmd.Flags().DurationVar(&delayFirst, "delay-first", 0, "delay before the first row") + cmd.Flags().DurationVar(&delay, "delay", 0, "delay before each following row") + cmd.Flags().IntVar(&failAfter, "fail-after", -1, "inject an iterator error after this many rows (0 fails on the first Next, -1 disables)") + return cmd +} + +func buildPagerRows(n int) []pagerRow { + rows := make([]pagerRow, 0, n) + for i := range n { + rows = append(rows, pagerRow{ + Name: fmt.Sprintf("item-%04d", i+1), + State: pagerStates[i%len(pagerStates)], + }) + } + return rows +} diff --git a/cmd/selftest/tui/pager_test.go b/cmd/selftest/tui/pager_test.go new file mode 100644 index 00000000000..a09e79934aa --- /dev/null +++ b/cmd/selftest/tui/pager_test.go @@ -0,0 +1,48 @@ +package tui + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPagerFakeIterator(t *testing.T) { + tests := []struct { + name string + rows int + failAfter int + // wantRows is the number of rows Next returns before it stops. + wantRows int + wantErr string + }{ + {name: "no failure yields every row", rows: 3, failAfter: -1, wantRows: 3}, + {name: "failure after two rows", rows: 5, failAfter: 2, wantRows: 2, wantErr: "injected iterator error after 2 rows"}, + {name: "failure on the first Next", rows: 5, failAfter: 0, wantRows: 0, wantErr: "injected iterator error after 0 rows"}, + {name: "failure past the end is never reached", rows: 2, failAfter: 5, wantRows: 2}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ctx := t.Context() + it := &pagerFakeIterator{rows: buildPagerRows(tc.rows), failAfter: tc.failAfter} + + got := 0 + var err error + for it.HasNext(ctx) { + var row pagerRow + row, err = it.Next(ctx) + if err != nil { + break + } + require.Equal(t, buildPagerRows(tc.rows)[got], row) + got++ + } + assert.Equal(t, tc.wantRows, got) + if tc.wantErr == "" { + assert.NoError(t, err) + } else { + assert.EqualError(t, err, tc.wantErr) + } + }) + } +} diff --git a/cmd/selftest/tui/profile.go b/cmd/selftest/tui/profile.go new file mode 100644 index 00000000000..d33f98a8265 --- /dev/null +++ b/cmd/selftest/tui/profile.go @@ -0,0 +1,53 @@ +package tui + +import ( + "fmt" + "io" + + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/env" + "github.com/spf13/cobra" +) + +// profileEnvVars are the variables cmdio, lipgloss and termenv consult when +// deciding on color and background, so a mismatch in a live terminal can be +// traced. COLORFGBG is the termenv background fallback on terminals. +var profileEnvVars = []string{ + "TERM", "COLORTERM", "CLICOLOR", "CLICOLOR_FORCE", "NO_COLOR", + "COLORFGBG", "CI", "TERM_PROGRAM", "WT_SESSION", +} + +func newProfileCmd() *cobra.Command { + return &cobra.Command{ + Use: "profile", + Short: "Print the color and prompt decisions cmdio makes for stdout and stderr", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() + w := cmd.OutOrStdout() + // NO_COLOR only removes color; TERM=dumb also rules out prompts and + // spinners. The env block below has the raw values, this line the decision. + fmt.Fprintf(w, "interactive=%s prompt=%t\n", cmdio.GetInteractiveMode(ctx), cmdio.IsPromptSupported(ctx)) + for _, s := range []struct { + name string + out io.Writer + }{ + {"stdout", cmd.OutOrStdout()}, + {"stderr", cmd.ErrOrStderr()}, + } { + r, color := cmdio.NewRenderer(ctx, s.out) + fmt.Fprintf(w, "%s: supports_color=%t profile=%s dark_background=%t\n", + s.name, color, r.ColorProfile().Name(), r.HasDarkBackground()) + } + fmt.Fprintln(w, "env:") + for _, name := range profileEnvVars { + value := env.Get(ctx, name) + if value == "" { + value = "(unset or empty)" + } + fmt.Fprintf(w, " %s=%s\n", name, value) + } + return nil + }, + } +} diff --git a/cmd/selftest/tui/spinner.go b/cmd/selftest/tui/spinner.go index 799ce0585d1..e29cf269fd0 100644 --- a/cmd/selftest/tui/spinner.go +++ b/cmd/selftest/tui/spinner.go @@ -1,6 +1,7 @@ package tui import ( + "fmt" "time" "github.com/databricks/cli/libs/cmdio" @@ -8,7 +9,10 @@ import ( ) func newSpinnerCmd() *cobra.Command { - var elapsed bool + var ( + elapsed bool + duration time.Duration + ) cmd := &cobra.Command{ Use: "spinner", Short: "cmdio.NewSpinner (progress indicator)", @@ -23,7 +27,11 @@ func newSpinnerCmd() *cobra.Command { for _, msg := range spinnerMessages { sp.Update(msg.text) - time.Sleep(msg.duration) + d := msg.duration + if duration > 0 { + d = duration / time.Duration(len(spinnerMessages)) + } + time.Sleep(d) } sp.Close() @@ -33,5 +41,12 @@ func newSpinnerCmd() *cobra.Command { }, } cmd.Flags().BoolVar(&elapsed, "elapsed", false, "show an MM:SS elapsed-time prefix on the spinner") + cmd.PreRunE = func(cmd *cobra.Command, args []string) error { + if duration < 0 { + return fmt.Errorf("--duration must not be negative, got %s", duration) + } + return nil + } + cmd.Flags().DurationVar(&duration, "duration", 0, "total time the spinner runs, split across its messages (0 keeps the built-in per-message timing)") return cmd } diff --git a/cmd/selftest/tui/table.go b/cmd/selftest/tui/table.go new file mode 100644 index 00000000000..4de12daa35d --- /dev/null +++ b/cmd/selftest/tui/table.go @@ -0,0 +1,49 @@ +package tui + +import ( + "fmt" + + "github.com/databricks/cli/libs/tableview" + "github.com/spf13/cobra" +) + +func newTableCmd() *cobra.Command { + var ( + rows int + cols int + ) + cmd := &cobra.Command{ + Use: "table", + Short: "tableview.Run over generated rows (interactive browser)", + Args: cobra.NoArgs, + PreRunE: func(cmd *cobra.Command, args []string) error { + if rows < 0 { + return fmt.Errorf("--rows must be non-negative, got %d", rows) + } + if cols < 1 { + return fmt.Errorf("--cols must be at least 1, got %d", cols) + } + return nil + }, + RunE: func(cmd *cobra.Command, args []string) error { + columns := make([]string, cols) + for c := range cols { + columns[c] = fmt.Sprintf("col-%02d", c+1) + } + data := make([][]string, rows) + for r := range rows { + data[r] = make([]string, cols) + for c := range cols { + data[r][c] = fmt.Sprintf("r%04d-c%02d", r+1, c+1) + } + } + // tableview.Run does not report how the user exited, only the error. + err := tableview.Run(cmd.Context(), cmd.OutOrStdout(), columns, data) + fmt.Fprintf(cmd.ErrOrStderr(), "tableview.Run returned: %v\n", err) + return err + }, + } + cmd.Flags().IntVar(&rows, "rows", 100, "number of generated rows") + cmd.Flags().IntVar(&cols, "cols", 4, "number of generated columns") + return cmd +} diff --git a/cmd/selftest/tui/tui.go b/cmd/selftest/tui/tui.go index f1b807fc930..8476b69ffb5 100644 --- a/cmd/selftest/tui/tui.go +++ b/cmd/selftest/tui/tui.go @@ -12,12 +12,17 @@ func New() *cobra.Command { newAskCmd(), newAskYesOrNoCmd(), newColorsCmd(), + newHuhCmd(), + newKeysCmd(), + newPagerCmd(), + newProfileCmd(), newPromptCmd(), newRunSelectCmd(), newSecretCmd(), newSelectCmd(), newSelectOrderedCmd(), newSpinnerCmd(), + newTableCmd(), ) return cmd