1package arg
 2
 3// Subcommand returns the user struct for the subcommand selected by
 4// the command line arguments most recently processed by the parser.
 5// The return value is always a pointer to a struct. If no subcommand
 6// was specified then it returns the top-level arguments struct. If
 7// no command line arguments have been processed by this parser then it
 8// returns nil.
 9func (p *Parser) Subcommand() interface{} {
10	if p.lastCmd == nil || p.lastCmd.parent == nil {
11		return nil
12	}
13	return p.val(p.lastCmd.dest).Interface()
14}
15
16// SubcommandNames returns the sequence of subcommands specified by the
17// user. If no subcommands were given then it returns an empty slice.
18func (p *Parser) SubcommandNames() []string {
19	if p.lastCmd == nil {
20		return nil
21	}
22
23	// make a list of ancestor commands
24	var ancestors []string
25	cur := p.lastCmd
26	for cur.parent != nil { // we want to exclude the root
27		ancestors = append(ancestors, cur.name)
28		cur = cur.parent
29	}
30
31	// reverse the list
32	out := make([]string, len(ancestors))
33	for i := 0; i < len(ancestors); i++ {
34		out[i] = ancestors[len(ancestors)-i-1]
35	}
36	return out
37}