Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
tamada committed May 20, 2023
1 parent 7f4660a commit 421e1ce
Show file tree
Hide file tree
Showing 12 changed files with 774 additions and 16 deletions.
105 changes: 94 additions & 11 deletions cmd/rrh/commands/alias/alias.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/spf13/cobra"
"github.com/tamada/rrh"
"gopkg.in/pipe.v2"
)

func New() *cobra.Command {
Expand All @@ -16,7 +17,7 @@ func New() *cobra.Command {
Args: validateArgs,
Long: `manage alias (different names of the commands)
list (no arguments give the registered aliases)
alias
alias
register ("--" means skip option parsing after that)
alias grlist -- repository list --entry group,id
update
Expand Down Expand Up @@ -113,7 +114,7 @@ func removeAliases(cmd *cobra.Command, args []string, aliasList []*Command, conf
resultAliases = r
}
dryRunMode, err := cmd.Flags().GetBool("dry-run")
if len(resultAliases) < len(aliasList) && err != nil && dryRunMode {
if len(resultAliases) < len(aliasList) || err != nil && dryRunMode {
storeAliases(resultAliases, config)
}
printDryRun(cmd, fmt.Sprintf("%s: remove alias (dry-run mode)", strings.Join(foundNames, ",")))
Expand Down Expand Up @@ -174,27 +175,109 @@ func removeAlias(command string, aliasList []*Command) []*Command {
}

func registerAlias(cmd *cobra.Command, args []string, aliasList []*Command, config *rrh.Config) error {
if item := FindAlias(args[0], aliasList); item != nil {
if !aliasOpts.updateFlag {
return fmt.Errorf("%s: already registered alias", args[0])
} else {
aliasList = removeAlias(args[0], aliasList)
}
if err := validateNewCommand(args, aliasList); err != nil {
return err
}
if aliasOpts.updateFlag {
aliasList = removeAlias(args[0], aliasList)
}
alias := &Command{Name: args[0], Values: args[1:]}
newList := append(aliasList, alias)
dryRunMode, err := cmd.Flags().GetBool("dry-run")
if err == nil && !dryRunMode {
fmt.Printf("storeAlias")
return storeAliases(newList, config)
}
return nil
}

func validateNewCommand(args []string, aliasList []*Command) error {
if item := FindAlias(args[0], aliasList); item != nil {
if !aliasOpts.updateFlag {
return fmt.Errorf("%s: already registered alias", args[0])
}
}
return validateWithoutRedirectSymbol(args)
}

func validateWithoutRedirectSymbol(args []string) error {
for _, arg := range args {
switch strings.TrimSpace(arg) {
case ">", ">>", "2>&1", ">&2", "2>", "2>>", "&>", "&>>", ">&", ">>&":
return fmt.Errorf("alias do not support shell redirection. use tee command")
}
}
return nil
}

func (cmd *Command) Execute(c *cobra.Command, args []string) error {
newArgs := cmd.Values
newArgs = append(newArgs, args[1:]...)
fmt.Printf("Execute(%v)\n", args)
newArgs := cmd.createArgs(args)
if hasPipe(newArgs) {
fmt.Printf("hasPipe(%v): true\n", newArgs)
return cmd.executePipe(c, newArgs)
}
fmt.Printf("hasPipe(%v): false\n", newArgs)

root := c.Root()
root.SetArgs(newArgs)
return root.Execute()
}

func (cmd *Command) createArgs(args []string) []string {
newArgs := cmd.Values
newArgs = append(newArgs, args[1:]...)
return newArgs
}

func (cmd *Command) executePipe(c *cobra.Command, args []string) error {
p := connectWithPipe(c, args)
return pipe.Run(p)
}

func connectWithPipe(c *cobra.Command, args []string) pipe.Pipe {
pipes := [][]string{}
newArgs := []string{}
for _, arg := range args {
arg := strings.TrimSpace(arg)
if arg == "|" {
if len(args) > 0 {
pipes = append(pipes, newArgs)
newArgs = []string{}
}
} else {
newArgs = append(newArgs, arg)
}
}
return combine(c, pipes)
}

func combine(c *cobra.Command, pipes [][]string) pipe.Pipe {
pipeArray := []pipe.Pipe{}
for index, args := range pipes {
if index == 0 {
pipeArray = append(pipeArray, convertCmd(c, args))
} else {
pipeArray = append(pipeArray, pipe.Exec(args[0], args[1:]...))
}
}
return pipe.Line(pipeArray...)
}

func convertCmd(c *cobra.Command, args []string) pipe.Pipe {
return func(s *pipe.State) error {
root := c.Root()
root.SetIn(s.Stdin)
root.SetOut(s.Stdout)
root.SetErr(s.Stderr)
return root.Execute()
}
}

func hasPipe(args []string) bool {
for _, arg := range args {
if arg == "|" {
return true
}
}
return false
}
74 changes: 74 additions & 0 deletions cmd/rrh/commands/alias/alias_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package alias

import (
"os"
"testing"

"github.com/tamada/rrh"
)

func TestValidateArguments(t *testing.T) {
testdata := []struct {
giveArgs []string
wontError bool
}{
{[]string{"ls"}, false},
{[]string{"ls", "|", "wc"}, false},
{[]string{"ls", ">", "list.txt"}, true},
}
for _, td := range testdata {
err := validateWithoutRedirectSymbol(td.giveArgs)
if err == nil && td.wontError || err != nil && !td.wontError {
t.Errorf("validateWithoutRedirectSymbol(%v) wont error %v, but got %v", td.giveArgs, td.wontError, err)
}
}
}

func Example_ListAlias() {
os.Setenv(rrh.AliasPath, "../../../../testdata/alias.json")
cmd := New()
cmd.SetOut(os.Stdout)
cmd.SetArgs([]string{})
cmd.Execute()
// Output:
// grlist=repository list --entry group,id
}

func TestRemoveAlias(t *testing.T) {
dbFile := rrh.RollbackAlias("../../../../testdata/database.json", "../../../../testdata/config.json", "../../../../testdata/alias.json", func(config *rrh.Config, oldDB *rrh.Database) {
cmd := New()
cmd.SetArgs([]string{"--remove", "grlist"})
err := cmd.Execute()
if err != nil {
t.Errorf("unexpected error: %s", err.Error())
}

commands, err := LoadAliases(config)
if err != nil {
t.Errorf("unexpected error: %s", err.Error())
}
if len(commands) > 0 {
t.Errorf("alias list wont 0, but got %d (%v)", len(commands), commands[0])
}
})
defer os.Remove(dbFile)
}

func TestRegisterNewAlias(t *testing.T) {
dbFile := rrh.RollbackAlias("../../../../testdata/database.json", "../../../../testdata/config.json", "../../../../testdata/alias.json", func(config *rrh.Config, oldDB *rrh.Database) {
cmd := New()
cmd.SetArgs([]string{"gl", "group", "list"})
err := cmd.Execute()
if err != nil {
t.Errorf("unexpected error: %s", err.Error())
}
commands, err := LoadAliases(config)
if err != nil {
t.Errorf("unexpected error: %s", err.Error())
}
if len(commands) != 2 {
t.Errorf("alias list wont 2, but got %d (%v)", len(commands), commands[0])
}
})
defer os.Remove(dbFile)
}
3 changes: 3 additions & 0 deletions cmd/rrh/commands/list/table_format.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ func (tf *tableFormat) Format(w io.Writer, r []*Result, le Entries, noAbbrevFlag
if tf.headerFlag {
writer.SetHeader(le.StringArray())
}
writer.SetBorder(false)
writer.SetNoWhiteSpace(true)
writer.SetTablePadding(" ")
for _, result := range r {
tf.formatEach(writer, result, le)
}
Expand Down
1 change: 1 addition & 0 deletions cmd/rrh/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ func findAndExecuteAlias(c *cobra.Command, args []string, config *rrh.Config) (b
if err != nil {
return false, err
}
c.SilenceUsage = true
return true, command.Execute(c, args)
}

Expand Down
Loading

0 comments on commit 421e1ce

Please sign in to comment.