summaryrefslogtreecommitdiff
path: root/run.go
blob: 5d9706f1a65313f35ed2d9905bd8014f411aece2 (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
74
75
// Package complete provides a tool for bash writing bash completion in go.
//
// Writing bash completion scripts is a hard work. This package provides an easy way
// to create bash completion scripts for any command, and also an easy way to install/uninstall
// the completion of the command.
package complete

import (
	"fmt"
	"os"
	"strings"

	"github.com/posener/complete/cmd"
)

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

// Run get a command, get the typed arguments from environment
// variable, and print out the complete options
// name is the name of command we want to auto complete.
// IMPORTANT: it must be the same name - if the auto complete
// completes the 'go' command, name must be equal to "go".
func Run(name string, c Command) {
	args, ok := getLine()
	if !ok {
		cmd.Run(name)
		return
	}
	Log("Completing args: %s", args)

	options := complete(c, args)

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

// complete get a command an command line arguments and returns
// matching completion options
func complete(c Command, args []string) (matching []string) {
	options, _ := c.options(args[:len(args)-1])

	// choose only matching options
	l := last(args)
	for _, option := range options {
		if option.Match(l) {
			matching = append(matching, option.String())
		}
	}
	return
}

func getLine() ([]string, bool) {
	line := os.Getenv(envComplete)
	if line == "" {
		return nil, false
	}
	return strings.Split(line, " "), true
}

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)
	}
}