google / subcommands

Go subcommand library.
Apache License 2.0
749 stars 48 forks source link

Prevent registering homonymous commands #32

Open gbrlsnchs opened 4 years ago

gbrlsnchs commented 4 years ago

I could find this behavior when using this library in conjunction with go-cmdtest.

Because of how test suites in go-cmdtest work, a subcommand can be tested several times with different flags and arguments. In order for this to happen, for each variation, the program's main function is called, what consists of registering commands, so subcommands.Register is called more than once for the same command in a single go test run.

Because go-cmdtest overrides os.Stdout and os.Stderr before each test, I correctly set them to my type that implements subcommands.Command just before registering it, so it points to the correct output set by go-cmdtest.

However, because I register commands with the same name more than once and they are stored in the same subcommands.Commander (subcommands.DefaultCommander), when executing the subcommand more than once, only the first one registered is picked.

Of course, I already solved my problem by creating a new subcommands.Commander in the main function, but if a subcommands.Commander can only execute the first command registered for a list of homonymous commands, there is no point of letting more than one homonym to be registered.

So, for fixing this, I think there is no point in discarding the newer ones. I guess the best solution would be to override a subcommand when another of same name already exists. This way, no unused homonyms will get appended.