cmd

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 25, 2022 License: MIT Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	API          = "api"
	ClientId     = "client_id"
	ClientSecret = "client_secret"
)

Variables

View Source
var ApiHostToUrlMap = map[string]string{
	"api.moltin.com":             "https://euwest.cm.elasticpath.com/",
	"useast.api.elasticpath.com": "https://useast.cm.elasticpath.com/",
}
View Source
var DeleteAll = &cobra.Command{
	Use:    "delete-all [RESOURCE]",
	Short:  "Deletes all of a resource.",
	Args:   cobra.MinimumNArgs(1),
	Hidden: false,
	RunE: func(cmd *cobra.Command, args []string) error {

		resource, ok := resources.GetResourceByName(args[0])
		if !ok {
			return fmt.Errorf("could not find resource %s", args[0])
		}

		if resource.GetCollectionInfo == nil {
			return fmt.Errorf("resource %s doesn't support GET collection", args[0])
		}

		if resource.DeleteEntityInfo == nil {
			return fmt.Errorf("resource %s doesn't support DELETE", args[0])
		}

		allParentEntityIds, err := getParentIds(context.Background(), resource)

		if err != nil {
			return fmt.Errorf("could not retrieve parent ids for for resource %s, error: %w", resource.PluralName, err)
		}

		if len(allParentEntityIds) == 1 {
			log.Infof("Resource %s is a top level resource need to scan only one path to delete all resources", resource.PluralName)
		} else {
			log.Infof("Resource %s is not a top level resource, need to scan %d paths to delete all resources", resource.PluralName, len(allParentEntityIds))
		}

		for _, parentEntityIds := range allParentEntityIds {
			lastIds := make([][]id.IdableAttributes, 1)
			for {
				resourceURL, err := resources.GenerateUrlViaIdableAttributes(resource.GetCollectionInfo, parentEntityIds)

				if err != nil {
					return err
				}

				params := url.Values{}
				params.Add("page[limit]", "25")

				resp, err := httpclient.DoRequest(context.Background(), "GET", resourceURL, params.Encode(), nil)

				if err != nil {
					return err
				}

				ids, err := apihelper.GetResourceIdsFromHttpResponse(resp)
				resp.Body.Close()

				allIds := make([][]id.IdableAttributes, 0)
				for _, id := range ids {
					allIds = append(allIds, append(parentEntityIds, id))
				}

				min := resource.DeleteEntityInfo.MinResources
				if reflect.DeepEqual(allIds, lastIds) {
					if min == len(lastIds) {
						log.Infof("The minimum number of resources for %s is %d, we have tried to delete %d but couldn't delete them, so we are complete",
							resource.PluralName, min, len(allIds))
					} else if min <= len(lastIds) {
						log.Warnf("The minimum number of resources for %s is %d, we have tried to delete %d currently but seem stuck, so we are done."+
							"Please check to ensure that the resource doesn't require related resources deleted first", resource.PluralName, min, len(allIds))
					} else if min > len(lastIds) {
						log.Warnf("The minimum number of resources for %s is %d, we have tried to delete %d currently but seem stuck, so we are done."+
							"Please check to ensure that the resource doesn't require related resources deleted first", resource.PluralName, min, len(allIds))
					}

					break
				} else {
					lastIds = allIds
				}

				if len(allIds) == 0 {
					log.Infof("Total ids retrieved for %s is %d, we are done", resource.PluralName, len(allIds))
					break
				}

				delPage(resource.DeleteEntityInfo, allIds)
			}
		}

		return aliases.ClearAllAliasesForJsonApiType(resource.JsonApiType)
	},

	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		if len(args) == 0 {
			return completion.Complete(completion.Request{
				Type: completion.CompletePluralResource,
				Verb: completion.Delete,
			})
		}

		return []string{}, cobra.ShellCompDirectiveNoFileComp
	},
}
View Source
var Logs = &cobra.Command{Use: "logs", Short: "Retrieve information about previous requests"}
View Source
var LogsClear = &cobra.Command{
	Use:   "clear",
	Short: "Clears all HTTP request and response logs",
	RunE: func(cmd *cobra.Command, args []string) error {
		return profiles.ClearAllRequestLogs()
	},
}
View Source
var LogsList = &cobra.Command{
	Use:   "list",
	Short: "List all HTTP logs",
	RunE: func(cmd *cobra.Command, args []string) error {
		files, err := profiles.GetAllRequestLogTitles()
		if err != nil {
			return err
		}

		for idx, name := range files {
			fmt.Printf("%d %s\n", idx, name)
		}
		return nil
	},
}
View Source
var LogsShow = &cobra.Command{
	Use:   "show <NUMBER>",
	Short: "Show HTTP logs for specific number",
	Args:  cobra.MinimumNArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {

		i, err := strconv.Atoi(args[0])

		if err != nil {
			return fmt.Errorf("could not get the %s entry => %w", args[0], err)
		}

		content, err := profiles.GetNthRequestLog(i)

		if err != nil {
			return fmt.Errorf("couldn't print logs: %v", err)
		}

		fmt.Println(content)

		return nil
	},
}
View Source
var ResetStore = &cobra.Command{
	Use:   "reset-store [STORE_ID]",
	Short: "Resets a store to it's initial state on a \"best effort\" basis.",
	Long:  "This command resets a store to it's initial state. There are some limitations to this as for instance orders cannot be deleted, nor can audit entries.",
	Args:  cobra.MinimumNArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		resource, ok := resources.GetResourceByName("customer-authentication-settings")

		if !ok {
			return fmt.Errorf("could not find resource %s, we need it to determine the store id.", args[0])
		}

		resourceURL, err := resources.GenerateUrl(resource.GetCollectionInfo, make([]string, 0))

		if err != nil {
			return err
		}

		params := url.Values{}

		resp, err := httpclient.DoRequest(context.Background(), "GET", resourceURL, params.Encode(), nil)

		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)

		if err != nil {
			return err
		}

		var jsonStruct = map[string]interface{}{}
		err = gojson.Unmarshal(body, &jsonStruct)
		if err != nil {
			return err
		}

		storeIdInterface, err := json.RunJQ(".data.id", jsonStruct)

		if err != nil {
			return err
		}

		storeId, ok := storeIdInterface.(string)

		if !ok {
			return fmt.Errorf("Could not retrieve store id, could not cast result to string %T => %v", storeIdInterface, storeIdInterface)
		}

		rx, err := regexp.Compile("^" + args[0] + "$")

		if err != nil {
			if storeId != args[0] {
				return fmt.Errorf("You are trying to reset store id '%s', but you passed '%s' to this command", storeId, args[0])
			}
		} else {
			if !rx.MatchString(storeId) {
				return fmt.Errorf("You are trying to reset store id '%s', but you passed '%s' to this command which doesn't match", storeId, args[0])
			}
		}

		errors := make([]string, 0)

		err, paymentGatewayErrors := resetResources()

		if err != nil {
			return err
		}

		errors = append(errors, paymentGatewayErrors...)

		resourceNames := resources.GetPluralResourceNames()
		sort.Strings(resourceNames)
		err, deleteAllResourceDataErrors := deleteAllResourceData(resourceNames)
		if err != nil {
			return err
		}

		errors = append(errors, deleteAllResourceDataErrors...)

		log.Warnf("The following errors occurred while deleting all data: \n\t%s", strings.Join(errors, "\n\t"))
		return nil

	},
}
View Source
var RootCmd = &cobra.Command{
	Use:   os.Args[0],
	Short: "A command line interface for interacting with the Elastic Path Commerce Cloud API",
	Long: `The EPCC CLI tool provides a powerful command line interface for interacting with the Elastic Path Commerce Cloud API.

The EPCC CLI tool uses environment variables for configuration and in particular a tool like https://direnv.net/ which
auto populates your shell with environment variables when you switch directories. This allows you to store a context in a folder,
and come back to it at any time.

Environment Variables

- EPCC_API_BASE_URL - The API endpoint that we will hit
- EPCC_CLIENT_ID - The client id (available in Commerce Manager)
- EPCC_CLIENT_SECRET - The client secret (available in Commerce Manager)
- EPCC_BETA_API_FEATURES - Beta features in the API we want to enable.
- EPCC_CLI_HTTP_HEADER_[0,1,...] - An additional HTTP header to set with all requests, the format should be "HeaderName: value"
- EPCC_PROFILE - The name of the profile we will use (isolates namespace, credentials, etc...)

`,
	PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
		log.SetLevel(logger.Loglevel)

		if config.Envs.EPCC_RATE_LIMIT != 0 {
			rateLimit = config.Envs.EPCC_RATE_LIMIT
		}
		log.Debugf("Rate limit set to %d request per second ", rateLimit)
		httpclient.Limit = rate.NewLimiter(rate.Limit(rateLimit), 1)

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

		return nil
	},

	SilenceUsage: true,
	Version:      fmt.Sprintf("%s (Commit %s)", version.Version, version.Commit),
}

Functions

func AddRootPreRunFunc added in v0.6.0

func AddRootPreRunFunc(f func(cmd *cobra.Command, args []string) error)

func Execute

func Execute()

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL