Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OnFinalize method #1788

Merged
merged 1 commit into from Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions cobra.go
Expand Up @@ -39,6 +39,7 @@ var templateFuncs = template.FuncMap{
}

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

// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
// to automatically enable in CLI tools.
Expand Down Expand Up @@ -84,6 +85,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
Expand Up @@ -833,6 +833,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 @@ -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.
// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
// functions.
Expand Down