Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 71 additions & 8 deletions cmd/selftest/tui/colors.go
Original file line number Diff line number Diff line change
@@ -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)
}
99 changes: 99 additions & 0 deletions cmd/selftest/tui/huh.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package tui

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nice to have] huh.go, profile.go, and table.go are new files with no corresponding _test.go, which .agents/rules/testing.md asks for. The rest of this directory was test-free before this PR, and the files are mostly cobra wiring for interactive commands, so the value is limited — but if any testable logic can be extracted (the way runRawKeys was pulled out of keys.go), a test file would be consistent with the pattern you already set here.


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
}
176 changes: 176 additions & 0 deletions cmd/selftest/tui/keys.go
Original file line number Diff line number Diff line change
@@ -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
}
}
}
Loading
Loading