From 6fd41afb940f7af90eaa73fa82a8d2a34b130623 Mon Sep 17 00:00:00 2001 From: Yann Soubeyrand Date: Tue, 14 Jul 2020 19:15:52 +0200 Subject: [PATCH] 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. --- cobra.go | 7 +++++++ command.go | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/cobra.go b/cobra.go index d01becc8..58bbeb45 100644 --- a/cobra.go +++ b/cobra.go @@ -38,6 +38,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. @@ -83,6 +84,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, diff --git a/command.go b/command.go index 5f1caccc..e67fcb25 100644 --- a/command.go +++ b/command.go @@ -807,6 +807,8 @@ func (c *Command) execute(a []string) (err error) { c.preRun() + defer c.postRun() + argWoFlags := c.Flags().Args() if c.DisableFlagParsing { argWoFlags = a @@ -873,6 +875,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 functions. func (c *Command) ExecuteContext(ctx context.Context) error {