refactor: removing huh as a dep (#742)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Revert "feat: huh gum write (#525)" This reverts commit 4d5d53169e89950000015994cd694ccc9e822f08. Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com> * Revert "Use Huh for Gum Confirm (#522)" This reverts commit f7572e387ebc7e9c52cd576b244535a89496860e. Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com> * revert: Use Huh for Gum Choose (#521) Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com> * revert: feat: huh for gum input (#524) * revert: feat: huh file picker (#523) * feat: remove huh * fix: timeouts * fix: lint issues * fix(choose): quit on ctrl+q ported over 63a3e8c8ce326ea97f1fd70e6266d7417a075082 * fix: ctrl+a to reverse selection Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com> * fix: better handle spin exit codes * fix(file): bind --[no-]permissions and --[no-]size * feat(confirm): show help * fix(confirm): fix help style * fix(file): help * fix(input): --no-show-help doesn't work * fix(input): help * fix(file): keymap improvement * fix(write): focus * feat(write): ctrl+e, keymaps, help * feat(choose): help * feat(filter): help * refactor: keymaps * fix(choose): only show 'toggle all' if there's no limit * fix(choose): don't show toggle if the choices are limited to 1 * fix(filter): match choose header color * fix(filter): add space above help * fix(filter): factor help into the height setting * chore(choose,filter): use verb for navigation label in help * fix(filter): hide toggle help if limit is 1 * fix(file): factor help into height setting (#746) * fix: lint issues * fix(file): handle ctrl+c * fix: remove full help * fix: lint ---------
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
- Co-authored-by: Christian Rocha <christian@rocha.is>
Diff stats
25 files+1370 added−288 removed
- other:+1370 added−288 removed
Provenance
- Commit
e30fc5e- Tree
211286b- Author
Carlos Alexandro Becker <caarlos0@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
d74e9ea
25 files changed+1370 added−288 removed
added:choose/choose.go+316 added
1+// Package choose provides an interface to choose one option from a given list2+// of options. The options can be provided as (new-line separated) stdin or a3+// list of arguments.4+//5+// It is different from the filter command as it does not provide a fuzzy6+// finding input, so it is best used for smaller lists of options.7+//8+// Let's pick from a list of gum flavors:9+//10+// $ gum choose "Strawberry" "Banana" "Cherry"11+package choose12+13+import (14+ "strings"15+ "time"16+17+ "github.com/charmbracelet/bubbles/help"18+ "github.com/charmbracelet/bubbles/key"19+ "github.com/charmbracelet/bubbles/paginator"20+ tea "github.com/charmbracelet/bubbletea"21+ "github.com/charmbracelet/gum/timeout"22+ "github.com/charmbracelet/lipgloss"23+)24+25+func defaultKeymap() keymap {26+ return keymap{27+ Down: key.NewBinding(28+ key.WithKeys("down", "j", "ctrl+j", "ctrl+n"),29+ key.WithHelp("↓", "down"),30+ ),31+ Up: key.NewBinding(32+ key.WithKeys("up", "k", "ctrl+k", "ctrl+p"),33+ key.WithHelp("↑", "up"),34+ ),35+ Right: key.NewBinding(36+ key.WithKeys("right", "l", "ctrl+f"),37+ key.WithHelp("→", "right"),38+ ),39+ Left: key.NewBinding(40+ key.WithKeys("left", "h", "ctrl+b"),41+ key.WithHelp("←", "left"),42+ ),43+ Home: key.NewBinding(44+ key.WithKeys("g", "home"),45+ key.WithHelp("g", "home"),46+ ),47+ End: key.NewBinding(48+ key.WithKeys("G", "end"),49+ key.WithHelp("G", "end"),50+ ),51+ ToggleAll: key.NewBinding(52+ key.WithKeys("a", "A", "ctrl+a"),53+ key.WithHelp("ctrl+a", "select all"),54+ key.WithDisabled(),55+ ),56+ Toggle: key.NewBinding(57+ key.WithKeys(" ", "tab", "x", "ctrl+@"),58+ key.WithHelp("x", "toggle"),59+ key.WithDisabled(),60+ ),61+ Abort: key.NewBinding(62+ key.WithKeys("ctrl+c", "esc"),63+ key.WithHelp("ctrl+c", "abort"),64+ ),65+ Submit: key.NewBinding(66+ key.WithKeys("enter", "ctrl+q"),67+ key.WithHelp("enter", "submit"),68+ ),69+ }70+}71+72+type keymap struct {73+ Down,74+ Up,75+ Right,76+ Left,77+ Home,78+ End,79+ ToggleAll,80+ Toggle,81+ Abort,82+ Submit key.Binding83+}84+85+// FullHelp implements help.KeyMap.86+func (k keymap) FullHelp() [][]key.Binding { return nil }87+88+// ShortHelp implements help.KeyMap.89+func (k keymap) ShortHelp() []key.Binding {90+ return []key.Binding{91+ k.Toggle,92+ key.NewBinding(93+ key.WithKeys("up", "down", "right", "left"),94+ key.WithHelp("↑↓←→", "navigate"),95+ ),96+ k.Submit,97+ k.ToggleAll,98+ }99+}100+101+type model struct {102+ height int103+ cursor string104+ selectedPrefix string105+ unselectedPrefix string106+ cursorPrefix string107+ header string108+ items []item109+ quitting bool110+ index int111+ limit int112+ numSelected int113+ currentOrder int114+ paginator paginator.Model115+ aborted bool116+ timedOut bool117+ showHelp bool118+ help help.Model119+ keymap keymap120+121+ // styles122+ cursorStyle lipgloss.Style123+ headerStyle lipgloss.Style124+ itemStyle lipgloss.Style125+ selectedItemStyle lipgloss.Style126+ hasTimeout bool127+ timeout time.Duration128+}129+130+type item struct {131+ text string132+ selected bool133+ order int134+}135+136+func (m model) Init() tea.Cmd {137+ return timeout.Init(m.timeout, nil)138+}139+140+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {141+ switch msg := msg.(type) {142+ case tea.WindowSizeMsg:143+ return m, nil144+ case timeout.TickTimeoutMsg:145+ if msg.TimeoutValue <= 0 {146+ m.quitting = true147+ m.timedOut = true148+ // If the user hasn't selected any items in a multi-select.149+ // Then we select the item that they have pressed enter on. If they150+ // have selected items, then we simply return them.151+ if m.numSelected < 1 {152+ m.items[m.index].selected = true153+ }154+ return m, tea.Quit155+ }156+ m.timeout = msg.TimeoutValue157+ return m, timeout.Tick(msg.TimeoutValue, msg.Data)158+ case tea.KeyMsg:159+ start, end := m.paginator.GetSliceBounds(len(m.items))160+ km := m.keymap161+ switch {162+ case key.Matches(msg, km.Down):163+ m.index++164+ if m.index >= len(m.items) {165+ m.index = 0166+ m.paginator.Page = 0167+ }168+ if m.index >= end {169+ m.paginator.NextPage()170+ }171+ case key.Matches(msg, km.Up):172+ m.index--173+ if m.index < 0 {174+ m.index = len(m.items) - 1175+ m.paginator.Page = m.paginator.TotalPages - 1176+ }177+ if m.index < start {178+ m.paginator.PrevPage()179+ }180+ case key.Matches(msg, km.Right):181+ m.index = clamp(m.index+m.height, 0, len(m.items)-1)182+ m.paginator.NextPage()183+ case key.Matches(msg, km.Left):184+ m.index = clamp(m.index-m.height, 0, len(m.items)-1)185+ m.paginator.PrevPage()186+ case key.Matches(msg, km.End):187+ m.index = len(m.items) - 1188+ m.paginator.Page = m.paginator.TotalPages - 1189+ case key.Matches(msg, km.Home):190+ m.index = 0191+ m.paginator.Page = 0192+ case key.Matches(msg, km.ToggleAll):193+ if m.limit <= 1 {194+ break195+ }196+ if m.numSelected < len(m.items) && m.numSelected < m.limit {197+ m = m.selectAll()198+ } else {199+ m = m.deselectAll()200+ }201+ case key.Matches(msg, km.Abort):202+ m.aborted = true203+ m.quitting = true204+ return m, tea.Quit205+ case key.Matches(msg, km.Toggle):206+ if m.limit == 1 {207+ break // no op208+ }209+210+ if m.items[m.index].selected {211+ m.items[m.index].selected = false212+ m.numSelected--213+ } else if m.numSelected < m.limit {214+ m.items[m.index].selected = true215+ m.items[m.index].order = m.currentOrder216+ m.numSelected++217+ m.currentOrder++218+ }219+ case key.Matches(msg, km.Submit):220+ m.quitting = true221+ if m.limit <= 1 && m.numSelected < 1 {222+ m.items[m.index].selected = true223+ }224+ return m, tea.Quit225+ }226+ }227+228+ var cmd tea.Cmd229+ m.paginator, cmd = m.paginator.Update(msg)230+ return m, cmd231+}232+233+func (m model) selectAll() model {234+ for i := range m.items {235+ if m.numSelected >= m.limit {236+ break // do not exceed given limit237+ }238+ if m.items[i].selected {239+ continue240+ }241+ m.items[i].selected = true242+ m.items[i].order = m.currentOrder243+ m.numSelected++244+ m.currentOrder++245+ }246+ return m247+}248+249+func (m model) deselectAll() model {250+ for i := range m.items {251+ m.items[i].selected = false252+ m.items[i].order = 0253+ }254+ m.numSelected = 0255+ m.currentOrder = 0256+ return m257+}258+259+func (m model) View() string {260+ if m.quitting {261+ return ""262+ }263+264+ var s strings.Builder265+ var timeoutStr string266+267+ start, end := m.paginator.GetSliceBounds(len(m.items))268+ for i, item := range m.items[start:end] {269+ if i == m.index%m.height {270+ s.WriteString(m.cursorStyle.Render(m.cursor))271+ } else {272+ s.WriteString(strings.Repeat(" ", lipgloss.Width(m.cursor)))273+ }274+275+ if item.selected {276+ if m.hasTimeout {277+ timeoutStr = timeout.Str(m.timeout)278+ }279+ s.WriteString(m.selectedItemStyle.Render(m.selectedPrefix + item.text + timeoutStr))280+ } else if i == m.index%m.height {281+ s.WriteString(m.cursorStyle.Render(m.cursorPrefix + item.text))282+ } else {283+ s.WriteString(m.itemStyle.Render(m.unselectedPrefix + item.text))284+ }285+ if i != m.height {286+ s.WriteRune('\n')287+ }288+ }289+290+ if m.paginator.TotalPages > 1 {291+ s.WriteString(strings.Repeat("\n", m.height-m.paginator.ItemsOnPage(len(m.items))+1))292+ s.WriteString(" " + m.paginator.View())293+ }294+295+ var parts []string296+297+ if m.header != "" {298+ parts = append(parts, m.headerStyle.Render(m.header))299+ }300+ parts = append(parts, s.String())301+ if m.showHelp {302+ parts = append(parts, m.help.View(m.keymap))303+ }304+305+ return lipgloss.JoinVertical(lipgloss.Left, parts...)306+}307+308+func clamp(x, low, high int) int {309+ if x < low {310+ return low311+ }312+ if x > high {313+ return high314+ }315+ return x316+}modified:choose/command.go+103 added-94 removed
3 unmodified lines4 "errors"5 "fmt"6 "os"7 "slices"8+ "sort"9 "strings"10 10- "github.com/charmbracelet/bubbles/key"11- "github.com/charmbracelet/huh"11+ "github.com/charmbracelet/bubbles/help"12+ "github.com/charmbracelet/bubbles/paginator"13+ tea "github.com/charmbracelet/bubbletea"14 "github.com/charmbracelet/lipgloss"15 "github.com/charmbracelet/x/ansi"16 "github.com/charmbracelet/x/term"17 18 "github.com/charmbracelet/gum/internal/exit"19 "github.com/charmbracelet/gum/internal/stdin"20 )21 20-const widthBuffer = 221-22 // Run provides a shell script interface for choosing between different through23 // options.24 func (o Options) Run() error {25+ var (26+ subduedStyle = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "#847A85", Dark: "#979797"})27+ verySubduedStyle = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "#DDDADA", Dark: "#3C3C3C"})28+ )29+30 if len(o.Options) <= 0 {31 input, _ := stdin.Read()32 if input == "" {33 return errors.New("no options provided, see `gum choose --help`")5 unmodified lines39 fmt.Println(o.Options[0])40 return nil41 }42 38- theme := huh.ThemeCharm()39- keymap := huh.NewDefaultKeyMap()40- keymap.Quit = key.NewBinding(key.WithKeys("ctrl+c", "ctrl+q"))41- options := huh.NewOptions(o.Options...)43+ // We don't need to display prefixes if we are only picking one option.44+ // Simply displaying the cursor is enough.45+ if o.Limit == 1 && !o.NoLimit {46+ o.SelectedPrefix = ""47+ o.UnselectedPrefix = ""48+ o.CursorPrefix = ""49+ }50 43- theme.Focused.Base = lipgloss.NewStyle()44- theme.Focused.Title = o.HeaderStyle.ToLipgloss()45- theme.Focused.SelectSelector = o.CursorStyle.ToLipgloss().SetString(o.Cursor)46- theme.Focused.MultiSelectSelector = o.CursorStyle.ToLipgloss().SetString(o.Cursor)47- theme.Focused.SelectedOption = o.SelectedItemStyle.ToLipgloss()48- theme.Focused.UnselectedOption = o.ItemStyle.ToLipgloss()49- theme.Focused.SelectedPrefix = o.SelectedItemStyle.ToLipgloss().SetString(o.SelectedPrefix)50- theme.Focused.UnselectedPrefix = o.ItemStyle.ToLipgloss().SetString(o.UnselectedPrefix)51+ if o.NoLimit {52+ o.Limit = len(o.Options) + 153+ }54 55 if o.Ordered {53- slices.SortFunc(options, func(a, b huh.Option[string]) int {54- return strings.Compare(a.Key, b.Key)55- })56+ slices.SortFunc(o.Options, strings.Compare)57 }58 58- for _, s := range o.Selected {59- for i, opt := range options {60- if s == opt.Key || s == opt.Value {61- options[i] = opt.Selected(true)59+ // Keep track of the selected items.60+ currentSelected := 061+ // Check if selected items should be used.62+ hasSelectedItems := len(o.Selected) > 063+ startingIndex := 064+ currentOrder := 065+ items := make([]item, len(o.Options))66+ for i, option := range o.Options {67+ var order int68+ // Check if the option should be selected.69+ isSelected := hasSelectedItems && currentSelected < o.Limit && slices.Contains(o.Selected, option)70+ // If the option is selected then increment the current selected count.71+ if isSelected {72+ if o.Limit == 1 {73+ // When the user can choose only one option don't select the option but74+ // start with the cursor hovering over it.75+ startingIndex = i76+ isSelected = false77+ } else {78+ currentSelected++79+ order = currentOrder80+ currentOrder++81 }82 }83+ items[i] = item{text: option, selected: isSelected, order: order}84 }85 66- width := max(widest(o.Options)+67- max(lipgloss.Width(o.SelectedPrefix)+lipgloss.Width(o.UnselectedPrefix))+68- lipgloss.Width(o.Cursor)+1, lipgloss.Width(o.Header)+widthBuffer)86+ // Use the pagination model to display the current and total number of87+ // pages.88+ pager := paginator.New()89+ pager.SetTotalPages((len(items) + o.Height - 1) / o.Height)90+ pager.PerPage = o.Height91+ pager.Type = paginator.Dots92+ pager.ActiveDot = subduedStyle.Render("•")93+ pager.InactiveDot = verySubduedStyle.Render("•")94+ pager.KeyMap = paginator.KeyMap{}95+ pager.Page = startingIndex / o.Height96 97+ km := defaultKeymap()98+ if o.NoLimit || o.Limit > 1 {99+ km.Toggle.SetEnabled(true)100+ }101 if o.NoLimit {71- o.Limit = 0102+ km.ToggleAll.SetEnabled(true)103 }104 74- if o.Limit > 1 || o.NoLimit {75- var choices []string76-77- field := huh.NewMultiSelect[string]().78- Options(options...).79- Title(o.Header).80- Height(o.Height).81- Limit(o.Limit).82- Value(&choices)83-84- form := huh.NewForm(huh.NewGroup(field))85-86- err := form.87- WithWidth(width).88- WithShowHelp(o.ShowHelp).89- WithTheme(theme).90- WithKeyMap(keymap).91- WithTimeout(o.Timeout).92- Run()93- if err != nil {94- return exit.Handle(err, o.Timeout)95- }96- if len(choices) > 0 {97- s := strings.Join(choices, "\n")98- ansiprint(s)99- }100- return nil101- }102-103- var choice string104-105- err := huh.NewForm(106- huh.NewGroup(107- huh.NewSelect[string]().108- Options(options...).109- Title(o.Header).110- Height(o.Height).111- Value(&choice),112- ),113- ).114- WithWidth(width).115- WithTheme(theme).116- WithKeyMap(keymap).117- WithTimeout(o.Timeout).118- WithShowHelp(o.ShowHelp).119- Run()105+ // Disable Keybindings since we will control it ourselves.106+ tm, err := tea.NewProgram(model{107+ index: startingIndex,108+ currentOrder: currentOrder,109+ height: o.Height,110+ cursor: o.Cursor,111+ header: o.Header,112+ selectedPrefix: o.SelectedPrefix,113+ unselectedPrefix: o.UnselectedPrefix,114+ cursorPrefix: o.CursorPrefix,115+ items: items,116+ limit: o.Limit,117+ paginator: pager,118+ cursorStyle: o.CursorStyle.ToLipgloss(),119+ headerStyle: o.HeaderStyle.ToLipgloss(),120+ itemStyle: o.ItemStyle.ToLipgloss(),121+ selectedItemStyle: o.SelectedItemStyle.ToLipgloss(),122+ numSelected: currentSelected,123+ hasTimeout: o.Timeout > 0,124+ timeout: o.Timeout,125+ showHelp: o.ShowHelp,126+ help: help.New(),127+ keymap: km,128+ }, tea.WithOutput(os.Stderr)).Run()129 if err != nil {121- return exit.Handle(err, o.Timeout)130+ return fmt.Errorf("failed to start tea program: %w", err)131 }123-124- if term.IsTerminal(os.Stdout.Fd()) {125- fmt.Println(choice)126- } else {127- fmt.Print(ansi.Strip(choice))132+ m := tm.(model)133+ if m.aborted {134+ return exit.ErrAborted135 }129-130- return nil131-}132-133-func widest(options []string) int {134- var maxw int135- for _, o := range options {136- w := lipgloss.Width(o)137- if w > maxw {138- maxw = w136+ if m.timedOut {137+ return exit.ErrTimeout138+ }139+ if o.Ordered && o.Limit > 1 {140+ sort.Slice(m.items, func(i, j int) bool {141+ return m.items[i].order < m.items[j].order142+ })143+ }144+ var s strings.Builder145+ for _, item := range m.items {146+ if item.selected {147+ s.WriteString(item.text)148+ s.WriteRune('\n')149 }150 }141- return maxw142-}151 144-func ansiprint(s string) {152 if term.IsTerminal(os.Stdout.Fd()) {146- fmt.Println(s)153+ fmt.Print(s.String())154 } else {148- fmt.Print(ansi.Strip(s))155+ fmt.Print(ansi.Strip(s.String()))156 }157+158+ return nil159 }modified:choose/options.go+2 added-2 removed
10 unmodified lines11 Options []string `arg:"" optional:"" help:"Options to choose from."`12 Limit int `help:"Maximum number of options to pick" default:"1" group:"Selection"`13 NoLimit bool `help:"Pick unlimited number of options (ignores limit)" group:"Selection"`14 Ordered bool `help:"Maintain the order of the selected options" env:"GUM_CHOOSE_ORDERED"`15- Height int `help:"Height of the list" default:"0" env:"GUM_CHOOSE_HEIGHT"`15+ Height int `help:"Height of the list" default:"10" env:"GUM_CHOOSE_HEIGHT"`16 Cursor string `help:"Prefix to show on item that corresponds to the cursor position" default:"> " env:"GUM_CHOOSE_CURSOR"`17- ShowHelp bool `help:"Show help keybinds" default:"true" negatable:"true" env:"GUM_CHOOSE_SHOW_HELP"`17+ ShowHelp bool `help:"Show help keybinds" default:"true" negatable:"" env:"GUM_CHOOSE_SHOW_HELP"`18 Header string `help:"Header value" default:"Choose:" env:"GUM_CHOOSE_HEADER"`19 CursorPrefix string `help:"Prefix to show on the cursor item (hidden if limit is 1)" default:"• " env:"GUM_CHOOSE_CURSOR_PREFIX"`20 SelectedPrefix string `help:"Prefix to show on selected items (hidden if limit is 1)" default:"✓ " env:"GUM_CHOOSE_SELECTED_PREFIX"`21 UnselectedPrefix string `help:"Prefix to show on unselected items (hidden if limit is 1)" default:"• " env:"GUM_CHOOSE_UNSELECTED_PREFIX"`8 unmodified linesmodified:confirm/command.go+30 added-25 removed
1 package confirm2 3 import (4+ "errors"5 "os"6 7+ "github.com/charmbracelet/bubbles/help"8 "github.com/charmbracelet/gum/internal/exit"7- "github.com/charmbracelet/huh"9+10+ tea "github.com/charmbracelet/bubbletea"11 )12 13 // Run provides a shell script interface for prompting a user to confirm an14 // action with an affirmative or negative answer.15 func (o Options) Run() error {13- theme := huh.ThemeCharm()14- theme.Focused.Title = o.PromptStyle.ToLipgloss()15- theme.Focused.FocusedButton = o.SelectedStyle.ToLipgloss()16- theme.Focused.BlurredButton = o.UnselectedStyle.ToLipgloss()17-18- choice := o.Default19-20- err := huh.NewForm(21- huh.NewGroup(22- huh.NewConfirm().23- Affirmative(o.Affirmative).24- Negative(o.Negative).25- Title(o.Prompt).26- Value(&choice),27- ),28- ).29- WithTimeout(o.Timeout).30- WithTheme(theme).31- WithShowHelp(o.ShowHelp).32- Run()16+ tm, err := tea.NewProgram(model{17+ affirmative: o.Affirmative,18+ negative: o.Negative,19+ confirmation: o.Default,20+ defaultSelection: o.Default,21+ timeout: o.Timeout,22+ hasTimeout: o.Timeout > 0,23+ keys: defaultKeymap(o.Affirmative, o.Negative),24+ help: help.New(),25+ showHelp: o.ShowHelp,26+ prompt: o.Prompt,27+ selectedStyle: o.SelectedStyle.ToLipgloss(),28+ unselectedStyle: o.UnselectedStyle.ToLipgloss(),29+ promptStyle: o.PromptStyle.ToLipgloss(),30+ }, tea.WithOutput(os.Stderr)).Run()31 if err != nil {34- return exit.Handle(err, o.Timeout)32+ return err33 }34 37- if !choice {38- os.Exit(1)35+ m := tm.(model)36+ if m.timedOut {37+ return exit.ErrTimeout38 }39+ if m.aborted {40+ return exit.ErrAborted41+ }42+ if m.confirmation {43+ return nil44+ }45 41- return nil46+ return errors.New("not confirmed")47 }added:confirm/confirm.go+194 added
1+// Package confirm provides an interface to ask a user to confirm an action.2+// The user is provided with an interface to choose an affirmative or negative3+// answer, which is then reflected in the exit code for use in scripting.4+//5+// If the user selects the affirmative answer, the program exits with 0. If the6+// user selects the negative answer, the program exits with 1.7+//8+// I.e. confirm if the user wants to delete a file9+//10+// $ gum confirm "Are you sure?" && rm file.txt11+package confirm12+13+import (14+ "time"15+16+ "github.com/charmbracelet/bubbles/help"17+ "github.com/charmbracelet/bubbles/key"18+ "github.com/charmbracelet/gum/timeout"19+20+ tea "github.com/charmbracelet/bubbletea"21+ "github.com/charmbracelet/lipgloss"22+)23+24+func defaultKeymap(affirmative, negative string) keymap {25+ return keymap{26+ Abort: key.NewBinding(27+ key.WithKeys("ctrl+c"),28+ key.WithHelp("ctrl+c", "cancel"),29+ ),30+ Quit: key.NewBinding(31+ key.WithKeys("esc"),32+ key.WithHelp("esc", "quit"),33+ ),34+ Negative: key.NewBinding(35+ key.WithKeys("n", "N", "q"),36+ key.WithHelp("n", negative),37+ ),38+ Affirmative: key.NewBinding(39+ key.WithKeys("y", "Y"),40+ key.WithHelp("y", affirmative),41+ ),42+ Toggle: key.NewBinding(43+ key.WithKeys(44+ "left",45+ "h",46+ "ctrl+n",47+ "shift+tab",48+ "right",49+ "l",50+ "ctrl+p",51+ "tab",52+ ),53+ key.WithHelp("←/→", "toggle"),54+ ),55+ Submit: key.NewBinding(56+ key.WithKeys("enter"),57+ key.WithHelp("enter", "submit"),58+ ),59+ }60+}61+62+type keymap struct {63+ Abort key.Binding64+ Quit key.Binding65+ Negative key.Binding66+ Affirmative key.Binding67+ Toggle key.Binding68+ Submit key.Binding69+}70+71+// FullHelp implements help.KeyMap.72+func (k keymap) FullHelp() [][]key.Binding { return nil }73+74+// ShortHelp implements help.KeyMap.75+func (k keymap) ShortHelp() []key.Binding {76+ return []key.Binding{k.Toggle, k.Submit, k.Affirmative, k.Negative}77+}78+79+type model struct {80+ prompt string81+ affirmative string82+ negative string83+ quitting bool84+ aborted bool85+ hasTimeout bool86+ showHelp bool87+ help help.Model88+ keys keymap89+ timeout time.Duration90+91+ confirmation bool92+ timedOut bool93+94+ defaultSelection bool95+96+ // styles97+ promptStyle lipgloss.Style98+ selectedStyle lipgloss.Style99+ unselectedStyle lipgloss.Style100+}101+102+func (m model) Init() tea.Cmd {103+ return timeout.Init(m.timeout, m.defaultSelection)104+}105+106+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {107+ switch msg := msg.(type) {108+ case tea.WindowSizeMsg:109+ return m, nil110+ case tea.KeyMsg:111+ switch {112+ case key.Matches(msg, m.keys.Abort):113+ m.confirmation = false114+ m.aborted = true115+ fallthrough116+ case key.Matches(msg, m.keys.Quit):117+ m.confirmation = false118+ m.quitting = true119+ return m, tea.Quit120+ case key.Matches(msg, m.keys.Negative):121+ m.confirmation = false122+ m.quitting = true123+ return m, tea.Quit124+ case key.Matches(msg, m.keys.Toggle):125+ if m.negative == "" {126+ break127+ }128+ m.confirmation = !m.confirmation129+ case key.Matches(msg, m.keys.Submit):130+ m.quitting = true131+ return m, tea.Quit132+ case key.Matches(msg, m.keys.Affirmative):133+ m.quitting = true134+ m.confirmation = true135+ return m, tea.Quit136+ }137+ case timeout.TickTimeoutMsg:138+ if msg.TimeoutValue <= 0 {139+ m.quitting = true140+ m.confirmation = m.defaultSelection141+ m.timedOut = true142+ return m, tea.Quit143+ }144+145+ m.timeout = msg.TimeoutValue146+ return m, timeout.Tick(msg.TimeoutValue, msg.Data)147+ }148+ return m, nil149+}150+151+func (m model) View() string {152+ if m.quitting {153+ return ""154+ }155+156+ var aff, neg, timeoutStrYes, timeoutStrNo string157+ timeoutStrNo = ""158+ timeoutStrYes = ""159+ if m.hasTimeout {160+ if m.defaultSelection {161+ timeoutStrYes = timeout.Str(m.timeout)162+ } else {163+ timeoutStrNo = timeout.Str(m.timeout)164+ }165+ }166+167+ if m.confirmation {168+ aff = m.selectedStyle.Render(m.affirmative + timeoutStrYes)169+ neg = m.unselectedStyle.Render(m.negative + timeoutStrNo)170+ } else {171+ aff = m.unselectedStyle.Render(m.affirmative + timeoutStrYes)172+ neg = m.selectedStyle.Render(m.negative + timeoutStrNo)173+ }174+175+ // If the option is intentionally empty, do not show it.176+ if m.negative == "" {177+ neg = ""178+ }179+180+ if m.showHelp {181+ return lipgloss.JoinVertical(182+ lipgloss.Left,183+ m.promptStyle.Render(m.prompt)+"\n",184+ lipgloss.JoinHorizontal(lipgloss.Left, aff, neg),185+ "\n"+m.help.View(m.keys),186+ )187+ }188+189+ return lipgloss.JoinVertical(190+ lipgloss.Left,191+ m.promptStyle.Render(m.prompt)+"\n",192+ lipgloss.JoinHorizontal(lipgloss.Left, aff, neg),193+ )194+}modified:file/command.go+46 added-36 removed
1 unmodified line2 3 import (4 "errors"5 "fmt"6+ "os"7 "path/filepath"8 9+ "github.com/charmbracelet/bubbles/filepicker"10+ "github.com/charmbracelet/bubbles/help"11+ tea "github.com/charmbracelet/bubbletea"12 "github.com/charmbracelet/gum/internal/exit"9- "github.com/charmbracelet/huh"10- "github.com/charmbracelet/lipgloss"13 )14 15 // Run is the interface to picking a file.16 func (o Options) Run() error {9 unmodified lines26 if err != nil {27 return fmt.Errorf("file not found: %w", err)28 }29 28- theme := huh.ThemeCharm()29- theme.Focused.Base = lipgloss.NewStyle()30- theme.Focused.File = o.FileStyle.ToLipgloss()31- theme.Focused.Directory = o.DirectoryStyle.ToLipgloss()32- theme.Focused.SelectedOption = o.SelectedStyle.ToLipgloss()30+ fp := filepicker.New()31+ fp.CurrentDirectory = path32+ fp.Path = path33+ fp.Height = o.Height34+ fp.AutoHeight = o.Height == 035+ fp.Cursor = o.Cursor36+ fp.DirAllowed = o.Directory37+ fp.FileAllowed = o.File38+ fp.ShowPermissions = o.Permissions39+ fp.ShowSize = o.Size40+ fp.ShowHidden = o.All41+ fp.Styles = filepicker.DefaultStyles()42+ fp.Styles.Cursor = o.CursorStyle.ToLipgloss()43+ fp.Styles.Symlink = o.SymlinkStyle.ToLipgloss()44+ fp.Styles.Directory = o.DirectoryStyle.ToLipgloss()45+ fp.Styles.File = o.FileStyle.ToLipgloss()46+ fp.Styles.Permission = o.PermissionsStyle.ToLipgloss()47+ fp.Styles.Selected = o.SelectedStyle.ToLipgloss()48+ fp.Styles.FileSize = o.FileSizeStyle.ToLipgloss()49+ m := model{50+ filepicker: fp,51+ timeout: o.Timeout,52+ hasTimeout: o.Timeout > 0,53+ aborted: false,54+ showHelp: o.ShowHelp,55+ help: help.New(),56+ keymap: defaultKeymap(),57+ }58 34- keymap := huh.NewDefaultKeyMap()35- keymap.FilePicker.Open.SetEnabled(false)36-37- // XXX: These should be file selected specific.38- theme.Focused.TextInput.Placeholder = o.PermissionsStyle.ToLipgloss()39- theme.Focused.TextInput.Prompt = o.CursorStyle.ToLipgloss()40-41- err = huh.NewForm(42- huh.NewGroup(43- huh.NewFilePicker().44- Picking(true).45- CurrentDirectory(path).46- Cursor(o.Cursor).47- DirAllowed(o.Directory).48- FileAllowed(o.File).49- Height(o.Height).50- ShowHidden(o.All).51- ShowSize(o.Size).52- ShowPermissions(o.Permissions).53- Value(&path),54- ),55- ).56- WithTimeout(o.Timeout).57- WithShowHelp(o.ShowHelp).58- WithKeyMap(keymap).59- WithTheme(theme).60- Run()59+ tm, err := tea.NewProgram(&m, tea.WithOutput(os.Stderr)).Run()60 if err != nil {62- return exit.Handle(err, o.Timeout)61+ return fmt.Errorf("unable to pick selection: %w", err)62 }63+ m = tm.(model)64+ if m.aborted {65+ return exit.ErrAborted66+ }67+ if m.timedOut {68+ return exit.ErrTimeout69+ }70+ if m.selectedPath == "" {71+ return errors.New("no file selected")72+ }73+64- fmt.Println(path)74+ fmt.Println(m.selectedPath)75 return nil76 }added:file/file.go+125 added
1+// Package file provides an interface to pick a file from a folder (tree).2+// The user is provided a file manager-like interface to navigate, to3+// select a file.4+//5+// Let's pick a file from the current directory:6+//7+// $ gum file8+// $ gum file .9+//10+// Let's pick a file from the home directory:11+//12+// $ gum file $HOME13+package file14+15+import (16+ "time"17+18+ "github.com/charmbracelet/bubbles/filepicker"19+ "github.com/charmbracelet/bubbles/help"20+ "github.com/charmbracelet/bubbles/key"21+ tea "github.com/charmbracelet/bubbletea"22+ "github.com/charmbracelet/gum/timeout"23+ "github.com/charmbracelet/lipgloss"24+)25+26+type keymap filepicker.KeyMap27+28+var keyQuit = key.NewBinding(29+ key.WithKeys("esc", "q"),30+ key.WithHelp("esc", "close"),31+)32+33+var keyAbort = key.NewBinding(34+ key.WithKeys("ctrl+c"),35+ key.WithHelp("ctrl+c", "abort"),36+)37+38+func defaultKeymap() keymap {39+ km := filepicker.DefaultKeyMap()40+ km.Down.SetHelp("↓", "down")41+ km.Up.SetHelp("↑", "up")42+ return keymap(km)43+}44+45+// FullHelp implements help.KeyMap.46+func (k keymap) FullHelp() [][]key.Binding { return nil }47+48+// ShortHelp implements help.KeyMap.49+func (k keymap) ShortHelp() []key.Binding {50+ return []key.Binding{51+ k.Up,52+ k.Down,53+ keyQuit,54+ k.Select,55+ }56+}57+58+type model struct {59+ filepicker filepicker.Model60+ selectedPath string61+ aborted bool62+ timedOut bool63+ quitting bool64+ timeout time.Duration65+ hasTimeout bool66+ showHelp bool67+ help help.Model68+ keymap keymap69+}70+71+func (m model) Init() tea.Cmd {72+ return tea.Batch(73+ timeout.Init(m.timeout, nil),74+ m.filepicker.Init(),75+ )76+}77+78+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {79+ switch msg := msg.(type) {80+ case tea.WindowSizeMsg:81+ if m.showHelp {82+ m.filepicker.Height -= lipgloss.Height(m.helpView())83+ }84+ case tea.KeyMsg:85+ switch {86+ case key.Matches(msg, keyAbort):87+ m.aborted = true88+ m.quitting = true89+ return m, tea.Quit90+ case key.Matches(msg, keyQuit):91+ m.quitting = true92+ return m, tea.Quit93+ }94+ case timeout.TickTimeoutMsg:95+ if msg.TimeoutValue <= 0 {96+ m.quitting = true97+ m.timedOut = true98+ return m, tea.Quit99+ }100+ m.timeout = msg.TimeoutValue101+ return m, timeout.Tick(msg.TimeoutValue, msg.Data)102+ }103+ var cmd tea.Cmd104+ m.filepicker, cmd = m.filepicker.Update(msg)105+ if didSelect, path := m.filepicker.DidSelectFile(msg); didSelect {106+ m.selectedPath = path107+ m.quitting = true108+ return m, tea.Quit109+ }110+ return m, cmd111+}112+113+func (m model) View() string {114+ if m.quitting {115+ return ""116+ }117+ if !m.showHelp {118+ return m.filepicker.View()119+ }120+ return m.filepicker.View() + m.helpView()121+}122+123+func (m model) helpView() string {124+ return "\n" + m.help.View(m.keymap)125+}modified:file/options.go+1 added-1 removed
17 unmodified lines18 File bool `help:"Allow files selection" default:"true" env:"GUM_FILE_FILE"`19 Directory bool `help:"Allow directories selection" default:"false" env:"GUM_FILE_DIRECTORY"`20 ShowHelp bool `help:"Show help key binds" negatable:"" default:"true" env:"GUM_FILE_SHOW_HELP"`21 22- Height int `help:"Maximum number of files to display" default:"0" env:"GUM_FILE_HEIGHT"`22+ Height int `help:"Maximum number of files to display" default:"10" env:"GUM_FILE_HEIGHT"`23 CursorStyle style.Styles `embed:"" prefix:"cursor." help:"The cursor style" set:"defaultForeground=212" envprefix:"GUM_FILE_CURSOR_"`24 SymlinkStyle style.Styles `embed:"" prefix:"symlink." help:"The style to use for symlinks" set:"defaultForeground=36" envprefix:"GUM_FILE_SYMLINK_"`25 DirectoryStyle style.Styles `embed:"" prefix:"directory." help:"The style to use for directories" set:"defaultForeground=99" envprefix:"GUM_FILE_DIRECTORY_"`26 FileStyle style.Styles `embed:"" prefix:"file." help:"The style to use for files" envprefix:"GUM_FILE_FILE_"`7 unmodified linesmodified:filter/command.go+14 added
4 unmodified lines5 "fmt"6 "os"7 "strings"8 9+ "github.com/charmbracelet/bubbles/help"10 "github.com/charmbracelet/bubbles/textinput"11 "github.com/charmbracelet/bubbles/viewport"12 tea "github.com/charmbracelet/bubbletea"13 "github.com/charmbracelet/x/ansi"53 unmodified lines67 default:68 matches = matchAll(o.Options)69 }70 71+ km := defaultKeymap()72+73 if o.NoLimit {74 o.Limit = len(o.Options)75 }76+ if o.NoLimit || o.Limit > 1 {77+ km.Toggle.SetEnabled(true)78+ km.ToggleAndPrevious.SetEnabled(true)79+ km.ToggleAndNext.SetEnabled(true)80+ }81 82 p := tea.NewProgram(model{83 choices: o.Options,84 indicator: o.Indicator,18 unmodified lines103 timeout: o.Timeout,104 hasTimeout: o.Timeout > 0,105 sort: o.Sort && o.FuzzySort,106 strict: o.Strict,107+ showHelp: o.ShowHelp,108+ keymap: km,109+ help: help.New(),110 }, options...)111 112 tm, err := p.Run()113 if err != nil {2 unmodified lines116 m := tm.(model)117 if m.aborted {118 return exit.ErrAborted119 }120+ if m.timedOut {121+ return exit.ErrTimeout122+ }123 124 isTTY := term.IsTerminal(os.Stdout.Fd())125 126 // allSelections contains values only if limit is greater24 unmodified linesmodified:filter/filter.go+97 added-11 removed
14 unmodified lines15 "time"16 17 "github.com/charmbracelet/gum/timeout"18 19+ "github.com/charmbracelet/bubbles/help"20+ "github.com/charmbracelet/bubbles/key"21 "github.com/charmbracelet/bubbles/textinput"22 "github.com/charmbracelet/bubbles/viewport"23 tea "github.com/charmbracelet/bubbletea"24 "github.com/charmbracelet/lipgloss"25 "github.com/sahilm/fuzzy"26 )27 28+func defaultKeymap() keymap {29+ return keymap{30+ Down: key.NewBinding(31+ key.WithKeys("down", "ctrl+j", "ctrl+n"),32+ key.WithHelp("↓", "down"),33+ ),34+ Up: key.NewBinding(35+ key.WithKeys("up", "ctrl+k", "ctrl+p"),36+ key.WithHelp("↑", "up"),37+ ),38+ ToggleAndNext: key.NewBinding(39+ key.WithKeys("tab"),40+ key.WithHelp("tab", "toggle"),41+ key.WithDisabled(),42+ ),43+ ToggleAndPrevious: key.NewBinding(44+ key.WithKeys("shift+tab"),45+ key.WithHelp("shift+tab", "toggle"),46+ key.WithDisabled(),47+ ),48+ Toggle: key.NewBinding(49+ key.WithKeys("ctrl+@"),50+ key.WithHelp("ctrl+@", "toggle"),51+ key.WithDisabled(),52+ ),53+ Abort: key.NewBinding(54+ key.WithKeys("ctrl+c", "esc"),55+ key.WithHelp("ctrl+c", "abort"),56+ ),57+ Submit: key.NewBinding(58+ key.WithKeys("enter", "ctrl+q"),59+ key.WithHelp("enter", "submit"),60+ ),61+ }62+}63+64+type keymap struct {65+ Down,66+ Up,67+ ToggleAndNext,68+ ToggleAndPrevious,69+ Toggle,70+ Abort,71+ Submit key.Binding72+}73+74+// FullHelp implements help.KeyMap.75+func (k keymap) FullHelp() [][]key.Binding { return nil }76+77+// ShortHelp implements help.KeyMap.78+func (k keymap) ShortHelp() []key.Binding {79+ return []key.Binding{80+ k.ToggleAndNext,81+ key.NewBinding(82+ key.WithKeys("up", "down"),83+ key.WithHelp("↑↓", "navigate"),84+ ),85+ k.Submit,86+ }87+}88+89 type model struct {90 textinput textinput.Model91 viewport *viewport.Model92 choices []string7 unmodified lines100 selectedPrefix string101 unselectedPrefix string102 height int103 aborted bool104+ timedOut bool105 quitting bool106 headerStyle lipgloss.Style107 matchStyle lipgloss.Style108 textStyle lipgloss.Style3 unmodified lines112 unselectedPrefixStyle lipgloss.Style113 reverse bool114 fuzzy bool115 sort bool116+ showHelp bool117+ keymap keymap118+ help help.Model119 timeout time.Duration120 hasTimeout bool121 strict bool122 }80 unmodified lines203 }204 205 m.viewport.SetContent(s.String())206 207+ help := ""208+ if m.showHelp {209+ help = m.helpView()210+ }211+212 // View the input and the filtered choices213 header := m.headerStyle.Render(m.header)214 if m.reverse {215 view := m.viewport.View() + "\n" + m.textinput.View()216+ if m.showHelp {217+ view += help218+ }219 if m.header != "" {220 return lipgloss.JoinVertical(lipgloss.Left, view, header)221 }222 223 return view224 }225 226 view := m.textinput.View() + "\n" + m.viewport.View()227+ if m.showHelp {228+ view += help229+ }230 if m.header != "" {231 return lipgloss.JoinVertical(lipgloss.Left, header, view)232 }233 return view234 }235 236+func (m model) helpView() string {237+ return "\n\n" + m.help.View(m.keymap)238+}239+240 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {241 var cmd tea.Cmd242 switch msg := msg.(type) {243 case timeout.TickTimeoutMsg:244 if msg.TimeoutValue <= 0 {245 m.quitting = true164- m.aborted = true246+ m.timedOut = true247 return m, tea.Quit248 }249 m.timeout = msg.TimeoutValue250 return m, timeout.Tick(msg.TimeoutValue, msg.Data)1 unmodified line252 case tea.WindowSizeMsg:253 if m.height == 0 || m.height > msg.Height {254 m.viewport.Height = msg.Height - lipgloss.Height(m.textinput.View())255 }174-175- // Make place in the view port if header is set256+ // Include the header in the height calculation.257 if m.header != "" {258 m.viewport.Height = m.viewport.Height - lipgloss.Height(m.headerStyle.Render(m.header))259 }260+ // Include the help in the total height calculation.261+ if m.showHelp {262+ m.viewport.Height = m.viewport.Height - lipgloss.Height(m.helpView())263+ }264 m.viewport.Width = msg.Width265 if m.reverse {266 m.viewport.YOffset = clamp(0, len(m.matches), len(m.matches)-m.viewport.Height)267 }268 case tea.KeyMsg:184- switch msg.String() {185- case "ctrl+c", "esc":269+ km := m.keymap270+ switch {271+ case key.Matches(msg, km.Abort):272 m.aborted = true273 m.quitting = true274 return m, tea.Quit189- case "enter":275+ case key.Matches(msg, km.Submit):276 m.quitting = true277 return m, tea.Quit192- case "ctrl+n", "ctrl+j", "down":278+ case key.Matches(msg, km.Down):279 m.CursorDown()194- case "ctrl+p", "ctrl+k", "up":280+ case key.Matches(msg, km.Up):281 m.CursorUp()196- case "tab":282+ case key.Matches(msg, km.ToggleAndNext):283 if m.limit == 1 {284 break // no op285 }286 m.ToggleSelection()287 m.CursorDown()202- case "shift+tab":288+ case key.Matches(msg, km.ToggleAndPrevious):289 if m.limit == 1 {290 break // no op291 }292 m.ToggleSelection()293 m.CursorUp()208- case "ctrl+@":294+ case key.Matches(msg, km.Toggle):295 if m.limit == 1 {296 break // no op297 }298 m.ToggleSelection()146 unmodified linesmodified:filter/options.go+2 added-1 removed
13 unmodified lines14 IndicatorStyle style.Styles `embed:"" prefix:"indicator." set:"defaultForeground=212" envprefix:"GUM_FILTER_INDICATOR_"`15 Limit int `help:"Maximum number of options to pick" default:"1" group:"Selection"`16 NoLimit bool `help:"Pick unlimited number of options (ignores limit)" group:"Selection"`17 SelectIfOne bool `help:"Select the given option if there is only one" group:"Selection"`18+ ShowHelp bool `help:"Show help keybinds" default:"true" negatable:"" env:"GUM_FILTER_SHOW_HELP"`19 Strict bool `help:"Only returns if anything matched. Otherwise return Filter" negatable:"" default:"true" group:"Selection"`20 SelectedPrefix string `help:"Character to indicate selected items (hidden if limit is 1)" default:" ◉ " env:"GUM_FILTER_SELECTED_PREFIX"`21 SelectedPrefixStyle style.Styles `embed:"" prefix:"selected-indicator." set:"defaultForeground=212" envprefix:"GUM_FILTER_SELECTED_PREFIX_"`22 UnselectedPrefix string `help:"Character to indicate unselected items (hidden if limit is 1)" default:" ○ " env:"GUM_FILTER_UNSELECTED_PREFIX"`23 UnselectedPrefixStyle style.Styles `embed:"" prefix:"unselected-prefix." set:"defaultForeground=240" envprefix:"GUM_FILTER_UNSELECTED_PREFIX_"`23- HeaderStyle style.Styles `embed:"" prefix:"header." set:"defaultForeground=240" envprefix:"GUM_FILTER_HEADER_"`24+ HeaderStyle style.Styles `embed:"" prefix:"header." set:"defaultForeground=99" envprefix:"GUM_FILTER_HEADER_"`25 Header string `help:"Header value" default:"" env:"GUM_FILTER_HEADER"`26 TextStyle style.Styles `embed:"" prefix:"text." envprefix:"GUM_FILTER_TEXT_"`27 CursorTextStyle style.Styles `embed:"" prefix:"cursor-text." envprefix:"GUM_FILTER_CURSOR_TEXT_"`28 MatchStyle style.Styles `embed:"" prefix:"match." set:"defaultForeground=212" envprefix:"GUM_FILTER_MATCH_"`15 unmodified linesmodified:input/command.go+46 added-40 removed
2 unmodified lines3 import (4 "fmt"5 "os"6 7- "github.com/charmbracelet/bubbles/key"7+ "github.com/charmbracelet/bubbles/help"8+ "github.com/charmbracelet/bubbles/textinput"9 tea "github.com/charmbracelet/bubbletea"9- "github.com/charmbracelet/huh"10- "github.com/charmbracelet/lipgloss"10 11+ "github.com/charmbracelet/gum/cursor"12 "github.com/charmbracelet/gum/internal/exit"13 "github.com/charmbracelet/gum/internal/stdin"14 )15 16 // Run provides a shell script interface for the text input bubble.17 // https://github.com/charmbracelet/bubbles/textinput18 func (o Options) Run() error {19- var value string19+ if o.Value == "" {20+ if in, _ := stdin.Read(); in != "" {21+ o.Value = in22+ }23+ }24+25+ i := textinput.New()26 if o.Value != "" {21- value = o.Value27+ i.SetValue(o.Value)28 } else if in, _ := stdin.Read(); in != "" {23- value = in29+ i.SetValue(in)30 }31+ i.Focus()32+ i.Prompt = o.Prompt33+ i.Placeholder = o.Placeholder34+ i.Width = o.Width35+ i.PromptStyle = o.PromptStyle.ToLipgloss()36+ i.PlaceholderStyle = o.PlaceholderStyle.ToLipgloss()37+ i.Cursor.Style = o.CursorStyle.ToLipgloss()38+ i.Cursor.SetMode(cursor.Modes[o.CursorMode])39+ i.CharLimit = o.CharLimit40 26- theme := huh.ThemeCharm()27- theme.Focused.Base = lipgloss.NewStyle()28- theme.Focused.TextInput.Cursor = o.CursorStyle.ToLipgloss()29- theme.Focused.TextInput.Placeholder = o.PlaceholderStyle.ToLipgloss()30- theme.Focused.TextInput.Prompt = o.PromptStyle.ToLipgloss()31- theme.Focused.Title = o.HeaderStyle.ToLipgloss()32-33- // Keep input keymap backwards compatible34- keymap := huh.NewDefaultKeyMap()35- keymap.Quit = key.NewBinding(key.WithKeys("ctrl+c", "esc"))36-37- echoMode := huh.EchoModeNormal41 if o.Password {39- echoMode = huh.EchoModePassword42+ i.EchoMode = textinput.EchoPassword43+ i.EchoCharacter = '•'44 }45 42- err := huh.NewForm(43- huh.NewGroup(44- huh.NewInput().45- Prompt(o.Prompt).46- Placeholder(o.Placeholder).47- CharLimit(o.CharLimit).48- EchoMode(echoMode).49- Title(o.Header).50- Value(&value),51- ),52- ).53- WithShowHelp(false).54- WithWidth(o.Width).55- WithTheme(theme).56- WithKeyMap(keymap).57- WithTimeout(o.Timeout).58- WithShowHelp(o.ShowHelp).59- WithProgramOptions(tea.WithOutput(os.Stderr)).60- Run()46+ p := tea.NewProgram(model{47+ textinput: i,48+ aborted: false,49+ header: o.Header,50+ headerStyle: o.HeaderStyle.ToLipgloss(),51+ timeout: o.Timeout,52+ hasTimeout: o.Timeout > 0,53+ autoWidth: o.Width < 1,54+ showHelp: o.ShowHelp,55+ help: help.New(),56+ keymap: defaultKeymap(),57+ }, tea.WithOutput(os.Stderr))58+ tm, err := p.Run()59 if err != nil {62- return exit.Handle(err, o.Timeout)60+ return fmt.Errorf("failed to run input: %w", err)61 }62 65- fmt.Println(value)63+ m := tm.(model)64+ if m.aborted {65+ return exit.ErrAborted66+ }67+ if m.timedOut {68+ return exit.ErrTimeout69+ }70+71+ fmt.Println(m.textinput.Value())72 return nil73 }added:input/input.go+112 added
1+// Package input provides a shell script interface for the text input bubble.2+// https://github.com/charmbracelet/bubbles/tree/master/textinput3+//4+// It can be used to prompt the user for some input. The text the user entered5+// will be sent to stdout.6+//7+// $ gum input --placeholder "What's your favorite gum?" > answer.text8+package input9+10+import (11+ "time"12+13+ "github.com/charmbracelet/bubbles/help"14+ "github.com/charmbracelet/bubbles/key"15+ "github.com/charmbracelet/bubbles/textinput"16+ tea "github.com/charmbracelet/bubbletea"17+ "github.com/charmbracelet/gum/timeout"18+ "github.com/charmbracelet/lipgloss"19+)20+21+type keymap textinput.KeyMap22+23+func defaultKeymap() keymap {24+ k := textinput.DefaultKeyMap25+ return keymap(k)26+}27+28+// FullHelp implements help.KeyMap.29+func (k keymap) FullHelp() [][]key.Binding { return nil }30+31+// ShortHelp implements help.KeyMap.32+func (k keymap) ShortHelp() []key.Binding {33+ return []key.Binding{34+ key.NewBinding(35+ key.WithKeys("enter"),36+ key.WithHelp("enter", "submit"),37+ ),38+ }39+}40+41+type model struct {42+ autoWidth bool43+ header string44+ headerStyle lipgloss.Style45+ textinput textinput.Model46+ quitting bool47+ timedOut bool48+ aborted bool49+ timeout time.Duration50+ hasTimeout bool51+ showHelp bool52+ help help.Model53+ keymap keymap54+}55+56+func (m model) Init() tea.Cmd {57+ return tea.Batch(58+ textinput.Blink,59+ timeout.Init(m.timeout, nil),60+ )61+}62+63+func (m model) View() string {64+ if m.quitting {65+ return ""66+ }67+ if m.header != "" {68+ header := m.headerStyle.Render(m.header)69+ return lipgloss.JoinVertical(lipgloss.Left, header, m.textinput.View())70+ }71+72+ if !m.showHelp {73+ return m.textinput.View()74+ }75+ return lipgloss.JoinVertical(76+ lipgloss.Top,77+ m.textinput.View(),78+ "",79+ m.help.View(m.keymap),80+ )81+}82+83+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {84+ switch msg := msg.(type) {85+ case timeout.TickTimeoutMsg:86+ if msg.TimeoutValue <= 0 {87+ m.quitting = true88+ m.timedOut = true89+ return m, tea.Quit90+ }91+ m.timeout = msg.TimeoutValue92+ return m, timeout.Tick(msg.TimeoutValue, msg.Data)93+ case tea.WindowSizeMsg:94+ if m.autoWidth {95+ m.textinput.Width = msg.Width - lipgloss.Width(m.textinput.Prompt) - 196+ }97+ case tea.KeyMsg:98+ switch msg.String() {99+ case "ctrl+c", "esc":100+ m.quitting = true101+ m.aborted = true102+ return m, tea.Quit103+ case "enter":104+ m.quitting = true105+ return m, tea.Quit106+ }107+ }108+109+ var cmd tea.Cmd110+ m.textinput, cmd = m.textinput.Update(msg)111+ return m, cmd112+}modified:input/options.go+1 added-1 removed
16 unmodified lines17 Value string `help:"Initial value (can also be passed via stdin)" default:""`18 CharLimit int `help:"Maximum value length (0 for no limit)" default:"400"`19 Width int `help:"Input width (0 for terminal width)" default:"0" env:"GUM_INPUT_WIDTH"`20 Password bool `help:"Mask input characters" default:"false"`21- ShowHelp bool `help:"Show help keybinds" default:"true" negatable:"true" env:"GUM_INPUT_SHOW_HELP"`21+ ShowHelp bool `help:"Show help keybinds" default:"true" negatable:"" env:"GUM_INPUT_SHOW_HELP"`22 Header string `help:"Header value" default:"" env:"GUM_INPUT_HEADER"`23 HeaderStyle style.Styles `embed:"" prefix:"header." set:"defaultForeground=240" envprefix:"GUM_INPUT_HEADER_"`24 Timeout time.Duration `help:"Timeout until input aborts" default:"0s" env:"GUM_INPUT_TIMEOUT"`25 }modified:internal/exit/exit.go+10 added-12 removed
1 package exit2 3 import (4 "errors"5- "fmt"6- "time"7-8- "github.com/charmbracelet/huh"5+ "strconv"6 )7 8 // StatusTimeout is the exit code for timed out commands.9 const StatusTimeout = 1241 unmodified line11 // StatusAborted is the exit code for aborted commands.12 const StatusAborted = 13013 14 // ErrAborted is the error to return when a gum command is aborted by Ctrl+C.18-var ErrAborted = huh.ErrUserAborted15+var ErrAborted = errors.New("user aborted")16 20-// Handle handles the error.21-func Handle(err error, d time.Duration) error {22- if errors.Is(err, huh.ErrTimeout) {23- return fmt.Errorf("%w after %s", huh.ErrTimeout, d)24- }25- return err26-}17+// ErrTimeout is the error returned when the timeout is reached.18+var ErrTimeout = errors.New("timeout")19+20+// ErrExit is a custom exit error.21+type ErrExit int22+23+// Error implements error.24+func (e ErrExit) Error() string { return "exit " + strconv.Itoa(int(e)) }modified:pager/command.go+9 added-3 removed
4 unmodified lines5 "regexp"6 7 "github.com/charmbracelet/bubbles/viewport"8 tea "github.com/charmbracelet/bubbletea"9+ "github.com/charmbracelet/gum/internal/exit"10 "github.com/charmbracelet/gum/internal/stdin"11 )12 13 // Run provides a shell script interface for the viewport bubble.15 unmodified lines29 return fmt.Errorf("provide some content to display")30 }31 }32 32- model := model{33+ tm, err := tea.NewProgram(model{34 viewport: vp,35 helpStyle: o.HelpStyle.ToLipgloss(),36 content: o.Content,37 origContent: o.Content,3 unmodified lines41 matchStyle: o.MatchStyle.ToLipgloss(),42 matchHighlightStyle: o.MatchHighlightStyle.ToLipgloss(),43 timeout: o.Timeout,44 hasTimeout: o.Timeout > 0,44- }45- _, err := tea.NewProgram(model, tea.WithAltScreen()).Run()45+ }, tea.WithAltScreen()).Run()46 if err != nil {47 return fmt.Errorf("unable to start program: %w", err)48 }49+50+ m := tm.(model)51+ if m.timedOut {52+ return exit.ErrTimeout53+ }54+55 return nil56 }modified:pager/pager.go+2 added
28 unmodified lines29 matchHighlightStyle lipgloss.Style30 maxWidth int31 timeout time.Duration32 hasTimeout bool33+ timedOut bool34 }35 36 func (m model) Init() tea.Cmd {37 return timeout.Init(m.timeout, nil)2 unmodified lines40 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {41 switch msg := msg.(type) {42 case timeout.TickTimeoutMsg:43 if msg.TimeoutValue <= 0 {44+ m.timedOut = true45 return m, tea.Quit46 }47 m.timeout = msg.TimeoutValue48 return m, timeout.Tick(msg.TimeoutValue, msg.Data)113 unmodified linesmodified:spin/command.go+7 added-8 removed
17 unmodified lines18 19 s := spinner.New()20 s.Style = o.SpinnerStyle.ToLipgloss()21 s.Spinner = spinnerMap[o.Spinner]22- m := model{22+ tm, err := tea.NewProgram(model{23 spinner: s,24 title: o.TitleStyle.ToLipgloss().Render(o.Title),25 command: o.Command,26 align: o.Align,27 showOutput: o.ShowOutput && isTTY,28 showError: o.ShowError,29 timeout: o.Timeout,30 hasTimeout: o.Timeout > 0,31- }32- p := tea.NewProgram(m, tea.WithOutput(os.Stderr))33- mm, err := p.Run()34- m = mm.(model)35-31+ }, tea.WithOutput(os.Stderr)).Run()32 if err != nil {33 return fmt.Errorf("failed to run spin: %w", err)34 }35 36+ m := tm.(model)37 if m.aborted {38 return exit.ErrAborted39 }40+ if m.timedOut {41+ return exit.ErrTimeout42+ }43 44 // If the command succeeds, and we are printing output and we are in a TTY then push the STDOUT we got to the actual45 // STDOUT for piping or other things.46 //nolint:nestif16 unmodified lines63 return fmt.Errorf("failed to write to stdout: %w", err)64 }65 }66 67- os.Exit(m.status)68- return nil67+ return exit.ErrExit(m.status)68 }modified:spin/spin.go+2 added-3 removed
20 unmodified lines21 "strings"22 "syscall"23 "time"24 25- "github.com/charmbracelet/gum/internal/exit"25 "github.com/charmbracelet/gum/timeout"26 "github.com/charmbracelet/x/term"27 28 "github.com/charmbracelet/bubbles/spinner"6 unmodified lines35 align string36 command []string37 quitting bool38 aborted bool39+ timedOut bool40 status int41 stdout string42 stderr string43 output string89 unmodified lines133 case timeout.TickTimeoutMsg:134 if msg.TimeoutValue <= 0 {135 // grab current output before closing for piped instances136 m.stdout = outbuf.String()137-138- m.status = exit.StatusAborted137+ m.timedOut = true138 return m, tea.Quit139 }140 m.timeout = msg.TimeoutValue141 return m, timeout.Tick(msg.TimeoutValue, msg.Data)18 unmodified linesmodified:write/command.go+46 added-28 removed
1 package write2 3 import (4 "fmt"5+ "os"6 "strings"7 8+ "github.com/charmbracelet/bubbles/help"9+ "github.com/charmbracelet/bubbles/textarea"10+ tea "github.com/charmbracelet/bubbletea"11+12+ "github.com/charmbracelet/gum/cursor"13+ "github.com/charmbracelet/gum/internal/exit"14 "github.com/charmbracelet/gum/internal/stdin"8- "github.com/charmbracelet/huh"15 )16 17 // Run provides a shell script interface for the text area bubble.18 // https://github.com/charmbracelet/bubbles/textarea2 unmodified lines21 if in != "" && o.Value == "" {22 o.Value = strings.ReplaceAll(in, "\r", "")23 }24 19- var value = o.Value25+ a := textarea.New()26+ a.Focus()27 21- theme := huh.ThemeCharm()22- theme.Focused.Base = o.BaseStyle.ToLipgloss()23- theme.Focused.TextInput.Cursor = o.CursorStyle.ToLipgloss()24- theme.Focused.Title = o.HeaderStyle.ToLipgloss()25- theme.Focused.TextInput.Placeholder = o.PlaceholderStyle.ToLipgloss()26- theme.Focused.TextInput.Prompt = o.PromptStyle.ToLipgloss()28+ a.Prompt = o.Prompt29+ a.Placeholder = o.Placeholder30+ a.ShowLineNumbers = o.ShowLineNumbers31+ a.CharLimit = o.CharLimit32 28- keymap := huh.NewDefaultKeyMap()29- keymap.Text.NewLine.SetHelp("ctrl+j", "new line")33+ style := textarea.Style{34+ Base: o.BaseStyle.ToLipgloss(),35+ Placeholder: o.PlaceholderStyle.ToLipgloss(),36+ CursorLine: o.CursorLineStyle.ToLipgloss(),37+ CursorLineNumber: o.CursorLineNumberStyle.ToLipgloss(),38+ EndOfBuffer: o.EndOfBufferStyle.ToLipgloss(),39+ LineNumber: o.LineNumberStyle.ToLipgloss(),40+ Prompt: o.PromptStyle.ToLipgloss(),41+ }42 31- err := huh.NewForm(32- huh.NewGroup(33- huh.NewText().34- Title(o.Header).35- Placeholder(o.Placeholder).36- CharLimit(o.CharLimit).37- ShowLineNumbers(o.ShowLineNumbers).38- Value(&value),39- ),40- ).41- WithWidth(o.Width).42- WithHeight(o.Height).43- WithTheme(theme).44- WithKeyMap(keymap).45- WithShowHelp(o.ShowHelp).46- Run()43+ a.BlurredStyle = style44+ a.FocusedStyle = style45+ a.Cursor.Style = o.CursorStyle.ToLipgloss()46+ a.Cursor.SetMode(cursor.Modes[o.CursorMode])47 48+ a.SetWidth(o.Width)49+ a.SetHeight(o.Height)50+ a.SetValue(o.Value)51+52+ p := tea.NewProgram(model{53+ textarea: a,54+ header: o.Header,55+ headerStyle: o.HeaderStyle.ToLipgloss(),56+ autoWidth: o.Width < 1,57+ help: help.New(),58+ showHelp: o.ShowHelp,59+ keymap: defaultKeymap(),60+ }, tea.WithOutput(os.Stderr), tea.WithReportFocus())61+ tm, err := p.Run()62 if err != nil {49- return err63+ return fmt.Errorf("failed to run write: %w", err)64 }65+ m := tm.(model)66+ if m.aborted {67+ return exit.ErrAborted68+ }69 52- fmt.Println(value)70+ fmt.Println(m.textarea.Value())71 return nil72 }modified:write/options.go+7 added-8 removed
14 unmodified lines15 CharLimit int `help:"Maximum value length (0 for no limit)" default:"400"`16 ShowHelp bool `help:"Show help key binds" negatable:"" default:"true" env:"GUM_WRITE_SHOW_HELP"`17 CursorMode string `prefix:"cursor." name:"mode" help:"Cursor mode" default:"blink" enum:"blink,hide,static" env:"GUM_WRITE_CURSOR_MODE"`18 19- BaseStyle style.Styles `embed:"" prefix:"base." envprefix:"GUM_WRITE_BASE_"`20- CursorStyle style.Styles `embed:"" prefix:"cursor." set:"defaultForeground=212" envprefix:"GUM_WRITE_CURSOR_"`21- HeaderStyle style.Styles `embed:"" prefix:"header." set:"defaultForeground=240" envprefix:"GUM_WRITE_HEADER_"`22- PlaceholderStyle style.Styles `embed:"" prefix:"placeholder." set:"defaultForeground=240" envprefix:"GUM_WRITE_PLACEHOLDER_"`23- PromptStyle style.Styles `embed:"" prefix:"prompt." set:"defaultForeground=7" envprefix:"GUM_WRITE_PROMPT_"`24-25- EndOfBufferStyle style.Styles `embed:"" prefix:"end-of-buffer." set:"defaultForeground=0" envprefix:"GUM_WRITE_END_OF_BUFFER_"`26- LineNumberStyle style.Styles `embed:"" prefix:"line-number." set:"defaultForeground=7" envprefix:"GUM_WRITE_LINE_NUMBER_"`19+ BaseStyle style.Styles `embed:"" prefix:"base." envprefix:"GUM_WRITE_BASE_"`20 CursorLineNumberStyle style.Styles `embed:"" prefix:"cursor-line-number." set:"defaultForeground=7" envprefix:"GUM_WRITE_CURSOR_LINE_NUMBER_"`21 CursorLineStyle style.Styles `embed:"" prefix:"cursor-line." envprefix:"GUM_WRITE_CURSOR_LINE_"`22+ CursorStyle style.Styles `embed:"" prefix:"cursor." set:"defaultForeground=212" envprefix:"GUM_WRITE_CURSOR_"`23+ EndOfBufferStyle style.Styles `embed:"" prefix:"end-of-buffer." set:"defaultForeground=0" envprefix:"GUM_WRITE_END_OF_BUFFER_"`24+ LineNumberStyle style.Styles `embed:"" prefix:"line-number." set:"defaultForeground=7" envprefix:"GUM_WRITE_LINE_NUMBER_"`25+ HeaderStyle style.Styles `embed:"" prefix:"header." set:"defaultForeground=240" envprefix:"GUM_WRITE_HEADER_"`26+ PlaceholderStyle style.Styles `embed:"" prefix:"placeholder." set:"defaultForeground=240" envprefix:"GUM_WRITE_PLACEHOLDER_"`27+ PromptStyle style.Styles `embed:"" prefix:"prompt." set:"defaultForeground=7" envprefix:"GUM_WRITE_PROMPT_"`28 }added:write/write.go+189 added
1+// Package write provides a shell script interface for the text area bubble.2+// https://github.com/charmbracelet/bubbles/tree/master/textarea3+//4+// It can be used to ask the user to write some long form of text (multi-line)5+// input. The text the user entered will be sent to stdout.6+// Text entry is completed with CTRL+D and aborted with CTRL+C or Escape.7+//8+// $ gum write > output.text9+package write10+11+import (12+ "io"13+ "os"14+15+ "github.com/charmbracelet/bubbles/help"16+ "github.com/charmbracelet/bubbles/key"17+ "github.com/charmbracelet/bubbles/textarea"18+ tea "github.com/charmbracelet/bubbletea"19+ "github.com/charmbracelet/lipgloss"20+ "github.com/charmbracelet/x/editor"21+)22+23+type keymap struct {24+ textarea.KeyMap25+ Submit key.Binding26+ Quit key.Binding27+ OpenInEditor key.Binding28+}29+30+// FullHelp implements help.KeyMap.31+func (k keymap) FullHelp() [][]key.Binding { return nil }32+33+// ShortHelp implements help.KeyMap.34+func (k keymap) ShortHelp() []key.Binding {35+ return []key.Binding{36+ k.InsertNewline,37+ k.OpenInEditor,38+ k.Submit,39+ }40+}41+42+func defaultKeymap() keymap {43+ km := textarea.DefaultKeyMap44+ km.InsertNewline = key.NewBinding(45+ key.WithKeys("ctrl+j"),46+ key.WithHelp("ctrl+j", "insert newline"),47+ )48+ return keymap{49+ KeyMap: km,50+ Quit: key.NewBinding(51+ key.WithKeys("ctrl+c"),52+ key.WithHelp("ctrl+c", "cancel"),53+ ),54+ OpenInEditor: key.NewBinding(55+ key.WithKeys("ctrl+e"),56+ key.WithHelp("ctrl+e", "open editor"),57+ ),58+ Submit: key.NewBinding(59+ key.WithKeys("enter"),60+ key.WithHelp("enter", "submit"),61+ ),62+ }63+}64+65+type model struct {66+ autoWidth bool67+ aborted bool68+ header string69+ headerStyle lipgloss.Style70+ quitting bool71+ textarea textarea.Model72+ showHelp bool73+ help help.Model74+ keymap keymap75+}76+77+func (m model) Init() tea.Cmd { return textarea.Blink }78+func (m model) View() string {79+ if m.quitting {80+ return ""81+ }82+83+ var parts []string84+85+ // Display the header above the text area if it is not empty.86+ if m.header != "" {87+ parts = append(parts, m.headerStyle.Render(m.header))88+ }89+ parts = append(parts, m.textarea.View())90+ if m.showHelp {91+ parts = append(parts, m.help.View(m.keymap))92+ }93+ return lipgloss.JoinVertical(lipgloss.Left, parts...)94+}95+96+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {97+ switch msg := msg.(type) {98+ case tea.WindowSizeMsg:99+ if m.autoWidth {100+ m.textarea.SetWidth(msg.Width)101+ }102+ case tea.FocusMsg, tea.BlurMsg:103+ var cmd tea.Cmd104+ m.textarea, cmd = m.textarea.Update(msg)105+ return m, cmd106+ case startEditorMsg:107+ return m, openEditor(msg.path, msg.lineno)108+ case editorFinishedMsg:109+ if msg.err != nil {110+ m.aborted = true111+ m.quitting = true112+ return m, tea.Quit113+ }114+ m.textarea.SetValue(msg.content)115+ case tea.KeyMsg:116+ km := m.keymap117+ switch {118+ case key.Matches(msg, km.Quit):119+ m.aborted = true120+ m.quitting = true121+ return m, tea.Quit122+ case key.Matches(msg, km.Submit):123+ m.quitting = true124+ return m, tea.Quit125+ case key.Matches(msg, km.OpenInEditor):126+ //nolint: gosec127+ return m, createTempFile(m.textarea.Value(), uint(m.textarea.Line())+1)128+ }129+ }130+131+ var cmd tea.Cmd132+ m.textarea, cmd = m.textarea.Update(msg)133+ return m, cmd134+}135+136+type startEditorMsg struct {137+ path string138+ lineno uint139+}140+141+type editorFinishedMsg struct {142+ content string143+ err error144+}145+146+func createTempFile(content string, lineno uint) tea.Cmd {147+ return func() tea.Msg {148+ f, err := os.CreateTemp("", "gum.*.md")149+ if err != nil {150+ return editorFinishedMsg{err: err}151+ }152+ _, err = io.WriteString(f, content)153+ if err != nil {154+ return editorFinishedMsg{err: err}155+ }156+ _ = f.Close()157+ return startEditorMsg{158+ path: f.Name(),159+ lineno: lineno,160+ }161+ }162+}163+164+func openEditor(path string, lineno uint) tea.Cmd {165+ cb := func(err error) tea.Msg {166+ if err != nil {167+ return editorFinishedMsg{168+ err: err,169+ }170+ }171+ bts, err := os.ReadFile(path)172+ if err != nil {173+ return editorFinishedMsg{err: err}174+ }175+ return editorFinishedMsg{176+ content: string(bts),177+ }178+ }179+ cmd, err := editor.Cmd(180+ "Gum",181+ path,182+ editor.LineNumber(lineno),183+ editor.EndOfLine(),184+ )185+ if err != nil {186+ return func() tea.Msg { return cb(err) }187+ }188+ return tea.ExecProcess(cmd, cb)189+}modified:go.mod+1 added-4 removed
6 unmodified lines7 github.com/alecthomas/mango-kong v0.1.08 github.com/charmbracelet/bubbles v0.20.09 github.com/charmbracelet/bubbletea v1.2.410 github.com/charmbracelet/glamour v0.8.011- github.com/charmbracelet/huh v0.6.1-0.20241125235914-50e7b0ecd1da11 github.com/charmbracelet/lipgloss v1.0.012 github.com/charmbracelet/log v0.4.013 github.com/charmbracelet/x/ansi v0.5.214+ github.com/charmbracelet/x/editor v0.1.015 github.com/charmbracelet/x/term v0.2.116 github.com/muesli/reflow v0.3.017 github.com/muesli/roff v0.1.018 github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a4 unmodified lines23 github.com/alecthomas/chroma/v2 v2.14.0 // indirect24 github.com/atotto/clipboard v0.1.4 // indirect25 github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect26 github.com/aymerick/douceur v0.2.0 // indirect27- github.com/catppuccin/go v0.2.0 // indirect28- github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect27 github.com/dlclark/regexp2 v1.11.0 // indirect28 github.com/dustin/go-humanize v1.0.1 // indirect29 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect30 github.com/go-logfmt/logfmt v0.6.0 // indirect2 unmodified lines33 github.com/mattn/go-isatty v0.0.20 // indirect34 github.com/mattn/go-localereader v0.0.1 // indirect35 github.com/mattn/go-runewidth v0.0.16 // indirect36 github.com/microcosm-cc/bluemonday v1.0.27 // indirect39- github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect37 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect38 github.com/muesli/cancelreader v0.2.2 // indirect39 github.com/muesli/mango v0.2.0 // indirect40 github.com/rivo/uniseg v0.4.7 // indirect9 unmodified linesmodified:go.sum+2 added-8 removed
16 unmodified lines17 github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=18 github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=19 github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=20 github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=21-github.com/catppuccin/go v0.2.0 h1:ktBeIrIP42b/8FGiScP9sgrWOss3lw0Z5SktRoithGA=22-github.com/catppuccin/go v0.2.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=21 github.com/charmbracelet/bubbles v0.20.0 h1:jSZu6qD8cRQ6k9OMfR1WlM+ruM8fkPWkHvQWD9LIutE=22 github.com/charmbracelet/bubbles v0.20.0/go.mod h1:39slydyswPy+uVOHZ5x/GjwVAFkCsV8IIVy+4MhzwwU=23 github.com/charmbracelet/bubbletea v1.2.4 h1:KN8aCViA0eps9SCOThb2/XPIlea3ANJLUkv3KnQRNCE=24 github.com/charmbracelet/bubbletea v1.2.4/go.mod h1:Qr6fVQw+wX7JkWWkVyXYk/ZUQ92a6XNekLXa3rR18MM=25 github.com/charmbracelet/glamour v0.8.0 h1:tPrjL3aRcQbn++7t18wOpgLyl8wrOHUEDS7IZ68QtZs=26 github.com/charmbracelet/glamour v0.8.0/go.mod h1:ViRgmKkf3u5S7uakt2czJ272WSg2ZenlYEZXT2x7Bjw=29-github.com/charmbracelet/huh v0.6.1-0.20241125235914-50e7b0ecd1da h1:q3WNIaHjiKcE3NrTeRfoQngMTvTUezIau0iF3T1sE4A=30-github.com/charmbracelet/huh v0.6.1-0.20241125235914-50e7b0ecd1da/go.mod h1:zBQ8egHPGjAW+/mEDhuBq25FRmd+R6bLTDPqLMvyH7s=27 github.com/charmbracelet/lipgloss v1.0.0 h1:O7VkGDvqEdGi93X+DeqsQ7PKHDgtQfF8j8/O2qFMQNg=28 github.com/charmbracelet/lipgloss v1.0.0/go.mod h1:U5fy9Z+C38obMs+T+tJqst9VGzlOYGj4ri9reL3qUlo=29 github.com/charmbracelet/log v0.4.0 h1:G9bQAcx8rWA2T3pWvx7YtPTPwgqpk7D68BX21IRW8ZM=30 github.com/charmbracelet/log v0.4.0/go.mod h1:63bXt/djrizTec0l11H20t8FDSvA4CRZJ1KH22MdptM=31 github.com/charmbracelet/x/ansi v0.5.2 h1:dEa1x2qdOZXD/6439s+wF7xjV+kZLu/iN00GuXXrU9E=32 github.com/charmbracelet/x/ansi v0.5.2/go.mod h1:KBUFw1la39nl0dLl10l5ORDAqGXaeurTQmwyyVKse/Q=33+github.com/charmbracelet/x/editor v0.1.0 h1:p69/dpvlwRTs9uYiPeAWruwsHqTFzHhTvQOd/WVSX98=34+github.com/charmbracelet/x/editor v0.1.0/go.mod h1:oivrEbcP/AYt/Hpvk5pwDXXrQ933gQS6UzL6fxqAGSA=35 github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b h1:MnAMdlwSltxJyULnrYbkZpp4k58Co7Tah3ciKhSNo0Q=36 github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=39-github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4=40-github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ=37 github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=38 github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=39 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=40 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=21 unmodified lines62 github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=63 github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=64 github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=65 github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=70-github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=71-github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=66 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=67 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=68 github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=69 github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=39 unmodified linesmodified:main.go+6 added-3 removed
5 unmodified lines6 "os"7 "runtime/debug"8 9 "github.com/alecthomas/kong"10- "github.com/charmbracelet/huh"10 "github.com/charmbracelet/lipgloss"11 "github.com/muesli/termenv"12 13 "github.com/charmbracelet/gum/internal/exit"57 unmodified lines71 "defaultStrikethrough": "false",72 },73 )74 if err := ctx.Run(); err != nil {75+ var ex exit.ErrExit76+ if errors.As(err, &ex) {77+ os.Exit(int(ex))78+ }76- if errors.Is(err, huh.ErrTimeout) {79+ if errors.Is(err, exit.ErrTimeout) {80 fmt.Fprintln(os.Stderr, err)81 os.Exit(exit.StatusTimeout)82 }80- if errors.Is(err, huh.ErrUserAborted) {83+ if errors.Is(err, exit.ErrAborted) {84 os.Exit(exit.StatusAborted)85 }86 fmt.Fprintln(os.Stderr, err)87 os.Exit(1)2 unmodified lines