From 9b3c8c0db0c3eb141cdb80b53ecd4069e1ac83ac Mon Sep 17 00:00:00 2001 From: Maas Lalani Date: Mon, 8 Aug 2022 16:54:24 -0400 Subject: [PATCH] Allow `--value` to pre-populate `gum filter` (#113) * Add --value option to filter command Modeled after fzf's --query option this allows the inital model to be prefiltered. Additionally, if the initial list, before being filtered by --value, is empty then treat this as an error. Filtering an empty list doesn't make sense. Co-authored-by: David Morgan --- filter/command.go | 21 +++++++++++++++++++-- filter/options.go | 1 + 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/filter/command.go b/filter/command.go index 746c504..8a00b7d 100644 --- a/filter/command.go +++ b/filter/command.go @@ -1,6 +1,7 @@ package filter import ( + "errors" "fmt" "os" "strings" @@ -9,6 +10,7 @@ import ( "github.com/charmbracelet/bubbles/textinput" "github.com/charmbracelet/bubbles/viewport" tea "github.com/charmbracelet/bubbletea" + "github.com/sahilm/fuzzy" "github.com/charmbracelet/gum/internal/exit" "github.com/charmbracelet/gum/internal/files" @@ -31,20 +33,35 @@ func (o Options) Run() error { var choices []string if input, _ := stdin.Read(); input != "" { - choices = strings.Split(strings.TrimSpace(input), "\n") + 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: matchAll(choices), + matches: matches, textinput: i, viewport: &v, indicatorStyle: o.IndicatorStyle.ToLipgloss(), diff --git a/filter/options.go b/filter/options.go index 0bd79d9..5173c84 100644 --- a/filter/options.go +++ b/filter/options.go @@ -13,4 +13,5 @@ type Options struct { PromptStyle style.Styles `embed:"" prefix:"prompt." set:"defaultForeground=240" envprefix:"GUM_FILTER_PROMPT_"` Width int `help:"Input width" default:"20" env:"GUM_FILTER_WIDTH"` Height int `help:"Input height" default:"0" env:"GUM_FILTER_HEIGHT"` + Value string `help:"Initial filter value" default:"" env:"GUM_FILTER_VALUE"` }