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
7 changes: 3 additions & 4 deletions cmd/commercemanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
"fmt"
"github.com/elasticpath/epcc-cli/config"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"net/url"
"os/exec"
Expand All @@ -27,8 +28,7 @@ var cmCommand = &cobra.Command{
}

if cmUrl == "" {
fmt.Printf("Don't know where Commerce Manager is for $EPCC_API_BASE_URL=%s \n", u)
return err
return fmt.Errorf("Don't know where Commerce Manager is for $EPCC_API_BASE_URL=%s \n", u)
}

switch runtime.GOOS {
Expand All @@ -43,11 +43,10 @@ var cmCommand = &cobra.Command{
}

if err != nil {
fmt.Println(err)
return err
}

fmt.Printf("Opening browser to %s", cmUrl)
log.Tracef("Opening browser to %s", cmUrl)

return nil
},
Expand Down
17 changes: 8 additions & 9 deletions cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ var get = &cobra.Command{
idCount = strings.Count(resourceURL, "%")
} else {
// Count ids in get-collection
resourceURL := resource.GetCollectionInfo.Url
resourceURL = resource.GetCollectionInfo.Url
idCount = strings.Count(resourceURL, "%")

// Determine if call should be get-collection or get-entity
Expand All @@ -65,26 +65,25 @@ var get = &cobra.Command{
}

// Submit request
resp, err := httpclient.DoRequest(context.TODO(), "GET", "/v2/"+args[0], params.Encode(), nil)
resp, err := httpclient.DoRequest(context.TODO(), "GET", resourceURL, params.Encode(), nil)

if err != nil {
return fmt.Errorf("Got error %s", err.Error())
}
defer resp.Body.Close()

// Check if error response
if resp.StatusCode >= 400 && resp.StatusCode <= 600 {
return fmt.Errorf(resp.Status)
}

// Print the body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}

json.PrintJson(string(body))
// Check if error response
if resp.StatusCode >= 400 && resp.StatusCode <= 600 {
json.PrintJson(string(body))
return fmt.Errorf(resp.Status)
}

return nil
return json.PrintJson(string(body))
},
}
20 changes: 16 additions & 4 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package cmd

import (
"fmt"
"github.com/elasticpath/epcc-cli/config"
"github.com/elasticpath/epcc-cli/external/logger"
log "github.com/sirupsen/logrus"
"github.com/thediveo/enumflag"
"os"

"github.com/caarlos0/env/v6"
Expand All @@ -28,7 +30,13 @@ func init() {
)

testJson.Flags().BoolVarP(&noWrapping, "no-wrapping", "", false, "if set, we won't wrap the output the json in a data tag")

rootCmd.PersistentFlags().Var(
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.")

}

var rootCmd = &cobra.Command{
Expand All @@ -47,11 +55,15 @@ 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) {
log.SetLevel(logger.Loglevel)
},
SilenceUsage: true,
}

func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
log.Errorf("Error occured while processing command %s", err)
os.Exit(1)
}
}
Expand All @@ -66,7 +78,7 @@ func initConfig() {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
log.Errorf("Error %s", err)
os.Exit(1)
}

Expand All @@ -79,7 +91,7 @@ func initConfig() {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; ignore error if desired
} else {
fmt.Println("Can't read config:", err)
log.Errorf("Can't read config %s", err)
os.Exit(1)
}

Expand Down
5 changes: 3 additions & 2 deletions external/authentication/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import (
"fmt"
"github.com/elasticpath/epcc-cli/config"
"github.com/elasticpath/epcc-cli/external/version"
"log"
log "github.com/sirupsen/logrus"

"net/http"
"net/url"
"strings"
Expand Down Expand Up @@ -96,6 +97,6 @@ func auth() (string, error) {
return "", err
}

log.Println("authentication successful")
log.Trace("Authentication successful")
return authResponse.AccessToken, nil
}
11 changes: 10 additions & 1 deletion external/httpclient/httpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/elasticpath/epcc-cli/config"
"github.com/elasticpath/epcc-cli/external/authentication"
"github.com/elasticpath/epcc-cli/external/version"
log "github.com/sirupsen/logrus"
"io"
"mime/multipart"
"net/http"
Expand Down Expand Up @@ -57,7 +58,15 @@ func doRequestInternal(ctx context.Context, method string, contentType string, p
req.Header.Add("EP-Beta-Features", config.Envs.EPCC_BETA_API_FEATURES)
}

return HttpClient.Do(req)
resp, err := HttpClient.Do(req)

