Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ export PATH=$PATH:($PWD)

`epcc get customers`

5. To add more profiles to use try the following command:
`epcc configure`

#### Simple CRUD

Expand Down
2 changes: 1 addition & 1 deletion cmd/aliases.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ var aliasClearCmd = &cobra.Command{
Use: "clear",
Short: "clear all aliases",
RunE: func(cmd *cobra.Command, args []string) error {
profileDirectory := profiles.GetProfileDataBaseURL()
profileDirectory := profiles.GetProfileDirectory()
os.RemoveAll(profileDirectory)
return nil
},
Expand Down
65 changes: 65 additions & 0 deletions cmd/configure.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package cmd

import (
"bufio"
"github.com/elasticpath/epcc-cli/config"
"github.com/elasticpath/epcc-cli/external/profiles"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/ini.v1"
"os"
"strings"
)

var configure = &cobra.Command{
Use: "configure",
Short: "Creates a profile by prompting for input over the command line.",
Long: "Will first prompt for a name then a series of variable specific for the user being created",
Run: func(cmd *cobra.Command, args []string) {

configPath := profiles.GetProfilePath()
cfg, err := ini.Load(configPath)
if err != nil {
log.Errorf("error loading to file " + configPath)
os.Exit(1)
}
newProfile := config.Env{}
reader := bufio.NewReader(os.Stdin)
println("Create new Profile")
print("Profile Name:")
text := readInput(reader)
print("API Base URL [https://api.moltin.com]:")
if input := readInput(reader); input != "" {
newProfile.EPCC_API_BASE_URL = input
} else {
newProfile.EPCC_API_BASE_URL = "https://api.moltin.com"
}
print("Client ID [None]:")
newProfile.EPCC_CLIENT_ID = readInput(reader)
print("Client Secret [None]:")
newProfile.EPCC_CLIENT_SECRET = readInput(reader)
print("(https://documentation.elasticpath.com/commerce-cloud/docs/api/basics/api-contract.html#beta-apis) [None]:")
newProfile.EPCC_BETA_API_FEATURES = readInput(reader)

section, err := cfg.NewSection(text)
section.ReflectFrom(&newProfile)
cfg.SaveTo(configPath)
if err != nil {
log.Errorf("error writing to file " + configPath)
os.Exit(1)
}
config.Envs = &newProfile
config.Profile = text

},
}

func readInput(reader *bufio.Reader) string {
response, err := reader.ReadString('\n')
if err != nil {
log.Errorf("error reading from stdin %s", err.Error())
os.Exit(1)
}
response = strings.TrimSuffix(response, "\n")
return response
}
39 changes: 13 additions & 26 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"github.com/elasticpath/epcc-cli/config"
"github.com/elasticpath/epcc-cli/external/logger"
"github.com/elasticpath/epcc-cli/external/profiles"
"github.com/elasticpath/epcc-cli/external/version"
"github.com/elasticpath/epcc-cli/globals"
log "github.com/sirupsen/logrus"
Expand All @@ -12,9 +13,7 @@ import (

"github.com/caarlos0/env/v6"
"github.com/elasticpath/epcc-cli/external/json"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

func init() {
Expand All @@ -35,6 +34,7 @@ func init() {
Logs,
resourceListCommand,
aliasesCmd,
configure,
login,
logout,
)
Expand All @@ -47,8 +47,10 @@ func init() {
enumflag.New(&logger.Loglevel, "log", logger.LoglevelIds, enumflag.EnumCaseInsensitive),
"log",
"sets logging level; can be 'trace', 'debug', 'info', 'warn', 'error', 'fatal', 'panic'")

RootCmd.PersistentFlags().BoolVarP(&json.MonochromeOutput, "monochrome-output", "M", false, "By default, epcc will output using colors if the terminal supports this. Use this option to disable it.")
RootCmd.PersistentFlags().StringSliceVarP(&globals.RawHeaders, "header", "H", []string{}, "Extra headers and values to include in the request when sending HTTP to a server. You may specify any number of extra headers.")
RootCmd.PersistentFlags().StringVarP(&config.Profile, "profile", "P", "", "overrides the current EPCC_PROFILE var to run the command with the chosen profile.")

aliasesCmd.AddCommand(aliasListCmd, aliasClearCmd)
}
Expand Down Expand Up @@ -84,31 +86,16 @@ func Execute() {
}

func initConfig() {
// Don't forget to read config either from cfgFile or from home directory!
cfgFile := ""
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
log.Errorf("Error %s", err)
os.Exit(1)
if config.Profile == "" {
envProfile, present := os.LookupEnv("EPCC_PROFILE")
if !present {
//creates configfile is this is users first time running app
profiles.GetProfilePath()
log.Println("profile tag and EPCC_PROFILE variable are absent")
return
}

// Search config in home directory with name ".cobra" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".epcc")
config.Profile = envProfile
}
config.Envs = profiles.GetProfile(config.Profile)

if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; ignore error if desired
} else {
log.Errorf("Can't read config %s", err)
os.Exit(1)
}

}
}
2 changes: 1 addition & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ type Env struct {
EPCC_CLIENT_ID string `env:"EPCC_CLIENT_ID"`
EPCC_CLIENT_SECRET string `env:"EPCC_CLIENT_SECRET"`
EPCC_BETA_API_FEATURES string `env:"EPCC_BETA_API_FEATURES"`
EPCC_PROFILE string `env:"EPCC_PROFILE"`
}

