feat: infer version of sub from parents (#1860)#2404
Open
tionichm wants to merge 2 commits into
Open
Conversation
`--version flag does not exist` is only thrown if version cannot be resolved
tionichm
commented
May 17, 2026
Comment on lines
+1234
to
+1252
| // inferVersion attempts to determine the version of an unversioned | ||
| // subcommand by querying the version of the parent. If the parent's | ||
| // version is not set, then the process continues until the root command | ||
| // is reached. If the root command is also unversioned, then the subcommand | ||
| // remains unversioned. | ||
| func (c *Command) inferVersion() string { | ||
| if c.Version != "" { | ||
| return c.Version | ||
| } | ||
| current := c | ||
| for current.HasParent() { | ||
| current = current.Parent() | ||
| if current.Version != "" { | ||
| return current.Version | ||
| } | ||
| } | ||
| return "" | ||
| } | ||
|
|
Author
There was a problem hiding this comment.
This could also alter Command.Version in place. I'll leave it up to the reviewer to decide.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
What
Example 1: Base case, works as expected for the root command
Example 2: Pass sub command after the flag. This is what the unit test does.
Example 3: Pass sub command before the flag. Now you can see it's not really working for sub commands.
Example 4: Pass an argument to the sub command. This shows that cobra must be interpreting "sub" as a flag value because it considers
footo be the sub commandExample 5: To further show that it is skipping over the sub, I can pass sub twice and it then says
--versionis an unknown flag for sub:Why