File tree Expand file tree Collapse file tree 2 files changed +29
-0
lines changed Expand file tree Collapse file tree 2 files changed +29
-0
lines changed Original file line number Diff line number Diff line change @@ -138,6 +138,8 @@ type Command struct {
138
138
RunE func (cmd * Command , args []string ) error
139
139
// PostRun: run after the Run command.
140
140
PostRun func (cmd * Command , args []string )
141
+ // Finalize: run at the end of the Run command, even if it panics.
142
+ Finalize func (cmd * Command , args []string )
141
143
// PostRunE: PostRun but returns an error.
142
144
PostRunE func (cmd * Command , args []string ) error
143
145
// PersistentPostRun: children of this command will inherit and execute after PostRun.
@@ -961,6 +963,11 @@ func (c *Command) execute(a []string) (err error) {
961
963
defer c .postRun ()
962
964
963
965
argWoFlags := c .Flags ().Args ()
966
+
967
+ if c .Finalize != nil {
968
+ defer c .Finalize (c , argWoFlags )
969
+ }
970
+
964
971
if c .DisableFlagParsing {
965
972
argWoFlags = a
966
973
}
Original file line number Diff line number Diff line change @@ -2952,3 +2952,25 @@ func TestHelpFuncExecuted(t *testing.T) {
2952
2952
2953
2953
checkStringContains (t , output , helpText )
2954
2954
}
2955
+
2956
+ func TestFinalizeCalledOnPanic (t * testing.T ) {
2957
+ finalizeCalls := 0
2958
+ defer func () {
2959
+ if recover () == nil {
2960
+ t .Error ("The code should have panicked due to panicking run" )
2961
+ }
2962
+ if finalizeCalls != 1 {
2963
+ t .Errorf ("finalize() called %d times, want 1" , finalizeCalls )
2964
+ }
2965
+ }()
2966
+ rootCmd := & Command {
2967
+ Use : "root" ,
2968
+ Run : func (cmd * Command , args []string ) {
2969
+ panic ("should panic" )
2970
+ },
2971
+ Finalize : func (cmd * Command , args []string ) {
2972
+ finalizeCalls ++
2973
+ },
2974
+ }
2975
+ executeCommand (rootCmd )
2976
+ }
You can’t perform that action at this time.
0 commit comments