3

I use the following code which need to pass value from functions root, value

var cfBuild = &cobra.Command{
    Use:   "build",
    Short: "Build",
    Run: func(cmd *cobra.Command, args []string) {


        root, value := Build(target)
    },
    PersistentPostRun: func(cmd *cobra.Command, args []string) {
   //Here I need to use root, value
   } 
}

I can do it by using global variable but is there a nice way to avoid global in this case ?

This is the repo, I didnt find any nice way to do it ... https://github.com/spf13/cobra

Btw there is option to use viper

like ...

Run: func(cmd *cobra.Command, args []string) {
    root, value := Build(target)
    viper.Set("root", root)
    viper.Set("value", value)

and then get it in the other method... Is it good direction?

  • A relevant issue: [How can I pass context.Context between pre/post-run hooks?](https://github.com/spf13/cobra/issues/563). – skovorodkin Apr 23 '18 at 12:48
  • 1
    If i understand correctly then this answer is the exact same problem; https://stackoverflow.com/a/49981932/6376471 – Zak Apr 23 '18 at 13:12
  • @Zak , well you answer as my question :) using env( with different approach, here is viper in you answer is terraform.io/docs/state , isnt it similar approach ?if not why? –  Apr 23 '18 at 19:38
  • `viper.Set(...)` will not persist between executions of the same program. The docs (https://godoc.org/github.com/spf13/viper#Set) talk say that viper will store the value set in its internal register which means that it will be lost after the program ends. Assuming in your case the program does not exit between `Run` and `PersistentPostRun` then you will be fine using viper. If `PersistentPostRun` is executed as another CLI tool execution then the values in `viper.Set(...)` will be lost. – Zak Apr 24 '18 at 07:20
  • @Zak - there is some example code for your solution proposal , some oss example for my context ? if yes please provide it as answer, the link to the second question doesnt help much for my case.... –  Apr 24 '18 at 14:41

1 Answers1

0

you don't need Viper for that. Just create 2 singletons (variables with global scope in the command file) and you can assign them to your Build function returns.

Example

package cmd

var (
    root,
    value string
)

var cfBuild = &cobra.Command{
    Use:   "build",
    Short: "Build",
    Run: func(cmd *cobra.Command, args []string) {
        root, value = Build(target)
    },
    PersistentPostRun: func(cmd *cobra.Command, args []string) {
        fmt.Printf("%s, %s", root, value)
   } 
}
Francesco Gualazzi
  • 919
  • 1
  • 10
  • 23