Skip to content

Commit

Permalink
Resolves #121 - Improving support for downstream libraries. (#120)
Browse files Browse the repository at this point in the history
Specifics:
* Add ability for downstream libraries to pass in persistent functions.
* Add ability for downstream libraries to pass in additional resources.

Other tweaks / fixes:
* Add descriptions to aliases and log commands.
* Fixed a few resource definitions
* Improved JSON Schema to have a few new optional resources.
* JSON Color formatting after 8K of text.
* Improved support for no-auth requests
  • Loading branch information
steve-r-west authored Apr 13, 2022
1 parent 4eb7163 commit a74b0c2
Show file tree
Hide file tree
Showing 12 changed files with 102 additions and 34 deletions.
1 change: 1 addition & 0 deletions cmd/aliases.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

var aliasesCmd = &cobra.Command{
Use: "aliases",
Short: "Provides information about aliases that can be used",
SilenceUsage: false,
}

Expand Down
4 changes: 4 additions & 0 deletions cmd/delete-all.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ var DeleteAll = &cobra.Command{
func getPage(resourceName string) ([]string, error) {
resp, err := getResource([]string{resourceName, "page[limit]", "25"})

if err != nil {
return []string{}, err
}

// Read the body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
Expand Down
4 changes: 4 additions & 0 deletions cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ var get = &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error {
resp, err := getResource(args)

if err != nil {
return err
}

// Print the body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,4 @@ var LogsShow = &cobra.Command{
},
}

var Logs = &cobra.Command{Use: "logs"}
var Logs = &cobra.Command{Use: "logs", Short: "Retrieve information about previous requests"}
18 changes: 17 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ func init() {
aliasesCmd.AddCommand(aliasListCmd, aliasClearCmd)
}

var persistentPreRunFuncs []func(cmd *cobra.Command, args []string) error

func AddRootPreRunFunc(f func(cmd *cobra.Command, args []string) error) {
persistentPreRunFuncs = append(persistentPreRunFuncs, f)
}

var RootCmd = &cobra.Command{
Use: os.Args[0],
Short: "A command line interface for interacting with the Elastic Path Commerce Cloud API",
Expand All @@ -72,9 +78,19 @@ Environment Variables
- EPCC_CLIENT_SECRET - The client secret (available in Commerce Manager)
- EPCC_BETA_API_FEATURES - Beta features in the API we want to enable.
`,
PersistentPreRun: func(cmd *cobra.Command, _ []string) {
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
log.SetLevel(logger.Loglevel)

for _, runFunc := range persistentPreRunFuncs {
err := runFunc(cmd, args)
if err != nil {
return err
}
}

return nil
},

SilenceUsage: true,
Version: fmt.Sprintf("EPCC CLI %s (Commit %s)", version.Version, version.Commit),
}
Expand Down
5 changes: 5 additions & 0 deletions external/authentication/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ func auth() (string, error) {

} else {
// Autologin using env vars
if config.Envs.EPCC_CLIENT_ID == "" {
log.Debug("No client secret found, no authentication will be used")
return "", nil
}

values.Set("client_id", config.Envs.EPCC_CLIENT_ID)
grantType = "implicit"

Expand Down
4 changes: 3 additions & 1 deletion external/httpclient/httpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ func doRequestInternal(ctx context.Context, method string, contentType string, p
return nil, err
}

req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
if bearerToken != "" {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
}

req.Header.Add("Content-Type", contentType)

Expand Down
5 changes: 3 additions & 2 deletions external/json/encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,11 @@ func (e *encoder) encode(v interface{}) {
default:
panic(fmt.Sprintf("invalid value: %v", v))
}
if e.w.Len() > 8*1024 {
// Original code to prevent buffering, but if we are outputting color this will break
/*if e.w.Len() > 8*1024 {
e.out.Write(e.w.Bytes())
e.w.Reset()
}
}*/
}

// ref: floatEncoder in encoding/json
Expand Down
2 changes: 1 addition & 1 deletion external/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ var LoglevelIds = map[log.Level][]string{
log.PanicLevel: {"panic"},
}

var Loglevel log.Level = log.InfoLevel
var Loglevel = log.InfoLevel

func init() {
log.SetOutput(os.Stderr)
Expand Down
73 changes: 52 additions & 21 deletions external/resources/resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package resources

import (
_ "embed"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)

Expand All @@ -12,27 +13,6 @@ var resources map[string]Resource

var resourcesSingular = map[string]Resource{}

func init() {

err := yaml.Unmarshal([]byte(resourceMetaData), &resources)
if err != nil {
panic("Couldn't load the resource meta data")
}

for key, val := range resources {
// Fix the key
val.Type = key

val.PluralName = key
for attributeName, attributeVal := range val.Attributes {
// Fix the key
attributeVal.Key = attributeName
}
resourcesSingular[val.SingularName] = val
}

}

type Resource struct {
// The type as far as the EPCC CLI is concerned.
Type string
Expand Down Expand Up @@ -137,3 +117,54 @@ func GetResourceByName(name string) (Resource, bool) {

return Resource{}, false
}

func GenerateResourceMetadataFromYaml(yamlTxt string) (map[string]Resource, error) {
resources := make(map[string]Resource)

err := yaml.Unmarshal([]byte(yamlTxt), &resources)
if err != nil {
return nil, err
}

return resources, nil
}

func AppendResourceData(newResources map[string]Resource) {
resourceCount := len(resources)
for key, val := range newResources {
resources[key] = val
}

log.Infof("Loading %d new resources, total resources went from %d to %d ", len(newResources), resourceCount, len(resources))

postProcessResourceMetadata()
}

func init() {

reses, err := GenerateResourceMetadataFromYaml(resourceMetaData)

if err != nil {
panic("Couldn't load the resource meta data")
}

resources = reses

postProcessResourceMetadata()
}

func postProcessResourceMetadata() {
resourcesSingular = make(map[string]Resource)

for key, val := range resources {
// Fix the key
val.Type = key

val.PluralName = key
for attributeName, attributeVal := range val.Attributes {
// Fix the key
attributeVal.Key = attributeName
}
resourcesSingular[val.SingularName] = val
}
}
12 changes: 6 additions & 6 deletions external/resources/resources.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ account-members:
email:
type: STRING
account-memberships:
singular-name: "account_membership"
singular-name: "account-membership"
json-api-type: "account_membership"
json-api-format: "legacy"
docs: "https://documentation.elasticpath.com/commerce-cloud/docs/api/customers-and-accounts/account-management/account-memberships/index.html"
Expand Down Expand Up @@ -610,7 +610,7 @@ order-transaction-refund:
docs: "https://documentation.elasticpath.com/commerce-cloud/docs/api/payments/transactions/refund-a-transaction.html"
url: "/v2/orders/{orders}/transactions/{order_transactions}/refund"
password-profiles:
singular-name: "password_profile"
singular-name: "password-profile"
json-api-type: "password_profile"
json-api-format: "legacy"
docs: "https://documentation.elasticpath.com/commerce-cloud/docs/api/single-sign-on/password-profiles/index.html"
Expand Down Expand Up @@ -943,7 +943,7 @@ pcm-product-prices:
currencies.CAD.includes_tax:
type: BOOL
promotion-codes:
singular-name: "promotion_code"
singular-name: "promotion-code"
json-api-type: "promotion_codes"
json-api-format: "legacy"
docs: "https://documentation.elasticpath.com/commerce-cloud/docs/api/promotions/get-promotion-codes.html"
Expand Down Expand Up @@ -1043,7 +1043,7 @@ settings:
calculation_method:
type: ENUM:simple,line
user-authentication-infos:
singular-name: "user_authentication_info"
singular-name: "user-authentication-info"
json-api-type: "user_authentication_info"
json-api-format: "legacy"
docs: "https://documentation.elasticpath.com/commerce-cloud/docs/api/single-sign-on/user-authentication-info/index.html"
Expand All @@ -1070,7 +1070,7 @@ user-authentication-infos:
email:
type: STRING
user-authentication-oidc-profile-infos:
singular-name: "user_authentication_oidc_profile_info"
singular-name: "user-authentication-oidc-profile-info"
json-api-type: "user_authentication_oidc_profile_info"
json-api-format: "legacy"
docs: "https://documentation.elasticpath.com/commerce-cloud/docs/api/single-sign-on/user-authentication-oidc-profile-info/index.html"
Expand Down Expand Up @@ -1169,4 +1169,4 @@ v2-products:
status:
type: ENUM:draft,live
commodity_type:
type: ENUM:physical,digital
type: ENUM:physical,digital
6 changes: 5 additions & 1 deletion external/resources/resources_schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
"properties" : {
"docs": { "type": "string", "pattern": "^https://" },
"url": { "type": "string" },
"content-type": { "type": "string" }
"min": { "type": "integer" }
},
"required": [ "url", "docs"]
},
Expand All @@ -68,6 +68,10 @@
"required": ["type"]
}
}
},
"singular-name": {
"type":"string",
"pattern": "^[A-Za-z-][A-Za-z0-9-]*$"
}
},
"required": [ "json-api-type", "json-api-format", "docs"]
Expand Down

0 comments on commit a74b0c2

Please sign in to comment.