From 94d2512c76accdd3fac7eb530573cf4f7ae8490e Mon Sep 17 00:00:00 2001 From: Naveen Gogineni Date: Tue, 24 Mar 2026 20:14:44 -0400 Subject: [PATCH] Fix:(issue_2275) Make flag action execution consistent --- command.go | 21 ++++++++------------- command_test.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 13 deletions(-) diff --git a/command.go b/command.go index cfdc5601dd..2a46b2eab1 100644 --- a/command.go +++ b/command.go @@ -582,19 +582,14 @@ func (cmd *Command) NArg() int { func (cmd *Command) runFlagActions(ctx context.Context) error { tracef("runFlagActions") - for fl := range cmd.setFlags { - /*tracef("checking %v:%v", fl.Names(), fl.IsSet()) - if !fl.IsSet() { - continue - }*/ - - //if pf, ok := fl.(LocalFlag); ok && !pf.IsLocal() { - // continue - //} - - if af, ok := fl.(ActionableFlag); ok { - if err := af.RunAction(ctx, cmd); err != nil { - return err + // run the flag actions in the same order that they are defined + // to maintain consistency. + for _, fl := range cmd.appliedFlags { + if _, inSet := cmd.setFlags[fl]; inSet { + if af, ok := fl.(ActionableFlag); ok { + if err := af.RunAction(ctx, cmd); err != nil { + return err + } } } } diff --git a/command_test.go b/command_test.go index 47528ac7e7..059061e92c 100644 --- a/command_test.go +++ b/command_test.go @@ -2185,6 +2185,54 @@ func TestCommand_OrderOfOperations(t *testing.T) { }) } +func TestFlagActionOrder(t *testing.T) { + tests := []struct { + Name string + Args []string + }{ + { + Name: "abc", + Args: []string{"", "--a", "--b", "--c"}, + }, + { + Name: "bca", + Args: []string{"", "--b", "--c", "--a"}, + }, + { + Name: "cba", + Args: []string{"", "--c", "--b", "--a"}, + }, + } + for _, tt := range tests { + t.Run(tt.Name, func(t *testing.T) { + str := "" + action := func(name string) func(context.Context, *Command, bool) error { + return func(_ context.Context, _ *Command, _ bool) error { + str += name + return nil + } + } + cmd := &Command{ + Flags: []Flag{ + &BoolFlag{Name: "a", Action: action("a")}, + &BoolFlag{Name: "b", Action: action("b")}, + &BoolFlag{Name: "c", Action: action("c")}, + }, + Action: func(_ context.Context, cmd *Command) error { + return nil + }, + } + + err := cmd.Run(buildTestContext(t), tt.Args) + require.NoError(t, err) + + if str != "abc" { + t.Errorf("expected 'abc' got '%s'", str) + } + }) + } +} + func TestCommand_Run_CommandWithSubcommandHasHelpTopic(t *testing.T) { subcommandHelpTopics := [][]string{ {"foo", "--help"},