summaryrefslogtreecommitdiff
path: root/command.go
blob: f3321fb877aa522fef4833a9a60a946f9fc27151 (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
package complete

type Commands map[string]Command

type Flags map[string]FlagOptions

type Command struct {
	Sub   Commands
	Flags Flags
}

// options returns all available complete options for the given command
// args are all except the last command line arguments relevant to the command
func (c *Command) options(args []string) (options []Option, only bool) {

	// remove the first argument, which is the command name
	args = args[1:]

	// if prev has something that needs to follow it,
	// it is the most relevant completion
	if options, ok := c.Flags[last(args)]; ok && options.HasFollow {
		return options.follows(), true
	}

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

	// if no subcommand was entered in any of the args, add the
	// subcommands as complete options.
	if sub == "" {
		options = append(options, c.subCommands()...)
	}

	// add global available complete options
	for flag := range c.Flags {
		options = append(options, Arg(flag))
	}

	return
}

func (c *Command) searchSub(args []string) (sub string, all []Option, only bool) {
	for i, arg := range args {
		if cmd, ok := c.Sub[arg]; ok {
			sub = arg
			all, only = cmd.options(args[i:])
			return
		}
	}
	return "", nil, false
}

func (c *Command) subCommands() []Option {
	subs := make([]Option, 0, len(c.Sub))
	for sub := range c.Sub {
		subs = append(subs, Arg(sub))
	}
	return subs
}