Skip to content

Commit

Permalink
Resolves #429 - Add support for --compact, fix a bug with autofill, a…
Browse files Browse the repository at this point in the history
…nd fix aliases
  • Loading branch information
steve-r-west committed Jan 6, 2024
1 parent f3cdda5 commit 9b8abef
Show file tree
Hide file tree
Showing 10 changed files with 119 additions and 12 deletions.
11 changes: 11 additions & 0 deletions cmd/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ func NewCreateCommand(parentCmd *cobra.Command) func() {
var autoFillOnCreate = false
var noBodyPrint = false
var outputJq = ""
var compactOutput = true
var setAlias = ""
var ifAliasExists = ""
var ifAliasDoesNotExist = ""
Expand All @@ -58,6 +59,7 @@ func NewCreateCommand(parentCmd *cobra.Command) func() {
overrides.OverrideUrlPath = ""
overrides.QueryParameters = nil
skipAliases = false
compactOutput = false
}

for _, resource := range resources.GetPluralResources() {
Expand Down Expand Up @@ -130,6 +132,14 @@ func NewCreateCommand(parentCmd *cobra.Command) func() {
if noBodyPrint {
return nil
} else {
if compactOutput {
body, err = json.Compact(body)

if err != nil {
return err
}
}

return json.PrintJson(body)
}

Expand Down Expand Up @@ -207,6 +217,7 @@ func NewCreateCommand(parentCmd *cobra.Command) func() {
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().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")
Expand Down
12 changes: 12 additions & 0 deletions cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func NewGetCommand(parentCmd *cobra.Command) func() {

// Ensure that any new options here are added to the resetFunc
var outputJq = ""
var compactOutput = false
var noBodyPrint = false
var retryWhileJQ = ""
var retryWhileJQMaxAttempts = uint16(1200)
Expand All @@ -41,12 +42,14 @@ func NewGetCommand(parentCmd *cobra.Command) func() {
overrides.QueryParameters = nil
overrides.OverrideUrlPath = ""
outputJq = ""
compactOutput = false
noBodyPrint = false
retryWhileJQ = ""
retryWhileJQMaxAttempts = uint16(1200)
ifAliasExists = ""
ifAliasDoesNotExist = ""
skipAliases = false

}

var getCmd = &cobra.Command{
Expand Down Expand Up @@ -195,6 +198,14 @@ func NewGetCommand(parentCmd *cobra.Command) func() {
if noBodyPrint {
return retriesFailedError
} else {
if compactOutput {
body, err = json.Compact(body)

if err != nil {
return err
}
}

printError := json.PrintJson(body)

if retriesFailedError != nil {
Expand Down Expand Up @@ -266,6 +277,7 @@ func NewGetCommand(parentCmd *cobra.Command) func() {
getCmd.PersistentFlags().StringVar(&overrides.OverrideUrlPath, "override-url-path", "", "Override the URL that will be used for the Request")
getCmd.PersistentFlags().StringSliceVarP(&overrides.QueryParameters, "query-parameters", "q", []string{}, "Pass in key=value an they will be added as query parameters")
getCmd.PersistentFlags().StringVarP(&outputJq, "output-jq", "", "", "A jq expression, if set we will restrict output to only this")
getCmd.PersistentFlags().BoolVarP(&compactOutput, "compact", "", false, "Hides some of the boiler plate keys and empty fields, etc...")
getCmd.PersistentFlags().StringVarP(&retryWhileJQ, "retry-while-jq", "", "", "A jq expression, if set and returns true we will retry the get command (see manual for examples)")
getCmd.PersistentFlags().Uint16VarP(&retryWhileJQMaxAttempts, "retry-while-jq-max-attempts", "", 1200, "The maximum number of attempts we will retry with jq")
getCmd.PersistentFlags().StringVarP(&ifAliasExists, "if-alias-exists", "", "", "If the alias exists we will run this command, otherwise exit with no error")
Expand Down
1 change: 1 addition & 0 deletions cmd/reset-store.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ func resetResourcesUndeletableResources(ctx context.Context, overrides *httpclie
{"authentication-realm", "last_read=array[2]", "redirect_uris", "[]", "duplicate_email_policy", "allowed"},
{"authentication-realm", "related_authentication-realm_for_customer-authentication-settings_last_read=entity", "name", "Buyer Organization"},
{"authentication-realm", "related_authentication_realm_for_account_authentication_settings_last_read=entity", "name", "Account Management Realm"},
{"account-authentication-settings", "enable_self_signup", "false", "auto_create_account_for_account_members", "false", "account_member_self_management", "disabled"},
{"log-ttl-settings", "days", "356"},
}

Expand Down
11 changes: 11 additions & 0 deletions cmd/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ func NewUpdateCommand(parentCmd *cobra.Command) func() {

// Ensure that any new options here are added to the resetFunc
var outputJq = ""
var compactOutput = false
var noBodyPrint = false
var ifAliasExists = ""
var ifAliasDoesNotExist = ""
Expand All @@ -34,6 +35,7 @@ func NewUpdateCommand(parentCmd *cobra.Command) func() {
overrides.QueryParameters = nil
overrides.OverrideUrlPath = ""
outputJq = ""
compactOutput = false
noBodyPrint = false
ifAliasExists = ""
ifAliasDoesNotExist = ""
Expand Down Expand Up @@ -120,6 +122,14 @@ func NewUpdateCommand(parentCmd *cobra.Command) func() {
if noBodyPrint {
return nil
} else {
if compactOutput {
body, err = json.Compact(body)

if err != nil {
return err
}
}

return json.PrintJson(body)
}

Expand Down Expand Up @@ -179,6 +189,7 @@ func NewUpdateCommand(parentCmd *cobra.Command) func() {
updateCmd.PersistentFlags().StringSliceVarP(&overrides.QueryParameters, "query-parameters", "q", []string{}, "Pass in key=value an they will be added as query parameters")
updateCmd.PersistentFlags().BoolVarP(&noBodyPrint, "silent", "s", false, "Don't print the body on success")
updateCmd.PersistentFlags().StringVarP(&outputJq, "output-jq", "", "", "A jq expression, if set we will restrict output to only this")
updateCmd.PersistentFlags().BoolVarP(&compactOutput, "compact", "", false, "Hides some of the boiler plate keys and empty fields, etc...")
updateCmd.PersistentFlags().StringVarP(&ifAliasExists, "if-alias-exists", "", "", "If the alias exists we will run this command, otherwise exit with no error")
updateCmd.PersistentFlags().StringVarP(&ifAliasDoesNotExist, "if-alias-does-not-exist", "", "", "If the alias does not exist we will run this command, otherwise exit with no error")
updateCmd.MarkFlagsMutuallyExclusive("if-alias-exists", "if-alias-does-not-exist")
Expand Down
7 changes: 7 additions & 0 deletions external/aliases/aliases.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,17 @@ func ResolveAliasValuesOrReturnIdentity(jsonApiType string, alternateJsonApiType
splitAlias := strings.Split(aliasName, "/")

if len(splitAlias) == 2 {
//
alternateJsonApiTypes = append(alternateJsonApiTypes, splitAlias[0])
aliasName = splitAlias[1]
}

if len(splitAlias) == 4 {
if splitAlias[0] == "alias" {
return ResolveAliasValuesOrReturnIdentity(splitAlias[1], []string{}, splitAlias[2], splitAlias[3])
}
}

if result, ok := GetAliasesForJsonApiTypeAndAlternates(jsonApiType, alternateJsonApiTypes)[aliasName]; ok {

if attribute == "id" {
Expand Down
6 changes: 4 additions & 2 deletions external/autofill/autofill.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ func GetJsonArrayForResource(r *resources.Resource) []string {
args := make([]string, 0)

for attributeName, data := range r.Attributes {
key := data.Key
key = strings.Replace(key, "data[n]", "data[0]", 1)
autofill := data.AutoFill

if strings.HasPrefix(autofill, "FUNC:") {
Expand Down Expand Up @@ -68,7 +70,7 @@ func GetJsonArrayForResource(r *resources.Resource) []string {
}
}

args = append(args, data.Key, arg)
args = append(args, key, arg)
} else {
log.Warnf("Got unexpected number of results from calling %s -> %d", methodName, len(result))
}
Expand All @@ -78,7 +80,7 @@ func GetJsonArrayForResource(r *resources.Resource) []string {
}

} else if strings.HasPrefix(autofill, "VALUE:") {
args = append(args, data.Key, strings.Trim(autofill[6:], " "))
args = append(args, key, strings.Trim(autofill[6:], " "))
}

}
Expand Down
52 changes: 52 additions & 0 deletions external/json/compact.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package json

import (
gojson "encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
)

var KeysToDelete = []string{
".data.links",
".data.meta",
".data[].links",
".data[].meta",
".links",
".meta",
"..|nulls",
`..|select(. == {})`,
`..|select(. == {})`,
`..|select(. == "")`,
}

func Compact(json string) (string, error) {

var obj interface{}

err := gojson.Unmarshal([]byte(json), &obj)

if err != nil {
return "", err
}

for _, key := range KeysToDelete {
newObj, err := RunJQWithArray(fmt.Sprintf("del(%s)", key), obj)

if err == nil {
if len(newObj) == 1 {
obj = newObj[0]
} else {
log.Warnf("Couldn't compact with key %s, due to unexpected result size", key)
return json, nil
}
}
}

str, err := gojson.Marshal(obj)

if err != nil {
return "", err
}

return string(str), err
}
1 change: 0 additions & 1 deletion external/json/to_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,5 +267,4 @@ func formatValue(v string) string {
} else {
return fmt.Sprintf("\"%s\"", v)
}

}
13 changes: 12 additions & 1 deletion external/resources/yaml/resources.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
account-authentication-settings:
singular-name: "account-authentication-setting"
json-api-type: "account-authentication-settings"
json-api-type: "account_authentication_settings"
json-api-format: "legacy"
docs: "https://documentation.elasticpath.com/commerce-cloud/docs/api/advanced/settings/account-authentication-settings/index.html"
get-collection:
Expand All @@ -9,6 +9,16 @@ account-authentication-settings:
get-entity:
docs: "https://documentation.elasticpath.com/commerce-cloud/docs/api/advanced/settings/account-authentication-settings/get-account-authentication-settings.html"
url: "/v2/settings/account-authentication"
update-entity:
docs: "https://elasticpath.dev/docs/commerce-cloud/authentication/single-sign-on/account-authentication-settings/update-account-authentication-settings"
url: "/v2/settings/account-authentication"
attributes:
enable_self_signup:
type: BOOL
auto_create_account_for_account_members:
type: BOOL
account_member_self_management:
type: BOOL
account-management-authentication-tokens:
singular-name: "account-management-authentication-token"
json-api-type: "account_management_authentication_token"
Expand Down Expand Up @@ -510,6 +520,7 @@ customer-cart-associations:
type: RESOURCE_ID:customer
data[n].type:
type: ENUM:customer
autofill: VALUE:customer
customer-addresses:
singular-name: "customer-address"
json-api-type: "address"
Expand Down
17 changes: 9 additions & 8 deletions external/runbooks/account-management.epcc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,19 @@ actions:
short: "Password (if set we will try and create a user-authentication-password-profile-info)"
commands:
# Initialize alias for Authentication Realm
- epcc get account-authentication-settings
- epcc get -s account-authentication-settings
# Initialize alias for password profile id
- epcc get password-profiles related_authentication_realm_for_account_authentication_settings_last_read=entity
- epcc create user-authentication-info related_authentication_realm_for_account_authentication_settings_last_read=entity name "{{.name}}" email "{{.email}}"
- epcc get -s password-profiles related_authentication_realm_for_account_authentication_settings_last_read=entity
- epcc create -s user-authentication-info related_authentication_realm_for_account_authentication_settings_last_read=entity name "{{.name}}" email "{{.email}}"
# TODO if we ever support variables, we should check whether we actually have that alias.
- |
{{ if ne (len .password) 0 }}
epcc create user-authentication-password-profile-info related_authentication_realm_for_account_authentication_settings_last_read=entity last_read=entity username "{{.email}}" password "{{.password}}" password_profile_id last_read=array[0]
{{ end }}
- epcc get account-member user_authentication_info/last_read=entity
- epcc create account name "Personal Account For {{ .name }}" legal_name "Individual Account For {{ .name }}"
- epcc create account-membership last_read=entity account_member_id user_authentication_info/last_read=entity
- epcc get account-member alias/user_authentication_info/last_read=entity/id
- epcc create -s account name "Personal Account For {{ .name }}" legal_name "Individual Account For {{ .name }}"
- epcc create -s account-membership last_read=entity account_member_id user_authentication_info/last_read=entity
catalog-rule-example:
description:
short: "Create some catalog rules"
Expand Down Expand Up @@ -77,13 +78,13 @@ actions:
- epcc create account name "Account 1" legal_name "Account 1"
- epcc create user-authentication-info related_authentication_realm_for_account_authentication_settings_last_read=entity name "Account 1" email "[email protected]"
- epcc create user-authentication-password-profile-info related_authentication_realm_for_account_authentication_settings_last_read=entity name=Account_1 username "{{.account_1_username}}" password "{{.account_1_password}}" password_profile_id last_read=array[0]
- epcc get account-member user_authentication_info/last_read=entity
- epcc get account-member alias/user_authentication_info/last_read=entity/id
- epcc create account-membership name=Account_1 account_member_id user_authentication_info/last_read=entity
# Create Account 2
- epcc create account name "Account 2" legal_name "Account 2"
- epcc create user-authentication-info related_authentication_realm_for_account_authentication_settings_last_read=entity name "Account 2" email "[email protected]"
- epcc create user-authentication-password-profile-info related_authentication_realm_for_account_authentication_settings_last_read=entity name=Account_2 username "{{.account_2_username}}" password "{{.account_2_password}}" password_profile_id last_read=array[0]
- epcc get account-member user_authentication_info/last_read=entity
- epcc get account-member alias/user_authentication_info/last_read=entity/id
- epcc create account-membership name=Account_2 account_member_id user_authentication_info/last_read=entity
# Create PXM Stuff
- |
Expand Down

0 comments on commit 9b8abef

Please sign in to comment.