Fix #1105: Execute commands with zero arguments correctly #1117
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
#1105 introduced a bug spotted in https://sourcegraph.slack.com/archives/C05MW2TMYAV/p1728932051783959 where commands that can take no arguments wouldn't run:
This was caused by
if len(args) == 0
which captured commands that didn't take arguments likelogin
.Reading through the original PR and discussion, I agree with this logic for choosing when to output to stdout/err.
There was another minor bug in the old code that I've fixed -
cmd.flagSet.Parse()
will print help to stderr and exit if passed a command that doesn't take subcommands and the--help
flag, such assrc version --help
. This previously ran before the--help
detection, so depending on the command some help output would still be written to stderr.Quick test cases
These make sense to me, following the logic suggested above - use
stdout
if help was requested, usestderr
if help was triggered due to an invalid set of arguments.src
goes to stdoutsrc help
goes to stdout (requesting help)src --help
goes to stderr (it's not a supported flag)src version
goes to stdout (correct usage of a zero-arg command)src version --help
goes to stdout (requesting help)src sbom
goes to stderr (missing args)src sbom --help
should go to stdout (requesting help)src sbom foobar
goes to stderr (invalid subcommand)src sbom fetch
goes to stderr (missing args)src sbom fetch --help
goes to stdout (requesting help)This is a helpful little wrapper that will print stdout/stderr in front of each line:
(go run ./cmd/src version --help 2>&1 1>&3 | sed 's/^/stderr: /' >&2) 3>&1 | sed 's/^/stdout: /
Test plan