Merge pull request #3 from posener/predicate-as-function-type

Predicate as function type
This commit is contained in:
Eyal Posener 2017-05-06 21:04:11 +03:00 committed by GitHub
commit 2b6aed2b1e
9 changed files with 118 additions and 121 deletions

View File

@ -8,7 +8,7 @@ before_install:
- go get -u -t ./... - go get -u -t ./...
script: script:
- ./go.test.sh - go test -v -race -coverprofile=coverage.txt -covermode=atomic
after_success: after_success:
- bash <(curl -s https://codecov.io/bash) - bash <(curl -s https://codecov.io/bash)

View File

@ -2,13 +2,13 @@ package complete
type Commands map[string]Command type Commands map[string]Command
type Flags map[string]*Predicate type Flags map[string]Predicate
type Command struct { type Command struct {
Name string Name string
Sub Commands Sub Commands
Flags Flags Flags Flags
Args *Predicate Args Predicate
} }
// options returns all available complete options for the given command // options returns all available complete options for the given command
@ -17,11 +17,11 @@ func (c *Command) options(args []string) (options []Option, only bool) {
// remove the first argument, which is the command name // remove the first argument, which is the command name
args = args[1:] args = args[1:]
last := last(args)
// if prev has something that needs to follow it, // if prev has something that needs to follow it,
// it is the most relevant completion // it is the most relevant completion
if predicate, ok := c.Flags[last(args)]; ok && predicate != nil { if predicate, ok := c.Flags[last]; ok && predicate != nil {
return predicate.predict(), true return predicate.predict(last), true
} }
sub, options, only := c.searchSub(args) sub, options, only := c.searchSub(args)
@ -41,7 +41,7 @@ func (c *Command) options(args []string) (options []Option, only bool) {
} }
// add additional expected argument of the command // add additional expected argument of the command
options = append(options, c.Args.predict()...) options = append(options, c.Args.predict(last)...)
return return
} }

View File

@ -1,12 +0,0 @@
#!/usr/bin/env bash
set -e
echo "" > coverage.txt
for d in $(go list ./... | grep -v vendor); do
go test -count 20 -v -race -coverprofile=profile.out -covermode=atomic $d
if [ -f profile.out ]; then
cat profile.out >> coverage.txt
rm profile.out
fi
done

View File

