Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

How to allow default command to accept arguments like --flag arg? #24

Closed
hartzell opened this issue Oct 18, 2015 · 1 comment
Closed

Comments

@hartzell
Copy link

I'm writing a tool that needs to accept these:

mytool
mytool -boolean_flag
mytool -string_flag arg

I'm using mitchellh/cli to implement a variety of subcommands and have a default command that handles the the first two cases above but in the third case it complains about "Invalid flags before the subcommand. ...".

I was hopeful that @yegle's changes in #20 would help, but it seems like it will have the same problem.

This change to cli.go gives me the behavior that I'm looking for. I'm unsure of any potential downsides.

diff --git a/cli.go b/cli.go
index bb676e3..dd039c2 100644
--- a/cli.go
+++ b/cli.go
@@ -174,9 +174,17 @@ func (c *CLI) processArgs() {

        // If we never found a subcommand and support a default command, then
        // switch to using that.
-       if c.subcommand == "" {
+       // If we found a subcommand that doesn't exist and there's a default
+       // command, perhaps what we though was a subcommand is really an
+       // argument to the default command.  Give the default command a shot
+       // at it.
+       if c.Commands[c.subcommand] == nil || c.subcommand == "" {
                if _, ok := c.Commands[""]; ok {
                        args := c.topFlags
+                       if c.Commands[c.subcommand] == nil {
+                               args = append(args, c.subcommand)
+                               c.subcommand = ""
+                       }
                        args = append(args, c.subcommandArgs...)
                        c.topFlags = nil
                        c.subcommandArgs = args

I realize that I've mixed metaphors a bit, but I'm unsure when/why indexing into a map and checking for a zero value is better than using the two value assignment. Stylistic feedback welcome!

hartzell pushed a commit to hartzell/roster that referenced this issue Oct 28, 2015
Special case `roster --list` and `roster --host hostname`.  I tried
doing this by making inventory the default command, but the way that cli
implemented you can't do '--host hostname', it tries to make 'hostname'
a subcommand and fails. See: mitchellh/cli#24
@hartzell
Copy link
Author

I ended up just handling the default case explicitly before diving into the cli bit.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant