/
create.go
365 lines (297 loc) · 11.4 KB
/
create.go
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package cmd
import (
"context"
gojson "encoding/json"
"fmt"
"github.com/elasticpath/epcc-cli/external/aliases"
"github.com/elasticpath/epcc-cli/external/autofill"
"github.com/elasticpath/epcc-cli/external/completion"
"github.com/elasticpath/epcc-cli/external/encoding"
"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/shutdown"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"io"
"net/http"
"net/url"
"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 := 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.PrintJson(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.PrintJson(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,
})
}
} 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
}
func createInternal(ctx context.Context, overrides *httpclient.HttpParameterOverrides, args []string, autoFillOnCreate bool, aliasName string, skipAliases bool) (string, error) {
shutdown.OutstandingOpCounter.Add(1)
defer shutdown.OutstandingOpCounter.Done()
// Find Resource
resource, ok := resources.GetResourceByName(args[0])
if !ok {
return "", fmt.Errorf("could not find resource %s", args[0])
}
if resource.CreateEntityInfo == nil {
return "", fmt.Errorf("resource %s doesn't support CREATE", args[0])
}
// Count ids in CreateEntity
resourceURL := resource.CreateEntityInfo.Url
idCount, err := resources.GetNumberOfVariablesNeeded(resourceURL)
if err != nil {
return "", err
}
// Replace ids with args in resourceURL
resourceURL, err = resources.GenerateUrl(resource.CreateEntityInfo, args[1:], true)
if overrides.OverrideUrlPath != "" {
log.Warnf("Overriding URL Path from %s to %s", resourceURL, overrides.OverrideUrlPath)
resourceURL = overrides.OverrideUrlPath
}
if err != nil {
return "", err
}
var resp *http.Response = nil
var resBody []byte
if resource.CreateEntityInfo.ContentType == "multipart/form-data" {
byteBuf, contentType, err := encoding.ToMultiPartEncoding(args[(idCount+1):], resource.NoWrapping, resource.JsonApiFormat == "complaint", resource.Attributes)
if err != nil {
return "", err
}
// Submit request
resp, err = httpclient.DoFileRequest(ctx, resourceURL, byteBuf, contentType)
} else {
// Assume it's application/json
params := url.Values{}
for _, v := range overrides.QueryParameters {
keyAndValue := strings.SplitN(v, "=", 2)
if len(keyAndValue) != 2 {
return "", fmt.Errorf("Could not parse query parameter %v, all query parameters should be a key and value format", keyAndValue)
}
params.Add(keyAndValue[0], keyAndValue[1])
}
if !resource.NoWrapping {
args = append(args, "type", resource.JsonApiType)
}
// Create the body from remaining args
jsonArgs := args[(idCount + 1):]
if autoFillOnCreate {
autofilledData := autofill.GetJsonArrayForResource(&resource)
jsonArgs = append(autofilledData, jsonArgs...)
}
body, err := json.ToJson(jsonArgs, resource.NoWrapping, resource.JsonApiFormat == "compliant", resource.Attributes, true)
if err != nil {
return "", err
}
// Submit request
resp, err = httpclient.DoRequest(ctx, "POST", resourceURL, params.Encode(), strings.NewReader(body))
}
if err != nil {
return "", fmt.Errorf("got error %s", err.Error())
} else if resp == nil {
return "", fmt.Errorf("got nil response with request: %s", resourceURL)
}
if resp.Body != nil {
defer resp.Body.Close()
// Print the body
resBody, err = io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// Check if error response
if resp.StatusCode >= 400 && resp.StatusCode <= 600 {
json.PrintJson(string(resBody))
return "", fmt.Errorf(resp.Status)
}
// 204 is no content, so we will skip it.
if resp.StatusCode != 204 {
if !skipAliases {
aliases.SaveAliasesForResources(string(resBody))
}
}
if aliasName != "" {
aliases.SetAliasForResource(string(resBody), aliasName)
}
return string(resBody), nil
} else {
return "", nil
}
}