gum/filter/command.go

62 lines
1.4 KiB
Go
Raw Normal View History

package filter
import (
"fmt"
"os"
"strings"
2022-07-20 19:39:22 +02:00
"github.com/alecthomas/kong"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
2022-07-31 03:21:00 +02:00
"github.com/charmbracelet/gum/internal/exit"
"github.com/charmbracelet/gum/internal/files"
2022-07-07 19:26:35 +02:00
"github.com/charmbracelet/gum/internal/stdin"
2022-07-20 19:39:22 +02:00
"github.com/charmbracelet/gum/style"
)
// Run provides a shell script interface for filtering through options, powered
// by the textinput bubble.
func (o Options) Run() error {
i := textinput.New()
i.Focus()
i.Prompt = o.Prompt
i.PromptStyle = o.PromptStyle.ToLipgloss()
i.Placeholder = o.Placeholder
i.Width = o.Width
var choices []string
2022-07-30 23:40:33 +02:00
if input, _ := stdin.Read(); input != "" {
2022-07-30 22:50:28 +02:00
choices = strings.Split(strings.TrimSpace(input), "\n")
} else {
choices = files.List()
}
p := tea.NewProgram(model{
choices: choices,
indicator: o.Indicator,
matches: matchAll(choices),
textinput: i,
indicatorStyle: o.IndicatorStyle.ToLipgloss(),
matchStyle: o.MatchStyle.ToLipgloss(),
textStyle: o.TextStyle.ToLipgloss(),
}, tea.WithOutput(os.Stderr))
tm, err := p.StartReturningModel()
m := tm.(model)
2022-07-31 03:10:36 +02:00
if m.aborted {
2022-07-31 03:41:18 +02:00
return exit.ErrAborted
2022-07-31 03:10:36 +02:00
}
if len(m.matches) > m.selected && m.selected >= 0 {
fmt.Println(m.matches[m.selected].Str)
}
return err
}
2022-07-20 19:39:22 +02:00
// BeforeReset hook. Used to unclutter style flags.
func (o Options) BeforeReset(ctx *kong.Context) error {
return style.HideFlags(ctx)
}