diff options
| author | Alex Flint <[email protected]> | 2019-05-03 16:08:29 -0700 |
|---|---|---|
| committer | Alex Flint <[email protected]> | 2019-05-03 16:08:29 -0700 |
| commit | bd97edec87a0541321c6e2529150e315ee11cd8b (patch) | |
| tree | 2da1d9c08c5b829d591f915a5113ec03a0ef2f1a /subcommand.go | |
| parent | 3c5e61a2927728226af0abafab402c511c4e27ac (diff) | |
add Parser.Subcommand and Parser.SubcommandNames
Diffstat (limited to 'subcommand.go')
| -rw-r--r-- | subcommand.go | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/subcommand.go b/subcommand.go new file mode 100644 index 0000000..b73e933 --- /dev/null +++ b/subcommand.go @@ -0,0 +1,37 @@ +package arg + +// Subcommand returns the user struct for the subcommand selected by +// the command line arguments most recently processed by the parser. +// The return value is always a pointer to a struct. If no subcommand +// was specified then it returns the top-level arguments struct. If +// no command line arguments have been processed by this parser then it +// returns nil. +func (p *Parser) Subcommand() interface{} { + if p.lastCmd == nil || p.lastCmd.parent == nil { + return nil + } + return p.readable(p.lastCmd.dest).Interface() +} + +// SubcommandNames returns the sequence of subcommands specified by the +// user. If no subcommands were given then it returns an empty slice. +func (p *Parser) SubcommandNames() []string { + if p.lastCmd == nil { + return nil + } + + // make a list of ancestor commands + var ancestors []string + cur := p.lastCmd + for cur.parent != nil { // we want to exclude the root + ancestors = append(ancestors, cur.name) + cur = cur.parent + } + + // reverse the list + out := make([]string, len(ancestors)) + for i := 0; i < len(ancestors); i++ { + out[i] = ancestors[len(ancestors)-i-1] + } + return out +} |
