summaryrefslogtreecommitdiff
path: root/complete.go
blob: 302486cebb7c4df5f2252eb81e36dff2670f6066 (plain)
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
58
59
60
61
62
63
64
65
66
package complete

import (
	"fmt"
	"os"
	"strings"
)

const (
	envComplete = "COMP_LINE"
	envDebug    = "COMP_DEBUG"
)

type Completer struct {
	Command
}

func New(c Command) *Completer {
	return &Completer{Command: c}
}

func (c *Completer) Complete() {
	args := getLine()
	Log("Completing args: %s", args)

	options := c.complete(args)

	Log("Completion: %s", options)
	output(options)
}

func (c *Completer) complete(args []string) []string {
	all, _ := c.options(args[:len(args)-1])
	return c.chooseRelevant(last(args), all)
}

func (c *Completer) chooseRelevant(last string, options []Option) (relevant []string) {
	for _, option := range options {
		if option.Matches(last) {
			relevant = append(relevant, option.String())
		}
	}
	return
}

func getLine() []string {
	line := os.Getenv(envComplete)
	if line == "" {
		panic("should be run as a complete script")
	}
	return strings.Split(line, " ")
}

func last(args []string) (last string) {
	if len(args) > 0 {
		last = args[len(args)-1]
	}
	return
}

func output(options []string) {
	// stdout of program defines the complete options
	for _, option := range options {
		fmt.Println(option)
	}
}