Skip to content
Myr

command.go

This file

Path

filter/command.go

174 lines · 4.6 KiB · Go

Last changed by

chore: prepare v2 (#1116)Drew Smirnoffbefore adoption02d6f06

History of this file

Take it

1package filter23import (4	"errors"5	"fmt"6	"os"7	"slices"8	"strings"910	"charm.land/bubbles/v2/help"11	"charm.land/bubbles/v2/textinput"12	"charm.land/bubbles/v2/viewport"13	tea "charm.land/bubbletea/v2"14	"charm.land/gum/v2/internal/files"15	"charm.land/gum/v2/internal/stdin"16	"charm.land/gum/v2/internal/timeout"17	"charm.land/gum/v2/internal/tty"18	"charm.land/gum/v2/style"19	"github.com/charmbracelet/x/ansi"20	"github.com/sahilm/fuzzy"21)2223// Run provides a shell script interface for filtering through options, powered24// by the textinput bubble.25func (o Options) Run() error {26	i := textinput.New()27	i.Focus()2829	i.Prompt = o.Prompt30	styles := i.Styles()31	styles.Focused.Prompt = o.PromptStyle.ToLipgloss()32	styles.Blurred.Prompt = o.PromptStyle.ToLipgloss()33	styles.Focused.Placeholder = o.PlaceholderStyle.ToLipgloss()34	styles.Blurred.Placeholder = o.PlaceholderStyle.ToLipgloss()35	i.SetStyles(styles)36	i.Placeholder = o.Placeholder37	i.SetWidth(o.Width)3839	v := viewport.New(viewport.WithWidth(o.Width), viewport.WithHeight(o.Height))4041	if len(o.Options) == 0 {42		if input, _ := stdin.Read(stdin.StripANSI(o.StripANSI)); input != "" {43			o.Options = strings.Split(input, o.InputDelimiter)44		} else {45			o.Options = files.List()46		}47	}4849	if len(o.Options) == 0 {50		return errors.New("no options provided, see `gum filter --help`")51	}5253	ctx, cancel := timeout.Context(o.Timeout)54	defer cancel()5556	options := []tea.ProgramOption{57		tea.WithOutput(os.Stderr),58		tea.WithContext(ctx),59	}6061	var matches []fuzzy.Match62	if o.Value != "" {63		i.SetValue(o.Value)64	}6566	choices := map[string]string{}67	filteringChoices := []string{}68	for _, opt := range o.Options {69		s := ansi.Strip(opt)70		choices[s] = opt71		filteringChoices = append(filteringChoices, s)72	}73	switch {74	case o.Value != "" && o.Fuzzy:75		matches = fuzzy.Find(o.Value, filteringChoices)76	case o.Value != "" && !o.Fuzzy:77		matches = exactMatches(o.Value, filteringChoices)78	default:79		matches = matchAll(filteringChoices)80	}8182	if o.NoLimit {83		o.Limit = len(o.Options)84	}8586	if o.SelectIfOne && len(matches) == 1 {87		tty.Println(matches[0].Str)88		return nil89	}9091	km := defaultKeymap()92	if o.NoLimit || o.Limit > 1 {93		km.Toggle.SetEnabled(true)94		km.ToggleAndPrevious.SetEnabled(true)95		km.ToggleAndNext.SetEnabled(true)96		km.ToggleAll.SetEnabled(true)97	}98	top, right, bottom, left := style.ParsePadding(o.Padding)99	m := model{100		choices:               choices,101		filteringChoices:      filteringChoices,102		indicator:             o.Indicator,103		matches:               matches,104		header:                o.Header,105		textinput:             i,106		viewport:              &v,107		indicatorStyle:        o.IndicatorStyle.ToLipgloss(),108		selectedPrefixStyle:   o.SelectedPrefixStyle.ToLipgloss(),109		selectedPrefix:        o.SelectedPrefix,110		unselectedPrefixStyle: o.UnselectedPrefixStyle.ToLipgloss(),111		unselectedPrefix:      o.UnselectedPrefix,112		matchStyle:            o.MatchStyle.ToLipgloss(),113		headerStyle:           o.HeaderStyle.ToLipgloss(),114		textStyle:             o.TextStyle.ToLipgloss(),115		cursorTextStyle:       o.CursorTextStyle.ToLipgloss(),116		height:                o.Height,117		padding:               []int{top, right, bottom, left},118		selected:              make(map[string]struct{}),119		limit:                 o.Limit,120		reverse:               o.Reverse,121		fuzzy:                 o.Fuzzy,122		sort:                  o.Sort && o.FuzzySort,123		strict:                o.Strict,124		showHelp:              o.ShowHelp,125		keymap:                km,126		help:                  help.New(),127	}128129	isSelectAll := len(o.Selected) == 1 && o.Selected[0] == "*"130	currentSelected := 0131	if len(o.Selected) > 0 {132		for i, option := range matches {133			if currentSelected >= o.Limit || (!isSelectAll && !slices.Contains(o.Selected, option.Str)) {134				continue135			}136			if o.Limit == 1 {137				m.cursor = i138				m.selected[option.Str] = struct{}{}139			} else {140				currentSelected++141				m.selected[option.Str] = struct{}{}142			}143		}144	}145146	tm, err := tea.NewProgram(m, options...).Run()147	if err != nil {148		return fmt.Errorf("unable to run filter: %w", err)149	}150151	m = tm.(model)152	if !m.submitted {153		return errors.New("nothing selected")154	}155156	// allSelections contains values only if limit is greater157	// than 1 or if flag --no-limit is passed, hence there is158	// no need to further checks159	if len(m.selected) > 0 {160		o.checkSelected(m)161	} else if len(m.matches) > m.cursor && m.cursor >= 0 {162		tty.Println(m.matches[m.cursor].Str)163	}164165	return nil166}167168func (o Options) checkSelected(m model) {169	out := make([]string, 0, len(m.selected))170	for k := range m.selected {171		out = append(out, k)172	}173	tty.Println(strings.Join(out, o.OutputDelimiter))174}