|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "sort" |
| 6 | + |
| 7 | + "github.com/elasticpath/epcc-cli/external/variables" |
| 8 | + log "github.com/sirupsen/logrus" |
| 9 | + "github.com/spf13/cobra" |
| 10 | +) |
| 11 | + |
| 12 | +var variablesCmd = &cobra.Command{ |
| 13 | + Use: "variables", |
| 14 | + Short: "Manage variables extracted from API responses", |
| 15 | + SilenceUsage: false, |
| 16 | +} |
| 17 | + |
| 18 | +var variableListCmd = &cobra.Command{ |
| 19 | + Use: "list", |
| 20 | + Short: "Lists all stored variables", |
| 21 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 22 | + allVars := variables.GetAllVariables() |
| 23 | + |
| 24 | + if len(allVars) == 0 { |
| 25 | + fmt.Println("No variables set.") |
| 26 | + return nil |
| 27 | + } |
| 28 | + |
| 29 | + names := make([]string, 0, len(allVars)) |
| 30 | + for name := range allVars { |
| 31 | + names = append(names, name) |
| 32 | + } |
| 33 | + sort.Strings(names) |
| 34 | + |
| 35 | + for _, name := range names { |
| 36 | + fmt.Printf("%s = %s\n", name, allVars[name]) |
| 37 | + } |
| 38 | + |
| 39 | + return nil |
| 40 | + }, |
| 41 | +} |
| 42 | + |
| 43 | +var variableClearCmd = &cobra.Command{ |
| 44 | + Use: "clear", |
| 45 | + Short: "Clear all stored variables", |
| 46 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 47 | + variables.ClearAllVariables() |
| 48 | + variables.FlushVariables() |
| 49 | + log.Info("Successfully cleared all variables") |
| 50 | + return nil |
| 51 | + }, |
| 52 | +} |
| 53 | + |
| 54 | +var variableSetCmd = &cobra.Command{ |
| 55 | + Use: "set <name> <value>", |
| 56 | + Short: "Set a variable to a value", |
| 57 | + Args: cobra.ExactArgs(2), |
| 58 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 59 | + variables.SetVariable(args[0], args[1]) |
| 60 | + log.Infof("Set variable %q = %q", args[0], args[1]) |
| 61 | + return nil |
| 62 | + }, |
| 63 | +} |
| 64 | + |
| 65 | +// NewVariablesCommand adds the variables command tree to a parent command. |
| 66 | +// Used by runbook command pool to enable `epcc variables set` in scripts. |
| 67 | +func NewVariablesCommand(parent *cobra.Command) { |
| 68 | + vCmd := &cobra.Command{ |
| 69 | + Use: "variables", |
| 70 | + Short: "Manage variables extracted from API responses", |
| 71 | + SilenceUsage: false, |
| 72 | + } |
| 73 | + vCmd.AddCommand( |
| 74 | + &cobra.Command{ |
| 75 | + Use: "list", |
| 76 | + Short: "Lists all stored variables", |
| 77 | + RunE: variableListCmd.RunE, |
| 78 | + }, |
| 79 | + &cobra.Command{ |
| 80 | + Use: "clear", |
| 81 | + Short: "Clear all stored variables", |
| 82 | + RunE: variableClearCmd.RunE, |
| 83 | + }, |
| 84 | + &cobra.Command{ |
| 85 | + Use: "set <name> <value>", |
| 86 | + Short: "Set a variable to a value", |
| 87 | + Args: cobra.ExactArgs(2), |
| 88 | + RunE: variableSetCmd.RunE, |
| 89 | + }, |
| 90 | + ) |
| 91 | + parent.AddCommand(vCmd) |
| 92 | +} |
0 commit comments