Skip to content

Commit 4a483d1

Browse files
committed
feat: add support for vars
1 parent 68ad347 commit 4a483d1

16 files changed

Lines changed: 618 additions & 3 deletions

File tree

cmd/create.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ func NewCreateCommand(parentCmd *cobra.Command) func() {
7272
ifAliasDoesNotExist = ""
7373
overrides.OverrideUrlPath = ""
7474
overrides.QueryParameters = nil
75+
overrides.SetVar = nil
7576
skipAliases = false
7677
compactOutput = false
7778
repeat = 1
@@ -289,6 +290,7 @@ func NewCreateCommand(parentCmd *cobra.Command) func() {
289290
createCmd.PersistentFlags().StringVarP(&logOnSuccess, "log-on-success", "", "", "Output the following message as an info if the result is successful")
290291
createCmd.PersistentFlags().StringVarP(&logOnFailure, "log-on-failure", "", "", "Output the following message as an error if the result fails")
291292
createCmd.PersistentFlags().StringVarP(&data, "data", "d", "", "Raw JSON data to use as the request body. If provided, positional arguments will be ignored.")
293+
createCmd.PersistentFlags().StringArrayVarP(&overrides.SetVar, "set-var", "", nil, "Extract a value from the response using a jq expression and store it as a variable (e.g., --set-var myid=.data.id)")
292294

293295
createCmd.MarkFlagsMutuallyExclusive("output-key-val", "output-jq", "silent", "compact")
294296
_ = createCmd.RegisterFlagCompletionFunc("output-jq", jqCompletionFunc)

cmd/delete.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ func NewDeleteCommand(parentCmd *cobra.Command) func() {
5757
resetFunc := func() {
5858
overrides.QueryParameters = nil
5959
overrides.OverrideUrlPath = ""
60+
overrides.SetVar = nil
6061
allow404 = false
6162
ifAliasExists = ""
6263
ifAliasDoesNotExist = ""
@@ -235,6 +236,7 @@ func NewDeleteCommand(parentCmd *cobra.Command) func() {
235236
deleteCmd.PersistentFlags().BoolVarP(&ignoreErrors, "ignore-errors", "", false, "Don't return non-zero on an error")
236237
deleteCmd.PersistentFlags().StringVarP(&logOnSuccess, "log-on-success", "", "", "Output the following message as an info if the result is successful")
237238
deleteCmd.PersistentFlags().StringVarP(&logOnFailure, "log-on-failure", "", "", "Output the following message as an error if the result fails")
239+
deleteCmd.PersistentFlags().StringArrayVarP(&overrides.SetVar, "set-var", "", nil, "Extract a value from the response using a jq expression and store it as a variable (e.g., --set-var myid=.data.id)")
238240
parentCmd.AddCommand(deleteCmd)
239241

240242
deleteCmd.MarkFlagsMutuallyExclusive("output-key-val", "silent")

cmd/get.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ func NewGetCommand(parentCmd *cobra.Command) func() {
4646
resetFunc := func() {
4747
overrides.QueryParameters = nil
4848
overrides.OverrideUrlPath = ""
49+
overrides.SetVar = nil
4950
outputJq = ""
5051
autoFillOnGet = false
5152
compactOutput = false
@@ -340,6 +341,7 @@ func NewGetCommand(parentCmd *cobra.Command) func() {
340341
getCmd.PersistentFlags().Uint32VarP(&repeatDelay, "repeat-delay", "", 100, "Delay (in ms) between repeats")
341342
getCmd.PersistentFlags().StringVarP(&logOnSuccess, "log-on-success", "", "", "Output the following message as an info if the result is successful")
342343
getCmd.PersistentFlags().StringVarP(&logOnFailure, "log-on-failure", "", "", "Output the following message as an error if the result fails")
344+
getCmd.PersistentFlags().StringArrayVarP(&overrides.SetVar, "set-var", "", nil, "Extract a value from the response using a jq expression and store it as a variable (e.g., --set-var myid=.data.id)")
343345

344346
getCmd.MarkFlagsMutuallyExclusive("output-key-val", "output-jq", "silent", "compact")
345347
_ = getCmd.RegisterFlagCompletionFunc("output-jq", jqCompletionFunc)

cmd/root.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"github.com/elasticpath/epcc-cli/external/profiles"
2121
"github.com/elasticpath/epcc-cli/external/resources"
2222
"github.com/elasticpath/epcc-cli/external/shutdown"
23+
"github.com/elasticpath/epcc-cli/external/variables"
2324
"github.com/elasticpath/epcc-cli/external/version"
2425
log "github.com/sirupsen/logrus"
2526
"github.com/thediveo/enumflag"
@@ -110,6 +111,7 @@ func InitializeCmd() {
110111
Logs,
111112
resourceListCommand,
112113
aliasesCmd,
114+
variablesCmd,
113115
configure,
114116
LoginCmd,
115117
logoutCmd,
@@ -166,6 +168,7 @@ func InitializeCmd() {
166168
ResetStore.PersistentFlags().BoolVarP(&DeleteApplicationKeys, "delete-application-keys", "", false, "if set, we delete application keys as well")
167169

168170
aliasesCmd.AddCommand(aliasListCmd, aliasClearCmd)
171+
variablesCmd.AddCommand(variableListCmd, variableClearCmd, variableSetCmd)
169172

170173
LoginCmd.AddCommand(loginClientCredentials)
171174
LoginCmd.AddCommand(loginImplicit)
@@ -318,6 +321,7 @@ func Execute() {
318321
httpclient.LogStats()
319322
aliases.FlushAliases()
320323
headergroups.FlushHeaderGroups()
324+
variables.FlushVariables()
321325

322326
if exit {
323327
os.Exit(3)

cmd/runbooks.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,7 @@ func generateRunbookCmd() *CommandAndReset {
573573
resetDeleteCmd := NewDeleteCommand(root)
574574
resetGetCmd := NewGetCommand(root)
575575
resetDeleteAllCmd := NewDeleteAllCommand(root)
576+
NewVariablesCommand(root)
576577
getDevCommands(root)
577578

578579
return &CommandAndReset{

cmd/update.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ func NewUpdateCommand(parentCmd *cobra.Command) func() {
5454
resetFunc := func() {
5555
overrides.QueryParameters = nil
5656
overrides.OverrideUrlPath = ""
57+
overrides.SetVar = nil
5758
outputJq = ""
5859
compactOutput = false
5960
noBodyPrint = false
@@ -310,6 +311,7 @@ func NewUpdateCommand(parentCmd *cobra.Command) func() {
310311
updateCmd.PersistentFlags().StringVarP(&logOnSuccess, "log-on-success", "", "", "Output the following message as an info if the result is successful")
311312
updateCmd.PersistentFlags().StringVarP(&logOnFailure, "log-on-failure", "", "", "Output the following message as an error if the result fails")
312313
updateCmd.PersistentFlags().StringVarP(&data, "data", "d", "", "Raw JSON data to use as the request body. If provided, positional arguments will be ignored.")
314+
updateCmd.PersistentFlags().StringArrayVarP(&overrides.SetVar, "set-var", "", nil, "Extract a value from the response using a jq expression and store it as a variable (e.g., --set-var myid=.data.id)")
313315

314316
updateCmd.MarkFlagsMutuallyExclusive("output-key-val", "output-jq", "silent", "compact")
315317
parentCmd.AddCommand(updateCmd)

cmd/variables.go

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
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+
}

external/httpclient/http_overrides.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ package httpclient
33
type HttpParameterOverrides struct {
44
QueryParameters []string
55
OverrideUrlPath string
6+
SetVar []string
67
}

external/json/to_json.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"github.com/elasticpath/epcc-cli/external/aliases"
1111
"github.com/elasticpath/epcc-cli/external/resources"
1212
"github.com/elasticpath/epcc-cli/external/templates"
13+
"github.com/elasticpath/epcc-cli/external/variables"
1314
"github.com/itchyny/gojq"
1415
"github.com/mitchellh/mapstructure"
1516
log "github.com/sirupsen/logrus"
@@ -173,6 +174,7 @@ func toJsonObject(args []string, noWrapping bool, compliant bool, attributes map
173174
}
174175
}
175176

177+
val = variables.ResolveVariableOrReturnIdentity(val)
176178
val = formatValue(val)
177179
processedArgs = append(processedArgs, jsonKey, val)
178180
}

external/resources/uritemplates.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77

88
"github.com/elasticpath/epcc-cli/external/aliases"
99
"github.com/elasticpath/epcc-cli/external/id"
10+
"github.com/elasticpath/epcc-cli/external/variables"
1011
log "github.com/sirupsen/logrus"
1112
"github.com/yosida95/uritemplate/v3"
1213
)
@@ -92,6 +93,7 @@ func GenerateUrl(urlInfo *CrudEntityInfo, args []string, useAliases bool) (strin
9293
values := uritemplate.Values{}
9394

9495
for idx, varName := range vars {
96+
argVal := variables.ResolveVariableOrReturnIdentity(args[idx])
9597
resourceType := ConvertUriTemplateValueToType(varName)
9698
varType, ok := GetResourceByName(resourceType)
9799
if ok {
@@ -101,13 +103,13 @@ func GenerateUrl(urlInfo *CrudEntityInfo, args []string, useAliases bool) (strin
101103
attribute = override
102104
}
103105
if useAliases {
104-
values[varName] = uritemplate.String(aliases.ResolveAliasValuesOrReturnIdentity(varType.JsonApiType, varType.AlternateJsonApiTypesForAliases, args[idx], attribute))
106+
values[varName] = uritemplate.String(aliases.ResolveAliasValuesOrReturnIdentity(varType.JsonApiType, varType.AlternateJsonApiTypesForAliases, argVal, attribute))
105107
} else {
106-
values[varName] = uritemplate.String(args[idx])
108+
values[varName] = uritemplate.String(argVal)
107109
}
108110
} else {
109111
log.Warnf("Could not find a resource with type %s, aliases are probably broken", resourceType)
110-
values[varName] = uritemplate.String(args[idx])
112+
values[varName] = uritemplate.String(argVal)
111113
}
112114

113115
}

0 commit comments

Comments
 (0)