From 7114df37efaaade6c1745276531f1145c683fe29 Mon Sep 17 00:00:00 2001 From: Stefan VanBuren Date: Thu, 19 Mar 2026 12:11:30 -0400 Subject: [PATCH] Allow ModifyCobra to modify subcommands As written, ModifyCobra will only apply to the root command. This fixes this so that a subcommand with a ModifyCobra field will have it applied. I realize this is a break-glass feature, but currently it's the only way for a command to modify its completions, which I'm looking to modify upstream for things like bufbuild/buf#2044. It also uses the builtin `max` as a cleanup; if we end up landing this, I plan to come back here to upgrade this repository. --- appcmd/appcmd.go | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/appcmd/appcmd.go b/appcmd/appcmd.go index 6b037d4..bb69359 100644 --- a/appcmd/appcmd.go +++ b/appcmd/appcmd.go @@ -68,7 +68,7 @@ type Command struct { // ModifyCobra will modify the underlying [cobra.Command] that is created from this [Command]. // // This should be used sparingly. Almost all operations should be able to be performed - // by the fields of Command. However, ModifyCommand exists as a break-class feature. + // by the fields of Command. However, ModifyCobra exists as a break-glass feature. ModifyCobra func(*cobra.Command) error // Version the version of the command. // @@ -226,13 +226,6 @@ func run( cobraCommand.AddCommand(manpagesCobraCommand) } - // Apply any modifications specified by ModifyCobra - if command.ModifyCobra != nil { - if err := command.ModifyCobra(cobraCommand); err != nil { - return err - } - } - cobraCommand.SetOut(container.Stderr()) args := app.Args(container)[1:] // cobra will implicitly create __complete and __completeNoDesc subcommands @@ -371,6 +364,12 @@ func commandToCobra( } // appcommand prints errors, disable to prevent duplicates. cobraCommand.SilenceErrors = true + // ModifyCobra is applied last so it can override anything set above. + if command.ModifyCobra != nil { + if err := command.ModifyCobra(cobraCommand); err != nil { + return nil, err + } + } return cobraCommand, nil } @@ -450,15 +449,8 @@ func maxPaddingRec(cmd *cobra.Command, curIndentCount int) int { maxPadding := (curIndentCount * 2) + len(cmd.Name()) for _, child := range cmd.Commands() { if !child.Hidden { - maxPadding = maxInt(maxPadding, maxPaddingRec(child, curIndentCount+1)) + maxPadding = max(maxPadding, maxPaddingRec(child, curIndentCount+1)) } } return maxPadding } - -func maxInt(i int, j int) int { - if i > j { - return i - } - return j -}