Support default commands.

Fixes #41.
This commit is contained in:
Alec Thomas
2020-01-23 20:56:25 +11:00
parent 5db71ed657
commit b66dcf3279
3 changed files with 67 additions and 1 deletions
+29 -1
View File
@@ -397,6 +397,24 @@ func (c *Context) trace(node *Node) (err error) { // nolint: gocyclo
return fmt.Errorf("unexpected token %s", token)
}
}
// End of the line, check for a default command.
var defaultNode *Path
for _, child := range node.Children {
if child.Type == CommandNode && child.Tag.Default != "" {
if defaultNode != nil {
return fmt.Errorf("can't have more than one default command under %s", node.Summary())
}
defaultNode = &Path{
Parent: child,
Command: child,
Flags: child.Flags,
}
}
}
if defaultNode != nil {
c.Path = append(c.Path, defaultNode)
}
return nil
}
@@ -617,6 +635,7 @@ func checkMissingChildren(node *Node) error {
missing = append(missing, strconv.Quote(strings.Join(missingArgs, " ")))
}
haveDefault := 0
for _, child := range node.Children {
if child.Hidden {
continue
@@ -627,10 +646,19 @@ func checkMissingChildren(node *Node) error {
}
missing = append(missing, strconv.Quote(child.Summary()))
} else {
if child.Tag.Default != "" {
if len(child.Children) > 0 {
return fmt.Errorf("default command %s must not have subcommands or arguments", child.Summary())
}
haveDefault++
}
missing = append(missing, strconv.Quote(child.Name))
}
}
if len(missing) == 0 {
if haveDefault > 1 {
return fmt.Errorf("more than one default command found under %s", node.Summary())
}
if len(missing) == 0 || haveDefault > 0 {
return nil
}