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 <david_a_morgan@icloud.com>
This commit is contained in:
Maas Lalani 2022-08-08 16:54:24 -04:00 committed by GitHub
parent c1a1a73a0e
commit 9b3c8c0db0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 2 deletions

View file

@ -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(),

View file

@ -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"`
}