File tree Expand file tree Collapse file tree 2 files changed +25
-10
lines changed Expand file tree Collapse file tree 2 files changed +25
-10
lines changed Original file line number Diff line number Diff line change @@ -964,10 +964,6 @@ func (c *Command) execute(a []string) (err error) {
964964
965965 argWoFlags := c .Flags ().Args ()
966966
967- if c .Finalize != nil {
968- defer c .Finalize (c , argWoFlags )
969- }
970-
971967 if c .DisableFlagParsing {
972968 argWoFlags = a
973969 }
@@ -988,6 +984,13 @@ func (c *Command) execute(a []string) (err error) {
988984 parents = append (parents , p )
989985 }
990986 }
987+ defer func () {
988+ for _ , p := range parents {
989+ if p .Finalize != nil {
990+ p .Finalize (c , argWoFlags )
991+ }
992+ }
993+ }()
991994 for _ , p := range parents {
992995 if p .PersistentPreRunE != nil {
993996 if err := p .PersistentPreRunE (c , argWoFlags ); err != nil {
Original file line number Diff line number Diff line change @@ -2953,24 +2953,36 @@ func TestHelpFuncExecuted(t *testing.T) {
29532953 checkStringContains (t , output , helpText )
29542954}
29552955
2956- func TestFinalizeCalledOnPanic (t * testing.T ) {
2957- finalizeCalls := 0
2956+ func TestFinalizeOfChildAndParentCalledOnPanic (t * testing.T ) {
2957+ parentFinalizeCalls := 0
2958+ childFinalizeCalls := 0
29582959 defer func () {
29592960 if recover () == nil {
29602961 t .Error ("The code should have panicked due to panicking run" )
29612962 }
2962- if finalizeCalls != 1 {
2963- t .Errorf ("finalize() called %d times, want 1" , finalizeCalls )
2963+ if parentFinalizeCalls != 1 {
2964+ t .Errorf ("finalize() of parent command called %d times, want 1" , parentFinalizeCalls )
2965+ }
2966+ if childFinalizeCalls != 1 {
2967+ t .Errorf ("finalize() of child command called %d times, want 1" , childFinalizeCalls )
29642968 }
29652969 }()
29662970 rootCmd := & Command {
29672971 Use : "root" ,
2972+ Run : emptyRun ,
2973+ Finalize : func (cmd * Command , args []string ) {
2974+ parentFinalizeCalls ++
2975+ },
2976+ }
2977+ subCmd := & Command {
2978+ Use : "sub" ,
29682979 Run : func (cmd * Command , args []string ) {
29692980 panic ("should panic" )
29702981 },
29712982 Finalize : func (cmd * Command , args []string ) {
2972- finalizeCalls ++
2983+ childFinalizeCalls ++
29732984 },
29742985 }
2975- executeCommand (rootCmd )
2986+ rootCmd .AddCommand (subCmd )
2987+ executeCommand (rootCmd , "sub" )
29762988}
You can’t perform that action at this time.
0 commit comments