if resp.StatusCode > 400 {
log.Warnf("%s %s ==> %s %s", method, reqURL.String(), resp.Proto, resp.Status)
} else if resp.StatusCode >= 200 && resp.StatusCode <= 399 {
log.Infof("%s %s ==> %s %s", method, reqURL.String(), resp.Proto, resp.Status)
}

return resp, err
}

// https://stackoverflow.com/questions/20205796/post-data-using-the-content-type-multipart-form-data
Expand Down
76 changes: 55 additions & 21 deletions external/json/encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,21 @@ import (
"runtime"
"sort"
"strconv"
"strings"
"unicode/utf8"
)

// This whole file is 98% based on being copied from https://github.com/itchyny/gojq/blob/main/cli/encoder.go
// https://github.com/itchyny/gojq/blob/main/cli/color.go

type encoder struct {
out io.Writer
w *bytes.Buffer
tab bool
indent int
depth int
buf [64]byte
out io.Writer
w *bytes.Buffer
tab bool
indent int
depth int
buf [64]byte
keyStack []string
}

type colorInfo struct {
Expand Down Expand Up @@ -65,6 +67,36 @@ func newColor(unix string, win wincolor.Color, winReset bool) colorInfo {
}
}

var unimportantPrefixes = map[string]bool{
"data": true,
"data.attributes": true,
"data.links": true,
"links": true,
"links.current": true,
"links.first": true,
"links.last": true,
"links.next": true,
"links.prev": true,
"meta": true,
"meta.page": true,
"meta.page.current": true,
"meta.page.limit": true,
"meta.page.offset": true,
"meta.page.total": true,
"meta.results.total": true,
"meta.results": true,
}

var importantPrefixes = map[string]bool{}

var urgentPrefixes = map[string]bool{
"errors.id": true,
"errors.status": true,
"errors.detail": true,
"errors.title": true,
"errors": true,
}

var (
resetColor = newColor("0", wincolor.FgDefault, true) // Reset
nullColor = newColor("90", wincolor.FgLightWhite, false) // Bright black
Expand Down Expand Up @@ -267,33 +299,35 @@ func (e *encoder) encodeMap(vs map[string]interface{}) {
e.writeIndent()
}

old := e.keyStack
e.keyStack = append(e.keyStack, kv.key)

prefix := strings.Join(e.keyStack, ".")

keyColorToUse := objectKeyColor
switch kv.key {
case "data":
fallthrough
case "id":
fallthrough
case "attributes":
fallthrough
case "type":

if _, ok := unimportantPrefixes[prefix]; ok {
keyColorToUse = unimportantObjectKeyColor
case "name":
fallthrough
case "email":
}

if _, ok := importantPrefixes[prefix]; ok {
keyColorToUse = importantObjectKeyColor
case "error":
fallthrough
case "errors":
keyColorToUse = urgentObjectKeyColor
}

if _, ok := urgentPrefixes[prefix]; ok {
keyColorToUse = urgentObjectKeyColor
}

e.encodeString(kv.key, &keyColorToUse)
e.writeByte(':', &objectColor)
if e.indent != 0 {
e.w.WriteByte(' ')
}

e.encode(kv.val)

e.keyStack = old

}
e.depth -= e.indent
if len(vs) > 0 && e.indent != 0 {
Expand Down
23 changes: 23 additions & 0 deletions external/logger/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package logger

import (
log "github.com/sirupsen/logrus"
"os"
)

// ③ Map 3rd party enumeration values to their textual representations
var LoglevelIds = map[log.Level][]string{
log.TraceLevel: {"trace"},
log.DebugLevel: {"debug"},
log.InfoLevel: {"info"},
log.WarnLevel: {"warning", "warn"},
log.ErrorLevel: {"error"},
log.FatalLevel: {"fatal"},
log.PanicLevel: {"panic"},
}

var Loglevel log.Level = log.InfoLevel

func init() {
log.SetOutput(os.Stderr)
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/itchyny/gojq v0.12.7
github.com/mattn/go-isatty v0.0.14
github.com/mitchellh/go-homedir v1.1.0
github.com/sirupsen/logrus v1.8.1
github.com/spf13/cobra v1.4.0
github.com/spf13/viper v1.10.1
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
Expand All @@ -26,6 +27,7 @@ require (
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/thediveo/enumflag v0.10.1 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
golang.org/x/sys v0.0.0-20220330033206-e17cdc41300f // indirect
golang.org/x/text v0.3.7 // indirect
Expand Down
Loading