Add Predictor interface

This commit is contained in:
Eyal Posener 2017-05-11 20:28:31 +03:00
parent a28594d28e
commit 967bae76f3
8 changed files with 131 additions and 128 deletions

29
args.go
View File

@ -1,25 +1,26 @@
package complete package complete
type args struct { // Args describes command line arguments
all []string type Args struct {
completed []string All []string
beingTyped string Completed []string
lastCompleted string Last string
LastCompleted string
} }
func newArgs(line []string) args { func newArgs(line []string) Args {
completed := removeLast(line) completed := removeLast(line)
return args{ return Args{
all: line[1:], All: line[1:],
completed: completed, Completed: completed,
beingTyped: last(line), Last: last(line),
lastCompleted: last(completed), LastCompleted: last(completed),
} }
} }
func (a args) from(i int) args { func (a Args) from(i int) Args {
a.all = a.all[i:] a.All = a.All[i:]
a.completed = a.completed[i:] a.Completed = a.Completed[i:]
return a return a
} }

View File

@ -12,30 +12,33 @@ type Command struct {
Sub Commands Sub Commands
// Flags is a map of flags that the command accepts. // Flags is a map of flags that the command accepts.
// The key is the flag name, and the value is it's prediction predict. // The key is the flag name, and the value is it's predictions.
Flags Flags Flags Flags
// Args are extra arguments that the command accepts, those who are // Args are extra arguments that the command accepts, those who are
// given without any flag before. // given without any flag before.
Args Predicate Args Predictor
} }
// Commands is the type of Sub member, it maps a command name to a command struct // Commands is the type of Sub member, it maps a command name to a command struct
type Commands map[string]Command type Commands map[string]Command
// Flags is the type Flags of the Flags member, it maps a flag name to the flag // Flags is the type Flags of the Flags member, it maps a flag name to the flag predictions.
// prediction predict. type Flags map[string]Predictor
type Flags map[string]Predicate
// predict returns all available complete predict for the given command // Predict returns all possible predictions for args according to the command struct
// all are all except the last command line arguments relevant to the command func (c *Command) Predict(a Args) (predictions []string) {
func (c *Command) predict(a args) (options []match.Matcher, only bool) { predictions, _ = c.predict(a)
return
}
func (c *Command) predict(a Args) (options []string, only bool) {
// if wordCompleted has something that needs to follow it, // if wordCompleted has something that needs to follow it,
// it is the most relevant completion // it is the most relevant completion
if predicate, ok := c.Flags[a.lastCompleted]; ok && predicate != nil { if predictor, ok := c.Flags[a.LastCompleted]; ok && predictor != nil {
Log("Predicting according to flag %s", a.beingTyped) Log("Predicting according to flag %s", a.Last)
return predicate.predict(a.beingTyped), true return predictor.Predict(a), true
} }
sub, options, only := c.searchSub(a) sub, options, only := c.searchSub(a)
@ -45,24 +48,28 @@ func (c *Command) predict(a args) (options []match.Matcher, only bool) {
// if no sub command was found, return a list of the sub commands // if no sub command was found, return a list of the sub commands
if sub == "" { if sub == "" {
options = append(options, c.subCommands()...) options = append(options, c.subCommands(a.Last)...)
} }
// add global available complete predict // add global available complete Predict
for flag := range c.Flags { for flag := range c.Flags {
options = append(options, match.Prefix(flag)) if m := match.Prefix(flag); m.Match(a.Last) {
options = append(options, m.String())
}
} }
// add additional expected argument of the command // add additional expected argument of the command
options = append(options, c.Args.predict(a.beingTyped)...) if c.Args != nil {
options = append(options, c.Args.Predict(a)...)
}
return return
} }
// searchSub searches recursively within sub commands if the sub command appear // searchSub searches recursively within sub commands if the sub command appear
// in the on of the arguments. // in the on of the arguments.
func (c *Command) searchSub(a args) (sub string, all []match.Matcher, only bool) { func (c *Command) searchSub(a Args) (sub string, all []string, only bool) {
for i, arg := range a.completed { for i, arg := range a.Completed {
if cmd, ok := c.Sub[arg]; ok { if cmd, ok := c.Sub[arg]; ok {
sub = arg sub = arg
all, only = cmd.predict(a.from(i)) all, only = cmd.predict(a.from(i))
@ -72,11 +79,12 @@ func (c *Command) searchSub(a args) (sub string, all []match.Matcher, only bool)
return return
} }
// suvCommands returns a list of matchers according to the sub command names // subCommands returns a list of matching sub commands
func (c *Command) subCommands() []match.Matcher { func (c *Command) subCommands(last string) (prediction []string) {
subs := make([]match.Matcher, 0, len(c.Sub))
for sub := range c.Sub { for sub := range c.Sub {
subs = append(subs, match.Prefix(sub)) if m := match.Prefix(sub); m.Match(last) {
prediction = append(prediction, m.String())
} }
return subs }
return
} }

View File

@ -51,27 +51,13 @@ func (c *Complete) Run() bool {
a := newArgs(line) a := newArgs(line)
options := complete(c.Command, a) options := c.Command.Predict(a)
Log("Completion: %s", options) Log("Completion: %s", options)
output(options) output(options)
return true return true
} }
// complete get a command an command line arguments and returns
// matching completion options
func complete(c Command, a args) (matching []string) {
options, _ := c.predict(a)
for _, option := range options {
Log("option %T, %s -> %t", option, option, option.Match(a.beingTyped))
if option.Match(a.beingTyped) {
matching = append(matching, option.String())
}
}
return
}
func getLine() ([]string, bool) { func getLine() ([]string, bool) {
line := os.Getenv(envComplete) line := os.Getenv(envComplete)
if line == "" { if line == "" {

View File

@ -13,20 +13,20 @@ func TestCompleter_Complete(t *testing.T) {
c := Command{ c := Command{
Sub: map[string]Command{ Sub: map[string]Command{
"sub1": { "sub1": {
Flags: map[string]Predicate{ Flags: map[string]Predictor{
"-flag1": PredictAnything, "-flag1": PredictAnything,
"-flag2": PredictNothing, "-flag2": PredictNothing,
}, },
}, },
"sub2": { "sub2": {
Flags: map[string]Predicate{ Flags: map[string]Predictor{
"-flag2": PredictNothing, "-flag2": PredictNothing,
"-flag3": PredictSet("opt1", "opt2", "opt12"), "-flag3": PredictSet("opt1", "opt2", "opt12"),
}, },
Args: Predicate(PredictDirs("*")).Or(PredictFiles("*.md")), Args: PredictOr(PredictDirs("*"), PredictFiles("*.md")),
}, },
}, },
Flags: map[string]Predicate{ Flags: map[string]Predictor{
"-h": PredictNothing, "-h": PredictNothing,
"-global1": PredictAnything, "-global1": PredictAnything,
"-o": PredictFiles("*.txt"), "-o": PredictFiles("*.txt"),
@ -176,7 +176,7 @@ func TestCompleter_Complete(t *testing.T) {
os.Setenv(envComplete, tt.args) os.Setenv(envComplete, tt.args)
line, _ := getLine() line, _ := getLine()
got := complete(c, newArgs(line)) got := c.Predict(newArgs(line))
sort.Strings(tt.want) sort.Strings(tt.want)
sort.Strings(got) sort.Strings(got)

View File

@ -6,9 +6,11 @@ import "github.com/posener/complete"
var ( var (
predictEllipsis = complete.PredictSet("./...") predictEllipsis = complete.PredictSet("./...")
goFilesOrPackages = complete.PredictFiles("*.go"). goFilesOrPackages = complete.PredictOr(
Or(complete.PredictDirs("*")). complete.PredictFiles("*.go"),
Or(predictEllipsis) complete.PredictDirs("*"),
predictEllipsis,
)
) )
func main() { func main() {

View File

@ -17,15 +17,16 @@ import (
// and then all the relevant function names. // and then all the relevant function names.
// for test names use prefix of 'Test' or 'Example', and for benchmark // for test names use prefix of 'Test' or 'Example', and for benchmark
// test names use 'Benchmark' // test names use 'Benchmark'
func predictTest(funcPrefix ...string) complete.Predicate { func predictTest(funcPrefix ...string) complete.Predictor {
return func(last string) []match.Matcher { return complete.PredictFunc(func(a complete.Args) (prediction []string) {
tests := testNames(funcPrefix) tests := testNames(funcPrefix)
options := make([]match.Matcher, len(tests)) for _, t := range tests {
for i := range tests { if m := match.Prefix(t); m.Match(a.Last) {
options[i] = match.Prefix(tests[i]) prediction = append(prediction, m.String())
} }
return options
} }
return
})
} }
// get all test names in current directory // get all test names in current directory

View File

@ -7,52 +7,70 @@ import (
"github.com/posener/complete/match" "github.com/posener/complete/match"
) )
// Predicate determines what terms can follow a command or a flag // 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, p.Predict(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 // It is used for auto completion, given last - the last word in the already
// in the command line, what words can complete it. // in the command line, what words can complete it.
type Predicate func(last string) []match.Matcher type PredictFunc func(Args) []string
// Or unions two predicate functions, so that the result predicate // Predict invokes the predict function and implements the Predictor interface
// returns the union of their predication func (p PredictFunc) Predict(a Args) []string {
func (p Predicate) Or(other Predicate) Predicate {
if p == nil {
return other
}
if other == nil {
return p
}
return func(last string) []match.Matcher { return append(p.predict(last), other.predict(last)...) }
}
func (p Predicate) predict(last string) []match.Matcher {
if p == nil { if p == nil {
return nil return nil
} }
return p(last) return p(a)
} }
// PredictNothing does not expect anything after. // PredictNothing does not expect anything after.
var PredictNothing Predicate var PredictNothing Predictor
// PredictAnything expects something, but nothing particular, such as a number // PredictAnything expects something, but nothing particular, such as a number
// or arbitrary name. // or arbitrary name.
func PredictAnything(last string) []match.Matcher { return nil } var PredictAnything = PredictFunc(func(Args) []string { return nil })
// PredictSet expects specific set of terms, given in the options argument. // PredictSet expects specific set of terms, given in the options argument.
func PredictSet(options ...string) Predicate { func PredictSet(options ...string) Predictor {
return func(last string) []match.Matcher { p := predictSet{}
ret := make([]match.Matcher, len(options)) for _, o := range options {
for i := range options { p = append(p, match.Prefix(o))
ret[i] = match.Prefix(options[i])
} }
return ret return p
} }
type predictSet []match.Prefix
func (p predictSet) Predict(a Args) (prediction []string) {
for _, m := range p {
if m.Match(a.Last) {
prediction = append(prediction, m.String())
}
}
return
} }
// PredictDirs will search for directories in the given started to be typed // PredictDirs will search for directories in the given started to be typed
// path, if no path was started to be typed, it will complete to directories // path, if no path was started to be typed, it will complete to directories
// in the current working directory. // in the current working directory.
func PredictDirs(pattern string) Predicate { func PredictDirs(pattern string) Predictor {
return files(pattern, true, false) return files(pattern, true, false)
} }
@ -60,19 +78,19 @@ func PredictDirs(pattern string) Predicate {
// be typed path, if no path was started to be typed, it will complete to files that // be typed path, if no path was started to be typed, it will complete to files that
// match the pattern in the current working directory. // match the pattern in the current working directory.
// To match any file, use "*" as pattern. To match go files use "*.go", and so on. // To match any file, use "*" as pattern. To match go files use "*.go", and so on.
func PredictFiles(pattern string) Predicate { func PredictFiles(pattern string) Predictor {
return files(pattern, false, true) return files(pattern, false, true)
} }
// PredictFilesOrDirs predict any file or directory that matches the pattern // PredictFilesOrDirs any file or directory that matches the pattern
func PredictFilesOrDirs(pattern string) Predicate { func PredictFilesOrDirs(pattern string) Predictor {
return files(pattern, true, true) return files(pattern, true, true)
} }
func files(pattern string, allowDirs, allowFiles bool) Predicate { func files(pattern string, allowDirs, allowFiles bool) PredictFunc {
return func(last string) []match.Matcher { return func(a Args) (prediction []string) {
dir := dirFromLast(last) dir := dirFromLast(a.Last)
Log("looking for files in %s (last=%s)", dir, last) Log("looking for files in %s (last=%s)", dir, a.Last)
files, err := filepath.Glob(filepath.Join(dir, pattern)) files, err := filepath.Glob(filepath.Join(dir, pattern))
if err != nil { if err != nil {
Log("failed glob operation with pattern '%s': %s", pattern, err) Log("failed glob operation with pattern '%s': %s", pattern, err)
@ -84,7 +102,13 @@ func files(pattern string, allowDirs, allowFiles bool) Predicate {
if !filepath.IsAbs(pattern) { if !filepath.IsAbs(pattern) {
filesToRel(files) filesToRel(files)
} }
return filesToMatchers(files) // add all matching files to prediction
for _, f := range files {
if m := match.File(f); m.Match(a.Last) {
prediction = append(prediction, m.String())
}
}
return
} }
} }
@ -130,14 +154,6 @@ func filesToRel(files []string) {
return return
} }
func filesToMatchers(files []string) []match.Matcher {
options := make([]match.Matcher, len(files))
for i, f := range files {
options[i] = match.File(f)
}
return options
}
// dirFromLast gives the directory of the current written // dirFromLast gives the directory of the current written
// last argument if it represents a file name being written. // last argument if it represents a file name being written.
// in case that it is not, we fall back to the current directory. // in case that it is not, we fall back to the current directory.

View File

@ -12,7 +12,7 @@ func TestPredicate(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
p Predicate p Predictor
arg string arg string
want []string want []string
}{ }{
@ -37,29 +37,24 @@ func TestPredicate(t *testing.T) {
p: PredictAnything, p: PredictAnything,
want: []string{}, want: []string{},
}, },
{
name: "nothing",
p: PredictNothing,
want: []string{},
},
{ {
name: "or: word with nil", name: "or: word with nil",
p: PredictSet("a").Or(PredictNothing), p: PredictOr(PredictSet("a"), nil),
want: []string{"a"}, want: []string{"a"},
}, },
{ {
name: "or: nil with word", name: "or: nil with word",
p: PredictNothing.Or(PredictSet("a")), p: PredictOr(nil, PredictSet("a")),
want: []string{"a"}, want: []string{"a"},
}, },
{ {
name: "or: nil with nil", name: "or: nil with nil",
p: PredictNothing.Or(PredictNothing), p: PredictOr(PredictNothing, PredictNothing),
want: []string{}, want: []string{},
}, },
{ {
name: "or: word with word with word", name: "or: word with word with word",
p: PredictSet("a").Or(PredictSet("b")).Or(PredictSet("c")), p: PredictOr(PredictSet("a"), PredictSet("b"), PredictSet("c")),
want: []string{"a", "b", "c"}, want: []string{"a", "b", "c"},
}, },
{ {
@ -118,18 +113,12 @@ func TestPredicate(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name+"?arg='"+tt.arg+"'", func(t *testing.T) { t.Run(tt.name+"?arg='"+tt.arg+"'", func(t *testing.T) {
matchers := tt.p.predict(tt.arg) matches := tt.p.Predict(newArgs(strings.Split(tt.arg, " ")))
matchersString := []string{} sort.Strings(matches)
for _, m := range matchers {
if m.Match(tt.arg) {
matchersString = append(matchersString, m.String())
}
}
sort.Strings(matchersString)
sort.Strings(tt.want) sort.Strings(tt.want)
got := strings.Join(matchersString, ",") got := strings.Join(matches, ",")
want := strings.Join(tt.want, ",") want := strings.Join(tt.want, ",")
if got != want { if got != want {