Skip to content
This repository has been archived by the owner on Jul 12, 2022. It is now read-only.

Set credential flags #824

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
20d5d07
Improved tests and resolve input logic
henriquemoraeszup Dec 11, 2020
e23b3c9
Fixing some tests
henriquemoraeszup Dec 14, 2020
02d2d7a
Merge branch 'master' of github.com:ZupIT/ritchie-cli into hm/delete-…
henriquemoraeszup Dec 14, 2020
0e9de1b
Fixing tests, segregating mocks
henriquemoraeszup Dec 14, 2020
24fc74c
Fixing provider
henriquemoraeszup Dec 14, 2020
47d5fc2
Merge branch 'master' of github.com:ZupIT/ritchie-cli into hm/delete-…
henriquemoraeszup Dec 15, 2020
d87b133
fixing tests
henriquemoraeszup Dec 15, 2020
ccbf9f2
Review corrections
henriquemoraeszup Dec 19, 2020
bdb7fc3
Fixing tests
henriquemoraeszup Dec 19, 2020
7c519e3
Extracting flag addition into a method
henriquemoraeszup Dec 21, 2020
7226fb2
Merge branch 'hm/delete-credential-flags' into hm/set-credential-flags
henriquemoraeszup Dec 22, 2020
aadd041
Set credential implemented, writing tests
henriquemoraeszup Dec 23, 2020
28da25c
creating flag slices
henriquemoraeszup Jan 7, 2021
4e3f1cd
Finishing flag implementation
henriquemoraeszup Jan 7, 2021
3415622
Merge branch 'master' of github.com:ZupIT/ritchie-cli into hm/set-cre…
henriquemoraeszup Jan 7, 2021
55efc23
Tests finished
henriquemoraeszup Jan 7, 2021
a4692e9
Merge branch 'master' of github.com:ZupIT/ritchie-cli into hm/set-cre…
henriquemoraeszup Jan 11, 2021
95152fa
Linter
henriquemoraeszup Jan 11, 2021
cfcdd44
Test correction
henriquemoraeszup Jan 11, 2021
44a5a64
Readjusting method file
henriquemoraeszup Jan 11, 2021
7148da2
Merge branch 'master' of github.com:ZupIT/ritchie-cli into hm/set-cre…
henriquemoraeszup Jan 11, 2021
22186b7
Go mod update
henriquemoraeszup Jan 11, 2021
855ccb2
Wrong bool prompt, increasing coverage
henriquemoraeszup Jan 11, 2021
97593b8
Reducing conditional
henriquemoraeszup Jan 12, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pkg/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ func addReservedFlags(flags *pflag.FlagSet, flagsToAdd flags) {
flags.BoolP(flag.name, flag.shortName, flag.defValue.(bool), flag.description)
case reflect.Int:
flags.IntP(flag.name, flag.shortName, flag.defValue.(int), flag.description)
case reflect.Slice:
flags.StringSliceP(flag.name, flag.shortName, []string{}, flag.description)
default:
warning := fmt.Sprintf("The %q type is not supported for the %q flag", flag.kind.String(), flag.name)
prompt.Warning(warning)
Expand Down
29 changes: 15 additions & 14 deletions pkg/cmd/delete_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const (
providerFlagDescription = "Provider name to delete"
)

type inputConfig struct {
type inputDeleteCredential struct {
provider string
}

Expand Down Expand Up @@ -100,49 +100,50 @@ func (d deleteCredentialCmd) runFormula() CommandRunnerFunc {
}
}

func (d *deleteCredentialCmd) resolveInput(cmd *cobra.Command, context string) (inputConfig, error) {
func (d *deleteCredentialCmd) resolveInput(cmd *cobra.Command, context string) (inputDeleteCredential, error) {
if IsFlagInput(cmd) {
return d.resolveFlags(cmd)
}
return d.resolvePrompt(context)
}

func (d *deleteCredentialCmd) resolvePrompt(context string) (inputConfig, error) {
func (d *deleteCredentialCmd) resolvePrompt(context string) (inputDeleteCredential, error) {
data, err := d.ReadCredentialsValueInEnv(d.CredentialsPath(), context)
if err != nil {
return inputConfig{}, err
return inputDeleteCredential{}, err
}

if len(data) == 0 {
return inputConfig{}, errors.New("you have no defined credentials in this env")
return inputDeleteCredential{}, errors.New("you have no defined credentials in this env")
}

providers := make([]string, 0, len(data))
providers := make([]string, len(data))
for _, c := range data {
providers = append(providers, c.Provider)
}

provider, err := d.List("Credentials: ", providers)
if err != nil {
return inputConfig{}, err
return inputDeleteCredential{}, err
}

if b, err := d.Bool("Are you sure want to delete this credential?", []string{"yes", "no"}); err != nil {
return inputConfig{}, err
return inputDeleteCredential{}, err
} else if !b {
return inputConfig{}, nil
return inputDeleteCredential{}, nil
}
return inputConfig{provider}, nil
return inputDeleteCredential{provider}, nil
}

func (d *deleteCredentialCmd) resolveFlags(cmd *cobra.Command) (inputConfig, error) {
func (d *deleteCredentialCmd) resolveFlags(cmd *cobra.Command) (inputDeleteCredential, error) {
provider, err := cmd.Flags().GetString(providerFlagName)
if err != nil {
return inputConfig{}, err
return inputDeleteCredential{}, err
} else if provider == "" {
return inputConfig{}, errors.New("please provide a value for 'provider'")
return inputDeleteCredential{}, errors.New("please provide a value for 'provider'")
}
return inputConfig{provider}, nil

return inputDeleteCredential{provider}, nil
}

// TODO: remove upon stdin deprecation
Expand Down
14 changes: 9 additions & 5 deletions pkg/cmd/delete_credential_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,31 +315,35 @@ func TestDeleteCredentialFormula(t *testing.T) {
inputBoolResult bool
inputListError error
fileShouldExist bool
args string
args []string
wantErr string
}{
{
name: "execute prompt with success",
args: []string{},
fabianofernandeszup marked this conversation as resolved.
Show resolved Hide resolved
inputBoolResult: true,
},
{
name: "execute flag with success",
args: "--provider=github",
name: "execute flag with success",
args: []string{"--provider=github"},
inputBoolResult: true,
},
{
name: "execute flag with empty provider fail",
args: "--provider=",
args: []string{"--provider="},
wantErr: "please provide a value for 'provider'",
fileShouldExist: true,
},
{
name: "fail on input list error",
args: []string{},
henriquemoraeszup marked this conversation as resolved.
Show resolved Hide resolved
wantErr: "some error",
inputListError: errors.New("some error"),
fileShouldExist: true,
},
{
name: "do nothing on input bool refusal",
args: []string{},
henriquemoraeszup marked this conversation as resolved.
Show resolved Hide resolved
inputBoolResult: false,
fileShouldExist: true,
},
Expand Down Expand Up @@ -368,7 +372,7 @@ func TestDeleteCredentialFormula(t *testing.T) {
cmd := NewDeleteCredentialCmd(credDeleter, credSettings, ctxFinder, boolMock, listMock)
// TODO: remove stdin flag after deprecation
cmd.PersistentFlags().Bool("stdin", false, "input by stdin")
cmd.SetArgs([]string{tt.args})
cmd.SetArgs(tt.args)

err = cmd.Execute()
if err != nil {
Expand Down
124 changes: 84 additions & 40 deletions pkg/cmd/set_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,37 +17,61 @@
package cmd

import (
"errors"
"fmt"
"os"
"reflect"
"strings"

"github.com/spf13/cobra"

"github.com/ZupIT/ritchie-cli/pkg/credential"
"github.com/ZupIT/ritchie-cli/pkg/prompt"
"github.com/ZupIT/ritchie-cli/pkg/stdin"
"github.com/ZupIT/ritchie-cli/pkg/stream"
)

const (
fieldsFlagName = "fields"
valuesFlagName = "values"
)

var inputTypes = []string{"plain text", "secret"}
var inputWay = []string{"type", "file"}

// setCredentialCmd type for set credential command.
type setCredentialCmd struct {
credential.Setter
credential.ReaderWriterPather
stream.FileReadExister
prompt.InputText
prompt.InputBool
prompt.InputList
prompt.InputPassword
}

var setCredentialFlags = flags{
{
name: providerFlagName,
kind: reflect.String,
defValue: "",
description: "provider name (i.e.: github)",
},
{
name: fieldsFlagName,
kind: reflect.Slice,
defValue: "",
description: "comma separated list of field names",
},
{
name: valuesFlagName,
kind: reflect.Slice,
defValue: "",
description: "comma separated list of field values",
},
}

// NewSetCredentialCmd creates a new cmd instance.
func NewSetCredentialCmd(
credSetter credential.Setter,
credFile credential.ReaderWriterPather,
file stream.FileReadExister,
inText prompt.InputText,
inBool prompt.InputBool,
inList prompt.InputList,
Expand All @@ -56,7 +80,6 @@ func NewSetCredentialCmd(
s := &setCredentialCmd{
Setter: credSetter,
ReaderWriterPather: credFile,
FileReadExister: file,
InputText: inText,
InputBool: inBool,
InputList: inList,
Expand All @@ -67,17 +90,19 @@ func NewSetCredentialCmd(
Use: "credential",
Short: "Set credential",
Long: `Set credentials for Github, Gitlab, AWS, UserPass, etc.`,
RunE: RunFuncE(s.runStdin(), s.runPrompt()),
RunE: RunFuncE(s.runStdin(), s.runFormula()),
ValidArgs: []string{""},
Args: cobra.OnlyValidArgs,
}
cmd.LocalFlags()

addReservedFlags(cmd.Flags(), setCredentialFlags)

return cmd
}

func (s setCredentialCmd) runPrompt() CommandRunnerFunc {
func (s setCredentialCmd) runFormula() CommandRunnerFunc {
return func(cmd *cobra.Command, args []string) error {
cred, err := s.prompt()
cred, err := s.resolveInput(cmd)
if err != nil {
return err
}
Expand All @@ -92,7 +117,14 @@ func (s setCredentialCmd) runPrompt() CommandRunnerFunc {
}
}

func (s setCredentialCmd) prompt() (credential.Detail, error) {
func (s *setCredentialCmd) resolveInput(cmd *cobra.Command) (credential.Detail, error) {
if IsFlagInput(cmd) {
return s.resolveFlags(cmd)
}
return s.resolvePrompt()
}

func (s *setCredentialCmd) resolvePrompt() (credential.Detail, error) {
if err := s.WriteDefaultCredentialsFields(s.ProviderPath()); err != nil {
return credential.Detail{}, err
}
Expand Down Expand Up @@ -147,50 +179,62 @@ func (s setCredentialCmd) prompt() (credential.Detail, error) {

inputs := credentials[providerChoose]

inputWayChoose, _ := s.List("Want to enter your credential typing or through a file?", inputWay)
for _, i := range inputs {
var value string
if inputWayChoose == inputWay[1] {
path, err := s.Text("Enter the credential file path for "+prompt.Cyan(i.Name)+":", true)
if i.Type == inputTypes[1] {
value, err = s.Password(i.Name + ":")
if err != nil {
return credential.Detail{}, err
}

if !s.FileReadExister.Exists(path) {
return credDetail, prompt.NewError("Cannot find any credential file at " + path)
}

byteValue, err := s.FileReadExister.Read(path)
if err != nil {
return credential.Detail{}, err
}
fabianofernandeszup marked this conversation as resolved.
Show resolved Hide resolved
if len(byteValue) == 0 {
return credential.Detail{}, prompt.NewError("Empty credential file!")
return credDetail, err
}

cred[i.Name] = string(byteValue)

} else {
if i.Type == inputTypes[1] {
value, err = s.Password(i.Name + ":")
if err != nil {
return credDetail, err
}
} else {
value, err = s.Text(i.Name+":", true)
if err != nil {
return credDetail, err
}
value, err = s.Text(i.Name+":", true)
if err != nil {
return credDetail, err
}
cred[i.Name] = value
}
cred[i.Name] = value
}
credDetail.Service = providerChoose
credDetail.Credential = cred

return credDetail, nil
}

func (s *setCredentialCmd) resolveFlags(cmd *cobra.Command) (credential.Detail, error) {
provider, err := cmd.Flags().GetString(providerFlagName)
if err != nil || provider == "" {
return credential.Detail{}, errors.New("please provide a value for 'provider'")
}

fields, err := cmd.Flags().GetStringSlice(fieldsFlagName)
if err != nil {
return credential.Detail{}, err
} else if len(fields) == 0 {
lucasdittrichzup marked this conversation as resolved.
Show resolved Hide resolved
return credential.Detail{}, errors.New("please provide a value for 'fields'")
}

values, err := cmd.Flags().GetStringSlice(valuesFlagName)
if err != nil {
return credential.Detail{}, err
} else if len(values) == 0 {
return credential.Detail{}, errors.New("please provide a value for 'values'")
}

if len(fields) != len(values) {
return credential.Detail{}, errors.New("number of fields does not match with number of values")
}

credentialMap := make(map[string]string)
for i := 0; i < len(fields); i++ {
credentialMap[fields[i]] = values[i]
}

return credential.Detail{
Service: provider,
Credential: credentialMap,
}, nil
}

func (s setCredentialCmd) runStdin() CommandRunnerFunc {
return func(cmd *cobra.Command, args []string) error {
cred, err := s.stdinResolver()
Expand Down
Loading