-
Notifications
You must be signed in to change notification settings - Fork 5
/
fzf.go
93 lines (75 loc) 路 1.72 KB
/
fzf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package fzf
import (
"fmt"
"reflect"
tea "github.com/charmbracelet/bubbletea"
)
var defaultFindOption = findOption{
itemPrefixFunc: nil,
}
// Fuzzy Finder.
type FZF struct {
option *option
model *model
program *tea.Program
}
// New returns a new Fuzzy Finder.
func New(opts ...Option) *FZF {
o := defaultOption
for _, opt := range opts {
opt(&o)
}
m := newModel(&o)
return &FZF{
option: &o,
model: m,
program: tea.NewProgram(m),
}
}
// Find launches the Fuzzy Finder and returns a list of indexes of the selected items.
func (fzf *FZF) Find(items interface{}, itemFunc func(i int) string, opts ...FindOption) ([]int, error) {
findOption := defaultFindOption
for _, opt := range opts {
opt(&findOption)
}
rv := reflect.ValueOf(items)
switch {
case rv.Kind() == reflect.Slice:
case rv.Kind() == reflect.Ptr && reflect.Indirect(rv).Kind() == reflect.Slice:
default:
return nil, fmt.Errorf("items must be a slice, but got %T", items)
}
is, err := newItems(rv, itemFunc)
if err != nil {
return nil, err
}
fzf.model.setItems(is)
fzf.model.setFindOption(&findOption)
if _, err := fzf.program.Run(); err != nil {
return nil, err
}
if fzf.model.abort {
return nil, ErrAbort
}
return fzf.model.choices, nil
}
// Quit quits the Fuzzy Finder.
func (fzf *FZF) Quit() {
fzf.program.Quit()
}
// Abort aborts the Fuzzy Finder.
func (fzf *FZF) Abort() {
fzf.model.abort = true
fzf.Quit()
}
// Option represents a option for the Find.
type FindOption func(o *findOption)
type findOption struct {
itemPrefixFunc func(i int) string
}
// WithItemPrefix sets the prefix function of the item.
func WithItemPrefix(f func(i int) string) FindOption {
return func(o *findOption) {
o.itemPrefixFunc = f
}
}