cobra
cobra copied to clipboard
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 seems reasonable.
However, I never really understood the use case for initializers.
What is the difference between using an initializer
/finalizer
compared to a PersistentPreRun
/PersistentPostRun
?
This seems reasonable. However, I never really understood the use case for initializers. What is the difference between using an
initializer
/finalizer
compared to aPersistentPreRun
/PersistentPostRun
?
PersistentPreRun
and PersistentPostRun
of the root command aren’t run if there are PersistentPreRun
and PersistentPostRun
in “intermediary commands”. For example, the program here https://github.com/yann-soubeyrand/cobra-test gives the following result:
❯ ./cobra-test parent child
initialize
parent persistent pre run
child called
parent persistent post run
finalize
Also, if using RunE
, a PostRun
may not be run in case of error:
https://github.com/spf13/cobra/blob/7039e1fa214cfc1de404ed6540158c8fda64a758/command.go#L872-L875
It may be interresting in some cases to be able to do some clean-up using a finalizer function.
I agree - this seems reasonable, but I think we're looking for a valid use case on this to keep the Cobra API thin: @yann-soubeyrand can you provide a small Cobra CLI program that would require this use case? Thanks much!
The program here https://github.com/yann-soubeyrand/cobra-test-2 has been initialized using cobra-cli init --viper
which creates the initConfig
function to load the configuration using viper. I’d like to have the ability to save the configuration at the end of the execution, hence my saveConfig
function. It can be tested like this:
❯ touch ~/.cobra-test-2
❯ ./cobra-test-2 config get
Using config file: /home/yann/.cobra-test-2
<nil>
❯ ./cobra-test-2 config set
Using config file: /home/yann/.cobra-test-2
❯ ./cobra-test-2 config get
Using config file: /home/yann/.cobra-test-2
value
In this simple case, I arguably could have done the write of the config at the end or in the PostRun
of my set command. However, in more complex programs where the configuration can be modified in several places, it’s useful to have a function which will be executed for sure at the end (unless there’s a panic or an explicit exit of course) which can be used to save the config.