@ -8,8 +8,8 @@ var (
predictEllipsis = complete.PredictSet("./...") predictEllipsis = complete.PredictSet("./...")
goFilesOrPackages = complete.PredictFiles("**.go"). goFilesOrPackages = complete.PredictFiles("**.go").
Or(complete.PredictDirs("./")). Or(complete.PredictDirs).
Or(predictEllipsis) Or(predictEllipsis)
) )
func main() { func main() {
@ -34,7 +34,7 @@ func main() {
"-installsuffix": complete.PredictAnything, "-installsuffix": complete.PredictAnything,
"-ldflags": complete.PredictAnything, "-ldflags": complete.PredictAnything,
"-linkshared": complete.PredictNothing, "-linkshared": complete.PredictNothing,
"-pkgdir": complete.PredictDirs("./"), "-pkgdir": complete.PredictDirs,
"-tags": complete.PredictAnything, "-tags": complete.PredictAnything,
"-toolexec": complete.PredictAnything, "-toolexec": complete.PredictAnything,
}, },
@ -45,7 +45,7 @@ func main() {
Flags: complete.Flags{ Flags: complete.Flags{
"-exec": complete.PredictAnything, "-exec": complete.PredictAnything,
}, },
Args: complete.PredictFiles("**.go"), Args: complete.PredictFiles("*.go"),
} }
test := complete.Command{ test := complete.Command{
@ -59,23 +59,23 @@ func main() {
"-count": complete.PredictAnything, "-count": complete.PredictAnything,
"-cover": complete.PredictNothing, "-cover": complete.PredictNothing,
"-covermode": complete.PredictSet("set", "count", "atomic"), "-covermode": complete.PredictSet("set", "count", "atomic"),
"-coverpkg": complete.PredictDirs("./"), "-coverpkg": complete.PredictDirs,
"-cpu": complete.PredictAnything, "-cpu": complete.PredictAnything,
"-run": predictTest("test"), "-run": predictTest("test"),
"-short": complete.PredictNothing, "-short": complete.PredictNothing,
"-timeout": complete.PredictAnything, "-timeout": complete.PredictAnything,
"-benchmem": complete.PredictNothing, "-benchmem": complete.PredictNothing,
"-blockprofile": complete.PredictFiles("**.out"), "-blockprofile": complete.PredictFiles("*.out"),
"-blockprofilerate": complete.PredictAnything, "-blockprofilerate": complete.PredictAnything,
"-coverprofile": complete.PredictFiles("**.out"), "-coverprofile": complete.PredictFiles("*.out"),
"-cpuprofile": complete.PredictFiles("**.out"), "-cpuprofile": complete.PredictFiles("*.out"),
"-memprofile": complete.PredictFiles("**.out"), "-memprofile": complete.PredictFiles("*.out"),
"-memprofilerate": complete.PredictAnything, "-memprofilerate": complete.PredictAnything,
"-mutexprofile": complete.PredictFiles("**.out"), "-mutexprofile": complete.PredictFiles("*.out"),
"-mutexprofilefraction": complete.PredictAnything, "-mutexprofilefraction": complete.PredictAnything,
"-outputdir": complete.PredictDirs("./"), "-outputdir": complete.PredictDirs,
"-trace": complete.PredictFiles("**.out"), "-trace": complete.PredictFiles("*.out"),
}, },
Args: goFilesOrPackages, Args: goFilesOrPackages,
} }
@ -115,7 +115,7 @@ func main() {
"-n": complete.PredictNothing, "-n": complete.PredictNothing,
"-x": complete.PredictNothing, "-x": complete.PredictNothing,
}, },
Args: complete.PredictDirs("./"), Args: complete.PredictDirs,
} }
list := complete.Command{ list := complete.Command{
@ -124,7 +124,7 @@ func main() {
"-f": complete.PredictAnything, "-f": complete.PredictAnything,
"-json": complete.PredictNothing, "-json": complete.PredictNothing,
}, },
Args: complete.PredictDirs("./"), Args: complete.PredictDirs,
} }
tool := complete.Command{ tool := complete.Command{
@ -141,7 +141,7 @@ func main() {
"-n": complete.PredictNothing, "-n": complete.PredictNothing,
"-x": complete.PredictNothing, "-x": complete.PredictNothing,
}, },
Args: complete.PredictDirs("./"), Args: complete.PredictDirs,
} }
env := complete.Command{ env := complete.Command{
@ -152,7 +152,7 @@ func main() {
version := complete.Command{} version := complete.Command{}
fix := complete.Command{ fix := complete.Command{
Args: complete.PredictDirs("./"), Args: complete.PredictDirs,
} }
// commands that also accepts the build flags // commands that also accepts the build flags

View File

@ -11,16 +11,14 @@ import (
"github.com/posener/complete" "github.com/posener/complete"
) )
func predictTest(testType string) *complete.Predicate { func predictTest(testType string) complete.Predicate {
return &complete.Predicate{ return func(last string) []complete.Option {
Predictor: func() []complete.Option { tests := testNames(testType)
tests := testNames(testType) options := make([]complete.Option, len(tests))
options := make([]complete.Option, len(tests)) for i := range tests {
for i := range tests { options[i] = complete.Arg(tests[i])
options[i] = complete.Arg(tests[i]) }
} return options
return options
},
} }
} }

View File

@ -5,10 +5,10 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"os/user" "os/user"
"path/filepath" "path/filepath"
"io/ioutil"
) )
type home struct{} type home struct{}

View File

