summaryrefslogtreecommitdiff
path: root/complete.go
blob: eedaa811ac2c36c66b8e2395e6d4cfd09a55912a (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
67
68
69
70
71
72
73
package complete

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

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

type Completer struct {
	Command
	log func(format string, args ...interface{})
}

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

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

	options := c.complete(args)

	c.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, list []string) (opts []string) {
	if last == "" {
		return list
	}
	for _, sub := range list {
		if strings.HasPrefix(sub, last) {
			opts = append(opts, sub)
		}
	}
	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)
	}
}