Skip to content

Commit e7e8bb0

Browse files
committed
feat: Add Finalize function to commands
This adds a "Finalize" function to the command, which is executed at the end of every run, even if the run panics
1 parent db3ddb5 commit e7e8bb0

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

command.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,8 @@ type Command struct {
138138
RunE func(cmd *Command, args []string) error
139139
// PostRun: run after the Run command.
140140
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)
141143
// PostRunE: PostRun but returns an error.
142144
PostRunE func(cmd *Command, args []string) error
143145
// PersistentPostRun: children of this command will inherit and execute after PostRun.
@@ -961,6 +963,11 @@ func (c *Command) execute(a []string) (err error) {
961963
defer c.postRun()
962964

963965
argWoFlags := c.Flags().Args()
966+
967+
if c.Finalize != nil {
968+
defer c.Finalize(c, argWoFlags)
969+
}
970+
964971
if c.DisableFlagParsing {
965972
argWoFlags = a
966973
}

command_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2952,3 +2952,25 @@ func TestHelpFuncExecuted(t *testing.T) {
29522952

29532953
checkStringContains(t, output, helpText)
29542954
}
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+
}

0 commit comments

Comments
 (0)