@ -25,6 +25,5 @@ func (root) Uninstall(cmd string, bin string) error {
} }
func getBashCompletionDLink(cmd string) string { func getBashCompletionDLink(cmd string) string {
return "/etc/bash_completion.d/"+cmd return "/etc/bash_completion.d/" + cmd
} }

View File

@ -6,74 +6,63 @@ import (
) )
// Predicate determines what terms can follow a command or a flag // Predicate determines what terms can follow a command or a flag
type Predicate struct { type Predicate func(last string) []Option
// Predictor is function that returns list of arguments that can
// come after the flag/command
Predictor func() []Option
}
// Or unions two predicate struct, so that the result predicate // Or unions two predicate struct, so that the result predicate
// returns the union of their predication // returns the union of their predication
func (p *Predicate) Or(other *Predicate) *Predicate { func (p Predicate) Or(other Predicate) Predicate {
if p == nil || other == nil { if p == nil || other == nil {
return nil return nil
} }
return &Predicate{ return func(last string) []Option { return append(p.predict(last), other.predict(last)...) }
Predictor: func() []Option { return append(p.predict(), other.predict()...) },
}
} }
func (p *Predicate) predict() []Option { func (p Predicate) predict(last string) []Option {
if p == nil || p.Predictor == nil { if p == nil {
return nil return nil
} }
return p.Predictor() return p(last)
} }
var ( var (
PredictNothing *Predicate = nil PredictNothing Predicate = nil
PredictAnything = &Predicate{}
) )
func PredictSet(options ...string) *Predicate { func PredictAnything(last string) []Option { return nil }
return &Predicate{
Predictor: func() []Option {
ret := make([]Option, len(options))
for i := range options {
ret[i] = Arg(options[i])
}
return ret
},
}
}
func PredictFiles(pattern string) *Predicate { func PredictSet(options ...string) Predicate {
return &Predicate{Predictor: glob(pattern)} return func(last string) []Option {
} ret := make([]Option, len(options))
for i := range options {
func PredictDirs(path string) *Predicate { ret[i] = Arg(options[i])
return &Predicate{Predictor: dirs(path)}
}
func dirs(path string) func() []Option {
return func() (options []Option) {
dirs := []string{}
filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
dirs = append(dirs, path)
}
return nil
})
if !filepath.IsAbs(path) {
filesToRel(dirs)
} }
return filesToOptions(dirs) return ret
} }
} }
func glob(pattern string) func() []Option { func PredictDirs(last string) (options []Option) {
return func() []Option { dir := dirFromLast(last)
files, err := filepath.Glob(pattern) return dirsAt(dir)
}
func dirsAt(path string) []Option {
dirs := []string{}
filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
dirs = append(dirs, path)
}
return nil
})
if !filepath.IsAbs(path) {
filesToRel(dirs)
}
return filesToOptions(dirs)
}
func PredictFiles(pattern string) Predicate {
return func(last string) []Option {
dir := dirFromLast(last)
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)
} }
@ -83,6 +72,7 @@ func glob(pattern string) func() []Option {
return filesToOptions(files) return filesToOptions(files)
} }
} }
func filesToRel(files []string) { func filesToRel(files []string) {
wd, err := os.Getwd() wd, err := os.Getwd()
if err != nil { if err != nil {
@ -97,6 +87,9 @@ func filesToRel(files []string) {
if err != nil { if err != nil {
continue continue
} }
if rel == "." {
rel = ""
}
files[i] = "./" + rel files[i] = "./" + rel
} }
return return
@ -109,3 +102,15 @@ func filesToOptions(files []string) []Option {
} }
return options return options
} }
// dirFromLast gives the directory of the current written
// last argument if it represents a file name being written.
// in case that it is not, we fall back to the current directory.
func dirFromLast(last string) string {
dir := filepath.Dir(last)
_, err := os.Stat(dir)
if err != nil {
return "./"
}
return dir
}

View File

