Skip to content

Commit

Permalink
Add OnFinalize method (#1788)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
yann-soubeyrand authored Oct 3, 2022
1 parent 07034fe commit 93d1913
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
7 changes: 7 additions & 0 deletions cobra.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ var templateFuncs = template.FuncMap{
}

var initializers []func()
var finalizers []func()

const (
defaultPrefixMatching = false
Expand Down Expand Up @@ -94,6 +95,12 @@ func OnInitialize(y ...func()) {
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.

// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
Expand Down
8 changes: 8 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -834,6 +834,8 @@ func (c *Command) execute(a []string) (err error) {

c.preRun()

defer c.postRun()

argWoFlags := c.Flags().Args()
if c.DisableFlagParsing {
argWoFlags = a
Expand Down Expand Up @@ -904,6 +906,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.
// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
// functions.
Expand Down

0 comments on commit 93d1913

Please sign in to comment.