Skip to content

Commit

Permalink
Resolves #126 #116 #122- Store logs under profile directory. (#127)
Browse files Browse the repository at this point in the history
Additional tweaks:
* Build an artifact in the pipeline
* Tweak version number login (#122)
* Tweak http log sanitization
* Refactor shared package away
* Tweak profile handling logic
  • Loading branch information
steve-r-west authored Apr 13, 2022
1 parent a74b0c2 commit cd89f50
Show file tree
Hide file tree
Showing 17 changed files with 306 additions and 180 deletions.
18 changes: 12 additions & 6 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,18 @@ jobs:
run: |
go test -v -cover ./cmd/ ./external/...
- name: Run GoReleaser
- name: Run GoReleaser (for Linux build and Syntax check)
uses: goreleaser/goreleaser-action@v2
env:
GOOS: linux
GOARCH: amd64
with:
version: latest
args: check
env:
GPG_FINGERPRINT: ${{ steps.import_gpg.outputs.fingerprint }}
# GitHub sets this automatically
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
args: build --single-target --snapshot

- name: 'Upload Artifact'
uses: actions/upload-artifact@v3
with:
name: distribution
path: dist/epcc-cli_linux_amd64
retention-days: 5
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,4 @@ bin
dist/
epcc-cli
epcc
profiles
.envrc
2 changes: 1 addition & 1 deletion .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ builds:
flags:
- -trimpath
ldflags:
- '-s -w -X version.version={{.Version}} -X version.commit={{.Commit}}'
- '-s -w -X github.com/elasticpath/epcc-cli/external/version.Version={{.Version}} -X github.com/elasticpath/epcc-cli/external/version.Commit={{.Commit}}'
goos:
- freebsd
- windows
Expand Down
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,4 +202,11 @@ INFO[0001] PUT https://api.moltin.com/v2/customers/8f720da2-37d1-41b7-94da-3fd35
7. Copying and pasting is terrible and as a result epcc-cli has a few ways of ameliorating the experience of working with ids.
To update the customer without the id, you can use an alias `last_customer` (and this will auto complete). For example `epcc update customer last_customer name "Jonah Smith"`
STEVE WILL FIX
## Development Tips
```bash
git fetch --all --tags && reflex -v -r '(\.go$)|(resources.yaml|go.mod)$' -- sh -c "go build -ldflags=\"-X github.com/elasticpath/epcc-cli/external/version.Version=$(git describe --tags --abbrev=0)+1 -X github.com/elasticpath/epcc-cli/external/version.Commit=$(git rev-parse --short HEAD)-dirty\" -o ./epcc"
```
4 changes: 2 additions & 2 deletions cmd/commercemanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package cmd
import (
"fmt"
"github.com/elasticpath/epcc-cli/config"
"github.com/elasticpath/epcc-cli/shared"
"github.com/elasticpath/epcc-cli/external/browser"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"net/url"
Expand All @@ -29,7 +29,7 @@ var cmCommand = &cobra.Command{
return fmt.Errorf("Don't know where Commerce Manager is for $EPCC_API_BASE_URL=%s \n", u)
}

err = shared.OpenUrl(cmUrl)
err = browser.OpenUrl(cmUrl)
if err != nil {
return err
}
Expand Down
4 changes: 1 addition & 3 deletions cmd/configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ var configure = &cobra.Command{
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()
configPath := profiles.GetConfigFilePath()
cfg, err := ini.Load(configPath)
if err != nil {
log.Errorf("error loading to file " + configPath)
Expand Down Expand Up @@ -49,8 +49,6 @@ var configure = &cobra.Command{
os.Exit(1)
}
config.Envs = &newProfile
config.Profile = text

},
}

Expand Down
14 changes: 7 additions & 7 deletions cmd/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package cmd

import (
"fmt"
"github.com/elasticpath/epcc-cli/external/browser"
"github.com/elasticpath/epcc-cli/external/completion"
"github.com/elasticpath/epcc-cli/external/resources"
"github.com/elasticpath/epcc-cli/shared"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -52,32 +52,32 @@ func openDoc(resourceDoc resources.Resource, verb string) error {
if len(resourceDoc.Docs) < 1 {
err = doDefault()
}
err = shared.OpenUrl(resourceDoc.Docs)
err = browser.OpenUrl(resourceDoc.Docs)
case "get-collection":
if resourceDoc.GetCollectionInfo != nil && len(resourceDoc.GetCollectionInfo.Docs) < 1 {
err = doDefault()
}
err = shared.OpenUrl(resourceDoc.GetCollectionInfo.Docs)
err = browser.OpenUrl(resourceDoc.GetCollectionInfo.Docs)
case "get":
if resourceDoc.GetEntityInfo != nil && len(resourceDoc.GetEntityInfo.Docs) < 1 {
err = doDefault()
}
err = shared.OpenUrl(resourceDoc.GetEntityInfo.Docs)
err = browser.OpenUrl(resourceDoc.GetEntityInfo.Docs)
case "update":
if resourceDoc.UpdateEntityInfo != nil && len(resourceDoc.UpdateEntityInfo.Docs) < 1 {
err = doDefault()
}
err = shared.OpenUrl(resourceDoc.UpdateEntityInfo.Docs)
err = browser.OpenUrl(resourceDoc.UpdateEntityInfo.Docs)
case "delete":
if resourceDoc.DeleteEntityInfo != nil && len(resourceDoc.DeleteEntityInfo.Docs) < 1 {
err = doDefault()
}
err = shared.OpenUrl(resourceDoc.DeleteEntityInfo.Docs)
err = browser.OpenUrl(resourceDoc.DeleteEntityInfo.Docs)
case "create":
if resourceDoc.CreateEntityInfo != nil && len(resourceDoc.CreateEntityInfo.Docs) < 1 {
err = doDefault()
}
err = shared.OpenUrl(resourceDoc.CreateEntityInfo.Docs)
err = browser.OpenUrl(resourceDoc.CreateEntityInfo.Docs)
default:
return fmt.Errorf("Could not find verb %s", verb)

Expand Down
44 changes: 23 additions & 21 deletions cmd/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,30 @@ package cmd

import (
"fmt"
"github.com/elasticpath/epcc-cli/shared"
"github.com/elasticpath/epcc-cli/external/profiles"
"github.com/spf13/cobra"
"os"
"strings"
"strconv"
)

var LogsClear = &cobra.Command{
Use: "clear",
Short: "Clears all HTTP request and response logs",
RunE: func(cmd *cobra.Command, args []string) error {
os.RemoveAll(shared.LogDirectory)
return nil
return profiles.ClearAllRequestLogs()
},
}

var LogsList = &cobra.Command{
Use: "list",
Short: "List all HTTP logs",
RunE: func(cmd *cobra.Command, args []string) error {
files := shared.AllFilesSortedByDate(shared.LogDirectory)
for i := 0; i < len(files); i++ {
name, _ := shared.Base64DecodeStripped(files[i].Name())
fmt.Println(name)
files, err := profiles.GetAllRequestLogTitles()
if err != nil {
return err
}

for idx, name := range files {
fmt.Printf("%d %s\n", idx, name)
}
return nil
},
Expand All @@ -35,20 +36,21 @@ var LogsShow = &cobra.Command{
Short: "Show HTTP logs for specific number",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
files := shared.AllFilesSortedByDate(shared.LogDirectory)
for i := 0; i < len(files); i++ {
name, _ := shared.Base64DecodeStripped(files[i].Name())
segments := strings.Split(name, " ")
if segments[0] == args[0] {
content, err := os.ReadFile(shared.LogDirectory + "/" + files[i].Name())
if err != nil {
return err
}
fmt.Print(string(content))
break
}

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
},
}
Expand Down
22 changes: 10 additions & 12 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func init() {

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.")
RootCmd.PersistentFlags().StringVarP(&profiles.ProfileName, "profile", "P", "default", "overrides the current EPCC_PROFILE var to run the command with the chosen profile.")

aliasesCmd.AddCommand(aliasListCmd, aliasClearCmd)
}
Expand Down Expand Up @@ -92,7 +92,7 @@ Environment Variables
},

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

func Execute() {
Expand All @@ -103,16 +103,14 @@ func Execute() {
}

func initConfig() {
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
}
config.Profile = envProfile
envProfileName, ok := os.LookupEnv("EPCC_PROFILE")
if ok {
profiles.ProfileName = envProfileName
}
config.Envs = profiles.GetProfile(config.Profile)
config.Envs = profiles.GetProfile(profiles.ProfileName)

// Override profile configuration with environment variables
if err := env.Parse(config.Envs); err != nil {
panic("Could not parse environment variables")
}
}
1 change: 0 additions & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,3 @@ type Env struct {
}

var Envs = &Env{}
var Profile string
4 changes: 2 additions & 2 deletions external/aliases/aliases.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
var filelock = sync.Mutex{}

func GetAliasesForJsonApiType(jsonApiType string) map[string]string {
profileDirectory := profiles.GetProfileDirectory()
profileDirectory := profiles.GetProfileDataDirectory()
aliasFile := getDirectoryForJsonApiType(profileDirectory, jsonApiType)

aliasMap := map[string]string{}
Expand Down Expand Up @@ -59,7 +59,7 @@ func SaveAliasesForResources(jsonTxt string) {

log.Tracef("All aliases: %s", results)

profileDirectory := profiles.GetProfileDirectory()
profileDirectory := profiles.GetProfileDataDirectory()
for resourceType, aliases := range results {
saveAliasesForResource(profileDirectory, resourceType, aliases)
}
Expand Down
10 changes: 10 additions & 0 deletions external/authentication/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import (
"encoding/json"
"fmt"
"github.com/elasticpath/epcc-cli/config"
"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"
"net/http/httputil"
"os"

"net/http"
Expand Down Expand Up @@ -107,11 +109,19 @@ func auth() (string, error) {
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("User-Agent", fmt.Sprintf("epcc-cli/%s-%s", version.Version, version.Commit))

dumpReq, err := httputil.DumpRequestOut(req, true)
if err != nil {
log.Errorf("error %v", err)
}

resp, err := HttpClient.Do(req)
if err != nil {
return "", err
}

dumpRes, _ := httputil.DumpResponse(resp, true)

profiles.LogRequestToDisk("POST", req.URL.Path, dumpReq, dumpRes, resp.StatusCode)
if resp.StatusCode != 200 {
return "", fmt.Errorf("error: unexpected status %s", resp.Status)
}
Expand Down
22 changes: 22 additions & 0 deletions external/browser/browser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package browser

import (
"fmt"
"os/exec"
"runtime"
)

func OpenUrl(url string) error {
switch runtime.GOOS {
case "linux":
exec.Command("xdg-open", url).Start()
case "windows":
exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
exec.Command("open", url).Start()
default:
return fmt.Errorf("unsupported platform")
}

return nil
}
Loading

0 comments on commit cd89f50

Please sign in to comment.