summaryrefslogtreecommitdiff
path: root/command.go
blob: 80b2f994c4de154dcf6ceeb5a62793adfa5c016b (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package complete

import "github.com/posener/complete/match"

// Command represents a command line
// It holds the data that enables auto completion of command line
// Command can also be a sub command.
type Command struct {
	// Sub is map of sub commands of the current command
	// The key refer to the sub command name, and the value is it's
	// Command descriptive struct.
	Sub Commands

	// Flags is a map of flags that the command accepts.
	// The key is the flag name, and the value is it's predictions.
	Flags Flags

	// Args are extra arguments that the command accepts, those who are
	// given without any flag before.
	Args Predictor
}

// Commands is the type of Sub member, it maps a command name to a command struct
type Commands map[string]Command

// Flags is the type Flags of the Flags member, it maps a flag name to the flag predictions.
type Flags map[string]Predictor

// Predict returns all possible predictions for args according to the command struct
func (c *Command) Predict(a Args) (predictions []string) {
	predictions, _ = c.predict(a)
	return
}

func (c *Command) predict(a Args) (options []string, only bool) {

	// if wordCompleted has something that needs to follow it,
	// it is the most relevant completion
	if predictor, ok := c.Flags[a.LastCompleted]; ok && predictor != nil {
		Log("Predicting according to flag %s", a.Last)
		return predictor.Predict(a), true
	}

	sub, options, only := c.searchSub(a)
	if only {
		return
	}

	// if no sub command was found, return a list of the sub commands
	if sub == "" {
		options = append(options, c.subCommands(a.Last)...)
	}

	// add global available complete options
	for flag := range c.Flags {
		if match.Prefix(flag, a.Last) {
			options = append(options, flag)
		}
	}

	// add additional expected argument of the command
	if c.Args != nil {
		options = append(options, c.Args.Predict(a)...)
	}

	return
}

// searchSub searches recursively within sub commands if the sub command appear
// in the on of the arguments.
func (c *Command) searchSub(a Args) (sub string, all []string, only bool) {
	for i, arg := range a.Completed {
		if cmd, ok := c.Sub[arg]; ok {
			sub = arg
			all, only = cmd.predict(a.from(i))
			return
		}
	}
	return
}

// subCommands returns a list of matching sub commands
func (c *Command) subCommands(last string) (prediction []string) {
	for sub := range c.Sub {
		if match.Prefix(sub, last) {
			prediction = append(prediction, sub)
		}
	}
	return
}