Skip to content

refactor: simplify parent command unknown-subcommand handling #688

Closed

Description

@lizhengfeng101

Background

PR #660 fixed parent commands silently exiting 0 on unknown subcommands by adding RunE with a manual len(args) > 0 check. The fix works correctly, but can be cleaned up.

Suggested improvements

1. Use cobra.NoArgs instead of manual args check

The current RunE reimplements what cobra.NoArgs already provides (same error format). Each parent command can be simplified to:

Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
    return cmd.Help()
},

Cobra validates Args before calling RunE, so the manual check is unnecessary.

2. Improve test isolation in cloneRootCmd

cloneRootCmd calls AddCommand on global command variables, which reassigns their .parent pointer to the clone without removing them from rootCmd.commands. This works today but is fragile. Options:

  • Use rootCmd directly (it already has SilenceUsage/SilenceErrors)
  • Add a t.Cleanup that re-parents commands back to rootCmd

References

Activity

  1. added
    enhancement
    good first issue
    on Aug 3, 2026
  2. amh1k commented on Aug 3, 2026

    @amh1k
    Contributor

    Would like to take this up

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementgood first issue

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions