From 7ee9623f2b5d4685a91a51d0823275754b4d3a0a Mon Sep 17 00:00:00 2001 From: Eyal Posener Date: Sat, 4 Nov 2017 10:21:41 +0200 Subject: Filter matches as a final stage This simplifies the prediction logic writing, the predictor doesn't need to filter our according to line matching, instead it returns everything and the filtering is done at the end. This does not break current behavior. --- complete.go | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) (limited to 'complete.go') diff --git a/complete.go b/complete.go index 1df6617..3647c28 100644 --- a/complete.go +++ b/complete.go @@ -8,10 +8,12 @@ package complete import ( "flag" "fmt" + "io" "os" "strings" "github.com/posener/complete/cmd" + "github.com/posener/complete/match" ) const ( @@ -23,6 +25,7 @@ const ( type Complete struct { Command Command cmd.CLI + Out io.Writer } // New creates a new complete command. @@ -34,6 +37,7 @@ func New(name string, command Command) *Complete { return &Complete{ Command: command, CLI: cmd.CLI{Name: name}, + Out: os.Stdout, } } @@ -59,13 +63,19 @@ func (c *Complete) Complete() bool { return c.CLI.Run() } Log("Completing line: %s", line) - a := newArgs(line) - options := c.Command.Predict(a) + Log("Options: %s", options) - Log("Completion: %s", options) - output(options) + // filter only options that match the last argument + matches := []string{} + for _, option := range options { + if match.Prefix(option, a.Last) { + matches = append(matches, option) + } + } + Log("Matches: %s", matches) + c.output(matches) return true } @@ -77,10 +87,9 @@ func getLine() ([]string, bool) { return strings.Split(line, " "), true } -func output(options []string) { - Log("") +func (c *Complete) output(options []string) { // stdout of program defines the complete options for _, option := range options { - fmt.Println(option) + fmt.Fprintln(c.Out, option) } } -- cgit v1.2.3