Add OnFinalize method

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.
This commit is contained in:
Yann Soubeyrand 2020-07-14 19:15:52 +02:00
parent dbf85f6104
commit 220e00224c
2 changed files with 15 additions and 0 deletions

View file

@ -39,6 +39,7 @@ var templateFuncs = template.FuncMap{
} }
var initializers []func() var initializers []func()
var finalizers []func()
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing // EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
// to automatically enable in CLI tools. // to automatically enable in CLI tools.
@ -84,6 +85,12 @@ func OnInitialize(y ...func()) {
initializers = append(initializers, y...) initializers = append(initializers, y...)
} }
// OnFinalize sets the passed functions to be run when each command's
// Execute method is terminated.
func OnFinalize(y ...func()) {
finalizers = append(finalizers, y...)
}
// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. // FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, // Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,

View file

@ -833,6 +833,8 @@ func (c *Command) execute(a []string) (err error) {
c.preRun() c.preRun()
defer c.postRun()
argWoFlags := c.Flags().Args() argWoFlags := c.Flags().Args()
if c.DisableFlagParsing { if c.DisableFlagParsing {
argWoFlags = a argWoFlags = a
@ -903,6 +905,12 @@ func (c *Command) preRun() {
} }
} }
func (c *Command) postRun() {
for _, x := range finalizers {
x()
}
}
// ExecuteContext is the same as Execute(), but sets the ctx on the command. // ExecuteContext is the same as Execute(), but sets the ctx on the command.
// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs // Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
// functions. // functions.