From bbda4def1ac6f7fba1d06cd017833866ec238f0c Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Wed, 15 Jul 2020 08:57:12 -0300 Subject: [PATCH 01/27] added command --- pkg/cmd/list_credential.go | 65 +++++++++++++++++++++++++++++ pkg/cmd/list_credential_test.go | 1 + pkg/cmd/set_credential.go | 36 ++-------------- pkg/formula/runner/default_setup.go | 9 ++-- 4 files changed, 73 insertions(+), 38 deletions(-) create mode 100644 pkg/cmd/list_credential.go create mode 100644 pkg/cmd/list_credential_test.go diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go new file mode 100644 index 000000000..ce1627c01 --- /dev/null +++ b/pkg/cmd/list_credential.go @@ -0,0 +1,65 @@ +package cmd + +import ( + "fmt" + + "github.com/gosuri/uitable" + "github.com/spf13/cobra" + + "github.com/ZupIT/ritchie-cli/pkg/credential" + "github.com/ZupIT/ritchie-cli/pkg/credential/credsingle" + "github.com/ZupIT/ritchie-cli/pkg/prompt" +) + +type listCredentialCmd struct { + credential.SingleSettings +} + +func NewListCredentialCmd( + ss credential.SingleSettings) *cobra.Command { + l := &listCredentialCmd{ss} + + cmd := &cobra.Command{ + Use: "credential", + Short: "List all credential names and fields.", + Example: "rit list credential", + RunE: l.run(), + } + + return cmd +} + +func printCredentialsTable(fields credential.Fields) { + table := uitable.New() + table.AddRow(prompt.Bold("CONTEXT"), prompt.Bold("PROVIDER"), prompt.Bold("NAME"), prompt.Bold("CREDENTIAL")) + switchColor := true + for c := range fields { + provider := fields[c] + for _, p := range provider { + if switchColor { + table.AddRow(c, p.Name) + switchColor = false + } else { + table.AddRow(prompt.Cyan(c), prompt.Cyan(p.Name)) + switchColor = true + } + + } + + } + fmt.Println(table) +} + + + +func (l listCredentialCmd) run() CommandRunnerFunc { + return func(cmd *cobra.Command, args []string) error { + data, err := l.ReadCredentials(credsingle.ProviderPath()) + if err != nil { + return err + } + + printCredentialsTable(data) + return nil + } +} \ No newline at end of file diff --git a/pkg/cmd/list_credential_test.go b/pkg/cmd/list_credential_test.go new file mode 100644 index 000000000..1d619dd05 --- /dev/null +++ b/pkg/cmd/list_credential_test.go @@ -0,0 +1 @@ +package cmd diff --git a/pkg/cmd/set_credential.go b/pkg/cmd/set_credential.go index 40d830d00..67e385888 100644 --- a/pkg/cmd/set_credential.go +++ b/pkg/cmd/set_credential.go @@ -71,8 +71,8 @@ func (s setCredentialCmd) runPrompt() CommandRunnerFunc { } func (s setCredentialCmd) prompt() (credential.Detail, error) { - err := s.WriteDefaultCredentials(credsingle.ProviderPath()) - if err != nil { + + if err := s.WriteDefaultCredentials(credsingle.ProviderPath()); err != nil { return credential.Detail{}, err } @@ -118,8 +118,7 @@ func (s setCredentialCmd) prompt() (credential.Detail, error) { } } credentials[newProvider] = newFields - err = s.WriteCredentials(credentials, credsingle.ProviderPath()) - if err != nil { + if err = s.WriteCredentials(credentials, credsingle.ProviderPath()); err != nil { return credDetail, err } @@ -136,7 +135,7 @@ func (s setCredentialCmd) prompt() (credential.Detail, error) { return credDetail, err } } else { - value, err = s.Text(i.Name, true) + value, err = s.Text(i.Name+":", true) if err != nil { return credDetail, err } @@ -174,30 +173,3 @@ func (s setCredentialCmd) stdinResolver() (credential.Detail, error) { } return credDetail, nil } - -func (s setCredentialCmd) profile(credDetail *credential.Detail) error { - profiles := map[string]credential.Type{ - "ME (for you)": credential.Me, - "OTHER (for another user)": credential.Other, - "ORG (for the organization)": credential.Org, - } - var types []string - for k := range profiles { - types = append(types, k) - } - - typ, err := s.List("Profile to add credential: ", types) - if err != nil { - return err - } - - if profiles[typ] == credential.Other { - credDetail.Username, err = s.Text("Username: ", true) - if err != nil { - return err - } - } - - credDetail.Type = profiles[typ] - return nil -} diff --git a/pkg/formula/runner/default_setup.go b/pkg/formula/runner/default_setup.go index 5d3e49f17..a5d1de8e1 100644 --- a/pkg/formula/runner/default_setup.go +++ b/pkg/formula/runner/default_setup.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io/ioutil" - "net/http" "os" "os/exec" @@ -15,8 +14,8 @@ import ( ) var ( - ErrFormulaBinNotFound = prompt.NewError("formula bin not found") - ErrConfigFileNotFound = prompt.NewError("config file not found") + ErrFormulaBinNotFound = prompt.NewError("formula bin not found") + ErrConfigFileNotFound = prompt.NewError("config file not found") ) const ( @@ -27,13 +26,11 @@ const ( type DefaultSetup struct { ritchieHome string - client *http.Client } -func NewDefaultSetup(ritchieHome string, c *http.Client) DefaultSetup { +func NewDefaultSetup(ritchieHome string) DefaultSetup { return DefaultSetup{ ritchieHome: ritchieHome, - client: c, } } From 1450cb6f4bc38c5ab33c126b44ea78f0757f9cf0 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Wed, 15 Jul 2020 08:57:44 -0300 Subject: [PATCH 02/27] add hide credential --- pkg/cmd/list_credential.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index ce1627c01..9a0185bf4 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -29,6 +29,18 @@ func NewListCredentialCmd( return cmd } +func hideCredential(credential string) string { + noHiddenChars := len(credential) / 3 + var hiddenCredential []rune + for i, r := range credential { + if i < len(credential)-noHiddenChars { + r ='*' + } + hiddenCredential = append(hiddenCredential, r) + } + return string(hiddenCredential) +} + func printCredentialsTable(fields credential.Fields) { table := uitable.New() table.AddRow(prompt.Bold("CONTEXT"), prompt.Bold("PROVIDER"), prompt.Bold("NAME"), prompt.Bold("CREDENTIAL")) From 995cb311a2a2cccec1a9e609ea9ae92e09991082 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Wed, 15 Jul 2020 09:44:07 -0300 Subject: [PATCH 03/27] change credential structure --- cmd/main.go | 11 ++- pkg/cmd/list_credential.go | 8 +- pkg/cmd/list_credential_test.go | 13 +++ pkg/cmd/set_credential.go | 20 ++--- pkg/credential/credsingle/credsingle_test.go | 36 -------- pkg/credential/{credsingle => find}/finder.go | 4 +- .../{credsingle => find}/finder_test.go | 11 +-- pkg/credential/{credsingle => }/path.go | 2 +- pkg/credential/{credsingle => set}/setter.go | 6 +- .../{credsingle => set}/setter_test.go | 6 +- .../{credsingle => set}/settings.go | 2 +- .../{credsingle => set}/settings_test.go | 2 +- pkg/crypto/cryptoutil/crypto_util.go | 85 ------------------- pkg/crypto/cryptoutil/crypto_util_test.go | 29 ------- pkg/env/envcredential/env_credential.go | 6 +- pkg/formula/runner/docker_runner.go | 1 - pkg/formula/runner/inputs.go | 2 + pkg/prompt/color.go | 4 + 18 files changed, 60 insertions(+), 188 deletions(-) delete mode 100644 pkg/credential/credsingle/credsingle_test.go rename pkg/credential/{credsingle => find}/finder.go (89%) rename pkg/credential/{credsingle => find}/finder_test.go (74%) rename pkg/credential/{credsingle => }/path.go (94%) rename pkg/credential/{credsingle => set}/setter.go (86%) rename pkg/credential/{credsingle => set}/setter_test.go (81%) rename pkg/credential/{credsingle => set}/settings.go (99%) rename pkg/credential/{credsingle => set}/settings_test.go (99%) delete mode 100644 pkg/crypto/cryptoutil/crypto_util.go delete mode 100644 pkg/crypto/cryptoutil/crypto_util_test.go diff --git a/cmd/main.go b/cmd/main.go index 7bdd711ab..2a4ce1873 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -8,6 +8,8 @@ import ( "k8s.io/kubectl/pkg/util/templates" + "github.com/ZupIT/ritchie-cli/pkg/credential/find" + "github.com/ZupIT/ritchie-cli/pkg/credential/set" "github.com/ZupIT/ritchie-cli/pkg/formula/builder" "github.com/ZupIT/ritchie-cli/pkg/formula/creator" "github.com/ZupIT/ritchie-cli/pkg/formula/repo" @@ -23,7 +25,6 @@ import ( "github.com/ZupIT/ritchie-cli/pkg/api" "github.com/ZupIT/ritchie-cli/pkg/autocomplete" "github.com/ZupIT/ritchie-cli/pkg/cmd" - "github.com/ZupIT/ritchie-cli/pkg/credential/credsingle" "github.com/ZupIT/ritchie-cli/pkg/env" "github.com/ZupIT/ritchie-cli/pkg/env/envcredential" "github.com/ZupIT/ritchie-cli/pkg/file/fileutil" @@ -78,10 +79,10 @@ func buildCommands() *cobra.Command { ctxRemover := rcontext.NewRemover(ritchieHomeDir, ctxFinder) ctxFindSetter := rcontext.NewFindSetter(ritchieHomeDir, ctxFinder, ctxSetter) ctxFindRemover := rcontext.NewFindRemover(ritchieHomeDir, ctxFinder, ctxRemover) - credSetter := credsingle.NewSetter(ritchieHomeDir, ctxFinder) - credFinder := credsingle.NewFinder(ritchieHomeDir, ctxFinder) + credSetter := set.NewSetter(ritchieHomeDir, ctxFinder) + credFinder := find.NewFinder(ritchieHomeDir, ctxFinder) treeManager := tree.NewTreeManager(ritchieHomeDir, repoLister, api.CoreCmds) - credSettings := credsingle.NewSingleSettings(fileManager) + credSettings := set.NewSingleSettings(fileManager) autocompleteGen := autocomplete.NewGenerator(treeManager) credResolver := envcredential.NewResolver(credFinder) envResolvers := make(env.Resolvers) @@ -134,6 +135,7 @@ func buildCommands() *cobra.Command { inputBool, inputList, inputPassword) + listCredentialCmd := cmd.NewListCredentialCmd(credSettings) deleteCtxCmd := cmd.NewDeleteContextCmd(ctxFindRemover, inputBool, inputList) setCtxCmd := cmd.NewSetContextCmd(ctxFindSetter, inputText, inputList) showCtxCmd := cmd.NewShowContextCmd(ctxFinder) @@ -156,6 +158,7 @@ func buildCommands() *cobra.Command { createCmd.AddCommand(createFormulaCmd) deleteCmd.AddCommand(deleteCtxCmd, deleteRepoCmd) listCmd.AddCommand(listRepoCmd) + listCmd.AddCommand(listCredentialCmd) setCmd.AddCommand(setCredentialCmd, setCtxCmd, setPriorityCmd) showCmd.AddCommand(showCtxCmd) buildCmd.AddCommand(buildFormulaCmd) diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index 9a0185bf4..dd8dee310 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -7,16 +7,16 @@ import ( "github.com/spf13/cobra" "github.com/ZupIT/ritchie-cli/pkg/credential" - "github.com/ZupIT/ritchie-cli/pkg/credential/credsingle" + "github.com/ZupIT/ritchie-cli/pkg/credential/set" "github.com/ZupIT/ritchie-cli/pkg/prompt" ) type listCredentialCmd struct { - credential.SingleSettings + set.SingleSettings } func NewListCredentialCmd( - ss credential.SingleSettings) *cobra.Command { + ss set.SingleSettings) *cobra.Command { l := &listCredentialCmd{ss} cmd := &cobra.Command{ @@ -66,7 +66,7 @@ func printCredentialsTable(fields credential.Fields) { func (l listCredentialCmd) run() CommandRunnerFunc { return func(cmd *cobra.Command, args []string) error { - data, err := l.ReadCredentials(credsingle.ProviderPath()) + data, err := l.ReadCredentials(set.ProviderPath()) if err != nil { return err } diff --git a/pkg/cmd/list_credential_test.go b/pkg/cmd/list_credential_test.go index 1d619dd05..e03f78fdf 100644 --- a/pkg/cmd/list_credential_test.go +++ b/pkg/cmd/list_credential_test.go @@ -1 +1,14 @@ package cmd + +import "testing" + +func TestNewListCredentialCmd(t *testing.T) { + cmd := NewListCredentialCmd(singleCredSettingsMock{}) + if cmd == nil { + t.Errorf("NewListCredentialCmd got %v", cmd) + } + + if err := cmd.Execute(); err != nil { + t.Errorf("%s = %v, want %v", cmd.Use, err, nil) + } +} \ No newline at end of file diff --git a/pkg/cmd/set_credential.go b/pkg/cmd/set_credential.go index 67e385888..021284157 100644 --- a/pkg/cmd/set_credential.go +++ b/pkg/cmd/set_credential.go @@ -8,7 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/ZupIT/ritchie-cli/pkg/credential" - "github.com/ZupIT/ritchie-cli/pkg/credential/credsingle" + "github.com/ZupIT/ritchie-cli/pkg/credential/set" "github.com/ZupIT/ritchie-cli/pkg/prompt" "github.com/ZupIT/ritchie-cli/pkg/stdin" ) @@ -17,8 +17,8 @@ var inputTypes = []string{"plain text", "secret"} // setCredentialCmd type for set credential command type setCredentialCmd struct { - credential.Setter - credential.SingleSettings + set.Setter + set.SingleSettings prompt.InputText prompt.InputBool prompt.InputList @@ -27,8 +27,8 @@ type setCredentialCmd struct { // NewSetCredentialCmd creates a new cmd instance func NewSetCredentialCmd( - credSetter credential.Setter, - credSetting credential.SingleSettings, + credSetter set.Setter, + credSetting set.SingleSettings, inText prompt.InputText, inBool prompt.InputBool, inList prompt.InputList, @@ -72,25 +72,25 @@ func (s setCredentialCmd) runPrompt() CommandRunnerFunc { func (s setCredentialCmd) prompt() (credential.Detail, error) { - if err := s.WriteDefaultCredentials(credsingle.ProviderPath()); err != nil { + if err := s.WriteDefaultCredentials(set.ProviderPath()); err != nil { return credential.Detail{}, err } var credDetail credential.Detail cred := credential.Credential{} - credentials, err := s.ReadCredentials(credsingle.ProviderPath()) + credentials, err := s.ReadCredentials(set.ProviderPath()) if err != nil { return credential.Detail{}, err } - providerArr := credsingle.NewProviderArr(credentials) + providerArr := set.NewProviderArr(credentials) providerChoose, err := s.List("Select your provider", providerArr) if err != nil { return credDetail, err } - if providerChoose == credsingle.AddNew { + if providerChoose == set.AddNew { newProvider, err := s.Text("Define your provider name:", true) if err != nil { return credDetail, err @@ -118,7 +118,7 @@ func (s setCredentialCmd) prompt() (credential.Detail, error) { } } credentials[newProvider] = newFields - if err = s.WriteCredentials(credentials, credsingle.ProviderPath()); err != nil { + if err = s.WriteCredentials(credentials, set.ProviderPath()); err != nil { return credDetail, err } diff --git a/pkg/credential/credsingle/credsingle_test.go b/pkg/credential/credsingle/credsingle_test.go deleted file mode 100644 index 08a04ab25..000000000 --- a/pkg/credential/credsingle/credsingle_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package credsingle - -import ( - "os" - "testing" - - "github.com/ZupIT/ritchie-cli/pkg/credential" - "github.com/ZupIT/ritchie-cli/pkg/rcontext" -) - -var ( - githubCred credential.Detail - ctxFinder rcontext.Finder -) - -type ctxFinderMock struct{} - -func (ctxFinderMock) Find() (holder rcontext.ContextHolder, err error) { - return rcontext.ContextHolder{}, nil -} - -func TestMain(m *testing.M) { - githubCred = credential.Detail{ - Username: "dennis.ritchie", - Credential: credential.Credential{ - "username": "dennis.ritchie", - "password": "unix@clang", - }, - Service: "github", - } - - ctxFinder = ctxFinderMock{} - - e := m.Run() - os.Exit(e) -} diff --git a/pkg/credential/credsingle/finder.go b/pkg/credential/find/finder.go similarity index 89% rename from pkg/credential/credsingle/finder.go rename to pkg/credential/find/finder.go index 406a1dabe..b91256050 100644 --- a/pkg/credential/credsingle/finder.go +++ b/pkg/credential/find/finder.go @@ -1,4 +1,4 @@ -package credsingle +package find import ( "encoding/json" @@ -28,7 +28,7 @@ func (f Finder) Find(provider string) (credential.Detail, error) { ctx.Current = rcontext.DefaultCtx } - cb, err := fileutil.ReadFile(File(f.homePath, ctx.Current, provider)) + cb, err := fileutil.ReadFile(credential.File(f.homePath, ctx.Current, provider)) if err != nil { return credential.Detail{}, err } diff --git a/pkg/credential/credsingle/finder_test.go b/pkg/credential/find/finder_test.go similarity index 74% rename from pkg/credential/credsingle/finder_test.go rename to pkg/credential/find/finder_test.go index 787d60ce1..0b7a79ec0 100644 --- a/pkg/credential/credsingle/finder_test.go +++ b/pkg/credential/find/finder_test.go @@ -1,4 +1,4 @@ -package credsingle +package find import ( "fmt" @@ -7,17 +7,18 @@ import ( "testing" "github.com/ZupIT/ritchie-cli/pkg/credential" + "github.com/ZupIT/ritchie-cli/pkg/credential/set" ) func TestFind(t *testing.T) { tmp := os.TempDir() - setter := NewSetter(tmp, ctxFinder, sessManager) - err := setter.Set(githubCred) + setter := set.NewSetter(tmp, credential.ctxFinder, sessManager) + err := setter.Set(credential.githubCred) if err != nil { fmt.Sprintln("Error in Set") return } - finder := NewFinder(tmp, ctxFinder, sessManager) + finder := NewFinder(tmp, credential.ctxFinder, sessManager) type out struct { cred credential.Detail @@ -33,7 +34,7 @@ func TestFind(t *testing.T) { name: "github", in: "github", out: out{ - cred: githubCred, + cred: credential.githubCred, err: nil, }, }, diff --git a/pkg/credential/credsingle/path.go b/pkg/credential/path.go similarity index 94% rename from pkg/credential/credsingle/path.go rename to pkg/credential/path.go index 9edf33610..f95788b93 100644 --- a/pkg/credential/credsingle/path.go +++ b/pkg/credential/path.go @@ -1,4 +1,4 @@ -package credsingle +package credential import ( "fmt" diff --git a/pkg/credential/credsingle/setter.go b/pkg/credential/set/setter.go similarity index 86% rename from pkg/credential/credsingle/setter.go rename to pkg/credential/set/setter.go index 3fb6e2e10..38b0f1bdd 100644 --- a/pkg/credential/credsingle/setter.go +++ b/pkg/credential/set/setter.go @@ -1,4 +1,4 @@ -package credsingle +package set import ( "encoding/json" @@ -33,12 +33,12 @@ func (s Setter) Set(cred credential.Detail) error { return err } - dir := Dir(s.homePath, ctx.Current) + dir := credential.Dir(s.homePath, ctx.Current) if err := fileutil.CreateDirIfNotExists(dir, 0700); err != nil { return err } - credFile := File(s.homePath, ctx.Current, cred.Service) + credFile := credential.File(s.homePath, ctx.Current, cred.Service) if err := fileutil.WriteFilePerm(credFile, cb, 0600); err != nil { return err } diff --git a/pkg/credential/credsingle/setter_test.go b/pkg/credential/set/setter_test.go similarity index 81% rename from pkg/credential/credsingle/setter_test.go rename to pkg/credential/set/setter_test.go index 80a7c43fb..0500e9aff 100644 --- a/pkg/credential/credsingle/setter_test.go +++ b/pkg/credential/set/setter_test.go @@ -1,4 +1,4 @@ -package credsingle +package set import ( "os" @@ -9,7 +9,7 @@ import ( func TestSet(t *testing.T) { tmp := os.TempDir() - setter := NewSetter(tmp, ctxFinder, sessManager) + setter := NewSetter(tmp, credential.ctxFinder, sessManager) tests := []struct { name string @@ -18,7 +18,7 @@ func TestSet(t *testing.T) { }{ { name: "github credential", - in: githubCred, + in: credential.githubCred, out: nil, }, } diff --git a/pkg/credential/credsingle/settings.go b/pkg/credential/set/settings.go similarity index 99% rename from pkg/credential/credsingle/settings.go rename to pkg/credential/set/settings.go index 65be0deed..c3bc118da 100644 --- a/pkg/credential/credsingle/settings.go +++ b/pkg/credential/set/settings.go @@ -1,4 +1,4 @@ -package credsingle +package set import ( "encoding/json" diff --git a/pkg/credential/credsingle/settings_test.go b/pkg/credential/set/settings_test.go similarity index 99% rename from pkg/credential/credsingle/settings_test.go rename to pkg/credential/set/settings_test.go index 159511aeb..2f14ebf00 100644 --- a/pkg/credential/credsingle/settings_test.go +++ b/pkg/credential/set/settings_test.go @@ -1,4 +1,4 @@ -package credsingle +package set import ( "fmt" diff --git a/pkg/crypto/cryptoutil/crypto_util.go b/pkg/crypto/cryptoutil/crypto_util.go deleted file mode 100644 index 8866e6b10..000000000 --- a/pkg/crypto/cryptoutil/crypto_util.go +++ /dev/null @@ -1,85 +0,0 @@ -package cryptoutil - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/sha256" - "encoding/base64" - "encoding/hex" - "fmt" - "github.com/denisbrodbeck/machineid" -) - -var iv = []byte{35, 46, 57, 24, 85, 35, 24, 74, 87, 35, 88, 98, 66, 32, 14, 05} - -func encodeBase64(b []byte) string { - return base64.StdEncoding.EncodeToString(b) -} - -func decodeBase64(s string) []byte { - data, err := base64.StdEncoding.DecodeString(s) - if err != nil { - panic(err) - } - return data -} - -// Encrypt encrypt data using aes -func Encrypt(key []byte, text string) string { - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - plaintext := []byte(fmt.Sprint(text)) - cfb := cipher.NewCFBEncrypter(block, iv) - cipherText := make([]byte, len(plaintext)) - cfb.XORKeyStream(cipherText, plaintext) - return encodeBase64(cipherText) -} - -// Decrypt decrypt data using aes -func Decrypt(key []byte, text string) string { - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - cipherText := decodeBase64(text) - cfb := cipher.NewCFBDecrypter(block, iv) - plaintext := make([]byte, len(cipherText)) - cfb.XORKeyStream(plaintext, cipherText) - return string(plaintext) -} - -// SumHash generate the hash sum of a text -func SumHash(text string) []byte { - hash := sha256.New() - return hash.Sum([]byte(text)) -} - -// EncodeHash encode the hash sum -func EncodeHash(hash []byte) string { - return hex.EncodeToString(hash[:]) -} - -// SumHashMachine generate a user machine ID, write the id and the text using sha256, and return the sum of the hash -func SumHashMachine(text string) ([]byte, error) { - id, err := machineid.ID() - if err != nil { - return nil, err - } - - hash := sha256.New() - _, err = hash.Write([]byte(text)) - if err != nil { - return nil, err - } - - _, err = hash.Write([]byte(id)) - if err != nil { - return nil, err - } - - sum := hash.Sum(nil) - - return sum, nil -} diff --git a/pkg/crypto/cryptoutil/crypto_util_test.go b/pkg/crypto/cryptoutil/crypto_util_test.go deleted file mode 100644 index 8d13aee28..000000000 --- a/pkg/crypto/cryptoutil/crypto_util_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package cryptoutil - -import ( - "os" - "testing" -) - -var ciphkey string - -func TestMain(m *testing.M) { - ciphkey = "65dTxbqk7rE3IFly1hnI1234" - os.Exit(m.Run()) -} - -func TestEncrypt(t *testing.T) { - want := "Q0jhx4gItMsD" - got := Encrypt([]byte(ciphkey), "radiation") - if got != want { - t.Errorf("Encrypt got %v, want %v", got, want) - } -} - -func TestDecrypt(t *testing.T) { - want := "radiation" - got := Decrypt([]byte(ciphkey), "Q0jhx4gItMsD") - if got != want { - t.Errorf("Decrypt got %v, want %v", got, want) - } -} diff --git a/pkg/env/envcredential/env_credential.go b/pkg/env/envcredential/env_credential.go index dbf9f8d1f..32d482994 100644 --- a/pkg/env/envcredential/env_credential.go +++ b/pkg/env/envcredential/env_credential.go @@ -3,15 +3,15 @@ package envcredential import ( "strings" - "github.com/ZupIT/ritchie-cli/pkg/credential" + "github.com/ZupIT/ritchie-cli/pkg/credential/find" ) type CredentialResolver struct { - credential.Finder + find.Finder } // NewResolver creates a credential resolver instance of Resolver interface -func NewResolver(cf credential.Finder) CredentialResolver { +func NewResolver(cf find.Finder) CredentialResolver { return CredentialResolver{cf} } diff --git a/pkg/formula/runner/docker_runner.go b/pkg/formula/runner/docker_runner.go index a14d1bfa3..80168388e 100644 --- a/pkg/formula/runner/docker_runner.go +++ b/pkg/formula/runner/docker_runner.go @@ -47,7 +47,6 @@ func (d DockerRunner) Run(def formula.Definition, inputType api.TermInputType) e if err := d.Inputs(cmd, setup, inputType); err != nil { return err } - for _, e := range cmd.Env { // Create a file named .env and add the environment variable inName=inValue if !fileutil.Exists(envFile) { if err := fileutil.WriteFile(envFile, []byte(e+"\n")); err != nil { diff --git a/pkg/formula/runner/inputs.go b/pkg/formula/runner/inputs.go index d4c3ee31d..ac712681c 100644 --- a/pkg/formula/runner/inputs.go +++ b/pkg/formula/runner/inputs.go @@ -223,6 +223,8 @@ func loadItems(input formula.Input, formulaPath string) ([]string, error) { func (d InputManager) resolveIfReserved(input formula.Input) (string, error) { s := strings.Split(input.Type, "_") resolver := d.envResolvers[s[0]] + fmt.Println(resolver) + if resolver != nil { return resolver.Resolve(input.Type) } diff --git a/pkg/prompt/color.go b/pkg/prompt/color.go index 84ac6a571..f0ac59030 100644 --- a/pkg/prompt/color.go +++ b/pkg/prompt/color.go @@ -42,3 +42,7 @@ func Yellow(text string) string { func Warning(text string) { color.Warn.Println(text) } + +func Cyan(text string) string { + return color.Cyan.Render(text) +} From 25f2325a38484b41acbb44a72411df2aad365fa8 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Fri, 17 Jul 2020 13:43:43 -0300 Subject: [PATCH 04/27] list working --- cmd/main.go | 3 +- pkg/cmd/list_credential.go | 43 +++--- pkg/cmd/mocks_test.go | 6 +- pkg/cmd/set_credential.go | 26 ++-- pkg/credential/credential.go | 33 +++-- pkg/credential/find/finder.go | 7 +- pkg/credential/set/settings.go | 113 ---------------- pkg/credential/set/settings_test.go | 21 +-- pkg/credential/settings.go | 169 ++++++++++++++++++++++++ pkg/env/envcredential/env_credential.go | 5 + pkg/formula/runner/default_runner.go | 6 +- pkg/formula/runner/inputs.go | 4 +- pkg/stream/file.go | 1 - 13 files changed, 247 insertions(+), 190 deletions(-) delete mode 100644 pkg/credential/set/settings.go create mode 100644 pkg/credential/settings.go diff --git a/cmd/main.go b/cmd/main.go index 2a4ce1873..cf496e3a8 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -8,6 +8,7 @@ import ( "k8s.io/kubectl/pkg/util/templates" + "github.com/ZupIT/ritchie-cli/pkg/credential" "github.com/ZupIT/ritchie-cli/pkg/credential/find" "github.com/ZupIT/ritchie-cli/pkg/credential/set" "github.com/ZupIT/ritchie-cli/pkg/formula/builder" @@ -82,7 +83,7 @@ func buildCommands() *cobra.Command { credSetter := set.NewSetter(ritchieHomeDir, ctxFinder) credFinder := find.NewFinder(ritchieHomeDir, ctxFinder) treeManager := tree.NewTreeManager(ritchieHomeDir, repoLister, api.CoreCmds) - credSettings := set.NewSingleSettings(fileManager) + credSettings := credential.NewSettings(fileManager) autocompleteGen := autocomplete.NewGenerator(treeManager) credResolver := envcredential.NewResolver(credFinder) envResolvers := make(env.Resolvers) diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index dd8dee310..ac93bfcd3 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -7,16 +7,15 @@ import ( "github.com/spf13/cobra" "github.com/ZupIT/ritchie-cli/pkg/credential" - "github.com/ZupIT/ritchie-cli/pkg/credential/set" "github.com/ZupIT/ritchie-cli/pkg/prompt" ) type listCredentialCmd struct { - set.SingleSettings + credential.Settings } func NewListCredentialCmd( - ss set.SingleSettings) *cobra.Command { + ss credential.Settings) *cobra.Command { l := &listCredentialCmd{ss} cmd := &cobra.Command{ @@ -34,44 +33,40 @@ func hideCredential(credential string) string { var hiddenCredential []rune for i, r := range credential { if i < len(credential)-noHiddenChars { - r ='*' + r = '*' } hiddenCredential = append(hiddenCredential, r) } return string(hiddenCredential) } -func printCredentialsTable(fields credential.Fields) { +func printCredentialsTable(fields credential.ListCredDatas) { table := uitable.New() - table.AddRow(prompt.Bold("CONTEXT"), prompt.Bold("PROVIDER"), prompt.Bold("NAME"), prompt.Bold("CREDENTIAL")) + table.MaxColWidth = 100 + table.Wrap = true + table.AddRow(prompt.Bold("NAME"), prompt.Bold("PROVIDER"), prompt.Bold("CONTEXT"), prompt.Bold("VALUE")) switchColor := true - for c := range fields { - provider := fields[c] - for _, p := range provider { - if switchColor { - table.AddRow(c, p.Name) - switchColor = false - } else { - table.AddRow(prompt.Cyan(c), prompt.Cyan(p.Name)) - switchColor = true - } - + for _, c := range fields { + if switchColor { + table.AddRow(c.Name, c.Provider, c.Context, hideCredential(c.Value)) + switchColor = false + } else { + table.AddRow(prompt.Cyan(c.Name), prompt.Cyan(c.Provider), prompt.Cyan(c.Context), prompt.Cyan(hideCredential(c.Value))) + switchColor = true } } fmt.Println(table) } - - func (l listCredentialCmd) run() CommandRunnerFunc { return func(cmd *cobra.Command, args []string) error { - data, err := l.ReadCredentials(set.ProviderPath()) - if err != nil { - return err - } + // TODO ler as pastas dentro de credentials para pegar os contextos + + // TODO separar os valores das credentials + data := l.Settings.ReadCredentialsValue(credential.CredentialsPath()) printCredentialsTable(data) return nil } -} \ No newline at end of file +} diff --git a/pkg/cmd/mocks_test.go b/pkg/cmd/mocks_test.go index f6916d84f..9552d5e61 100644 --- a/pkg/cmd/mocks_test.go +++ b/pkg/cmd/mocks_test.go @@ -235,15 +235,15 @@ type credSettingsMock struct{} type singleCredSettingsMock struct{} -func (s singleCredSettingsMock) WriteDefaultCredentials(path string) error { +func (s singleCredSettingsMock) WriteDefaultCredentialsFields(path string) error { return nil } -func (s singleCredSettingsMock) ReadCredentials(path string) (credential.Fields, error) { +func (s singleCredSettingsMock) ReadCredentialsFields(path string) (credential.Fields, error) { return nil, nil } -func (s singleCredSettingsMock) WriteCredentials(fields credential.Fields, path string) error { +func (s singleCredSettingsMock) WriteCredentialsFields(fields credential.Fields, path string) error { return nil } diff --git a/pkg/cmd/set_credential.go b/pkg/cmd/set_credential.go index 021284157..4c58898d3 100644 --- a/pkg/cmd/set_credential.go +++ b/pkg/cmd/set_credential.go @@ -18,7 +18,7 @@ var inputTypes = []string{"plain text", "secret"} // setCredentialCmd type for set credential command type setCredentialCmd struct { set.Setter - set.SingleSettings + credential.Settings prompt.InputText prompt.InputBool prompt.InputList @@ -28,19 +28,19 @@ type setCredentialCmd struct { // NewSetCredentialCmd creates a new cmd instance func NewSetCredentialCmd( credSetter set.Setter, - credSetting set.SingleSettings, + credSetting credential.Settings, inText prompt.InputText, inBool prompt.InputBool, inList prompt.InputList, inPass prompt.InputPassword, ) *cobra.Command { s := &setCredentialCmd{ - Setter: credSetter, - SingleSettings: credSetting, - InputText: inText, - InputBool: inBool, - InputList: inList, - InputPassword: inPass, + Setter: credSetter, + Settings: credSetting, + InputText: inText, + InputBool: inBool, + InputList: inList, + InputPassword: inPass, } cmd := &cobra.Command{ @@ -72,25 +72,25 @@ func (s setCredentialCmd) runPrompt() CommandRunnerFunc { func (s setCredentialCmd) prompt() (credential.Detail, error) { - if err := s.WriteDefaultCredentials(set.ProviderPath()); err != nil { + if err := s.WriteDefaultCredentialsFields(credential.ProviderPath()); err != nil { return credential.Detail{}, err } var credDetail credential.Detail cred := credential.Credential{} - credentials, err := s.ReadCredentials(set.ProviderPath()) + credentials, err := s.ReadCredentialsFields(credential.ProviderPath()) if err != nil { return credential.Detail{}, err } - providerArr := set.NewProviderArr(credentials) + providerArr := credential.NewProviderArr(credentials) providerChoose, err := s.List("Select your provider", providerArr) if err != nil { return credDetail, err } - if providerChoose == set.AddNew { + if providerChoose == credential.AddNew { newProvider, err := s.Text("Define your provider name:", true) if err != nil { return credDetail, err @@ -118,7 +118,7 @@ func (s setCredentialCmd) prompt() (credential.Detail, error) { } } credentials[newProvider] = newFields - if err = s.WriteCredentials(credentials, set.ProviderPath()); err != nil { + if err = s.WriteCredentialsFields(credentials, credential.ProviderPath()); err != nil { return credDetail, err } diff --git a/pkg/credential/credential.go b/pkg/credential/credential.go index 7b36b7af8..5ee2960e7 100644 --- a/pkg/credential/credential.go +++ b/pkg/credential/credential.go @@ -1,14 +1,5 @@ package credential -const ( - // Other credential path /admin - Other Type = "admin" - // Me credential path /me - Me Type = "me" - // Org credential path /org - Org Type = "org" -) - // Info represents a credential information of the user. type Detail struct { Username string `json:"username"` @@ -32,8 +23,16 @@ type Field struct { Type string `json:"type"` } -// Fields represents a collection of credential fields returned by the Server (Team). -// Fields are used on single to represents providers.json +type ListCredDatas []ListCredData + +type ListCredData struct { + Provider string + Name string + Value string + Context string +} + +// Fields are used to represents providers.json type Fields map[string][]Field type Setter interface { @@ -44,12 +43,10 @@ type Finder interface { Find(service string) (Detail, error) } -type Settings interface { - Fields() (Fields, error) +type Operations interface { + ReadCredentialsFields(path string) (Fields, error) + ReadCredentialsValue(path string) string + WriteCredentialsFields(fields Fields, path string) error + WriteDefaultCredentialsFields(path string) error } -type SingleSettings interface { - ReadCredentials(path string) (Fields, error) - WriteCredentials(fields Fields, path string) error - WriteDefaultCredentials(path string) error -} \ No newline at end of file diff --git a/pkg/credential/find/finder.go b/pkg/credential/find/finder.go index b91256050..eb8ef35ad 100644 --- a/pkg/credential/find/finder.go +++ b/pkg/credential/find/finder.go @@ -2,6 +2,7 @@ package find import ( "encoding/json" + "fmt" "github.com/ZupIT/ritchie-cli/pkg/credential" "github.com/ZupIT/ritchie-cli/pkg/file/fileutil" @@ -32,11 +33,13 @@ func (f Finder) Find(provider string) (credential.Detail, error) { if err != nil { return credential.Detail{}, err } - + fmt.Println(string(cb)) cred := &credential.Detail{} if err := json.Unmarshal(cb, cred); err != nil { return credential.Detail{}, err } - + fmt.Println("on finder.go") + fmt.Println(cred.Credential["aws"]) + fmt.Println("nothing") return *cred, nil } diff --git a/pkg/credential/set/settings.go b/pkg/credential/set/settings.go deleted file mode 100644 index c3bc118da..000000000 --- a/pkg/credential/set/settings.go +++ /dev/null @@ -1,113 +0,0 @@ -package set - -import ( - "encoding/json" - "fmt" - "os" - - "github.com/ZupIT/ritchie-cli/pkg/credential" - "github.com/ZupIT/ritchie-cli/pkg/stream" -) - -const AddNew = "Add a new" - -type SingleSettings struct { - file stream.FileWriteReadExister -} - -func NewSingleSettings(file stream.FileWriteReadExister) SingleSettings { - return SingleSettings{file: file} -} - -func (s SingleSettings) ReadCredentials(path string) (credential.Fields, error) { - - var fields credential.Fields - - if s.file.Exists(path) { - cBytes, _ := s.file.Read(path) - err := json.Unmarshal(cBytes, &fields) - if err != nil { - return fields, err - } - } - - return fields, nil -} - -func (s SingleSettings) WriteCredentials(fields credential.Fields, path string) error { - fieldsData, err := json.Marshal(fields) - if err != nil { - return err - } - err = s.file.Write(path, fieldsData) - if err != nil { - return err - } - - return nil -} - -// WriteDefault is a non override version of WriteCredentials -// used to create providers.json if user dont have it -func (s SingleSettings) WriteDefaultCredentials(path string) error { - if !s.file.Exists(path) { - err := s.WriteCredentials(NewDefaultCredentials(), path) - return err - } - return nil -} - -func NewDefaultCredentials() credential.Fields { - var username = credential.Field{ - Name: "username", - Type: "text", - } - - var token = credential.Field{ - Name: "token", - Type: "password", - } - - var accessKeyId = credential.Field{ - Name: "accessKeyId", - Type: "text", - } - - var secretAccessKey = credential.Field{ - Name: "secretAccessKey", - Type: "password", - } - - var base64config = credential.Field{ - Name: "base64config", - Type: "text", - } - - var dc = credential.Fields{ - "Add a new": []credential.Field{}, - "github": []credential.Field{username, token}, - "gitlab": []credential.Field{username, token}, - "aws": []credential.Field{accessKeyId, secretAccessKey}, - "jenkins": []credential.Field{username, token}, - "kubeconfig": []credential.Field{base64config}, - } - - return dc -} - -func ProviderPath() string { - homeDir, _ := os.UserHomeDir() - providerDir := fmt.Sprintf("%s/.rit/repo/providers.json", homeDir) - return providerDir -} - -func NewProviderArr(fields credential.Fields) []string { - var providerArr []string - for k := range fields { - if k != AddNew { - providerArr = append(providerArr, k) - } - } - providerArr = append(providerArr, AddNew) - return providerArr -} diff --git a/pkg/credential/set/settings_test.go b/pkg/credential/set/settings_test.go index 2f14ebf00..2ed8254f7 100644 --- a/pkg/credential/set/settings_test.go +++ b/pkg/credential/set/settings_test.go @@ -6,11 +6,12 @@ import ( "strings" "testing" + "github.com/ZupIT/ritchie-cli/pkg/credential" "github.com/ZupIT/ritchie-cli/pkg/stream" ) var fileManager = stream.NewFileManager() -var credSettings = NewSingleSettings(fileManager) +var credSettings = credential.NewSettings(fileManager) func providersPath() string { tempDir := os.TempDir() @@ -20,7 +21,7 @@ func providersPath() string { func TestSingleSettings_ReadCredentials(t *testing.T) { - credentials, err := credSettings.ReadCredentials("../../../testdata/credentials.json") + credentials, err := credSettings.ReadCredentialsFields("../../../testdata/credentials.json") if err != nil { t.Errorf("Error on on read credentials function") } @@ -31,7 +32,7 @@ func TestSingleSettings_ReadCredentials(t *testing.T) { } func TestSingleSettings_WriteCredentials(t *testing.T) { - err := credSettings.WriteCredentials(NewDefaultCredentials(), providersPath()) + err := credSettings.WriteCredentialsFields(credential.NewDefaultCredentials(), providersPath()) defer os.Remove(providersPath()) if err != nil { t.Errorf("Error while write credentials: %s", err) @@ -39,7 +40,7 @@ func TestSingleSettings_WriteCredentials(t *testing.T) { } func TestSingleSettings_WriteDefaultCredentials(t *testing.T) { - err := credSettings.WriteDefaultCredentials(providersPath()) + err := credSettings.WriteDefaultCredentialsFields(providersPath()) defer os.Remove(providersPath()) if err != nil { t.Errorf("Error while write credentials: %s", err) @@ -47,7 +48,7 @@ func TestSingleSettings_WriteDefaultCredentials(t *testing.T) { } func TestNewDefaultCredentials(t *testing.T) { - defaultCredentials := NewDefaultCredentials() + defaultCredentials := credential.NewDefaultCredentials() if defaultCredentials == nil { t.Errorf("Default credentials cannot be nill") @@ -59,7 +60,7 @@ func TestNewDefaultCredentials(t *testing.T) { } func TestProviderPath(t *testing.T) { - provider := ProviderPath() + provider := credential.ProviderPath() slicedPath := strings.Split(provider, "/") providersJson := slicedPath[len(slicedPath)-1] @@ -69,11 +70,11 @@ func TestProviderPath(t *testing.T) { } func TestProvidersArr(t *testing.T) { - credentials := NewDefaultCredentials() - providersArray := NewProviderArr(credentials) + credentials := credential.NewDefaultCredentials() + providersArray := credential.NewProviderArr(credentials) - if providersArray[len(providersArray)-1] != AddNew { - t.Errorf("%q option must be the last one", AddNew) + if providersArray[len(providersArray)-1] != credential.AddNew { + t.Errorf("%q option must be the last one", credential.AddNew) } if providersArray == nil { diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go new file mode 100644 index 000000000..fe16b7060 --- /dev/null +++ b/pkg/credential/settings.go @@ -0,0 +1,169 @@ +package credential + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "log" + "os" + + "github.com/ZupIT/ritchie-cli/pkg/stream" +) + +const AddNew = "Add a new" + +type Settings struct { + file stream.FileWriteReadExister +} + +func NewSettings(file stream.FileWriteReadExister) Settings { + return Settings{file: file} +} + +func (s Settings) ReadCredentialsFields(path string) (Fields, error) { + fields := Fields{} + + if s.file.Exists(path) { + cBytes, _ := s.file.Read(path) + err := json.Unmarshal(cBytes, &fields) + if err != nil { + return fields, err + } + } + + return fields, nil +} + +func (s Settings) ReadCredentialsValue(path string) []ListCredData { + var creds []ListCredData + var cred ListCredData + var detail Detail + ctx := ctxArr() + + for _, c := range ctx { + providers := providerByCtx(c) + for _, p := range providers { + cBytes, _ := s.file.Read(CredentialsPath() + c + "/" + p) + json.Unmarshal(cBytes, &detail) + + for k, v := range detail.Credential { + cred.Provider = detail.Service + cred.Context = c + cred.Value = v + cred.Name = k + creds = append(creds, cred) + } + } + + } + return creds +} + +func providerByCtx(ctx string) []string { + var providers []string + files, err := ioutil.ReadDir(CredentialsPath() + "/" + ctx) + if err != nil { + log.Fatal(err) + } + for _, f := range files { + providers = append(providers, f.Name()) + } + return providers +} + +func ctxArr() []string { + var ctx []string + files, err := ioutil.ReadDir(CredentialsPath()) + if err != nil { + log.Fatal(err) + } + for _, f := range files { + if f.IsDir() { + ctx = append(ctx, f.Name()) + } + } + return ctx +} + +func (s Settings) WriteCredentialsFields(fields Fields, path string) error { + fieldsData, err := json.Marshal(fields) + if err != nil { + return err + } + err = s.file.Write(path, fieldsData) + if err != nil { + return err + } + return nil +} + +// WriteDefault is a non override version of WriteCredentialsFields +// used to create providers.json if user dont have it +func (s Settings) WriteDefaultCredentialsFields(path string) error { + if !s.file.Exists(path) { + err := s.WriteCredentialsFields(NewDefaultCredentials(), path) + return err + } + return nil +} + +func NewDefaultCredentials() Fields { + username := Field{ + Name: "username", + Type: "text", + } + + token := Field{ + Name: "token", + Type: "password", + } + + accessKey := Field{ + Name: "accessKey", + Type: "text", + } + + secretAccessKey := Field{ + Name: "secretAccessKey", + Type: "password", + } + + base64config := Field{ + Name: "base64config", + Type: "text", + } + + dc := Fields{ + AddNew: []Field{}, + "github": []Field{username, token}, + "gitlab": []Field{username, token}, + "aws": []Field{accessKey, secretAccessKey}, + "jenkins": []Field{username, token}, + "kubeconfig": []Field{base64config}, + } + + return dc +} + +func ProviderPath() string { + homeDir, _ := os.UserHomeDir() + providerDir := fmt.Sprintf("%s/.rit/credentials/providers.json", homeDir) + return providerDir +} + +func CredentialsPath() string { + homeDir, _ := os.UserHomeDir() + credentialPath := fmt.Sprintf("%s/.rit/credentials/", homeDir) + return credentialPath +} + +func NewProviderArr(fields Fields) []string { + var providerArr []string + for k := range fields { + if k != AddNew { + providerArr = append(providerArr, k) + } + } + providerArr = append(providerArr, AddNew) + return providerArr +} diff --git a/pkg/env/envcredential/env_credential.go b/pkg/env/envcredential/env_credential.go index 32d482994..9de62d5c4 100644 --- a/pkg/env/envcredential/env_credential.go +++ b/pkg/env/envcredential/env_credential.go @@ -1,6 +1,7 @@ package envcredential import ( + "fmt" "strings" "github.com/ZupIT/ritchie-cli/pkg/credential/find" @@ -18,11 +19,15 @@ func NewResolver(cf find.Finder) CredentialResolver { func (c CredentialResolver) Resolve(name string) (string, error) { s := strings.Split(name, "_") service := strings.ToLower(s[1]) + fmt.Println(s) + cred, err := c.Find(service) if err != nil { return "", err } k := strings.ToLower(s[2]) + fmt.Println(cred.Credential[k] + "aaa") + return cred.Credential[k], nil } diff --git a/pkg/formula/runner/default_runner.go b/pkg/formula/runner/default_runner.go index c4b632a96..c680dddf8 100644 --- a/pkg/formula/runner/default_runner.go +++ b/pkg/formula/runner/default_runner.go @@ -27,19 +27,19 @@ func (d DefaultRunner) Run(def formula.Definition, inputType api.TermInputType) } cmd := &exec.Cmd{ - Path: setup.BinName, + Path: setup.BinName, Stdout: os.Stdout, - Stdin: os.Stdin, + Stdin: os.Stdin, Stderr: os.Stderr, } cmd.Env = os.Environ() pwdEnv := fmt.Sprintf(formula.EnvPattern, formula.PwdEnv, setup.Pwd) cPwdEnv := fmt.Sprintf(formula.EnvPattern, formula.CPwdEnv, setup.Pwd) + cmd.Env = append(cmd.Env, pwdEnv) cmd.Env = append(cmd.Env, cPwdEnv) - if err := d.Inputs(cmd, setup, inputType); err != nil { return err } diff --git a/pkg/formula/runner/inputs.go b/pkg/formula/runner/inputs.go index ac712681c..2b2cdd098 100644 --- a/pkg/formula/runner/inputs.go +++ b/pkg/formula/runner/inputs.go @@ -137,6 +137,8 @@ func (d InputManager) fromPrompt(cmd *exec.Cmd, setup formula.Setup) error { // add the variable inName=inValue to cmd.Env func addEnv(cmd *exec.Cmd, inName, inValue string) { e := fmt.Sprintf(formula.EnvPattern, strings.ToUpper(inName), inValue) + fmt.Println("ADDENV on inputs.go") + fmt.Println(e) cmd.Env = append(cmd.Env, e) } @@ -223,8 +225,6 @@ func loadItems(input formula.Input, formulaPath string) ([]string, error) { func (d InputManager) resolveIfReserved(input formula.Input) (string, error) { s := strings.Split(input.Type, "_") resolver := d.envResolvers[s[0]] - fmt.Println(resolver) - if resolver != nil { return resolver.Resolve(input.Type) } diff --git a/pkg/stream/file.go b/pkg/stream/file.go index b75c8784a..ca9a2fe57 100644 --- a/pkg/stream/file.go +++ b/pkg/stream/file.go @@ -84,7 +84,6 @@ func (f FileManager) Read(path string) ([]byte, error) { if err != nil && !os.IsNotExist(err) { return nil, err } - return b, err } From 03b7fb652213c5e07e22b35082b8e77512c4b36c Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Fri, 17 Jul 2020 16:07:35 -0300 Subject: [PATCH 05/27] refactor table --- pkg/cmd/list_credential.go | 14 +++----------- pkg/credential/settings.go | 2 -- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index ac93bfcd3..121cd13c4 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -7,7 +7,6 @@ import ( "github.com/spf13/cobra" "github.com/ZupIT/ritchie-cli/pkg/credential" - "github.com/ZupIT/ritchie-cli/pkg/prompt" ) type listCredentialCmd struct { @@ -44,17 +43,10 @@ func printCredentialsTable(fields credential.ListCredDatas) { table := uitable.New() table.MaxColWidth = 100 table.Wrap = true - table.AddRow(prompt.Bold("NAME"), prompt.Bold("PROVIDER"), prompt.Bold("CONTEXT"), prompt.Bold("VALUE")) - switchColor := true - for _, c := range fields { - if switchColor { - table.AddRow(c.Name, c.Provider, c.Context, hideCredential(c.Value)) - switchColor = false - } else { - table.AddRow(prompt.Cyan(c.Name), prompt.Cyan(c.Provider), prompt.Cyan(c.Context), prompt.Cyan(hideCredential(c.Value))) - switchColor = true - } + table.AddRow("Name", "Value", "Provider", "Context") + for _, c := range fields { + table.AddRow(c.Name, hideCredential(c.Value), c.Provider, c.Context, ) } fmt.Println(table) } diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index fe16b7060..cfe427bea 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -45,7 +45,6 @@ func (s Settings) ReadCredentialsValue(path string) []ListCredData { for _, p := range providers { cBytes, _ := s.file.Read(CredentialsPath() + c + "/" + p) json.Unmarshal(cBytes, &detail) - for k, v := range detail.Credential { cred.Provider = detail.Service cred.Context = c @@ -54,7 +53,6 @@ func (s Settings) ReadCredentialsValue(path string) []ListCredData { creds = append(creds, cred) } } - } return creds } From c7fdad913ded2e88da5340f0e3d8b14b9bd65f6f Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Fri, 17 Jul 2020 19:02:26 -0300 Subject: [PATCH 06/27] remove comments --- pkg/cmd/list_credential.go | 21 ++++++++++++--------- pkg/credential/find/finder.go | 7 ++----- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index 121cd13c4..367b3fd07 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/cobra" "github.com/ZupIT/ritchie-cli/pkg/credential" + "github.com/ZupIT/ritchie-cli/pkg/prompt" ) type listCredentialCmd struct { @@ -28,10 +29,10 @@ func NewListCredentialCmd( } func hideCredential(credential string) string { - noHiddenChars := len(credential) / 3 + mustHideIndex := len(credential) / 3 var hiddenCredential []rune for i, r := range credential { - if i < len(credential)-noHiddenChars { + if i > mustHideIndex { r = '*' } hiddenCredential = append(hiddenCredential, r) @@ -41,22 +42,24 @@ func hideCredential(credential string) string { func printCredentialsTable(fields credential.ListCredDatas) { table := uitable.New() - table.MaxColWidth = 100 + table.MaxColWidth = 50 table.Wrap = true - table.AddRow("Name", "Value", "Provider", "Context") + + table.AddRow( + prompt.Bold("NAME"), + prompt.Bold("VALUE"), + prompt.Bold("PROVIDER"), + prompt.Bold("CONTEXT"), + ) for _, c := range fields { - table.AddRow(c.Name, hideCredential(c.Value), c.Provider, c.Context, ) + table.AddRow(c.Name, hideCredential(c.Value), c.Provider, c.Context) } fmt.Println(table) } func (l listCredentialCmd) run() CommandRunnerFunc { return func(cmd *cobra.Command, args []string) error { - - // TODO ler as pastas dentro de credentials para pegar os contextos - - // TODO separar os valores das credentials data := l.Settings.ReadCredentialsValue(credential.CredentialsPath()) printCredentialsTable(data) return nil diff --git a/pkg/credential/find/finder.go b/pkg/credential/find/finder.go index eb8ef35ad..b91256050 100644 --- a/pkg/credential/find/finder.go +++ b/pkg/credential/find/finder.go @@ -2,7 +2,6 @@ package find import ( "encoding/json" - "fmt" "github.com/ZupIT/ritchie-cli/pkg/credential" "github.com/ZupIT/ritchie-cli/pkg/file/fileutil" @@ -33,13 +32,11 @@ func (f Finder) Find(provider string) (credential.Detail, error) { if err != nil { return credential.Detail{}, err } - fmt.Println(string(cb)) + cred := &credential.Detail{} if err := json.Unmarshal(cb, cred); err != nil { return credential.Detail{}, err } - fmt.Println("on finder.go") - fmt.Println(cred.Credential["aws"]) - fmt.Println("nothing") + return *cred, nil } From 6f0c003a797482b12e47a2682ba961229ef5a788 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Tue, 21 Jul 2020 09:58:46 -0300 Subject: [PATCH 07/27] change folder structure --- cmd/main.go | 6 ++---- pkg/cmd/set_credential.go | 5 ++--- pkg/credential/credential.go | 4 ++-- pkg/credential/{find => }/finder.go | 15 +++++++-------- pkg/credential/{find => }/finder_test.go | 15 ++++++--------- pkg/credential/{set => }/setter.go | 9 ++++----- pkg/credential/{set => }/setter_test.go | 13 +++++++------ pkg/credential/{set => }/settings_test.go | 19 +++++++++---------- pkg/env/envcredential/env_credential.go | 7 +++---- 9 files changed, 42 insertions(+), 51 deletions(-) rename pkg/credential/{find => }/finder.go (61%) rename pkg/credential/{find => }/finder_test.go (67%) rename pkg/credential/{set => }/setter.go (75%) rename pkg/credential/{set => }/setter_test.go (68%) rename pkg/credential/{set => }/settings_test.go (75%) diff --git a/cmd/main.go b/cmd/main.go index cf496e3a8..04c3698a6 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -9,8 +9,6 @@ import ( "k8s.io/kubectl/pkg/util/templates" "github.com/ZupIT/ritchie-cli/pkg/credential" - "github.com/ZupIT/ritchie-cli/pkg/credential/find" - "github.com/ZupIT/ritchie-cli/pkg/credential/set" "github.com/ZupIT/ritchie-cli/pkg/formula/builder" "github.com/ZupIT/ritchie-cli/pkg/formula/creator" "github.com/ZupIT/ritchie-cli/pkg/formula/repo" @@ -80,8 +78,8 @@ func buildCommands() *cobra.Command { ctxRemover := rcontext.NewRemover(ritchieHomeDir, ctxFinder) ctxFindSetter := rcontext.NewFindSetter(ritchieHomeDir, ctxFinder, ctxSetter) ctxFindRemover := rcontext.NewFindRemover(ritchieHomeDir, ctxFinder, ctxRemover) - credSetter := set.NewSetter(ritchieHomeDir, ctxFinder) - credFinder := find.NewFinder(ritchieHomeDir, ctxFinder) + credSetter := credential.NewSetter(ritchieHomeDir, ctxFinder) + credFinder := credential.NewFinder(ritchieHomeDir, ctxFinder) treeManager := tree.NewTreeManager(ritchieHomeDir, repoLister, api.CoreCmds) credSettings := credential.NewSettings(fileManager) autocompleteGen := autocomplete.NewGenerator(treeManager) diff --git a/pkg/cmd/set_credential.go b/pkg/cmd/set_credential.go index 4c58898d3..e32ddf17d 100644 --- a/pkg/cmd/set_credential.go +++ b/pkg/cmd/set_credential.go @@ -8,7 +8,6 @@ import ( "github.com/spf13/cobra" "github.com/ZupIT/ritchie-cli/pkg/credential" - "github.com/ZupIT/ritchie-cli/pkg/credential/set" "github.com/ZupIT/ritchie-cli/pkg/prompt" "github.com/ZupIT/ritchie-cli/pkg/stdin" ) @@ -17,7 +16,7 @@ var inputTypes = []string{"plain text", "secret"} // setCredentialCmd type for set credential command type setCredentialCmd struct { - set.Setter + credential.Setter credential.Settings prompt.InputText prompt.InputBool @@ -27,7 +26,7 @@ type setCredentialCmd struct { // NewSetCredentialCmd creates a new cmd instance func NewSetCredentialCmd( - credSetter set.Setter, + credSetter credential.Setter, credSetting credential.Settings, inText prompt.InputText, inBool prompt.InputBool, diff --git a/pkg/credential/credential.go b/pkg/credential/credential.go index 5ee2960e7..89864306b 100644 --- a/pkg/credential/credential.go +++ b/pkg/credential/credential.go @@ -35,11 +35,11 @@ type ListCredData struct { // Fields are used to represents providers.json type Fields map[string][]Field -type Setter interface { +type CredSetter interface { Set(d Detail) error } -type Finder interface { +type CredFinder interface { Find(service string) (Detail, error) } diff --git a/pkg/credential/find/finder.go b/pkg/credential/finder.go similarity index 61% rename from pkg/credential/find/finder.go rename to pkg/credential/finder.go index b91256050..4883e899a 100644 --- a/pkg/credential/find/finder.go +++ b/pkg/credential/finder.go @@ -1,9 +1,8 @@ -package find +package credential import ( "encoding/json" - "github.com/ZupIT/ritchie-cli/pkg/credential" "github.com/ZupIT/ritchie-cli/pkg/file/fileutil" "github.com/ZupIT/ritchie-cli/pkg/rcontext" ) @@ -20,22 +19,22 @@ func NewFinder(homePath string, cf rcontext.Finder) Finder { } } -func (f Finder) Find(provider string) (credential.Detail, error) { +func (f Finder) Find(provider string) (Detail, error) { ctx, err := f.ctxFinder.Find() if err != nil { - return credential.Detail{}, err + return Detail{}, err } else if ctx.Current == "" { ctx.Current = rcontext.DefaultCtx } - cb, err := fileutil.ReadFile(credential.File(f.homePath, ctx.Current, provider)) + cb, err := fileutil.ReadFile(File(f.homePath, ctx.Current, provider)) if err != nil { - return credential.Detail{}, err + return Detail{}, err } - cred := &credential.Detail{} + cred := &Detail{} if err := json.Unmarshal(cb, cred); err != nil { - return credential.Detail{}, err + return Detail{}, err } return *cred, nil diff --git a/pkg/credential/find/finder_test.go b/pkg/credential/finder_test.go similarity index 67% rename from pkg/credential/find/finder_test.go rename to pkg/credential/finder_test.go index 0b7a79ec0..8f503b365 100644 --- a/pkg/credential/find/finder_test.go +++ b/pkg/credential/finder_test.go @@ -1,27 +1,24 @@ -package find +package credential import ( "fmt" "os" "reflect" "testing" - - "github.com/ZupIT/ritchie-cli/pkg/credential" - "github.com/ZupIT/ritchie-cli/pkg/credential/set" ) func TestFind(t *testing.T) { tmp := os.TempDir() - setter := set.NewSetter(tmp, credential.ctxFinder, sessManager) - err := setter.Set(credential.githubCred) + setter := NewSetter(tmp, ) + err := setter.Set(githubCred) if err != nil { fmt.Sprintln("Error in Set") return } - finder := NewFinder(tmp, credential.ctxFinder, sessManager) + finder := NewFinder(tmp, ctxFinder, sessManager) type out struct { - cred credential.Detail + cred Detail err error } @@ -34,7 +31,7 @@ func TestFind(t *testing.T) { name: "github", in: "github", out: out{ - cred: credential.githubCred, + cred: githubCred, err: nil, }, }, diff --git a/pkg/credential/set/setter.go b/pkg/credential/setter.go similarity index 75% rename from pkg/credential/set/setter.go rename to pkg/credential/setter.go index 38b0f1bdd..b60b9d976 100644 --- a/pkg/credential/set/setter.go +++ b/pkg/credential/setter.go @@ -1,9 +1,8 @@ -package set +package credential import ( "encoding/json" - "github.com/ZupIT/ritchie-cli/pkg/credential" "github.com/ZupIT/ritchie-cli/pkg/file/fileutil" "github.com/ZupIT/ritchie-cli/pkg/rcontext" ) @@ -20,7 +19,7 @@ func NewSetter(homePath string, cf rcontext.Finder) Setter { } } -func (s Setter) Set(cred credential.Detail) error { +func (s Setter) Set(cred Detail) error { ctx, err := s.ctxFinder.Find() if err != nil { return err @@ -33,12 +32,12 @@ func (s Setter) Set(cred credential.Detail) error { return err } - dir := credential.Dir(s.homePath, ctx.Current) + dir := Dir(s.homePath, ctx.Current) if err := fileutil.CreateDirIfNotExists(dir, 0700); err != nil { return err } - credFile := credential.File(s.homePath, ctx.Current, cred.Service) + credFile := File(s.homePath, ctx.Current, cred.Service) if err := fileutil.WriteFilePerm(credFile, cb, 0600); err != nil { return err } diff --git a/pkg/credential/set/setter_test.go b/pkg/credential/setter_test.go similarity index 68% rename from pkg/credential/set/setter_test.go rename to pkg/credential/setter_test.go index 0500e9aff..fa0cc892f 100644 --- a/pkg/credential/set/setter_test.go +++ b/pkg/credential/setter_test.go @@ -1,24 +1,25 @@ -package set +package credential import ( "os" "testing" - - "github.com/ZupIT/ritchie-cli/pkg/credential" ) func TestSet(t *testing.T) { tmp := os.TempDir() - setter := NewSetter(tmp, credential.ctxFinder, sessManager) + + setter := NewSetter(tmp, ctxFinder, sessManager) + + tests := []struct { name string - in credential.Detail + in Detail out error }{ { name: "github credential", - in: credential.githubCred, + in: githubCred, out: nil, }, } diff --git a/pkg/credential/set/settings_test.go b/pkg/credential/settings_test.go similarity index 75% rename from pkg/credential/set/settings_test.go rename to pkg/credential/settings_test.go index 2ed8254f7..3f9e5fe2a 100644 --- a/pkg/credential/set/settings_test.go +++ b/pkg/credential/settings_test.go @@ -1,4 +1,4 @@ -package set +package credential import ( "fmt" @@ -6,12 +6,11 @@ import ( "strings" "testing" - "github.com/ZupIT/ritchie-cli/pkg/credential" "github.com/ZupIT/ritchie-cli/pkg/stream" ) var fileManager = stream.NewFileManager() -var credSettings = credential.NewSettings(fileManager) +var credSettings = NewSettings(fileManager) func providersPath() string { tempDir := os.TempDir() @@ -32,7 +31,7 @@ func TestSingleSettings_ReadCredentials(t *testing.T) { } func TestSingleSettings_WriteCredentials(t *testing.T) { - err := credSettings.WriteCredentialsFields(credential.NewDefaultCredentials(), providersPath()) + err := credSettings.WriteCredentialsFields(NewDefaultCredentials(), providersPath()) defer os.Remove(providersPath()) if err != nil { t.Errorf("Error while write credentials: %s", err) @@ -48,7 +47,7 @@ func TestSingleSettings_WriteDefaultCredentials(t *testing.T) { } func TestNewDefaultCredentials(t *testing.T) { - defaultCredentials := credential.NewDefaultCredentials() + defaultCredentials := NewDefaultCredentials() if defaultCredentials == nil { t.Errorf("Default credentials cannot be nill") @@ -60,7 +59,7 @@ func TestNewDefaultCredentials(t *testing.T) { } func TestProviderPath(t *testing.T) { - provider := credential.ProviderPath() + provider := ProviderPath() slicedPath := strings.Split(provider, "/") providersJson := slicedPath[len(slicedPath)-1] @@ -70,11 +69,11 @@ func TestProviderPath(t *testing.T) { } func TestProvidersArr(t *testing.T) { - credentials := credential.NewDefaultCredentials() - providersArray := credential.NewProviderArr(credentials) + credentials := NewDefaultCredentials() + providersArray := NewProviderArr(credentials) - if providersArray[len(providersArray)-1] != credential.AddNew { - t.Errorf("%q option must be the last one", credential.AddNew) + if providersArray[len(providersArray)-1] != AddNew { + t.Errorf("%q option must be the last one", AddNew) } if providersArray == nil { diff --git a/pkg/env/envcredential/env_credential.go b/pkg/env/envcredential/env_credential.go index 9de62d5c4..41aff26ce 100644 --- a/pkg/env/envcredential/env_credential.go +++ b/pkg/env/envcredential/env_credential.go @@ -2,17 +2,16 @@ package envcredential import ( "fmt" + "github.com/ZupIT/ritchie-cli/pkg/credential" "strings" - - "github.com/ZupIT/ritchie-cli/pkg/credential/find" ) type CredentialResolver struct { - find.Finder + credential.Finder } // NewResolver creates a credential resolver instance of Resolver interface -func NewResolver(cf find.Finder) CredentialResolver { +func NewResolver(cf credential.Finder) CredentialResolver { return CredentialResolver{cf} } From 4a9b01cb948a90886f52baef0ec09203d032dfc0 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Tue, 21 Jul 2020 19:25:23 -0300 Subject: [PATCH 08/27] changing tests --- pkg/credential/finder_test.go | 19 ++++++++++++++++--- pkg/credential/setter.go | 3 ++- pkg/credential/setter_test.go | 5 +---- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/pkg/credential/finder_test.go b/pkg/credential/finder_test.go index 8f503b365..da7320029 100644 --- a/pkg/credential/finder_test.go +++ b/pkg/credential/finder_test.go @@ -1,21 +1,33 @@ package credential import ( + "errors" "fmt" "os" "reflect" "testing" + + "github.com/ZupIT/ritchie-cli/pkg/rcontext" +) + +var ( + githubCred Detail + ctxFinder rcontext.Finder ) + + +var errTest = errors.New("Ai pai") + func TestFind(t *testing.T) { tmp := os.TempDir() - setter := NewSetter(tmp, ) + setter := NewSetter(tmp, ctxFinder) err := setter.Set(githubCred) if err != nil { fmt.Sprintln("Error in Set") return } - finder := NewFinder(tmp, ctxFinder, sessManager) + finder := NewFinder(tmp, ctxFinder) type out struct { cred Detail @@ -32,7 +44,7 @@ func TestFind(t *testing.T) { in: "github", out: out{ cred: githubCred, - err: nil, + err:errTest , }, }, } @@ -50,5 +62,6 @@ func TestFind(t *testing.T) { t.Errorf("Find(%s) got %v, want %v", tt.name, got, out.cred) } }) + fmt.Println(tt) } } diff --git a/pkg/credential/setter.go b/pkg/credential/setter.go index b60b9d976..ea4207de2 100644 --- a/pkg/credential/setter.go +++ b/pkg/credential/setter.go @@ -23,7 +23,8 @@ func (s Setter) Set(cred Detail) error { ctx, err := s.ctxFinder.Find() if err != nil { return err - } else if ctx.Current == "" { + } + if ctx.Current == "" { ctx.Current = rcontext.DefaultCtx } diff --git a/pkg/credential/setter_test.go b/pkg/credential/setter_test.go index fa0cc892f..d2ba47d9c 100644 --- a/pkg/credential/setter_test.go +++ b/pkg/credential/setter_test.go @@ -7,10 +7,7 @@ import ( func TestSet(t *testing.T) { tmp := os.TempDir() - - setter := NewSetter(tmp, ctxFinder, sessManager) - - + setter := NewSetter(tmp, ctxFinder) tests := []struct { name string From 4bed601e5d5305c45e1b11e2b1b83e101ef37431 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Wed, 22 Jul 2020 18:36:31 -0300 Subject: [PATCH 09/27] tests ok --- pkg/cmd/list_credential_test.go | 22 +++++++------- pkg/cmd/mocks_test.go | 20 ++++++++----- pkg/cmd/set_credential.go | 8 ++--- pkg/cmd/set_credential_test.go | 53 ++++++++++++++++----------------- pkg/cmd/show_context.go | 4 +-- pkg/credential/credential.go | 2 +- pkg/credential/finder.go | 12 ++++---- pkg/credential/finder_test.go | 18 +---------- pkg/credential/setter.go | 12 ++++---- pkg/credential/setter_test.go | 11 ++++++- pkg/credential/settings_test.go | 22 +++++++------- pkg/rcontext/context.go | 6 ++-- pkg/rcontext/find_remover.go | 4 +-- pkg/rcontext/find_setter.go | 4 +-- pkg/rcontext/finder.go | 8 ++--- pkg/rcontext/remover.go | 4 +-- pkg/rcontext/setter.go | 4 +-- run-tests.sh | 2 +- 18 files changed, 108 insertions(+), 108 deletions(-) diff --git a/pkg/cmd/list_credential_test.go b/pkg/cmd/list_credential_test.go index e03f78fdf..738933041 100644 --- a/pkg/cmd/list_credential_test.go +++ b/pkg/cmd/list_credential_test.go @@ -1,14 +1,12 @@ package cmd -import "testing" - -func TestNewListCredentialCmd(t *testing.T) { - cmd := NewListCredentialCmd(singleCredSettingsMock{}) - if cmd == nil { - t.Errorf("NewListCredentialCmd got %v", cmd) - } - - if err := cmd.Execute(); err != nil { - t.Errorf("%s = %v, want %v", cmd.Use, err, nil) - } -} \ No newline at end of file +// func TestNewListCredentialCmd(t *testing.T) { +// cmd := NewListCredentialCmd(credential.Settings{}) +// if cmd == nil { +// t.Errorf("NewListCredentialCmd got %v", cmd) +// } +// +// if err := cmd.Execute(); err != nil { +// t.Errorf("%s = %v, want %v", cmd.Use, err, nil) +// } +// } \ No newline at end of file diff --git a/pkg/cmd/mocks_test.go b/pkg/cmd/mocks_test.go index a8c812f0d..c5773d7e8 100644 --- a/pkg/cmd/mocks_test.go +++ b/pkg/cmd/mocks_test.go @@ -194,7 +194,7 @@ func (repoListerNonEmptyMock) List() (formula.Repos, error) { Name: "repoName", Priority: 0, }, - }, nil + },nil } type repoListerErrorMock struct{} @@ -223,17 +223,23 @@ func (credSetterMock) Set(d credential.Detail) error { return nil } -type singleCredSettingsMock struct{} - -func (s singleCredSettingsMock) WriteDefaultCredentialsFields(path string) error { - return nil +type credSettingsMock struct{ + error } -func (s singleCredSettingsMock) ReadCredentialsFields(path string) (credential.Fields, error) { +func (s credSettingsMock) ReadCredentialsFields(path string) (credential.Fields, error) { return credential.Fields{}, nil } -func (s singleCredSettingsMock) WriteCredentialsFields(fields credential.Fields, path string) error { +func (s credSettingsMock) ReadCredentialsValue(path string) string { + return "" +} + +func (s credSettingsMock) WriteDefaultCredentialsFields(path string) error { + return nil +} + +func (s credSettingsMock) WriteCredentialsFields(fields credential.Fields, path string) error { return nil } diff --git a/pkg/cmd/set_credential.go b/pkg/cmd/set_credential.go index 52cb834a5..871e9ec95 100644 --- a/pkg/cmd/set_credential.go +++ b/pkg/cmd/set_credential.go @@ -17,7 +17,7 @@ var inputTypes = []string{"plain text", "secret"} // setCredentialCmd type for set credential command type setCredentialCmd struct { credential.Setter - credential.Settings + credential.Operations prompt.InputText prompt.InputBool prompt.InputList @@ -27,15 +27,15 @@ type setCredentialCmd struct { // NewSetCredentialCmd creates a new cmd instance func NewSetCredentialCmd( credSetter credential.Setter, - credSetting credential.Settings, + credSetting credential.Operations, inText prompt.InputText, inBool prompt.InputBool, inList prompt.InputList, inPass prompt.InputPassword, ) *cobra.Command { s := &setCredentialCmd{ - Setter: credSetter, - Settings: credSetting, + Setter: credSetter, + Operations: credSetting, InputText: inText, InputBool: inBool, InputList: inList, diff --git a/pkg/cmd/set_credential_test.go b/pkg/cmd/set_credential_test.go index b530e06c6..5e2b79791 100644 --- a/pkg/cmd/set_credential_test.go +++ b/pkg/cmd/set_credential_test.go @@ -4,20 +4,19 @@ import ( "testing" "github.com/ZupIT/ritchie-cli/pkg/credential" - "github.com/ZupIT/ritchie-cli/pkg/credential/credsingle" "github.com/ZupIT/ritchie-cli/pkg/prompt" ) func Test_setCredentialCmd_runPrompt(t *testing.T) { type fields struct { - Setter credential.Setter - SingleSettings credential.SingleSettings - InputText prompt.InputText - InputBool prompt.InputBool - InputList prompt.InputList - InputPassword prompt.InputPassword + Setter credential.Setter + Operations credential.Operations + InputText prompt.InputText + InputBool prompt.InputBool + InputList prompt.InputList + InputPassword prompt.InputPassword } - tests := []struct { + var tests = []struct { name string fields fields wantErr bool @@ -25,36 +24,36 @@ func Test_setCredentialCmd_runPrompt(t *testing.T) { { name: "Run with success", fields: fields{ - Setter: credSetterMock{}, - SingleSettings: singleCredSettingsMock{}, - InputText: inputSecretMock{}, - InputBool: inputFalseMock{}, - InputList: inputListCredMock{}, - InputPassword: inputPasswordMock{}, + Setter: credSetterMock{}, + Operations: credSettingsMock{}, + InputText: inputSecretMock{}, + InputBool: inputFalseMock{}, + InputList: inputListCredMock{}, + InputPassword: inputPasswordMock{}, }, wantErr: false, }, { name: "Run with success AddNew", fields: fields{ - Setter: credSetterMock{}, - SingleSettings: singleCredSettingsMock{}, - InputText: inputSecretMock{}, - InputBool: inputFalseMock{}, - InputList: inputListCustomMock{credsingle.AddNew}, - InputPassword: inputPasswordMock{}, + Setter: credSetterMock{}, + Operations: credSettingsMock{}, + InputText: inputSecretMock{}, + InputBool: inputFalseMock{}, + InputList: inputListCustomMock{credential.AddNew}, + InputPassword: inputPasswordMock{}, }, wantErr: false, }, { name: "Fail when list return err", fields: fields{ - Setter: credSetterMock{}, - SingleSettings: singleCredSettingsMock{}, - InputText: inputSecretMock{}, - InputBool: inputFalseMock{}, - InputList: inputListErrorMock{}, - InputPassword: inputPasswordMock{}, + Setter: credSetterMock{}, + Operations: credSettingsMock{}, + InputText: inputSecretMock{}, + InputBool: inputFalseMock{}, + InputList: inputListErrorMock{}, + InputPassword: inputPasswordMock{}, }, wantErr: true, }, @@ -63,7 +62,7 @@ func Test_setCredentialCmd_runPrompt(t *testing.T) { t.Run(tt.name, func(t *testing.T) { o := NewSetCredentialCmd( tt.fields.Setter, - tt.fields.SingleSettings, + tt.fields.Operations, tt.fields.InputText, tt.fields.InputBool, tt.fields.InputList, diff --git a/pkg/cmd/show_context.go b/pkg/cmd/show_context.go index 89c8dbc8e..f6e15894d 100644 --- a/pkg/cmd/show_context.go +++ b/pkg/cmd/show_context.go @@ -10,10 +10,10 @@ import ( ) type showContextCmd struct { - rcontext.Finder + rcontext.CtxFinder } -func NewShowContextCmd(f rcontext.Finder) *cobra.Command { +func NewShowContextCmd(f rcontext.CtxFinder) *cobra.Command { s := showContextCmd{f} return &cobra.Command{ diff --git a/pkg/credential/credential.go b/pkg/credential/credential.go index 89864306b..67303971d 100644 --- a/pkg/credential/credential.go +++ b/pkg/credential/credential.go @@ -35,7 +35,7 @@ type ListCredData struct { // Fields are used to represents providers.json type Fields map[string][]Field -type CredSetter interface { +type Setter interface { Set(d Detail) error } diff --git a/pkg/credential/finder.go b/pkg/credential/finder.go index 4883e899a..3d8269953 100644 --- a/pkg/credential/finder.go +++ b/pkg/credential/finder.go @@ -9,10 +9,10 @@ import ( type Finder struct { homePath string - ctxFinder rcontext.Finder + ctxFinder rcontext.CtxFinder } -func NewFinder(homePath string, cf rcontext.Finder) Finder { +func NewFinder(homePath string, cf rcontext.CtxFinder) Finder { return Finder{ homePath: homePath, ctxFinder: cf, @@ -21,12 +21,14 @@ func NewFinder(homePath string, cf rcontext.Finder) Finder { func (f Finder) Find(provider string) (Detail, error) { ctx, err := f.ctxFinder.Find() + if err != nil { return Detail{}, err - } else if ctx.Current == "" { + } + if ctx.Current == "" { ctx.Current = rcontext.DefaultCtx } - + cb, err := fileutil.ReadFile(File(f.homePath, ctx.Current, provider)) if err != nil { return Detail{}, err @@ -36,6 +38,6 @@ func (f Finder) Find(provider string) (Detail, error) { if err := json.Unmarshal(cb, cred); err != nil { return Detail{}, err } - return *cred, nil + } diff --git a/pkg/credential/finder_test.go b/pkg/credential/finder_test.go index da7320029..dcb502ff2 100644 --- a/pkg/credential/finder_test.go +++ b/pkg/credential/finder_test.go @@ -1,30 +1,16 @@ package credential import ( - "errors" - "fmt" "os" "reflect" "testing" - - "github.com/ZupIT/ritchie-cli/pkg/rcontext" -) - -var ( - githubCred Detail - ctxFinder rcontext.Finder ) - - -var errTest = errors.New("Ai pai") - func TestFind(t *testing.T) { tmp := os.TempDir() setter := NewSetter(tmp, ctxFinder) err := setter.Set(githubCred) if err != nil { - fmt.Sprintln("Error in Set") return } finder := NewFinder(tmp, ctxFinder) @@ -44,7 +30,7 @@ func TestFind(t *testing.T) { in: "github", out: out{ cred: githubCred, - err:errTest , + err:nil , }, }, } @@ -53,7 +39,6 @@ func TestFind(t *testing.T) { t.Run(tt.name, func(t *testing.T) { out := tt.out got, err := finder.Find(tt.in) - if err != nil && err.Error() != out.err.Error() { t.Errorf("Find(%s) got %v, want %v", tt.name, err, out.err) } @@ -62,6 +47,5 @@ func TestFind(t *testing.T) { t.Errorf("Find(%s) got %v, want %v", tt.name, got, out.cred) } }) - fmt.Println(tt) } } diff --git a/pkg/credential/setter.go b/pkg/credential/setter.go index ea4207de2..1126fdffe 100644 --- a/pkg/credential/setter.go +++ b/pkg/credential/setter.go @@ -2,24 +2,25 @@ package credential import ( "encoding/json" + "fmt" "github.com/ZupIT/ritchie-cli/pkg/file/fileutil" "github.com/ZupIT/ritchie-cli/pkg/rcontext" ) -type Setter struct { +type SetManager struct { homePath string - ctxFinder rcontext.Finder + ctxFinder rcontext.CtxFinder } -func NewSetter(homePath string, cf rcontext.Finder) Setter { - return Setter{ +func NewSetter(homePath string, cf rcontext.CtxFinder) SetManager { + return SetManager{ homePath: homePath, ctxFinder: cf, } } -func (s Setter) Set(cred Detail) error { +func (s SetManager) Set(cred Detail) error { ctx, err := s.ctxFinder.Find() if err != nil { return err @@ -40,6 +41,7 @@ func (s Setter) Set(cred Detail) error { credFile := File(s.homePath, ctx.Current, cred.Service) if err := fileutil.WriteFilePerm(credFile, cb, 0600); err != nil { + fmt.Println(err) return err } diff --git a/pkg/credential/setter_test.go b/pkg/credential/setter_test.go index d2ba47d9c..fd99dc829 100644 --- a/pkg/credential/setter_test.go +++ b/pkg/credential/setter_test.go @@ -1,14 +1,21 @@ package credential import ( + "fmt" "os" "testing" + + "github.com/ZupIT/ritchie-cli/pkg/rcontext" +) + +var ( + githubCred = Detail{Service: "github"} + ctxFinder = rcontext.FindManager{CtxFile: ""} ) func TestSet(t *testing.T) { tmp := os.TempDir() setter := NewSetter(tmp, ctxFinder) - tests := []struct { name string in Detail @@ -26,7 +33,9 @@ func TestSet(t *testing.T) { got := setter.Set(tt.in) if got != tt.out { t.Errorf("Set(%s) got %v, want %v", tt.name, got, tt.out) + fmt.Println("ok") } }) } } + diff --git a/pkg/credential/settings_test.go b/pkg/credential/settings_test.go index 3f9e5fe2a..36fa1e164 100644 --- a/pkg/credential/settings_test.go +++ b/pkg/credential/settings_test.go @@ -18,17 +18,17 @@ func providersPath() string { return path } -func TestSingleSettings_ReadCredentials(t *testing.T) { - - credentials, err := credSettings.ReadCredentialsFields("../../../testdata/credentials.json") - if err != nil { - t.Errorf("Error on on read credentials function") - } - - if credentials == nil || len(credentials) <= 0 { - t.Errorf("Error on on read credentials function, cannot be empty or null") - } -} +// func TestSingleSettings_ReadCredentials(t *testing.T) { +// +// credentials, err := credSettings.ReadCredentialsFields("../../../testdata/credentials.json") +// if err != nil { +// t.Errorf("Error on on read credentials function") +// } +// +// if credentials == nil || len(credentials) <= 0 { +// t.Errorf("Error on on read credentials function, cannot be empty or null") +// } +// } func TestSingleSettings_WriteCredentials(t *testing.T) { err := credSettings.WriteCredentialsFields(NewDefaultCredentials(), providersPath()) diff --git a/pkg/rcontext/context.go b/pkg/rcontext/context.go index 8304e9c68..09c530415 100644 --- a/pkg/rcontext/context.go +++ b/pkg/rcontext/context.go @@ -15,7 +15,7 @@ type Setter interface { Set(ctx string) (ContextHolder, error) } -type Finder interface { +type CtxFinder interface { Find() (ContextHolder, error) } @@ -24,11 +24,11 @@ type Remover interface { } type FindRemover interface { - Finder + CtxFinder Remover } type FindSetter interface { - Finder + CtxFinder Setter } diff --git a/pkg/rcontext/find_remover.go b/pkg/rcontext/find_remover.go index 8a3e3e5e9..c1b1caf04 100644 --- a/pkg/rcontext/find_remover.go +++ b/pkg/rcontext/find_remover.go @@ -4,10 +4,10 @@ import "fmt" type FindRemoverManager struct { ctxFile string - Finder + CtxFinder Remover } -func NewFindRemover(homePath string, f Finder, r Remover) FindRemoverManager { +func NewFindRemover(homePath string, f CtxFinder, r Remover) FindRemoverManager { return FindRemoverManager{fmt.Sprintf(ContextPath, homePath), f, r} } diff --git a/pkg/rcontext/find_setter.go b/pkg/rcontext/find_setter.go index b2643b13c..47a9641a6 100644 --- a/pkg/rcontext/find_setter.go +++ b/pkg/rcontext/find_setter.go @@ -4,10 +4,10 @@ import "fmt" type FindSetterManager struct { ctxFile string - Finder + CtxFinder Setter } -func NewFindSetter(homePath string, f Finder, s Setter) FindSetterManager { +func NewFindSetter(homePath string, f CtxFinder, s Setter) FindSetterManager { return FindSetterManager{fmt.Sprintf(ContextPath, homePath), f, s} } diff --git a/pkg/rcontext/finder.go b/pkg/rcontext/finder.go index 079e5f83f..c63556317 100644 --- a/pkg/rcontext/finder.go +++ b/pkg/rcontext/finder.go @@ -8,21 +8,21 @@ import ( ) type FindManager struct { - ctxFile string + CtxFile string } func NewFinder(homePath string) FindManager { - return FindManager{ctxFile: fmt.Sprintf(ContextPath, homePath)} + return FindManager{CtxFile: fmt.Sprintf(ContextPath, homePath)} } func (f FindManager) Find() (ContextHolder, error) { ctxHolder := ContextHolder{} - if !fileutil.Exists(f.ctxFile) { + if !fileutil.Exists(f.CtxFile) { return ctxHolder, nil } - file, err := fileutil.ReadFile(f.ctxFile) + file, err := fileutil.ReadFile(f.CtxFile) if err != nil { return ctxHolder, err } diff --git a/pkg/rcontext/remover.go b/pkg/rcontext/remover.go index 7bb126105..577cc3329 100644 --- a/pkg/rcontext/remover.go +++ b/pkg/rcontext/remover.go @@ -9,10 +9,10 @@ import ( type RemoveManager struct { ctxFile string - finder Finder + finder CtxFinder } -func NewRemover(homePath string, f Finder) RemoveManager { +func NewRemover(homePath string, f CtxFinder) RemoveManager { return RemoveManager{ctxFile: fmt.Sprintf(ContextPath, homePath), finder: f} } diff --git a/pkg/rcontext/setter.go b/pkg/rcontext/setter.go index 62083e044..9a014d57e 100644 --- a/pkg/rcontext/setter.go +++ b/pkg/rcontext/setter.go @@ -11,10 +11,10 @@ import ( type SetterManager struct { ctxFile string - finder Finder + finder CtxFinder } -func NewSetter(homePath string, f Finder) Setter { +func NewSetter(homePath string, f CtxFinder) Setter { return SetterManager{ctxFile: fmt.Sprintf(ContextPath, homePath), finder: f} } diff --git a/run-tests.sh b/run-tests.sh index 3b268074a..81f767161 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -6,4 +6,4 @@ for i in $(go list ./pkg/... | grep -v vendor/); do go tool cover -func=bin/cov.out done -echo "\033[0;32m All tests run with success :D" \ No newline at end of file +echo "\033[0;32m All tests run with success" \ No newline at end of file From 10ab106e41a9442ce80dbf0801adf88936011bce Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Wed, 22 Jul 2020 18:52:05 -0300 Subject: [PATCH 10/27] fix lint --- pkg/cmd/list_credential.go | 2 +- pkg/cmd/mocks_test.go | 4 ++-- pkg/credential/credential.go | 2 +- pkg/credential/finder.go | 2 +- pkg/credential/settings.go | 4 ++-- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index 367b3fd07..2a848f523 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -60,7 +60,7 @@ func printCredentialsTable(fields credential.ListCredDatas) { func (l listCredentialCmd) run() CommandRunnerFunc { return func(cmd *cobra.Command, args []string) error { - data := l.Settings.ReadCredentialsValue(credential.CredentialsPath()) + data := l.Settings.ReadCredentialsValue() printCredentialsTable(data) return nil } diff --git a/pkg/cmd/mocks_test.go b/pkg/cmd/mocks_test.go index c5773d7e8..21252d942 100644 --- a/pkg/cmd/mocks_test.go +++ b/pkg/cmd/mocks_test.go @@ -231,8 +231,8 @@ func (s credSettingsMock) ReadCredentialsFields(path string) (credential.Fields, return credential.Fields{}, nil } -func (s credSettingsMock) ReadCredentialsValue(path string) string { - return "" +func (s credSettingsMock) ReadCredentialsValue() []credential.ListCredData { + return []credential.ListCredData{} } func (s credSettingsMock) WriteDefaultCredentialsFields(path string) error { diff --git a/pkg/credential/credential.go b/pkg/credential/credential.go index 67303971d..e8571a182 100644 --- a/pkg/credential/credential.go +++ b/pkg/credential/credential.go @@ -45,7 +45,7 @@ type CredFinder interface { type Operations interface { ReadCredentialsFields(path string) (Fields, error) - ReadCredentialsValue(path string) string + ReadCredentialsValue() []ListCredData WriteCredentialsFields(fields Fields, path string) error WriteDefaultCredentialsFields(path string) error } diff --git a/pkg/credential/finder.go b/pkg/credential/finder.go index 3d8269953..dc86851cd 100644 --- a/pkg/credential/finder.go +++ b/pkg/credential/finder.go @@ -28,7 +28,7 @@ func (f Finder) Find(provider string) (Detail, error) { if ctx.Current == "" { ctx.Current = rcontext.DefaultCtx } - + cb, err := fileutil.ReadFile(File(f.homePath, ctx.Current, provider)) if err != nil { return Detail{}, err diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index cfe427bea..d1fe9e2d3 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -34,7 +34,7 @@ func (s Settings) ReadCredentialsFields(path string) (Fields, error) { return fields, nil } -func (s Settings) ReadCredentialsValue(path string) []ListCredData { +func (s Settings) ReadCredentialsValue() []ListCredData { var creds []ListCredData var cred ListCredData var detail Detail @@ -44,7 +44,7 @@ func (s Settings) ReadCredentialsValue(path string) []ListCredData { providers := providerByCtx(c) for _, p := range providers { cBytes, _ := s.file.Read(CredentialsPath() + c + "/" + p) - json.Unmarshal(cBytes, &detail) + _ = json.Unmarshal(cBytes, &detail) for k, v := range detail.Credential { cred.Provider = detail.Service cred.Context = c From dbaf07452486f38d385b030306abb26eb363a41d Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Wed, 22 Jul 2020 19:56:47 -0300 Subject: [PATCH 11/27] remove single name on tests, --- pkg/cmd/list_credential.go | 2 +- pkg/cmd/list_credential_test.go | 29 +++++++++++++++++++---------- pkg/cmd/mocks_test.go | 4 ++-- pkg/credential/credential.go | 2 +- pkg/credential/settings.go | 9 +++++---- pkg/credential/settings_test.go | 28 ++++++++++++++-------------- 6 files changed, 42 insertions(+), 32 deletions(-) diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index 2a848f523..787c655e2 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -60,7 +60,7 @@ func printCredentialsTable(fields credential.ListCredDatas) { func (l listCredentialCmd) run() CommandRunnerFunc { return func(cmd *cobra.Command, args []string) error { - data := l.Settings.ReadCredentialsValue() + data, _ := l.Settings.ReadCredentialsValue() printCredentialsTable(data) return nil } diff --git a/pkg/cmd/list_credential_test.go b/pkg/cmd/list_credential_test.go index 738933041..b30bcb090 100644 --- a/pkg/cmd/list_credential_test.go +++ b/pkg/cmd/list_credential_test.go @@ -1,12 +1,21 @@ package cmd -// func TestNewListCredentialCmd(t *testing.T) { -// cmd := NewListCredentialCmd(credential.Settings{}) -// if cmd == nil { -// t.Errorf("NewListCredentialCmd got %v", cmd) -// } -// -// if err := cmd.Execute(); err != nil { -// t.Errorf("%s = %v, want %v", cmd.Use, err, nil) -// } -// } \ No newline at end of file +import ( + "testing" + + "github.com/ZupIT/ritchie-cli/pkg/credential" + "github.com/ZupIT/ritchie-cli/pkg/stream" +) + +func Test_ListCredentialCmd(t *testing.T) { + fileManager := stream.NewFileManager() + credSettings := credential.NewSettings(fileManager) + + t.Run("Success case", func(t *testing.T) { + o := NewListCredentialCmd(credSettings) + if err := o.Execute();err !=nil{ + t.Errorf("Test_ListCredentialCmd error = %s", err) + } + }) + +} diff --git a/pkg/cmd/mocks_test.go b/pkg/cmd/mocks_test.go index 21252d942..c8ed1622f 100644 --- a/pkg/cmd/mocks_test.go +++ b/pkg/cmd/mocks_test.go @@ -231,8 +231,8 @@ func (s credSettingsMock) ReadCredentialsFields(path string) (credential.Fields, return credential.Fields{}, nil } -func (s credSettingsMock) ReadCredentialsValue() []credential.ListCredData { - return []credential.ListCredData{} +func (s credSettingsMock) ReadCredentialsValue() ([]credential.ListCredData, error) { + return []credential.ListCredData{}, nil } func (s credSettingsMock) WriteDefaultCredentialsFields(path string) error { diff --git a/pkg/credential/credential.go b/pkg/credential/credential.go index e8571a182..76b30409a 100644 --- a/pkg/credential/credential.go +++ b/pkg/credential/credential.go @@ -45,7 +45,7 @@ type CredFinder interface { type Operations interface { ReadCredentialsFields(path string) (Fields, error) - ReadCredentialsValue() []ListCredData + ReadCredentialsValue() ([]ListCredData, error) WriteCredentialsFields(fields Fields, path string) error WriteDefaultCredentialsFields(path string) error } diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index d1fe9e2d3..b7842ba93 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -22,7 +22,6 @@ func NewSettings(file stream.FileWriteReadExister) Settings { func (s Settings) ReadCredentialsFields(path string) (Fields, error) { fields := Fields{} - if s.file.Exists(path) { cBytes, _ := s.file.Read(path) err := json.Unmarshal(cBytes, &fields) @@ -34,7 +33,7 @@ func (s Settings) ReadCredentialsFields(path string) (Fields, error) { return fields, nil } -func (s Settings) ReadCredentialsValue() []ListCredData { +func (s Settings) ReadCredentialsValue() ([]ListCredData, error) { var creds []ListCredData var cred ListCredData var detail Detail @@ -44,7 +43,9 @@ func (s Settings) ReadCredentialsValue() []ListCredData { providers := providerByCtx(c) for _, p := range providers { cBytes, _ := s.file.Read(CredentialsPath() + c + "/" + p) - _ = json.Unmarshal(cBytes, &detail) + if err := json.Unmarshal(cBytes, &detail); err != nil { + return creds, err + } for k, v := range detail.Credential { cred.Provider = detail.Service cred.Context = c @@ -54,7 +55,7 @@ func (s Settings) ReadCredentialsValue() []ListCredData { } } } - return creds + return creds, nil } func providerByCtx(ctx string) []string { diff --git a/pkg/credential/settings_test.go b/pkg/credential/settings_test.go index 36fa1e164..c5ed91f14 100644 --- a/pkg/credential/settings_test.go +++ b/pkg/credential/settings_test.go @@ -18,19 +18,19 @@ func providersPath() string { return path } -// func TestSingleSettings_ReadCredentials(t *testing.T) { -// -// credentials, err := credSettings.ReadCredentialsFields("../../../testdata/credentials.json") -// if err != nil { -// t.Errorf("Error on on read credentials function") -// } -// -// if credentials == nil || len(credentials) <= 0 { -// t.Errorf("Error on on read credentials function, cannot be empty or null") -// } -// } - -func TestSingleSettings_WriteCredentials(t *testing.T) { +func TestSettings_ReadCredentials(t *testing.T) { + + credentials, err := credSettings.ReadCredentialsFields("../../testdata/credentials.json") + if err != nil { + t.Errorf("Error on on read credentials function") + } + + if credentials == nil || len(credentials) <= 0 { + t.Errorf("Error on on read credentials function, cannot be empty or null") + } +} + +func TestSettings_WriteCredentials(t *testing.T) { err := credSettings.WriteCredentialsFields(NewDefaultCredentials(), providersPath()) defer os.Remove(providersPath()) if err != nil { @@ -38,7 +38,7 @@ func TestSingleSettings_WriteCredentials(t *testing.T) { } } -func TestSingleSettings_WriteDefaultCredentials(t *testing.T) { +func TestSettings_WriteDefaultCredentials(t *testing.T) { err := credSettings.WriteDefaultCredentialsFields(providersPath()) defer os.Remove(providersPath()) if err != nil { From 9b04bfcfcf121ac04de7d2c04d183b8b355662fa Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Wed, 22 Jul 2020 20:11:36 -0300 Subject: [PATCH 12/27] refactor --- pkg/cmd/list_credential.go | 9 ++++++++- pkg/credential/settings.go | 5 +---- pkg/env/envcredential/env_credential.go | 7 ++----- pkg/formula/runner/inputs.go | 2 -- pkg/prompt/color.go | 6 +----- run-tests.sh | 2 +- 6 files changed, 13 insertions(+), 18 deletions(-) diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index 787c655e2..1366b9056 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -1,6 +1,7 @@ package cmd import ( + "errors" "fmt" "github.com/gosuri/uitable" @@ -14,6 +15,9 @@ type listCredentialCmd struct { credential.Settings } +var setCredCmd = prompt.Bold("rit set credential") +var ErrCannotReadCredentials = errors.New("Cannot read any credentials. Use: " + setCredCmd) + func NewListCredentialCmd( ss credential.Settings) *cobra.Command { l := &listCredentialCmd{ss} @@ -60,7 +64,10 @@ func printCredentialsTable(fields credential.ListCredDatas) { func (l listCredentialCmd) run() CommandRunnerFunc { return func(cmd *cobra.Command, args []string) error { - data, _ := l.Settings.ReadCredentialsValue() + data, err := l.Settings.ReadCredentialsValue() + if err != nil { + return ErrCannotReadCredentials + } printCredentialsTable(data) return nil } diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index b7842ba93..9180270fb 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -72,10 +72,7 @@ func providerByCtx(ctx string) []string { func ctxArr() []string { var ctx []string - files, err := ioutil.ReadDir(CredentialsPath()) - if err != nil { - log.Fatal(err) - } + files, _ := ioutil.ReadDir(CredentialsPath()) for _, f := range files { if f.IsDir() { ctx = append(ctx, f.Name()) diff --git a/pkg/env/envcredential/env_credential.go b/pkg/env/envcredential/env_credential.go index 41aff26ce..31ea2b6c0 100644 --- a/pkg/env/envcredential/env_credential.go +++ b/pkg/env/envcredential/env_credential.go @@ -1,9 +1,9 @@ package envcredential import ( - "fmt" - "github.com/ZupIT/ritchie-cli/pkg/credential" "strings" + + "github.com/ZupIT/ritchie-cli/pkg/credential" ) type CredentialResolver struct { @@ -18,7 +18,6 @@ func NewResolver(cf credential.Finder) CredentialResolver { func (c CredentialResolver) Resolve(name string) (string, error) { s := strings.Split(name, "_") service := strings.ToLower(s[1]) - fmt.Println(s) cred, err := c.Find(service) if err != nil { @@ -26,7 +25,5 @@ func (c CredentialResolver) Resolve(name string) (string, error) { } k := strings.ToLower(s[2]) - fmt.Println(cred.Credential[k] + "aaa") - return cred.Credential[k], nil } diff --git a/pkg/formula/runner/inputs.go b/pkg/formula/runner/inputs.go index 2b2cdd098..d4c3ee31d 100644 --- a/pkg/formula/runner/inputs.go +++ b/pkg/formula/runner/inputs.go @@ -137,8 +137,6 @@ func (d InputManager) fromPrompt(cmd *exec.Cmd, setup formula.Setup) error { // add the variable inName=inValue to cmd.Env func addEnv(cmd *exec.Cmd, inName, inValue string) { e := fmt.Sprintf(formula.EnvPattern, strings.ToUpper(inName), inValue) - fmt.Println("ADDENV on inputs.go") - fmt.Println(e) cmd.Env = append(cmd.Env, e) } diff --git a/pkg/prompt/color.go b/pkg/prompt/color.go index f0ac59030..f508480b8 100644 --- a/pkg/prompt/color.go +++ b/pkg/prompt/color.go @@ -41,8 +41,4 @@ func Yellow(text string) string { } func Warning(text string) { color.Warn.Println(text) -} - -func Cyan(text string) string { - return color.Cyan.Render(text) -} +} \ No newline at end of file diff --git a/run-tests.sh b/run-tests.sh index 81f767161..ac160718c 100755 --- a/run-tests.sh +++ b/run-tests.sh @@ -6,4 +6,4 @@ for i in $(go list ./pkg/... | grep -v vendor/); do go tool cover -func=bin/cov.out done -echo "\033[0;32m All tests run with success" \ No newline at end of file +echo "\033[0;32m Unit tests run with success" \ No newline at end of file From fe6d95edc1803591ef121aab47260964fe89862f Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Thu, 23 Jul 2020 15:41:12 -0300 Subject: [PATCH 13/27] add test --- pkg/cmd/list_credential.go | 15 ++++++++------- pkg/cmd/mocks_test.go | 2 +- pkg/cmd/set_credential.go | 1 + pkg/credential/credential.go | 2 +- pkg/credential/settings.go | 23 +++++++++++------------ pkg/credential/settings_test.go | 21 ++++++++++++++++----- pkg/env/envcredential/env_credential.go | 1 - pkg/formula/runner/default_runner.go | 1 - pkg/formula/runner/docker_runner.go | 1 + pkg/prompt/color.go | 4 ++++ testdata/.rit/credentials/default/jenkins | 1 + 11 files changed, 44 insertions(+), 28 deletions(-) create mode 100644 testdata/.rit/credentials/default/jenkins diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index 1366b9056..89ee74a0d 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -1,7 +1,6 @@ package cmd import ( - "errors" "fmt" "github.com/gosuri/uitable" @@ -15,9 +14,6 @@ type listCredentialCmd struct { credential.Settings } -var setCredCmd = prompt.Bold("rit set credential") -var ErrCannotReadCredentials = errors.New("Cannot read any credentials. Use: " + setCredCmd) - func NewListCredentialCmd( ss credential.Settings) *cobra.Command { l := &listCredentialCmd{ss} @@ -59,14 +55,19 @@ func printCredentialsTable(fields credential.ListCredDatas) { for _, c := range fields { table.AddRow(c.Name, hideCredential(c.Value), c.Provider, c.Context) } - fmt.Println(table) + if len(table.Rows) < 2 { + setCmd := prompt.Cyan("rit set credential") + fmt.Printf("You dont have any credential, use %s\n", setCmd) + } else { + fmt.Println(table) + } } func (l listCredentialCmd) run() CommandRunnerFunc { return func(cmd *cobra.Command, args []string) error { - data, err := l.Settings.ReadCredentialsValue() + data, err := l.Settings.ReadCredentialsValue(credential.CredentialsPath()) if err != nil { - return ErrCannotReadCredentials + return err } printCredentialsTable(data) return nil diff --git a/pkg/cmd/mocks_test.go b/pkg/cmd/mocks_test.go index c8ed1622f..f32d6234a 100644 --- a/pkg/cmd/mocks_test.go +++ b/pkg/cmd/mocks_test.go @@ -231,7 +231,7 @@ func (s credSettingsMock) ReadCredentialsFields(path string) (credential.Fields, return credential.Fields{}, nil } -func (s credSettingsMock) ReadCredentialsValue() ([]credential.ListCredData, error) { +func (s credSettingsMock) ReadCredentialsValue(path string) ([]credential.ListCredData, error) { return []credential.ListCredData{}, nil } diff --git a/pkg/cmd/set_credential.go b/pkg/cmd/set_credential.go index 871e9ec95..0caf1e0d2 100644 --- a/pkg/cmd/set_credential.go +++ b/pkg/cmd/set_credential.go @@ -158,6 +158,7 @@ func (s setCredentialCmd) runStdin() CommandRunnerFunc { } prompt.Success(fmt.Sprintf("✔ %s credential saved!", strings.Title(cred.Service))) + prompt.Info("Check your credentials using rit list credential") return nil } } diff --git a/pkg/credential/credential.go b/pkg/credential/credential.go index 76b30409a..094f0a723 100644 --- a/pkg/credential/credential.go +++ b/pkg/credential/credential.go @@ -45,7 +45,7 @@ type CredFinder interface { type Operations interface { ReadCredentialsFields(path string) (Fields, error) - ReadCredentialsValue() ([]ListCredData, error) + ReadCredentialsValue(path string) ([]ListCredData, error) WriteCredentialsFields(fields Fields, path string) error WriteDefaultCredentialsFields(path string) error } diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index 9180270fb..f04985ea2 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "io/ioutil" - "log" "os" "github.com/ZupIT/ritchie-cli/pkg/stream" @@ -33,16 +32,16 @@ func (s Settings) ReadCredentialsFields(path string) (Fields, error) { return fields, nil } -func (s Settings) ReadCredentialsValue() ([]ListCredData, error) { +func (s Settings) ReadCredentialsValue(path string) ([]ListCredData, error) { var creds []ListCredData var cred ListCredData var detail Detail - ctx := ctxArr() + ctx := ctxArr(path) for _, c := range ctx { - providers := providerByCtx(c) + providers, _ := providerByCtx(c, path) for _, p := range providers { - cBytes, _ := s.file.Read(CredentialsPath() + c + "/" + p) + cBytes, _ := s.file.Read(path + c + "/" + p) if err := json.Unmarshal(cBytes, &detail); err != nil { return creds, err } @@ -58,21 +57,21 @@ func (s Settings) ReadCredentialsValue() ([]ListCredData, error) { return creds, nil } -func providerByCtx(ctx string) []string { +func providerByCtx(ctx , path string) ([]string, error) { var providers []string - files, err := ioutil.ReadDir(CredentialsPath() + "/" + ctx) + files, err := ioutil.ReadDir(path + "/" + ctx) if err != nil { - log.Fatal(err) + return providers, err } for _, f := range files { providers = append(providers, f.Name()) } - return providers + return providers, nil } -func ctxArr() []string { +func ctxArr(path string) []string { var ctx []string - files, _ := ioutil.ReadDir(CredentialsPath()) + files, _ := ioutil.ReadDir(path) for _, f := range files { if f.IsDir() { ctx = append(ctx, f.Name()) @@ -143,7 +142,7 @@ func NewDefaultCredentials() Fields { func ProviderPath() string { homeDir, _ := os.UserHomeDir() - providerDir := fmt.Sprintf("%s/.rit/credentials/providers.json", homeDir) + providerDir := fmt.Sprintf("%s/.rit/providers.json", homeDir) return providerDir } diff --git a/pkg/credential/settings_test.go b/pkg/credential/settings_test.go index c5ed91f14..d13a25739 100644 --- a/pkg/credential/settings_test.go +++ b/pkg/credential/settings_test.go @@ -18,15 +18,26 @@ func providersPath() string { return path } -func TestSettings_ReadCredentials(t *testing.T) { +func TestSettings_ReadCredentialsFields(t *testing.T) { credentials, err := credSettings.ReadCredentialsFields("../../testdata/credentials.json") if err != nil { - t.Errorf("Error on on read credentials function") + t.Errorf("Error reading credentials fields") } if credentials == nil || len(credentials) <= 0 { - t.Errorf("Error on on read credentials function, cannot be empty or null") + t.Errorf("Error reading credentials fields, cannot be empty or null") + } +} + +func TestSettings_ReadCredentialsValue(t *testing.T) { + credentials, err := credSettings.ReadCredentialsValue("../../testdata/.rit/credentials/") + if err != nil { + t.Errorf("Error reading credentials: %s", err) + } + + if credentials == nil || len(credentials) <= 0 { + t.Errorf("Error reading credentials, cannot be empty or null") } } @@ -34,7 +45,7 @@ func TestSettings_WriteCredentials(t *testing.T) { err := credSettings.WriteCredentialsFields(NewDefaultCredentials(), providersPath()) defer os.Remove(providersPath()) if err != nil { - t.Errorf("Error while write credentials: %s", err) + t.Errorf("Error writing credentials: %s", err) } } @@ -42,7 +53,7 @@ func TestSettings_WriteDefaultCredentials(t *testing.T) { err := credSettings.WriteDefaultCredentialsFields(providersPath()) defer os.Remove(providersPath()) if err != nil { - t.Errorf("Error while write credentials: %s", err) + t.Errorf("Error writing credentials: %s", err) } } diff --git a/pkg/env/envcredential/env_credential.go b/pkg/env/envcredential/env_credential.go index 31ea2b6c0..dbf9f8d1f 100644 --- a/pkg/env/envcredential/env_credential.go +++ b/pkg/env/envcredential/env_credential.go @@ -18,7 +18,6 @@ func NewResolver(cf credential.Finder) CredentialResolver { func (c CredentialResolver) Resolve(name string) (string, error) { s := strings.Split(name, "_") service := strings.ToLower(s[1]) - cred, err := c.Find(service) if err != nil { return "", err diff --git a/pkg/formula/runner/default_runner.go b/pkg/formula/runner/default_runner.go index c680dddf8..7ea6f6f18 100644 --- a/pkg/formula/runner/default_runner.go +++ b/pkg/formula/runner/default_runner.go @@ -36,7 +36,6 @@ func (d DefaultRunner) Run(def formula.Definition, inputType api.TermInputType) cmd.Env = os.Environ() pwdEnv := fmt.Sprintf(formula.EnvPattern, formula.PwdEnv, setup.Pwd) cPwdEnv := fmt.Sprintf(formula.EnvPattern, formula.CPwdEnv, setup.Pwd) - cmd.Env = append(cmd.Env, pwdEnv) cmd.Env = append(cmd.Env, cPwdEnv) diff --git a/pkg/formula/runner/docker_runner.go b/pkg/formula/runner/docker_runner.go index 80168388e..a14d1bfa3 100644 --- a/pkg/formula/runner/docker_runner.go +++ b/pkg/formula/runner/docker_runner.go @@ -47,6 +47,7 @@ func (d DockerRunner) Run(def formula.Definition, inputType api.TermInputType) e if err := d.Inputs(cmd, setup, inputType); err != nil { return err } + for _, e := range cmd.Env { // Create a file named .env and add the environment variable inName=inValue if !fileutil.Exists(envFile) { if err := fileutil.WriteFile(envFile, []byte(e+"\n")); err != nil { diff --git a/pkg/prompt/color.go b/pkg/prompt/color.go index f508480b8..c4cd2aa0c 100644 --- a/pkg/prompt/color.go +++ b/pkg/prompt/color.go @@ -41,4 +41,8 @@ func Yellow(text string) string { } func Warning(text string) { color.Warn.Println(text) +} + +func Cyan(text string) string { + return color.Cyan.Render(text) } \ No newline at end of file diff --git a/testdata/.rit/credentials/default/jenkins b/testdata/.rit/credentials/default/jenkins new file mode 100644 index 000000000..34d1882e3 --- /dev/null +++ b/testdata/.rit/credentials/default/jenkins @@ -0,0 +1 @@ +{"username":"","credential":{"token":"123ygy11231fhgd41h","username":"123","password":"pass"},"service":"github","type":""} \ No newline at end of file From ad7ffbf28aa4eab7bf06b8eddb9a1c79b22579c4 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Fri, 24 Jul 2020 09:36:45 -0300 Subject: [PATCH 14/27] add more test --- pkg/cmd/mocks_test.go | 10 ++++++-- pkg/cmd/set_credential_test.go | 12 ++++++++++ pkg/credential/settings_test.go | 42 ++++++++++++++++++++++++++++++--- 3 files changed, 59 insertions(+), 5 deletions(-) diff --git a/pkg/cmd/mocks_test.go b/pkg/cmd/mocks_test.go index f32d6234a..94327266e 100644 --- a/pkg/cmd/mocks_test.go +++ b/pkg/cmd/mocks_test.go @@ -30,6 +30,12 @@ func (inputTextValidatorMock) Text(name string, validate func(interface{}) error return "mocked text", nil } +type inputTextErrorMock struct{} + +func (inputTextErrorMock) Text(name string, required bool, helper ...string) (string, error) { + return "", errors.New("error on input text") +} + type inputSecretMock struct{} func (inputSecretMock) Text(name string, required bool, helper ...string) (string, error) { @@ -194,7 +200,7 @@ func (repoListerNonEmptyMock) List() (formula.Repos, error) { Name: "repoName", Priority: 0, }, - },nil + }, nil } type repoListerErrorMock struct{} @@ -223,7 +229,7 @@ func (credSetterMock) Set(d credential.Detail) error { return nil } -type credSettingsMock struct{ +type credSettingsMock struct { error } diff --git a/pkg/cmd/set_credential_test.go b/pkg/cmd/set_credential_test.go index 5e2b79791..08b7ba0f9 100644 --- a/pkg/cmd/set_credential_test.go +++ b/pkg/cmd/set_credential_test.go @@ -57,6 +57,18 @@ func Test_setCredentialCmd_runPrompt(t *testing.T) { }, wantErr: true, }, + { + name: "Fail when text return err", + fields: fields{ + Setter: credSetterMock{}, + Operations: credSettingsMock{}, + InputText: inputTextErrorMock{}, + InputBool: inputFalseMock{}, + InputList: inputListCustomMock{credential.AddNew}, + InputPassword: inputPasswordMock{}, + }, + wantErr: true, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/pkg/credential/settings_test.go b/pkg/credential/settings_test.go index d13a25739..ed032f9de 100644 --- a/pkg/credential/settings_test.go +++ b/pkg/credential/settings_test.go @@ -42,10 +42,35 @@ func TestSettings_ReadCredentialsValue(t *testing.T) { } func TestSettings_WriteCredentials(t *testing.T) { - err := credSettings.WriteCredentialsFields(NewDefaultCredentials(), providersPath()) defer os.Remove(providersPath()) - if err != nil { - t.Errorf("Error writing credentials: %s", err) + var tests = []struct { + name string + path string + fields Fields + wantErr bool + }{ + { + name: "Run with success", + path: providersPath(), + fields: NewDefaultCredentials(), + wantErr: false, + }, + { + name: "Error with invalid path", + path: "", + fields: NewDefaultCredentials(), + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := credSettings.WriteCredentialsFields(tt.fields, tt.path) + if (err != nil) != tt.wantErr { + t.Errorf("Write credentials fields error = %v, wantErr %v", err, tt.wantErr) + } + + }) } } @@ -79,6 +104,17 @@ func TestProviderPath(t *testing.T) { } } +func TestCredentialsPath(t *testing.T){ + credentials := CredentialsPath() + slicedPath := strings.Split(credentials, "/") + providersDir := slicedPath[len(slicedPath)-2] + + if providersDir != "credentials"{ + t.Errorf("Providers path must end on credentials dir") + } +} + + func TestProvidersArr(t *testing.T) { credentials := NewDefaultCredentials() providersArray := NewProviderArr(credentials) From cff13f169e8b7eb5af5217b00344bec1d193b1cd Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Fri, 24 Jul 2020 14:32:46 -0300 Subject: [PATCH 15/27] refactor --- pkg/cmd/list_credential.go | 3 +-- pkg/credential/setter.go | 2 -- pkg/credential/setter_test.go | 2 -- pkg/credential/settings.go | 4 +--- 4 files changed, 2 insertions(+), 9 deletions(-) diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index 89ee74a0d..c40e07d9f 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -14,8 +14,7 @@ type listCredentialCmd struct { credential.Settings } -func NewListCredentialCmd( - ss credential.Settings) *cobra.Command { +func NewListCredentialCmd(ss credential.Settings) *cobra.Command { l := &listCredentialCmd{ss} cmd := &cobra.Command{ diff --git a/pkg/credential/setter.go b/pkg/credential/setter.go index 1126fdffe..825cd4d5a 100644 --- a/pkg/credential/setter.go +++ b/pkg/credential/setter.go @@ -2,7 +2,6 @@ package credential import ( "encoding/json" - "fmt" "github.com/ZupIT/ritchie-cli/pkg/file/fileutil" "github.com/ZupIT/ritchie-cli/pkg/rcontext" @@ -41,7 +40,6 @@ func (s SetManager) Set(cred Detail) error { credFile := File(s.homePath, ctx.Current, cred.Service) if err := fileutil.WriteFilePerm(credFile, cb, 0600); err != nil { - fmt.Println(err) return err } diff --git a/pkg/credential/setter_test.go b/pkg/credential/setter_test.go index fd99dc829..8e87d454c 100644 --- a/pkg/credential/setter_test.go +++ b/pkg/credential/setter_test.go @@ -1,7 +1,6 @@ package credential import ( - "fmt" "os" "testing" @@ -33,7 +32,6 @@ func TestSet(t *testing.T) { got := setter.Set(tt.in) if got != tt.out { t.Errorf("Set(%s) got %v, want %v", tt.name, got, tt.out) - fmt.Println("ok") } }) } diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index f04985ea2..74cde2a68 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -23,12 +23,10 @@ func (s Settings) ReadCredentialsFields(path string) (Fields, error) { fields := Fields{} if s.file.Exists(path) { cBytes, _ := s.file.Read(path) - err := json.Unmarshal(cBytes, &fields) - if err != nil { + if err := json.Unmarshal(cBytes, &fields); err != nil { return fields, err } } - return fields, nil } From bfe9b949a3dd636f16564caa7bd9655fe0fbeed4 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Fri, 24 Jul 2020 15:35:13 -0300 Subject: [PATCH 16/27] path now use filepath.Join --- pkg/credential/settings.go | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index 74cde2a68..9a996eab6 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -2,9 +2,9 @@ package credential import ( "encoding/json" - "fmt" "io/ioutil" "os" + "path/filepath" "github.com/ZupIT/ritchie-cli/pkg/stream" ) @@ -39,7 +39,7 @@ func (s Settings) ReadCredentialsValue(path string) ([]ListCredData, error) { for _, c := range ctx { providers, _ := providerByCtx(c, path) for _, p := range providers { - cBytes, _ := s.file.Read(path + c + "/" + p) + cBytes, _ := s.file.Read(filepath.Join(path, c, p)) if err := json.Unmarshal(cBytes, &detail); err != nil { return creds, err } @@ -55,12 +55,13 @@ func (s Settings) ReadCredentialsValue(path string) ([]ListCredData, error) { return creds, nil } -func providerByCtx(ctx , path string) ([]string, error) { +func providerByCtx(ctx, path string) ([]string, error) { var providers []string - files, err := ioutil.ReadDir(path + "/" + ctx) + files, err := ioutil.ReadDir(filepath.Join(path, ctx)) if err != nil { - return providers, err + return providers, err } + for _, f := range files { providers = append(providers, f.Name()) } @@ -140,14 +141,12 @@ func NewDefaultCredentials() Fields { func ProviderPath() string { homeDir, _ := os.UserHomeDir() - providerDir := fmt.Sprintf("%s/.rit/providers.json", homeDir) - return providerDir + return filepath.Join(homeDir, ".rit/providers.json") } func CredentialsPath() string { homeDir, _ := os.UserHomeDir() - credentialPath := fmt.Sprintf("%s/.rit/credentials/", homeDir) - return credentialPath + return filepath.Join(homeDir, ".rit/credentials/") } func NewProviderArr(fields Fields) []string { From 53cf17a24673b529e6f83efee831e764fb46a221 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Fri, 24 Jul 2020 17:51:52 -0300 Subject: [PATCH 17/27] changed to dirManager --- cmd/main.go | 2 +- pkg/cmd/list_credential_test.go | 3 ++- pkg/credential/settings.go | 40 ++++++++------------------------- pkg/credential/settings_test.go | 6 +++-- pkg/stream/file.go | 7 ++++++ 5 files changed, 23 insertions(+), 35 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 140384242..8ac99fe8f 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -83,7 +83,7 @@ func buildCommands() *cobra.Command { credSetter := credential.NewSetter(ritchieHomeDir, ctxFinder) credFinder := credential.NewFinder(ritchieHomeDir, ctxFinder) treeManager := tree.NewTreeManager(ritchieHomeDir, repoLister, api.CoreCmds) - credSettings := credential.NewSettings(fileManager) + credSettings := credential.NewSettings(fileManager, dirManager) autocompleteGen := autocomplete.NewGenerator(treeManager) credResolver := envcredential.NewResolver(credFinder) envResolvers := make(env.Resolvers) diff --git a/pkg/cmd/list_credential_test.go b/pkg/cmd/list_credential_test.go index b30bcb090..839a2f1fa 100644 --- a/pkg/cmd/list_credential_test.go +++ b/pkg/cmd/list_credential_test.go @@ -9,7 +9,8 @@ import ( func Test_ListCredentialCmd(t *testing.T) { fileManager := stream.NewFileManager() - credSettings := credential.NewSettings(fileManager) + dirManager := stream.NewDirManager(fileManager) + credSettings := credential.NewSettings(fileManager, dirManager) t.Run("Success case", func(t *testing.T) { o := NewListCredentialCmd(credSettings) diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index 9a996eab6..31bd3e987 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -2,7 +2,6 @@ package credential import ( "encoding/json" - "io/ioutil" "os" "path/filepath" @@ -12,11 +11,15 @@ import ( const AddNew = "Add a new" type Settings struct { - file stream.FileWriteReadExister + file stream.FileWriteReadExisterLister + dir stream.DirLister } -func NewSettings(file stream.FileWriteReadExister) Settings { - return Settings{file: file} +func NewSettings(file stream.FileWriteReadExisterLister, dir stream.DirLister) Settings { + return Settings{ + file: file, + dir: dir, + } } func (s Settings) ReadCredentialsFields(path string) (Fields, error) { @@ -34,10 +37,9 @@ func (s Settings) ReadCredentialsValue(path string) ([]ListCredData, error) { var creds []ListCredData var cred ListCredData var detail Detail - ctx := ctxArr(path) - + ctx, _ := s.dir.List(path, true) for _, c := range ctx { - providers, _ := providerByCtx(c, path) + providers, _ := s.file.List(filepath.Join(path, c)) for _, p := range providers { cBytes, _ := s.file.Read(filepath.Join(path, c, p)) if err := json.Unmarshal(cBytes, &detail); err != nil { @@ -55,30 +57,6 @@ func (s Settings) ReadCredentialsValue(path string) ([]ListCredData, error) { return creds, nil } -func providerByCtx(ctx, path string) ([]string, error) { - var providers []string - files, err := ioutil.ReadDir(filepath.Join(path, ctx)) - if err != nil { - return providers, err - } - - for _, f := range files { - providers = append(providers, f.Name()) - } - return providers, nil -} - -func ctxArr(path string) []string { - var ctx []string - files, _ := ioutil.ReadDir(path) - for _, f := range files { - if f.IsDir() { - ctx = append(ctx, f.Name()) - } - } - return ctx -} - func (s Settings) WriteCredentialsFields(fields Fields, path string) error { fieldsData, err := json.Marshal(fields) if err != nil { diff --git a/pkg/credential/settings_test.go b/pkg/credential/settings_test.go index ed032f9de..404d034d6 100644 --- a/pkg/credential/settings_test.go +++ b/pkg/credential/settings_test.go @@ -10,7 +10,8 @@ import ( ) var fileManager = stream.NewFileManager() -var credSettings = NewSettings(fileManager) +var dirManager = stream.NewDirManager(fileManager) +var credSettings = NewSettings(fileManager, dirManager) func providersPath() string { tempDir := os.TempDir() @@ -107,7 +108,8 @@ func TestProviderPath(t *testing.T) { func TestCredentialsPath(t *testing.T){ credentials := CredentialsPath() slicedPath := strings.Split(credentials, "/") - providersDir := slicedPath[len(slicedPath)-2] + fmt.Println(slicedPath) + providersDir := slicedPath[len(slicedPath)-1] if providersDir != "credentials"{ t.Errorf("Providers path must end on credentials dir") diff --git a/pkg/stream/file.go b/pkg/stream/file.go index ca9a2fe57..a034b5b34 100644 --- a/pkg/stream/file.go +++ b/pkg/stream/file.go @@ -52,6 +52,13 @@ type FileWriteReadExister interface { FileExister } +type FileWriteReadExisterLister interface { + FileWriter + FileReader + FileExister + FileLister +} + type FileWriteReadExistRemover interface { FileWriter FileReader From e481ec6f0ede8c28806f75eee85a21b900582e16 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Mon, 27 Jul 2020 09:20:24 -0300 Subject: [PATCH 18/27] working on changes --- cmd/main.go | 2 +- pkg/credential/settings.go | 4 ++-- pkg/rcontext/finder.go | 14 +++++++++----- pkg/rcontext/finder_test.go | 12 +++++++++--- pkg/rcontext/remover_test.go | 5 ++++- pkg/rcontext/setter_test.go | 5 ++++- 6 files changed, 29 insertions(+), 13 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 8ac99fe8f..ae28d3bea 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -75,7 +75,7 @@ func buildCommands() *cobra.Command { repoPrioritySetter := repo.NewPrioritySetter(ritchieHomeDir, fileManager, dirManager) tplManager := template.NewManager(api.RitchieHomeDir()) - ctxFinder := rcontext.NewFinder(ritchieHomeDir) + ctxFinder := rcontext.NewFinder(ritchieHomeDir, fileManager) ctxSetter := rcontext.NewSetter(ritchieHomeDir, ctxFinder) ctxRemover := rcontext.NewRemover(ritchieHomeDir, ctxFinder) ctxFindSetter := rcontext.NewFindSetter(ritchieHomeDir, ctxFinder, ctxSetter) diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index 31bd3e987..d1dd680e8 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -12,13 +12,13 @@ const AddNew = "Add a new" type Settings struct { file stream.FileWriteReadExisterLister - dir stream.DirLister + dir stream.DirLister } func NewSettings(file stream.FileWriteReadExisterLister, dir stream.DirLister) Settings { return Settings{ file: file, - dir: dir, + dir: dir, } } diff --git a/pkg/rcontext/finder.go b/pkg/rcontext/finder.go index c63556317..dd04c5d0d 100644 --- a/pkg/rcontext/finder.go +++ b/pkg/rcontext/finder.go @@ -4,25 +4,29 @@ import ( "encoding/json" "fmt" - "github.com/ZupIT/ritchie-cli/pkg/file/fileutil" + "github.com/ZupIT/ritchie-cli/pkg/stream" ) type FindManager struct { CtxFile string + file stream.FileReadExister } -func NewFinder(homePath string) FindManager { - return FindManager{CtxFile: fmt.Sprintf(ContextPath, homePath)} +func NewFinder(homePath string, file stream.FileReadExister) FindManager { + return FindManager{ + CtxFile: fmt.Sprintf(ContextPath, homePath), + file: file, + } } func (f FindManager) Find() (ContextHolder, error) { ctxHolder := ContextHolder{} - if !fileutil.Exists(f.CtxFile) { + if !f.file.Exists(f.CtxFile) { return ctxHolder, nil } - file, err := fileutil.ReadFile(f.CtxFile) + file, err := f.file.Read(f.CtxFile) if err != nil { return ctxHolder, err } diff --git a/pkg/rcontext/finder_test.go b/pkg/rcontext/finder_test.go index 7010babcb..343c950c4 100644 --- a/pkg/rcontext/finder_test.go +++ b/pkg/rcontext/finder_test.go @@ -5,11 +5,14 @@ import ( "os" "reflect" "testing" + + "github.com/ZupIT/ritchie-cli/pkg/stream" ) func TestFind(t *testing.T) { tmp := os.TempDir() - finder := NewFinder(tmp) + file := stream.NewFileManager() + finder := NewFinder(tmp, file) setter := NewSetter(tmp, finder) type in struct { @@ -29,9 +32,12 @@ func TestFind(t *testing.T) { }{ { name: "empty context", - in: nil, + in: &in{ + ctx: "", + holder: ContextHolder{Current: ""}, + }, out: &out{ - want: ContextHolder{}, + want: ContextHolder{Current: ""}, err: nil, }, }, diff --git a/pkg/rcontext/remover_test.go b/pkg/rcontext/remover_test.go index f40beec9e..eb8e1edef 100644 --- a/pkg/rcontext/remover_test.go +++ b/pkg/rcontext/remover_test.go @@ -5,11 +5,14 @@ import ( "os" "reflect" "testing" + + "github.com/ZupIT/ritchie-cli/pkg/stream" ) func TestRemove(t *testing.T) { tmp := os.TempDir() - finder := NewFinder(tmp) + file := stream.NewFileManager() + finder := NewFinder(tmp, file) setter := NewSetter(tmp, finder) remover := NewRemover(tmp, finder) diff --git a/pkg/rcontext/setter_test.go b/pkg/rcontext/setter_test.go index f9e9d3c79..4ab020746 100644 --- a/pkg/rcontext/setter_test.go +++ b/pkg/rcontext/setter_test.go @@ -4,11 +4,14 @@ import ( "os" "reflect" "testing" + + "github.com/ZupIT/ritchie-cli/pkg/stream" ) func TestSet(t *testing.T) { tmp := os.TempDir() - finder := NewFinder(tmp) + file := stream.NewFileManager() + finder := NewFinder(tmp, file) setter := NewSetter(tmp, finder) type out struct { From 689d963e4a374d943107b18571043e58a1fb9841 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Mon, 27 Jul 2020 13:32:15 -0300 Subject: [PATCH 19/27] whatever --- pkg/stream/mocks/mock.go | 1 + 1 file changed, 1 insertion(+) create mode 100644 pkg/stream/mocks/mock.go diff --git a/pkg/stream/mocks/mock.go b/pkg/stream/mocks/mock.go new file mode 100644 index 000000000..f726b26e5 --- /dev/null +++ b/pkg/stream/mocks/mock.go @@ -0,0 +1 @@ +package mocks From 1055ac0f7019b3bd50ef98d0ca222d73157266d9 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Mon, 27 Jul 2020 13:32:40 -0300 Subject: [PATCH 20/27] whatever --- pkg/rcontext/finder_test.go | 93 ++++++++++++++++++++++++++----------- pkg/stream/mocks/mock.go | 31 ++++++++++++- 2 files changed, 96 insertions(+), 28 deletions(-) diff --git a/pkg/rcontext/finder_test.go b/pkg/rcontext/finder_test.go index 343c950c4..a76f49ce4 100644 --- a/pkg/rcontext/finder_test.go +++ b/pkg/rcontext/finder_test.go @@ -1,23 +1,21 @@ package rcontext import ( - "fmt" + "errors" "os" "reflect" "testing" "github.com/ZupIT/ritchie-cli/pkg/stream" + sMock "github.com/ZupIT/ritchie-cli/pkg/stream/mocks" ) func TestFind(t *testing.T) { tmp := os.TempDir() - file := stream.NewFileManager() - finder := NewFinder(tmp, file) - setter := NewSetter(tmp, finder) type in struct { - ctx string - holder ContextHolder + holder ContextHolder + FileReadExister stream.FileReadExister } type out struct { @@ -31,48 +29,89 @@ func TestFind(t *testing.T) { out *out }{ { - name: "empty context", - in: &in{ - ctx: "", + name: "default context and existing ctx file", + in: &in{ holder: ContextHolder{Current: ""}, + FileReadExister: sMock.FileReadExisterCustomMock{ + ReadMock: func(path string) ([]byte, error) { + return []byte("{\"current_context\":\"default\"}"), nil + }, + ExistsMock: func(path string) bool { + return true + }, + }, }, out: &out{ - want: ContextHolder{Current: ""}, + want: ContextHolder{Current: "default"}, err: nil, }, }, { - name: "dev context", + name: "default context and missing ctx file", in: &in{ - ctx: dev, - holder: ContextHolder{Current: dev}, + holder: ContextHolder{Current: ""}, + FileReadExister: sMock.FileReadExisterCustomMock{ + ReadMock: func(path string) ([]byte, error) { + return []byte("{\"current_context\":\"default\"}"), nil + }, + ExistsMock: func(path string) bool { + return false + }, + }, }, out: &out{ - want: ContextHolder{Current: dev, All: []string{dev}}, + want: ContextHolder{Current: ""}, err: nil, }, }, + { + name: "default context and error on read file", + in: &in{ + holder: ContextHolder{Current: ""}, + FileReadExister: sMock.FileReadExisterCustomMock{ + ReadMock: func(path string) ([]byte, error) { + return []byte(""), errors.New("error reading file") + }, + ExistsMock: func(path string) bool { + return true + }, + }, + }, + out: &out{ + want: ContextHolder{Current: ""}, + err: errors.New("error reading file"), + }, + }, + { + name: "default context and incorrect json", + in: &in{ + holder: ContextHolder{Current: "default"}, + FileReadExister: sMock.FileReadExisterCustomMock{ + ReadMock: func(path string) ([]byte, error) { + return []byte(""), nil + }, + ExistsMock: func(path string) bool { + return true + }, + }, + }, + out: &out{ + want: ContextHolder{Current: ""}, + err: errors.New("unexpected end of JSON input"), + }, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - in := tt.in - if in != nil { - _, err := setter.Set(in.ctx) - if err != nil { - fmt.Sprintln("Error in Set") - return - } - } - + finder := NewFinder(tmp, tt.in.FileReadExister) out := tt.out got, err := finder.Find() - if err != nil { - t.Errorf("Find(%s) got %v, want %v", tt.name, err, out.err) + if err != nil && err.Error() != out.err.Error() { + t.Errorf("Find(%s) - Execution error - got %v, want %v", tt.name, err, out.err) } if !reflect.DeepEqual(out.want, got) { - t.Errorf("Find(%s) got %v, want %v", tt.name, got, out.want) + t.Errorf("Find(%s) - Error in the expected response - got %v, want %v", tt.name, got, out.want) } }) } diff --git a/pkg/stream/mocks/mock.go b/pkg/stream/mocks/mock.go index f726b26e5..3b4029ad2 100644 --- a/pkg/stream/mocks/mock.go +++ b/pkg/stream/mocks/mock.go @@ -1 +1,30 @@ -package mocks +package stream + +type FileReadExisterCustomMock struct { + ReadMock func(path string) ([]byte, error) + ExistsMock func(path string) bool +} + +// Read of FileManagerCustomMock +func (fmc FileReadExisterCustomMock) Read(path string) ([]byte, error) { + return fmc.ReadMock(path) +} + +// Exists of FileManagerCustomMock +func (fmc FileReadExisterCustomMock) Exists(path string) bool { + return fmc.ExistsMock(path) +} + +type FileWriterCustomMock struct { + WriteMock func(path string, content []byte) error +} + +func (wcm FileWriterCustomMock) Write(path string, content []byte) error { + return wcm.WriteMock(path, content) +} + +type FileWriterMock struct{} + +func (FileWriterMock) Write(path string, content []byte) error { + return nil +} \ No newline at end of file From cd59c46e22515304cd96c814c78138ff0285d4c5 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Mon, 27 Jul 2020 13:34:28 -0300 Subject: [PATCH 21/27] mocks --- pkg/stream/mocks/mock.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 pkg/stream/mocks/mock.go diff --git a/pkg/stream/mocks/mock.go b/pkg/stream/mocks/mock.go new file mode 100644 index 000000000..3b4029ad2 --- /dev/null +++ b/pkg/stream/mocks/mock.go @@ -0,0 +1,30 @@ +package stream + +type FileReadExisterCustomMock struct { + ReadMock func(path string) ([]byte, error) + ExistsMock func(path string) bool +} + +// Read of FileManagerCustomMock +func (fmc FileReadExisterCustomMock) Read(path string) ([]byte, error) { + return fmc.ReadMock(path) +} + +// Exists of FileManagerCustomMock +func (fmc FileReadExisterCustomMock) Exists(path string) bool { + return fmc.ExistsMock(path) +} + +type FileWriterCustomMock struct { + WriteMock func(path string, content []byte) error +} + +func (wcm FileWriterCustomMock) Write(path string, content []byte) error { + return wcm.WriteMock(path, content) +} + +type FileWriterMock struct{} + +func (FileWriterMock) Write(path string, content []byte) error { + return nil +} \ No newline at end of file From 0f1197c7d2cc34404e56851e1d622f49bd0bb9f6 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Mon, 27 Jul 2020 15:00:44 -0300 Subject: [PATCH 22/27] separate operations interface --- cmd/main.go | 2 +- pkg/cmd/list_credential_test.go | 4 +- pkg/cmd/set_credential.go | 8 +-- pkg/cmd/set_credential_test.go | 12 ++--- pkg/cmd/show_context.go | 4 +- pkg/credential/credential.go | 10 +++- pkg/credential/finder.go | 4 +- pkg/credential/finder_test.go | 2 +- pkg/credential/setter.go | 12 ++--- pkg/credential/setter_test.go | 13 ++++- pkg/credential/settings.go | 4 +- pkg/credential/settings_test.go | 3 +- pkg/rcontext/context.go | 6 +-- pkg/rcontext/find_remover.go | 4 +- pkg/rcontext/find_setter.go | 4 +- pkg/rcontext/finder.go | 8 +-- pkg/rcontext/finder_test.go | 95 +++++++++++++++++++++++---------- pkg/rcontext/remover.go | 4 +- pkg/rcontext/setter.go | 4 +- 19 files changed, 132 insertions(+), 71 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index ae28d3bea..b8b88cb27 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -83,7 +83,7 @@ func buildCommands() *cobra.Command { credSetter := credential.NewSetter(ritchieHomeDir, ctxFinder) credFinder := credential.NewFinder(ritchieHomeDir, ctxFinder) treeManager := tree.NewTreeManager(ritchieHomeDir, repoLister, api.CoreCmds) - credSettings := credential.NewSettings(fileManager, dirManager) + credSettings := credential.NewSettings(fileManager, dirManager, userHomeDir) autocompleteGen := autocomplete.NewGenerator(treeManager) credResolver := envcredential.NewResolver(credFinder) envResolvers := make(env.Resolvers) diff --git a/pkg/cmd/list_credential_test.go b/pkg/cmd/list_credential_test.go index 839a2f1fa..173acc1d1 100644 --- a/pkg/cmd/list_credential_test.go +++ b/pkg/cmd/list_credential_test.go @@ -1,6 +1,7 @@ package cmd import ( + "os" "testing" "github.com/ZupIT/ritchie-cli/pkg/credential" @@ -10,7 +11,8 @@ import ( func Test_ListCredentialCmd(t *testing.T) { fileManager := stream.NewFileManager() dirManager := stream.NewDirManager(fileManager) - credSettings := credential.NewSettings(fileManager, dirManager) + homeDir, _ := os.UserHomeDir() + credSettings := credential.NewSettings(fileManager, dirManager, homeDir) t.Run("Success case", func(t *testing.T) { o := NewListCredentialCmd(credSettings) diff --git a/pkg/cmd/set_credential.go b/pkg/cmd/set_credential.go index 0caf1e0d2..6e78206eb 100644 --- a/pkg/cmd/set_credential.go +++ b/pkg/cmd/set_credential.go @@ -17,7 +17,7 @@ var inputTypes = []string{"plain text", "secret"} // setCredentialCmd type for set credential command type setCredentialCmd struct { credential.Setter - credential.Operations + credential.ReaderWriter prompt.InputText prompt.InputBool prompt.InputList @@ -27,15 +27,15 @@ type setCredentialCmd struct { // NewSetCredentialCmd creates a new cmd instance func NewSetCredentialCmd( credSetter credential.Setter, - credSetting credential.Operations, + file credential.ReaderWriter, inText prompt.InputText, inBool prompt.InputBool, inList prompt.InputList, inPass prompt.InputPassword, ) *cobra.Command { s := &setCredentialCmd{ - Setter: credSetter, - Operations: credSetting, + Setter: credSetter, + ReaderWriter: file, InputText: inText, InputBool: inBool, InputList: inList, diff --git a/pkg/cmd/set_credential_test.go b/pkg/cmd/set_credential_test.go index 08b7ba0f9..2d41b74e5 100644 --- a/pkg/cmd/set_credential_test.go +++ b/pkg/cmd/set_credential_test.go @@ -10,7 +10,7 @@ import ( func Test_setCredentialCmd_runPrompt(t *testing.T) { type fields struct { Setter credential.Setter - Operations credential.Operations + file credential.ReaderWriter InputText prompt.InputText InputBool prompt.InputBool InputList prompt.InputList @@ -25,7 +25,7 @@ func Test_setCredentialCmd_runPrompt(t *testing.T) { name: "Run with success", fields: fields{ Setter: credSetterMock{}, - Operations: credSettingsMock{}, + file: credSettingsMock{}, InputText: inputSecretMock{}, InputBool: inputFalseMock{}, InputList: inputListCredMock{}, @@ -37,7 +37,7 @@ func Test_setCredentialCmd_runPrompt(t *testing.T) { name: "Run with success AddNew", fields: fields{ Setter: credSetterMock{}, - Operations: credSettingsMock{}, + file: credSettingsMock{}, InputText: inputSecretMock{}, InputBool: inputFalseMock{}, InputList: inputListCustomMock{credential.AddNew}, @@ -49,7 +49,7 @@ func Test_setCredentialCmd_runPrompt(t *testing.T) { name: "Fail when list return err", fields: fields{ Setter: credSetterMock{}, - Operations: credSettingsMock{}, + file: credSettingsMock{}, InputText: inputSecretMock{}, InputBool: inputFalseMock{}, InputList: inputListErrorMock{}, @@ -61,7 +61,7 @@ func Test_setCredentialCmd_runPrompt(t *testing.T) { name: "Fail when text return err", fields: fields{ Setter: credSetterMock{}, - Operations: credSettingsMock{}, + file: credSettingsMock{}, InputText: inputTextErrorMock{}, InputBool: inputFalseMock{}, InputList: inputListCustomMock{credential.AddNew}, @@ -74,7 +74,7 @@ func Test_setCredentialCmd_runPrompt(t *testing.T) { t.Run(tt.name, func(t *testing.T) { o := NewSetCredentialCmd( tt.fields.Setter, - tt.fields.Operations, + tt.fields.file, tt.fields.InputText, tt.fields.InputBool, tt.fields.InputList, diff --git a/pkg/cmd/show_context.go b/pkg/cmd/show_context.go index f6e15894d..89c8dbc8e 100644 --- a/pkg/cmd/show_context.go +++ b/pkg/cmd/show_context.go @@ -10,10 +10,10 @@ import ( ) type showContextCmd struct { - rcontext.CtxFinder + rcontext.Finder } -func NewShowContextCmd(f rcontext.CtxFinder) *cobra.Command { +func NewShowContextCmd(f rcontext.Finder) *cobra.Command { s := showContextCmd{f} return &cobra.Command{ diff --git a/pkg/credential/credential.go b/pkg/credential/credential.go index 094f0a723..951682d3d 100644 --- a/pkg/credential/credential.go +++ b/pkg/credential/credential.go @@ -43,10 +43,18 @@ type CredFinder interface { Find(service string) (Detail, error) } -type Operations interface { +type Reader interface { ReadCredentialsFields(path string) (Fields, error) ReadCredentialsValue(path string) ([]ListCredData, error) +} + +type Writer interface { WriteCredentialsFields(fields Fields, path string) error WriteDefaultCredentialsFields(path string) error } +type ReaderWriter interface { + Reader + Writer +} + diff --git a/pkg/credential/finder.go b/pkg/credential/finder.go index dc86851cd..55aab3fa0 100644 --- a/pkg/credential/finder.go +++ b/pkg/credential/finder.go @@ -9,10 +9,10 @@ import ( type Finder struct { homePath string - ctxFinder rcontext.CtxFinder + ctxFinder rcontext.Finder } -func NewFinder(homePath string, cf rcontext.CtxFinder) Finder { +func NewFinder(homePath string, cf rcontext.Finder) Finder { return Finder{ homePath: homePath, ctxFinder: cf, diff --git a/pkg/credential/finder_test.go b/pkg/credential/finder_test.go index dcb502ff2..6b53b10e4 100644 --- a/pkg/credential/finder_test.go +++ b/pkg/credential/finder_test.go @@ -30,7 +30,7 @@ func TestFind(t *testing.T) { in: "github", out: out{ cred: githubCred, - err:nil , + err: nil, }, }, } diff --git a/pkg/credential/setter.go b/pkg/credential/setter.go index 825cd4d5a..73c9730fb 100644 --- a/pkg/credential/setter.go +++ b/pkg/credential/setter.go @@ -8,19 +8,19 @@ import ( ) type SetManager struct { - homePath string - ctxFinder rcontext.CtxFinder + homePath string + ctx rcontext.Finder } -func NewSetter(homePath string, cf rcontext.CtxFinder) SetManager { +func NewSetter(homePath string, cf rcontext.Finder) SetManager { return SetManager{ - homePath: homePath, - ctxFinder: cf, + homePath: homePath, + ctx: cf, } } func (s SetManager) Set(cred Detail) error { - ctx, err := s.ctxFinder.Find() + ctx, err := s.ctx.Find() if err != nil { return err } diff --git a/pkg/credential/setter_test.go b/pkg/credential/setter_test.go index 8e87d454c..32c8a0a20 100644 --- a/pkg/credential/setter_test.go +++ b/pkg/credential/setter_test.go @@ -5,14 +5,24 @@ import ( "testing" "github.com/ZupIT/ritchie-cli/pkg/rcontext" + stream "github.com/ZupIT/ritchie-cli/pkg/stream/mocks" ) var ( githubCred = Detail{Service: "github"} - ctxFinder = rcontext.FindManager{CtxFile: ""} + streamMock = stream.FileReadExisterCustomMock{ + ReadMock: func(path string) ([]byte, error) { + return []byte("{\"current_context\":\"default\"}"), nil + }, + ExistsMock: func(path string) bool { + return true + }, + } + ctxFinder = rcontext.FindManager{CtxFile: "", File: streamMock} ) func TestSet(t *testing.T) { + tmp := os.TempDir() setter := NewSetter(tmp, ctxFinder) tests := []struct { @@ -36,4 +46,3 @@ func TestSet(t *testing.T) { }) } } - diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index d1dd680e8..9e8d399ba 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -13,12 +13,14 @@ const AddNew = "Add a new" type Settings struct { file stream.FileWriteReadExisterLister dir stream.DirLister + homeDir string } -func NewSettings(file stream.FileWriteReadExisterLister, dir stream.DirLister) Settings { +func NewSettings(file stream.FileWriteReadExisterLister, dir stream.DirLister, homeDir string) Settings { return Settings{ file: file, dir: dir, + homeDir : homeDir, } } diff --git a/pkg/credential/settings_test.go b/pkg/credential/settings_test.go index 404d034d6..5713ba549 100644 --- a/pkg/credential/settings_test.go +++ b/pkg/credential/settings_test.go @@ -11,7 +11,8 @@ import ( var fileManager = stream.NewFileManager() var dirManager = stream.NewDirManager(fileManager) -var credSettings = NewSettings(fileManager, dirManager) +var homeDir, _ = os.UserHomeDir() +var credSettings = NewSettings(fileManager, dirManager, homeDir) func providersPath() string { tempDir := os.TempDir() diff --git a/pkg/rcontext/context.go b/pkg/rcontext/context.go index 09c530415..8304e9c68 100644 --- a/pkg/rcontext/context.go +++ b/pkg/rcontext/context.go @@ -15,7 +15,7 @@ type Setter interface { Set(ctx string) (ContextHolder, error) } -type CtxFinder interface { +type Finder interface { Find() (ContextHolder, error) } @@ -24,11 +24,11 @@ type Remover interface { } type FindRemover interface { - CtxFinder + Finder Remover } type FindSetter interface { - CtxFinder + Finder Setter } diff --git a/pkg/rcontext/find_remover.go b/pkg/rcontext/find_remover.go index c1b1caf04..8a3e3e5e9 100644 --- a/pkg/rcontext/find_remover.go +++ b/pkg/rcontext/find_remover.go @@ -4,10 +4,10 @@ import "fmt" type FindRemoverManager struct { ctxFile string - CtxFinder + Finder Remover } -func NewFindRemover(homePath string, f CtxFinder, r Remover) FindRemoverManager { +func NewFindRemover(homePath string, f Finder, r Remover) FindRemoverManager { return FindRemoverManager{fmt.Sprintf(ContextPath, homePath), f, r} } diff --git a/pkg/rcontext/find_setter.go b/pkg/rcontext/find_setter.go index 47a9641a6..b2643b13c 100644 --- a/pkg/rcontext/find_setter.go +++ b/pkg/rcontext/find_setter.go @@ -4,10 +4,10 @@ import "fmt" type FindSetterManager struct { ctxFile string - CtxFinder + Finder Setter } -func NewFindSetter(homePath string, f CtxFinder, s Setter) FindSetterManager { +func NewFindSetter(homePath string, f Finder, s Setter) FindSetterManager { return FindSetterManager{fmt.Sprintf(ContextPath, homePath), f, s} } diff --git a/pkg/rcontext/finder.go b/pkg/rcontext/finder.go index dd04c5d0d..e0c65aab4 100644 --- a/pkg/rcontext/finder.go +++ b/pkg/rcontext/finder.go @@ -9,24 +9,24 @@ import ( type FindManager struct { CtxFile string - file stream.FileReadExister + File stream.FileReadExister } func NewFinder(homePath string, file stream.FileReadExister) FindManager { return FindManager{ CtxFile: fmt.Sprintf(ContextPath, homePath), - file: file, + File: file, } } func (f FindManager) Find() (ContextHolder, error) { ctxHolder := ContextHolder{} - if !f.file.Exists(f.CtxFile) { + if !f.File.Exists(f.CtxFile) { return ctxHolder, nil } - file, err := f.file.Read(f.CtxFile) + file, err := f.File.Read(f.CtxFile) if err != nil { return ctxHolder, err } diff --git a/pkg/rcontext/finder_test.go b/pkg/rcontext/finder_test.go index 343c950c4..4975a1095 100644 --- a/pkg/rcontext/finder_test.go +++ b/pkg/rcontext/finder_test.go @@ -1,23 +1,21 @@ package rcontext import ( - "fmt" + "errors" "os" "reflect" "testing" "github.com/ZupIT/ritchie-cli/pkg/stream" + sMock "github.com/ZupIT/ritchie-cli/pkg/stream/mocks" ) func TestFind(t *testing.T) { tmp := os.TempDir() - file := stream.NewFileManager() - finder := NewFinder(tmp, file) - setter := NewSetter(tmp, finder) type in struct { - ctx string - holder ContextHolder + holder ContextHolder + FileReadExister stream.FileReadExister } type out struct { @@ -31,49 +29,90 @@ func TestFind(t *testing.T) { out *out }{ { - name: "empty context", - in: &in{ - ctx: "", + name: "default context and existing ctx file", + in: &in{ holder: ContextHolder{Current: ""}, + FileReadExister: sMock.FileReadExisterCustomMock{ + ReadMock: func(path string) ([]byte, error) { + return []byte("{\"current_context\":\"default\"}"), nil + }, + ExistsMock: func(path string) bool { + return true + }, + }, }, out: &out{ - want: ContextHolder{Current: ""}, + want: ContextHolder{Current: "default"}, err: nil, }, }, { - name: "dev context", + name: "default context and missing ctx file", in: &in{ - ctx: dev, - holder: ContextHolder{Current: dev}, + holder: ContextHolder{Current: ""}, + FileReadExister: sMock.FileReadExisterCustomMock{ + ReadMock: func(path string) ([]byte, error) { + return []byte("{\"current_context\":\"default\"}"), nil + }, + ExistsMock: func(path string) bool { + return false + }, + }, }, out: &out{ - want: ContextHolder{Current: dev, All: []string{dev}}, + want: ContextHolder{Current: ""}, err: nil, }, }, + { + name: "default context and error on read file", + in: &in{ + holder: ContextHolder{Current: ""}, + FileReadExister: sMock.FileReadExisterCustomMock{ + ReadMock: func(path string) ([]byte, error) { + return []byte(""), errors.New("error reading file") + }, + ExistsMock: func(path string) bool { + return true + }, + }, + }, + out: &out{ + want: ContextHolder{Current: ""}, + err: errors.New("error reading file"), + }, + }, + { + name: "default context and incorrect json", + in: &in{ + holder: ContextHolder{Current: "default"}, + FileReadExister: sMock.FileReadExisterCustomMock{ + ReadMock: func(path string) ([]byte, error) { + return []byte(""), nil + }, + ExistsMock: func(path string) bool { + return true + }, + }, + }, + out: &out{ + want: ContextHolder{Current: ""}, + err: errors.New("unexpected end of JSON input"), + }, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - - in := tt.in - if in != nil { - _, err := setter.Set(in.ctx) - if err != nil { - fmt.Sprintln("Error in Set") - return - } - } - + finder := NewFinder(tmp, tt.in.FileReadExister) out := tt.out got, err := finder.Find() - if err != nil { - t.Errorf("Find(%s) got %v, want %v", tt.name, err, out.err) + if err != nil && err.Error() != out.err.Error() { + t.Errorf("Find(%s) - Execution error - got %v, want %v", tt.name, err, out.err) } if !reflect.DeepEqual(out.want, got) { - t.Errorf("Find(%s) got %v, want %v", tt.name, got, out.want) + t.Errorf("Find(%s) - Error in the expected response - got %v, want %v", tt.name, got, out.want) } }) } -} +} \ No newline at end of file diff --git a/pkg/rcontext/remover.go b/pkg/rcontext/remover.go index 577cc3329..7bb126105 100644 --- a/pkg/rcontext/remover.go +++ b/pkg/rcontext/remover.go @@ -9,10 +9,10 @@ import ( type RemoveManager struct { ctxFile string - finder CtxFinder + finder Finder } -func NewRemover(homePath string, f CtxFinder) RemoveManager { +func NewRemover(homePath string, f Finder) RemoveManager { return RemoveManager{ctxFile: fmt.Sprintf(ContextPath, homePath), finder: f} } diff --git a/pkg/rcontext/setter.go b/pkg/rcontext/setter.go index 9a014d57e..62083e044 100644 --- a/pkg/rcontext/setter.go +++ b/pkg/rcontext/setter.go @@ -11,10 +11,10 @@ import ( type SetterManager struct { ctxFile string - finder CtxFinder + finder Finder } -func NewSetter(homePath string, f CtxFinder) Setter { +func NewSetter(homePath string, f Finder) Setter { return SetterManager{ctxFile: fmt.Sprintf(ContextPath, homePath), finder: f} } From f4fa669aeb7dc6fb921d55989e18aeb2d48385b6 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Mon, 27 Jul 2020 15:30:02 -0300 Subject: [PATCH 23/27] add tutorial finder mock on list repo --- pkg/cmd/list_repo_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/cmd/list_repo_test.go b/pkg/cmd/list_repo_test.go index 217da6601..53ac6d61c 100644 --- a/pkg/cmd/list_repo_test.go +++ b/pkg/cmd/list_repo_test.go @@ -63,7 +63,7 @@ func Test_listRepoCmd_runFunc(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - lr := NewListRepoCmd(tt.in.RepositoryLister) + lr := NewListRepoCmd(tt.in.RepositoryLister, TutorialFinderMock{}) lr.PersistentFlags().Bool("stdin", false, "input by stdin") if err := lr.Execute(); (err != nil) != tt.wantErr { t.Errorf("setCredentialCmd_runPrompt() error = %v, wantErr %v", err, tt.wantErr) From 8140ae52d5b43d3a071b17b1f9f3c2e9d056eb34 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Mon, 27 Jul 2020 16:00:20 -0300 Subject: [PATCH 24/27] fix duplicated credentials --- pkg/cmd/tutorial.go | 6 ++++-- pkg/credential/settings.go | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/pkg/cmd/tutorial.go b/pkg/cmd/tutorial.go index 0c667a788..3496624d5 100644 --- a/pkg/cmd/tutorial.go +++ b/pkg/cmd/tutorial.go @@ -74,8 +74,10 @@ func (o tutorialCmd) runPrompt() CommandRunnerFunc { return err } - o.Set(response) - + _, err = o.Set(response) + if err != nil { + return err + } prompt.Success("Set tutorial successful!") return nil } diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index 9e8d399ba..35049881d 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -53,6 +53,7 @@ func (s Settings) ReadCredentialsValue(path string) ([]ListCredData, error) { cred.Value = v cred.Name = k creds = append(creds, cred) + detail = Detail{} } } } From 57b4909465a5a8d07fd4b8b3d7cc73153a26c784 Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Mon, 27 Jul 2020 17:06:04 -0300 Subject: [PATCH 25/27] change homeDir --- pkg/cmd/list_credential.go | 2 +- pkg/cmd/mocks_test.go | 8 ++++++++ pkg/cmd/set_credential.go | 22 +++++++++++----------- pkg/cmd/set_credential_test.go | 2 +- pkg/credential/credential.go | 15 ++++++++++----- pkg/credential/settings.go | 23 ++++++++++------------- pkg/credential/settings_test.go | 8 ++++---- 7 files changed, 45 insertions(+), 35 deletions(-) diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index c40e07d9f..3e7c2f9a5 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -64,7 +64,7 @@ func printCredentialsTable(fields credential.ListCredDatas) { func (l listCredentialCmd) run() CommandRunnerFunc { return func(cmd *cobra.Command, args []string) error { - data, err := l.Settings.ReadCredentialsValue(credential.CredentialsPath()) + data, err := l.Settings.ReadCredentialsValue(l.CredentialsPath()) if err != nil { return err } diff --git a/pkg/cmd/mocks_test.go b/pkg/cmd/mocks_test.go index 6c8db8bb8..4f4583b29 100644 --- a/pkg/cmd/mocks_test.go +++ b/pkg/cmd/mocks_test.go @@ -250,6 +250,14 @@ func (s credSettingsMock) WriteCredentialsFields(fields credential.Fields, path return nil } +func (s credSettingsMock) ProviderPath() string { + return "" +} + +func (s credSettingsMock) CredentialsPath () string { + return "" +} + type runnerMock struct { error error } diff --git a/pkg/cmd/set_credential.go b/pkg/cmd/set_credential.go index 6e78206eb..a44130fea 100644 --- a/pkg/cmd/set_credential.go +++ b/pkg/cmd/set_credential.go @@ -17,7 +17,7 @@ var inputTypes = []string{"plain text", "secret"} // setCredentialCmd type for set credential command type setCredentialCmd struct { credential.Setter - credential.ReaderWriter + credential.ReaderWriterPather prompt.InputText prompt.InputBool prompt.InputList @@ -27,19 +27,19 @@ type setCredentialCmd struct { // NewSetCredentialCmd creates a new cmd instance func NewSetCredentialCmd( credSetter credential.Setter, - file credential.ReaderWriter, + file credential.ReaderWriterPather, inText prompt.InputText, inBool prompt.InputBool, inList prompt.InputList, inPass prompt.InputPassword, ) *cobra.Command { s := &setCredentialCmd{ - Setter: credSetter, - ReaderWriter: file, - InputText: inText, - InputBool: inBool, - InputList: inList, - InputPassword: inPass, + Setter: credSetter, + ReaderWriterPather: file, + InputText: inText, + InputBool: inBool, + InputList: inList, + InputPassword: inPass, } cmd := &cobra.Command{ @@ -71,14 +71,14 @@ func (s setCredentialCmd) runPrompt() CommandRunnerFunc { func (s setCredentialCmd) prompt() (credential.Detail, error) { - if err := s.WriteDefaultCredentialsFields(credential.ProviderPath()); err != nil { + if err := s.WriteDefaultCredentialsFields(s.ProviderPath()); err != nil { return credential.Detail{}, err } var credDetail credential.Detail cred := credential.Credential{} - credentials, err := s.ReadCredentialsFields(credential.ProviderPath()) + credentials, err := s.ReadCredentialsFields(s.ProviderPath()) if err != nil { return credential.Detail{}, err } @@ -116,7 +116,7 @@ func (s setCredentialCmd) prompt() (credential.Detail, error) { } } credentials[newProvider] = newFields - if err = s.WriteCredentialsFields(credentials, credential.ProviderPath()); err != nil { + if err = s.WriteCredentialsFields(credentials, s.ProviderPath()); err != nil { return credDetail, err } diff --git a/pkg/cmd/set_credential_test.go b/pkg/cmd/set_credential_test.go index 2d41b74e5..48f2abf99 100644 --- a/pkg/cmd/set_credential_test.go +++ b/pkg/cmd/set_credential_test.go @@ -10,7 +10,7 @@ import ( func Test_setCredentialCmd_runPrompt(t *testing.T) { type fields struct { Setter credential.Setter - file credential.ReaderWriter + file credential.ReaderWriterPather InputText prompt.InputText InputBool prompt.InputBool InputList prompt.InputList diff --git a/pkg/credential/credential.go b/pkg/credential/credential.go index 951682d3d..5742fa828 100644 --- a/pkg/credential/credential.go +++ b/pkg/credential/credential.go @@ -27,9 +27,9 @@ type ListCredDatas []ListCredData type ListCredData struct { Provider string - Name string - Value string - Context string + Name string + Value string + Context string } // Fields are used to represents providers.json @@ -53,8 +53,13 @@ type Writer interface { WriteDefaultCredentialsFields(path string) error } -type ReaderWriter interface { +type Pather interface { + ProviderPath() string + CredentialsPath() string +} + +type ReaderWriterPather interface { Reader Writer + Pather } - diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index 35049881d..8199636a2 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -2,7 +2,6 @@ package credential import ( "encoding/json" - "os" "path/filepath" "github.com/ZupIT/ritchie-cli/pkg/stream" @@ -11,16 +10,16 @@ import ( const AddNew = "Add a new" type Settings struct { - file stream.FileWriteReadExisterLister - dir stream.DirLister - homeDir string + file stream.FileWriteReadExisterLister + dir stream.DirLister + HomeDir string } func NewSettings(file stream.FileWriteReadExisterLister, dir stream.DirLister, homeDir string) Settings { return Settings{ - file: file, - dir: dir, - homeDir : homeDir, + file: file, + dir: dir, + HomeDir: homeDir, } } @@ -120,14 +119,12 @@ func NewDefaultCredentials() Fields { return dc } -func ProviderPath() string { - homeDir, _ := os.UserHomeDir() - return filepath.Join(homeDir, ".rit/providers.json") +func (s Settings) ProviderPath() string { + return filepath.Join(s.HomeDir, ".rit/providers.json") } -func CredentialsPath() string { - homeDir, _ := os.UserHomeDir() - return filepath.Join(homeDir, ".rit/credentials/") +func (s Settings) CredentialsPath() string { + return filepath.Join(s.HomeDir, ".rit/credentials/") } func NewProviderArr(fields Fields) []string { diff --git a/pkg/credential/settings_test.go b/pkg/credential/settings_test.go index 5713ba549..0e21ed003 100644 --- a/pkg/credential/settings_test.go +++ b/pkg/credential/settings_test.go @@ -43,7 +43,7 @@ func TestSettings_ReadCredentialsValue(t *testing.T) { } } -func TestSettings_WriteCredentials(t *testing.T) { +func TestSettings_WriteCredentialsFields(t *testing.T) { defer os.Remove(providersPath()) var tests = []struct { name string @@ -76,7 +76,7 @@ func TestSettings_WriteCredentials(t *testing.T) { } } -func TestSettings_WriteDefaultCredentials(t *testing.T) { +func TestSettings_WriteDefaultCredentialsFields(t *testing.T) { err := credSettings.WriteDefaultCredentialsFields(providersPath()) defer os.Remove(providersPath()) if err != nil { @@ -97,7 +97,7 @@ func TestNewDefaultCredentials(t *testing.T) { } func TestProviderPath(t *testing.T) { - provider := ProviderPath() + provider := credSettings.ProviderPath() slicedPath := strings.Split(provider, "/") providersJson := slicedPath[len(slicedPath)-1] @@ -107,7 +107,7 @@ func TestProviderPath(t *testing.T) { } func TestCredentialsPath(t *testing.T){ - credentials := CredentialsPath() + credentials := credSettings.CredentialsPath() slicedPath := strings.Split(credentials, "/") fmt.Println(slicedPath) providersDir := slicedPath[len(slicedPath)-1] From 347c7e49f9eefa7937ff82a632b03a7c74bb048b Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Tue, 28 Jul 2020 13:14:59 -0300 Subject: [PATCH 26/27] change credential table --- pkg/cmd/list_credential.go | 19 ++--------- pkg/credential/credential.go | 3 +- pkg/credential/settings.go | 48 +++++++++++++++++++++------ pkg/credential/settings_test.go | 1 - pkg/rtutorial/finder_test.go | 58 ++++++++++++++++----------------- pkg/stream/file.go | 3 +- 6 files changed, 71 insertions(+), 61 deletions(-) diff --git a/pkg/cmd/list_credential.go b/pkg/cmd/list_credential.go index 3e7c2f9a5..703559865 100644 --- a/pkg/cmd/list_credential.go +++ b/pkg/cmd/list_credential.go @@ -27,32 +27,17 @@ func NewListCredentialCmd(ss credential.Settings) *cobra.Command { return cmd } -func hideCredential(credential string) string { - mustHideIndex := len(credential) / 3 - var hiddenCredential []rune - for i, r := range credential { - if i > mustHideIndex { - r = '*' - } - hiddenCredential = append(hiddenCredential, r) - } - return string(hiddenCredential) -} - func printCredentialsTable(fields credential.ListCredDatas) { table := uitable.New() - table.MaxColWidth = 50 table.Wrap = true - table.AddRow( - prompt.Bold("NAME"), - prompt.Bold("VALUE"), + prompt.Bold("CREDENTIAL"), prompt.Bold("PROVIDER"), prompt.Bold("CONTEXT"), ) for _, c := range fields { - table.AddRow(c.Name, hideCredential(c.Value), c.Provider, c.Context) + table.AddRow(c.Credential, c.Provider, c.Context) } if len(table.Rows) < 2 { setCmd := prompt.Cyan("rit set credential") diff --git a/pkg/credential/credential.go b/pkg/credential/credential.go index 5742fa828..ed442c7ec 100644 --- a/pkg/credential/credential.go +++ b/pkg/credential/credential.go @@ -27,8 +27,7 @@ type ListCredDatas []ListCredData type ListCredData struct { Provider string - Name string - Value string + Credential string Context string } diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index 8199636a2..6feccd18e 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -3,6 +3,7 @@ package credential import ( "encoding/json" "path/filepath" + "strings" "github.com/ZupIT/ritchie-cli/pkg/stream" ) @@ -10,12 +11,12 @@ import ( const AddNew = "Add a new" type Settings struct { - file stream.FileWriteReadExisterLister + file stream.FileWriteReadExistLister dir stream.DirLister HomeDir string } -func NewSettings(file stream.FileWriteReadExisterLister, dir stream.DirLister, homeDir string) Settings { +func NewSettings(file stream.FileWriteReadExistLister, dir stream.DirLister, homeDir string) Settings { return Settings{ file: file, dir: dir, @@ -46,19 +47,46 @@ func (s Settings) ReadCredentialsValue(path string) ([]ListCredData, error) { if err := json.Unmarshal(cBytes, &detail); err != nil { return creds, err } - for k, v := range detail.Credential { - cred.Provider = detail.Service - cred.Context = c - cred.Value = v - cred.Name = k - creds = append(creds, cred) - detail = Detail{} - } + cred.Credential = formatCredential(string(cBytes)) + cred.Provider = detail.Service + cred.Context = c + creds = append(creds, cred) + detail = Detail{} } } return creds, nil } +func formatCredential(credential string) string { + arr := strings.Split(credential, "credential") + arr2 := strings.Split(arr[1], "service") + res := strings.TrimPrefix(arr2[0], "\":") + res = strings.TrimSuffix(res, ",\"") + + splitedCredential := strings.Split(res, "\"") + for i, c := range splitedCredential { + if c == ":" { + splitedCredential[i+1] = hide(splitedCredential[i+1]) + } + } + + return strings.Join(splitedCredential, "\"") +} + +func hide(credential string) string { + mustHideIndex := len(credential) / 3 + var hiddenCredential []rune + for i, r := range credential { + if i > mustHideIndex { + r = '*' + } + hiddenCredential = append(hiddenCredential, r) + } + + return string(hiddenCredential) +} + + func (s Settings) WriteCredentialsFields(fields Fields, path string) error { fieldsData, err := json.Marshal(fields) if err != nil { diff --git a/pkg/credential/settings_test.go b/pkg/credential/settings_test.go index 0e21ed003..b33ddeb6f 100644 --- a/pkg/credential/settings_test.go +++ b/pkg/credential/settings_test.go @@ -21,7 +21,6 @@ func providersPath() string { } func TestSettings_ReadCredentialsFields(t *testing.T) { - credentials, err := credSettings.ReadCredentialsFields("../../testdata/credentials.json") if err != nil { t.Errorf("Error reading credentials fields") diff --git a/pkg/rtutorial/finder_test.go b/pkg/rtutorial/finder_test.go index 777464fa4..b9be92a6d 100644 --- a/pkg/rtutorial/finder_test.go +++ b/pkg/rtutorial/finder_test.go @@ -11,41 +11,36 @@ import ( sMocks "github.com/ZupIT/ritchie-cli/pkg/stream/mocks" ) +var errReadingFile = errors.New("Error reading file") + func TestFind(t *testing.T) { type out struct { err error want TutorialHolder - waitError bool + wantError bool } - err := errors.New("some error") - tests := []struct { - name string - out *out - FileReadExister stream.FileReadExister + name string + in stream.FileReadExister + out *out }{ { name: "With no tutorial file", - out: &out{ - want: TutorialHolder{Current: "enabled"}, - err: nil, - waitError: false, - }, - FileReadExister: sMocks.FileReadExisterCustomMock{ + in: sMocks.FileReadExisterCustomMock{ ExistsMock: func(path string) bool { return false }, }, - }, - { - name: "With existing tutorial file", out: &out{ - want: TutorialHolder{Current: "disabled"}, + want: TutorialHolder{Current: "enabled"}, err: nil, - waitError: false, + wantError: false, }, - FileReadExister: sMocks.FileReadExisterCustomMock{ + }, + { + name: "With existing tutorial file", + in: sMocks.FileReadExisterCustomMock{ ReadMock: func(path string) ([]byte, error) { return []byte("{\"tutorial\":\"disabled\"}"), nil }, @@ -53,22 +48,27 @@ func TestFind(t *testing.T) { return true }, }, + out: &out{ + want: TutorialHolder{Current: "disabled"}, + err: nil, + wantError: false, + }, }, { name: "Error reading the tutorial file", - out: &out{ - want: TutorialHolder{Current: "enabled"}, - err: err, - waitError: true, - }, - FileReadExister: sMocks.FileReadExisterCustomMock{ + in: sMocks.FileReadExisterCustomMock{ ReadMock: func(path string) ([]byte, error) { - return []byte(""), err + return []byte(""), errReadingFile }, ExistsMock: func(path string) bool { return true }, }, + out: &out{ + want: TutorialHolder{Current: "enabled"}, + err: errReadingFile, + wantError: true, + }, }, } @@ -78,15 +78,15 @@ func TestFind(t *testing.T) { tmpTutorial := fmt.Sprintf(TutorialPath, tmp) defer os.RemoveAll(tmpTutorial) - finder := NewFinder(tmp, tt.FileReadExister) + finder := NewFinder(tmp, tt.in) out := tt.out got, err := finder.Find() - if err != nil && !tt.out.waitError { - t.Errorf("Set(%s) - Execution error - got %v, want %v", tt.name, err, out.err) + if err != nil && !tt.out.wantError { + t.Errorf("%s - Execution error - got %v, want %v", tt.name, err, out.err) } if !reflect.DeepEqual(out.want, got) { - t.Errorf("Set(%s) - Error in the expected response - got %v, want %v", tt.name, got, out.want) + t.Errorf("%s - Error in the expected response - got %v, want %v", tt.name, got, out.want) } }) } diff --git a/pkg/stream/file.go b/pkg/stream/file.go index cf82f1fe6..e15405bc1 100644 --- a/pkg/stream/file.go +++ b/pkg/stream/file.go @@ -66,7 +66,7 @@ type FileWriteReadExister interface { FileExister } -type FileWriteReadExisterLister interface { +type FileWriteReadExistLister interface { FileWriter FileReader FileExister @@ -119,7 +119,6 @@ func (f FileManager) Exists(path string) bool { if _, err := os.Stat(path); os.IsNotExist(err) { return false } - return true } From 96b8550f9b6f02d8a5bee1dc652930cdac1a9ccd Mon Sep 17 00:00:00 2001 From: victor-schumacher Date: Tue, 28 Jul 2020 13:59:54 -0300 Subject: [PATCH 27/27] add format to long credential values, change infos on list help --- pkg/cmd/list.go | 8 ++++---- pkg/credential/settings.go | 42 +++++++++++++++++++++++--------------- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/pkg/cmd/list.go b/pkg/cmd/list.go index 98da89829..eb1009d58 100644 --- a/pkg/cmd/list.go +++ b/pkg/cmd/list.go @@ -5,15 +5,15 @@ import "github.com/spf13/cobra" const descListLong = ` This command consists of multiple subcommands to interact with ritchie. -It can be used to list formulas, repositories and other objects. +It can be used to list repositories or credentials. ` // NewListCmd create a new list instance func NewListCmd() *cobra.Command { return &cobra.Command{ Use: "list SUBCOMMAND", - Short: "List repositories", - Long: "List all formula repositories.", - Example: "rit list repo", + Short: "List repositories or credentials", + Long: descListLong, + Example: "rit list repo, rit list credential", } } diff --git a/pkg/credential/settings.go b/pkg/credential/settings.go index 6feccd18e..93030dab0 100644 --- a/pkg/credential/settings.go +++ b/pkg/credential/settings.go @@ -58,35 +58,45 @@ func (s Settings) ReadCredentialsValue(path string) ([]ListCredData, error) { } func formatCredential(credential string) string { - arr := strings.Split(credential, "credential") - arr2 := strings.Split(arr[1], "service") - res := strings.TrimPrefix(arr2[0], "\":") - res = strings.TrimSuffix(res, ",\"") + credArr := strings.Split(credential, "credential") + credArr = strings.Split(credArr[1], "service") - splitedCredential := strings.Split(res, "\"") + credValue := strings.TrimPrefix(credArr[0], "\":") + credValue = strings.TrimSuffix(credValue, ",\"") + + splitedCredential := strings.Split(credValue, "\"") for i, c := range splitedCredential { if c == ":" { - splitedCredential[i+1] = hide(splitedCredential[i+1]) + splitedCredential[i+1] = formatCredValue(splitedCredential[i+1]) } } return strings.Join(splitedCredential, "\"") } -func hide(credential string) string { - mustHideIndex := len(credential) / 3 - var hiddenCredential []rune - for i, r := range credential { - if i > mustHideIndex { - r = '*' +func formatCredValue(credential string) string { + if credLen := len(credential); credLen > 20 { + var resumedCredential []rune + for i, r := range credential { + resumedCredential = append(resumedCredential, r) + if i > 10 { + break + } + } + return string(resumedCredential) + "..." + } else { + var hiddenCredential []rune + mustHideIndex := credLen / 3 + for i, r := range credential { + if i > mustHideIndex { + r = '*' + } + hiddenCredential = append(hiddenCredential, r) } - hiddenCredential = append(hiddenCredential, r) + return string(hiddenCredential) } - - return string(hiddenCredential) } - func (s Settings) WriteCredentialsFields(fields Fields, path string) error { fieldsData, err := json.Marshal(fields) if err != nil {