-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcreate.go
More file actions
238 lines (201 loc) · 8.18 KB
/
create.go
File metadata and controls
238 lines (201 loc) · 8.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package cmd
import (
"context"
gojson "encoding/json"
"fmt"
"github.com/elasticpath/epcc-cli/external/aliases"
"github.com/elasticpath/epcc-cli/external/completion"
"github.com/elasticpath/epcc-cli/external/httpclient"
"github.com/elasticpath/epcc-cli/external/json"
"github.com/elasticpath/epcc-cli/external/resources"
"github.com/elasticpath/epcc-cli/external/rest"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"strings"
)
func NewCreateCommand(parentCmd *cobra.Command) func() {
var createCmd = &cobra.Command{
Use: "create",
Short: "Creates a resource",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return fmt.Errorf("please specify a resource, epcc create [RESOURCE], see epcc create --help")
} else {
return fmt.Errorf("invalid resource [%s] specified, see all with epcc create --help", args[0])
}
},
}
overrides := &httpclient.HttpParameterOverrides{
QueryParameters: nil,
OverrideUrlPath: "",
}
// Ensure that any new options here are added to the resetFunc
var autoFillOnCreate = false
var noBodyPrint = false
var outputJq = ""
var compactOutput = true
var setAlias = ""
var ifAliasExists = ""
var ifAliasDoesNotExist = ""
var skipAliases = false
var repeat uint32 = 1
var repeatDelay uint32 = 100
var ignoreErrors = false
resetFunc := func() {
autoFillOnCreate = false
noBodyPrint = false
outputJq = ""
setAlias = ""
ifAliasExists = ""
ifAliasDoesNotExist = ""
overrides.OverrideUrlPath = ""
overrides.QueryParameters = nil
skipAliases = false
compactOutput = false
repeat = 1
repeatDelay = 100
ignoreErrors = false
}
for _, resource := range resources.GetPluralResources() {
if resource.CreateEntityInfo == nil {
continue
}
resource := resource
resourceName := resource.SingularName
var createResourceCmd = &cobra.Command{
Use: GetCreateUsageString(resource),
Short: GetCreateShort(resource),
Long: GetCreateLong(resource),
Example: GetCreateExample(resource),
Args: GetArgFunctionForCreate(resource),
RunE: func(cmd *cobra.Command, args []string) error {
c := func(cmd *cobra.Command, args []string) error {
if ifAliasExists != "" {
aliasId := aliases.ResolveAliasValuesOrReturnIdentity(resource.JsonApiType, resource.AlternateJsonApiTypesForAliases, ifAliasExists, "id")
if aliasId == ifAliasExists {
// If the aliasId is the same as requested, it means an alias did not exist.
log.Infof("Alias [%s] does not exist, not continuing run", ifAliasExists)
return nil
}
}
if ifAliasDoesNotExist != "" {
aliasId := aliases.ResolveAliasValuesOrReturnIdentity(resource.JsonApiType, resource.AlternateJsonApiTypesForAliases, ifAliasDoesNotExist, "id")
if aliasId != ifAliasDoesNotExist {
// If the aliasId is different than the request then it does exist.
log.Infof("Alias [%s] does exist (value: %s), not continuing run", ifAliasDoesNotExist, aliasId)
return nil
}
}
body, err := rest.CreateInternal(context.Background(), overrides, append([]string{resourceName}, args...), autoFillOnCreate, setAlias, skipAliases)
if err != nil {
return err
}
if outputJq != "" {
output, err := json.RunJQOnStringWithArray(outputJq, body)
if err != nil {
return err
}
for _, outputLine := range output {
outputJson, err := gojson.Marshal(outputLine)
if err != nil {
return err
}
err = json.PrintJsonToStdout(string(outputJson))
if err != nil {
return err
}
}
return nil
}
if noBodyPrint {
return nil
} else {
if compactOutput {
body, err = json.Compact(body)
if err != nil {
return err
}
}
return json.PrintJsonToStdout(body)
}
}
return repeater(c, repeat, repeatDelay, cmd, args, ignoreErrors)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
// Find Resource
resource, ok := resources.GetResourceByName(resourceName)
if ok {
if resource.CreateEntityInfo != nil {
resourceURL := resource.CreateEntityInfo.Url
idCount, _ := resources.GetNumberOfVariablesNeeded(resourceURL)
if len(args)-idCount >= 0 { // Arg is after IDs
if (len(args)-idCount)%2 == 0 { // This is an attribute key
usedAttributes := make(map[string]int)
for i := idCount; i < len(args); i = i + 2 {
usedAttributes[args[i]] = 0
}
// I think this allows you to complete the current argument
// This is necessary because if you are using something with a wildcard or regex
// You won't see it in the attribute list, and therefore it won't be able to auto complete it.
// I now think this does nothing.
toComplete := strings.ReplaceAll(toComplete, "<ENTER>", "")
if toComplete != "" {
usedAttributes[toComplete] = 0
}
return completion.Complete(completion.Request{
Type: completion.CompleteAttributeKey,
Resource: resource,
Attributes: usedAttributes,
Verb: completion.Create,
ToComplete: toComplete,
})
} else { // This is an attribute value
return completion.Complete(completion.Request{
Type: completion.CompleteAttributeValue,
Resource: resource,
Verb: completion.Create,
Attribute: args[len(args)-1],
ToComplete: toComplete,
AllowTemplates: true,
})
}
} else {
// Arg is in IDS
// Must be for a resource completion
types, err := resources.GetTypesOfVariablesNeeded(resourceURL)
if err != nil {
return []string{}, cobra.ShellCompDirectiveNoFileComp
}
typeIdxNeeded := len(args)
if completionResource, ok := resources.GetResourceByName(types[typeIdxNeeded]); ok {
return completion.Complete(completion.Request{
Type: completion.CompleteAlias,
Resource: completionResource,
})
}
}
}
}
return []string{}, cobra.ShellCompDirectiveNoFileComp
},
}
createCmd.AddCommand(createResourceCmd)
}
parentCmd.AddCommand(createCmd)
createCmd.PersistentFlags().StringVar(&overrides.OverrideUrlPath, "override-url-path", "", "Override the URL that will be used for the Request")
createCmd.PersistentFlags().BoolVarP(&autoFillOnCreate, "auto-fill", "", false, "Auto generate value for fields")
createCmd.PersistentFlags().BoolVarP(&noBodyPrint, "silent", "s", false, "Don't print the body on success")
createCmd.PersistentFlags().StringSliceVarP(&overrides.QueryParameters, "query-parameters", "q", []string{}, "Pass in key=value an they will be added as query parameters")
createCmd.PersistentFlags().StringVarP(&outputJq, "output-jq", "", "", "A jq expression, if set we will restrict output to only this")
createCmd.PersistentFlags().BoolVarP(&compactOutput, "compact", "", false, "Hides some of the boiler plate keys and empty fields, etc...")
createCmd.PersistentFlags().BoolVarP(&ignoreErrors, "ignore-errors", "", false, "Don't return non zero on an error")
createCmd.PersistentFlags().StringVarP(&setAlias, "save-as-alias", "", "", "A name to save the created resource as")
createCmd.PersistentFlags().StringVarP(&ifAliasExists, "if-alias-exists", "", "", "If the alias exists we will run this command, otherwise exit with no error")
createCmd.PersistentFlags().StringVarP(&ifAliasDoesNotExist, "if-alias-does-not-exist", "", "", "If the alias does not exist we will run this command, otherwise exit with no error")
createCmd.PersistentFlags().BoolVarP(&skipAliases, "skip-alias-processing", "", false, "if set, we don't process the response for aliases")
createCmd.MarkFlagsMutuallyExclusive("if-alias-exists", "if-alias-does-not-exist")
createCmd.PersistentFlags().Uint32VarP(&repeat, "repeat", "", 1, "Number of times to repeat the command")
createCmd.PersistentFlags().Uint32VarP(&repeatDelay, "repeat-delay", "", 100, "Delay (in ms) between repeats")
_ = createCmd.RegisterFlagCompletionFunc("output-jq", jqCompletionFunc)
return resetFunc
}