gum/filter/command.go

94 lines
2.1 KiB
Go
Raw Normal View History

package filter
import (
"errors"
"fmt"
"os"
"strings"
2022-07-20 19:39:22 +02:00
"github.com/alecthomas/kong"
"github.com/charmbracelet/bubbles/textinput"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/sahilm/fuzzy"
2022-08-05 00:45:19 +02:00
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
v := viewport.New(o.Width, o.Height)
var choices []string
2022-07-30 23:40:33 +02:00
if input, _ := stdin.Read(); input != "" {
input = strings.TrimSpace(input)
if input != "" {
choices = strings.Split(input, "\n")
}
} else {
choices = files.List()
}
if len(choices) == 0 {
return errors.New("no options provided, see `gum filter --help`")
}
options := []tea.ProgramOption{tea.WithOutput(os.Stderr)}
if o.Height == 0 {
options = append(options, tea.WithAltScreen())
}
var matches []fuzzy.Match
if o.Value != "" {
i.SetValue(o.Value)
matches = fuzzy.Find(o.Value, choices)
} else {
matches = matchAll(choices)
}
p := tea.NewProgram(model{
choices: choices,
indicator: o.Indicator,
matches: matches,
textinput: i,
viewport: &v,
indicatorStyle: o.IndicatorStyle.ToLipgloss(),
matchStyle: o.MatchStyle.ToLipgloss(),
textStyle: o.TextStyle.ToLipgloss(),
height: o.Height,
}, options...)
2022-08-04 17:15:21 +02:00
tm, err := p.StartReturningModel()
2022-08-05 00:45:19 +02:00
if err != nil {
return fmt.Errorf("unable to run filter: %w", err)
}
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)
}
2022-08-05 00:45:19 +02:00
return nil
}
2022-07-20 19:39:22 +02:00
// BeforeReset hook. Used to unclutter style flags.
func (o Options) BeforeReset(ctx *kong.Context) error {
2022-08-05 00:45:19 +02:00
style.HideFlags(ctx)
return nil
2022-07-20 19:39:22 +02:00
}