Skip to content

Commit

Permalink
[cmd] Improve argument display in --noop and debug modes
Browse files Browse the repository at this point in the history
  • Loading branch information
mislav committed May 25, 2020
1 parent bc70e56 commit 3df5526
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
14 changes: 12 additions & 2 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,17 @@ type Cmd struct {
}

func (cmd Cmd) String() string {
return fmt.Sprintf("%s %s", cmd.Name, strings.Join(cmd.Args, " "))
args := make([]string, len(cmd.Args))
for i, a := range cmd.Args {
if strings.ContainsRune(a, '"') {
args[i] = fmt.Sprintf(`'%s'`, a)
} else if a == "" || strings.ContainsRune(a, '\'') || strings.ContainsRune(a, ' ') {
args[i] = fmt.Sprintf(`"%s"`, a)
} else {
args[i] = a
}
}
return fmt.Sprintf("%s %s", cmd.Name, strings.Join(args, " "))
}

// WithArg returns the current argument
Expand Down Expand Up @@ -138,7 +148,7 @@ func NewWithArray(cmd []string) *Cmd {

func verboseLog(cmd *Cmd) {
if os.Getenv("HUB_VERBOSE") != "" {
msg := fmt.Sprintf("$ %s %s", cmd.Name, strings.Join(cmd.Args, " "))
msg := fmt.Sprintf("$ %s", cmd.String())
if ui.IsTerminal(os.Stderr) {
msg = fmt.Sprintf("\033[35m%s\033[0m", msg)
}
Expand Down
8 changes: 8 additions & 0 deletions cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,11 @@ func TestWithArg(t *testing.T) {
assert.Equal(t, "git", execCmd.Name)
assert.Equal(t, 4, len(execCmd.Args))
}

func Test_String(t *testing.T) {
c := Cmd{
Name: "echo",
Args: []string{"hi", "hello world", "don't", `"fake news"`},
}
assert.Equal(t, `echo hi "hello world" "don't" '"fake news"'`, c.String())
}
4 changes: 2 additions & 2 deletions commands/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@ func TestInitInAnotherDir(t *testing.T) {

commands := args.Commands()
assert.Equal(t, 2, len(commands))
assert.Equal(t, "git init --template mytpl --shared=umask my project", commands[0].String())
assert.Equal(t, "git init --template mytpl --shared=umask \"my project\"", commands[0].String())

currentDir, err := os.Getwd()
assert.Equal(t, nil, err)

expected := fmt.Sprintf(
"git --git-dir %s remote add origin [email protected]:jingweno/%s.git",
"git --git-dir \"%s\" remote add origin [email protected]:jingweno/%s.git",
filepath.Join(currentDir, "my project", ".git"),
"my-project",
)
Expand Down

0 comments on commit 3df5526

Please sign in to comment.