var Envs = &Env{}
var Profile string
77 changes: 40 additions & 37 deletions external/profiles/profiles.go
Original file line number Diff line number Diff line change
@@ -1,57 +1,60 @@
package profiles

import (
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/elasticpath/epcc-cli/config"
log "github.com/sirupsen/logrus"
"net/url"
"gopkg.in/ini.v1"
"os"
"path/filepath"
)

func GetProfileName() string {
if config.Envs.EPCC_PROFILE != "" {
log.Tracef("Using EPCC_PROFILE value for profile %s", config.Envs.EPCC_PROFILE)
return config.Envs.EPCC_PROFILE
} else {
u, err := url.Parse(config.Envs.EPCC_API_BASE_URL)
profileName := ""
if err != nil {
result := newSHA256([]byte(config.Envs.EPCC_CLIENT_ID + ":" + config.Envs.EPCC_API_BASE_URL))
profileName = hex.EncodeToString(result)
} else {
profileName = fmt.Sprintf("%s-%s", u.Host, config.Envs.EPCC_CLIENT_ID)
}
//profile name is set to config.Profile in InitConfig

log.Tracef("Using auto generated profile name %s", profileName)

return profileName
func GetProfileDirectory() string {
home, err := os.UserHomeDir()
if err != nil {
log.Errorf("could not get home directory")
os.Exit(1)
}
configDir := home + "/.epcc/profiles_data"
configDir = filepath.FromSlash(configDir)
//built in check if dir exists
if err = os.MkdirAll(configDir, 0700); err != nil {
log.Errorf("could not make directory")
}
}

func GetProfileDirectory() string {
profileDir := GetProfileDataBaseURL() + GetProfileName()
return configDir
}

log.Tracef("Creating profile directory %s", profileDir)
if err := os.MkdirAll(profileDir, 0700); err != nil {
panic(fmt.Sprintf("Could not create home directory %v", err))
func GetProfilePath() string {
configPath := GetProfileDirectory()
configPath = filepath.FromSlash(configPath + "/config")
if _, err := os.Stat(configPath); err != nil {
log.Trace("could not find file at " + configPath)
file, err := os.Create(configPath)
defer file.Close()
if err != nil {
log.Errorf("could not create file at " + configPath)
}
log.Trace("creating config file at " + configPath)
}

return profileDir
return configPath
}

func GetProfileDataBaseURL() string {
homeDir, err := os.UserHomeDir()
func GetProfile(name string) *config.Env {
result := config.Env{}
configPath := GetProfilePath()
cfg, err := ini.Load(configPath)
if err != nil {
panic(fmt.Sprintf("Could not get user hoem directory home directory %v", err))
log.Errorf("could not load file at " + configPath)
os.Exit(1)
}
if !cfg.HasSection(name) {
log.Errorf("could not find profile in file")
os.Exit(1)
}
cfg.Section(name).MapTo(&result)
return &result

return homeDir + "/.epcc/profiles_data/"
}

// NewSHA256 ...
func newSHA256(data []byte) []byte {
hash := sha256.Sum256(data)
return hash[:]
}