-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathpredict.go
More file actions
57 lines (50 loc) · 1.59 KB
/
predict.go
File metadata and controls
57 lines (50 loc) · 1.59 KB
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
package complete
// Predictor implements a predict method, in which given
// command line arguments returns a list of options it predicts.
type Predictor interface {
Predict(Args) []string
}
// PredictOr unions two predicate functions, so that the result predicate
// returns the union of their predication
func PredictOr(predictors ...Predictor) Predictor {
return PredictFunc(func(a Args) (prediction []string) {
for _, p := range predictors {
if p == nil {
continue
}
prediction = append(prediction, predictAndFilterPrefix(p, a)...)
}
return
})
}
// PredictFunc determines what terms can follow a command or a flag
// It is used for auto completion, given last - the last word in the already
// in the command line, what words can complete it.
type PredictFunc func(Args) []string
// Predict invokes the predict function and implements the Predictor interface
func (p PredictFunc) Predict(a Args) []string {
if p == nil {
return nil
}
return p(a)
}
// PredictNothing does not expect anything after.
var PredictNothing Predictor
// PredictAnything expects something, but nothing particular, such as a number
// or arbitrary name.
var PredictAnything = PredictFunc(func(Args) []string { return nil })
func predictAndFilterPrefix(p Predictor, a Args) []string {
options := p.Predict(a)
prefixerFunc := DefaultPrefixFilter
prefixFilter, ok := p.(PrefixFilter)
if ok {
prefixerFunc = prefixFilter.FilterPrefix
}
matches := make([]string, 0, len(options))
for _, option := range options {
if prefixerFunc(option, a.Last) {
matches = append(matches, option)
}
}
return matches
}