complete/predicate.go

72 lines
1.4 KiB
Go
Raw Normal View History

2017-05-05 08:57:22 -05:00
package complete
2017-05-05 13:57:21 -05:00
import (
"os"
"path/filepath"
)
2017-05-05 13:59:10 -05:00
// Predicate determines what terms can follow a command or a flag
type Predicate struct {
// Expects determine if the predicate expects something after.
// flags/commands that do not expect any specific argument should
// leave it on false
Expects bool
// Predictor is function that returns list of arguments that can
// come after the flag/command
Predictor func() []Option
2017-05-05 13:57:21 -05:00
}
2017-05-05 13:59:10 -05:00
func (f *Predicate) predict() []Option {
if f.Predictor == nil {
2017-05-05 13:57:21 -05:00
return nil
}
2017-05-05 13:59:10 -05:00
return f.Predictor()
2017-05-05 08:57:22 -05:00
}
var (
2017-05-05 13:59:10 -05:00
PredictNothing = Predicate{Expects: false}
PredictAnything = Predicate{Expects: true}
2017-05-05 08:57:22 -05:00
)
2017-05-05 13:59:10 -05:00
func PredictFiles(pattern string) Predicate {
return Predicate{
Expects: true,
Predictor: glob(pattern),
2017-05-05 13:57:21 -05:00
}
}
func glob(pattern string) func() []Option {
return func() []Option {
files, err := filepath.Glob(pattern)
if err != nil {
logger("failed glob operation with pattern '%s': %s", pattern, err)
}
if !filepath.IsAbs(pattern) {
filesToRel(files)
}
options := make([]Option, len(files))
for i, f := range files {
options[i] = ArgFileName(f)
}
return options
}
}
func filesToRel(files []string) {
wd, err := os.Getwd()
if err != nil {
return
}
for i := range files {
abs, err := filepath.Abs(files[i])
if err != nil {
continue
}
rel, err := filepath.Rel(wd, abs)
if err != nil {
continue
}
files[i] = "./" + rel
}
return
}