Skip to content

Commit 93d1913

Browse files
Add OnFinalize method (#1788)
This method is the OnInitialize counterpart. Like OnInitialize which allows loading the configuration before each command is executed, OnFinalize allows saving the configuration after each command has been executed.
1 parent 07034fe commit 93d1913

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

cobra.go

+7
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ var templateFuncs = template.FuncMap{
4040
}
4141

4242
var initializers []func()
43+
var finalizers []func()
4344

4445
const (
4546
defaultPrefixMatching = false
@@ -94,6 +95,12 @@ func OnInitialize(y ...func()) {
9495
initializers = append(initializers, y...)
9596
}
9697

98+
// OnFinalize sets the passed functions to be run when each command's
99+
// Execute method is terminated.
100+
func OnFinalize(y ...func()) {
101+
finalizers = append(finalizers, y...)
102+
}
103+
97104
// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
98105

99106
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,

command.go

+8
Original file line numberDiff line numberDiff line change
@@ -834,6 +834,8 @@ func (c *Command) execute(a []string) (err error) {
834834

835835
c.preRun()
836836

837+
defer c.postRun()
838+
837839
argWoFlags := c.Flags().Args()
838840
if c.DisableFlagParsing {
839841
argWoFlags = a
@@ -904,6 +906,12 @@ func (c *Command) preRun() {
904906
}
905907
}
906908

909+
func (c *Command) postRun() {
910+
for _, x := range finalizers {
911+
x()
912+
}
913+
}
914+
907915
// ExecuteContext is the same as Execute(), but sets the ctx on the command.
908916
// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
909917
// functions.

0 commit comments

Comments
 (0)