@ -9,30 +9,37 @@ import (
func TestCompleter_Complete(t *testing.T) { func TestCompleter_Complete(t *testing.T) {
t.Parallel() t.Parallel()
// Set debug environment variable so logs will be printed
if testing.Verbose() { if testing.Verbose() {
os.Setenv(envDebug, "1") os.Setenv(envDebug, "1")
} }
// Change to tests directory for testing completion of files and directories
err := os.Chdir("./tests")
if err != nil {
t.Fatal(err)
}
c := Command{ c := Command{
Sub: map[string]Command{ Sub: map[string]Command{
"sub1": { "sub1": {
Flags: map[string]*Predicate{ Flags: map[string]Predicate{
"-flag1": PredictAnything, "-flag1": PredictAnything,
"-flag2": PredictNothing, "-flag2": PredictNothing,
}, },
}, },
"sub2": { "sub2": {
Flags: map[string]*Predicate{ Flags: map[string]Predicate{
"-flag2": PredictNothing, "-flag2": PredictNothing,
"-flag3": PredictSet("opt1", "opt2", "opt12"), "-flag3": PredictSet("opt1", "opt2", "opt12"),
}, },
Args: PredictDirs("./tests/").Or(PredictFiles("./tests/*.md")), Args: Predicate(PredictDirs).Or(PredictFiles("*.md")),
}, },
}, },
Flags: map[string]*Predicate{ Flags: map[string]Predicate{
"-h": PredictNothing, "-h": PredictNothing,
"-global1": PredictAnything, "-global1": PredictAnything,
"-o": PredictFiles("./tests/*.txt"), "-o": PredictFiles("*.txt"),
}, },
} }
@ -44,7 +51,7 @@ func TestCompleter_Complete(t *testing.T) {
allGlobals = append(allGlobals, flag) allGlobals = append(allGlobals, flag)
} }
testTXTFiles := []string{"./tests/a.txt", "./tests/b.txt", "./tests/c.txt"} testTXTFiles := []string{"./a.txt", "./b.txt", "./c.txt"}
tests := []struct { tests := []struct {
args string args string
@ -84,19 +91,19 @@ func TestCompleter_Complete(t *testing.T) {
}, },
{ {
args: "sub2 ", args: "sub2 ",
want: []string{"./tests", "-flag2", "-flag3", "-h", "-global1", "-o"}, want: []string{"./", "./dir", "./readme.md", "-flag2", "-flag3", "-h", "-global1", "-o"},
}, },
{ {
args: "sub2 tests", args: "sub2 ./",
want: []string{"./tests", "./tests/readme.md", "./tests/dir"}, want: []string{"./", "./readme.md", "./dir"},
}, },
{ {
args: "sub2 tests/re", args: "sub2 re",
want: []string{"./tests/readme.md"}, want: []string{"./readme.md"},
}, },
{ {
args: "sub2 -flag2 ", args: "sub2 -flag2 ",
want: []string{"./tests", "-flag2", "-flag3", "-h", "-global1", "-o"}, want: []string{"./", "./dir", "./readme.md", "-flag2", "-flag3", "-h", "-global1", "-o"},
}, },
{ {
args: "sub1 -fl", args: "sub1 -fl",
@ -132,30 +139,30 @@ func TestCompleter_Complete(t *testing.T) {
}, },
{ {
args: "-o ", args: "-o ",
want: []string{},
},
{
args: "-o ./tes",
want: []string{},
},
{
args: "-o tests/",
want: testTXTFiles, want: testTXTFiles,
}, },
{ {
args: "-o tests", args: "-o ./no-su",
want: []string{},
},
{
args: "-o ./",
want: testTXTFiles, want: testTXTFiles,
}, },
{ {
args: "-o ./compl", args: "-o ",
want: testTXTFiles,
},
{
args: "-o ./read",
want: []string{}, want: []string{},
}, },
{ {
args: "-o ./complete.go", args: "-o ./readme.md",
want: []string{}, want: []string{},
}, },
{ {
args: "-o ./complete.go ", args: "-o ./readme.md ",
want: allGlobals, want: allGlobals,
}, },
{ {