Skip to content

Commit

Permalink
🐞 fix: Repair the command parsing issue in the fixCommand function
Browse files Browse the repository at this point in the history
  • Loading branch information
sohaha committed Feb 26, 2024
1 parent 23016c1 commit 124574c
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 9 deletions.
35 changes: 26 additions & 9 deletions zshell/shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -305,16 +305,33 @@ func CallbackRunContext(ctx context.Context, command string, callback func(out s
}

func fixCommand(command string) (runCommand []string) {
tmp := ""
for _, v := range strings.Split(command, " ") {
if strings.HasSuffix(v, "\\") {
tmp += v[:len(v)-1] + " "
} else {
if tmp != "" {
v = tmp + v
tmp = ""
var current []rune
quoted := false
quoteType := '\000'
escaped := false
for i, c := range command {
if escaped {
current = append(current, c)
escaped = false
} else if c == '\\' {
escaped = true
} else if c == '"' || c == '\'' {
if quoted && c == quoteType {
quoted = false
quoteType = '\000'
} else if !quoted {
quoted = true
quoteType = c
}
runCommand = append(runCommand, v)
} else if c == ' ' && !quoted {
runCommand = append(runCommand, string(current))
current = nil
} else {
current = append(current, c)
}

if i == len(command)-1 {
runCommand = append(runCommand, string(current))
}
}
return
Expand Down
17 changes: 17 additions & 0 deletions zshell/shell_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,20 @@ func TestCallbackRun(t *testing.T) {
tt.NoError(err)
tt.Log("code", <-code)
}

func Test_fixCommand(t *testing.T) {
tt := zlsgo.NewTest(t)

e := []string{"ping", "www.npmjs.com"}
r := fixCommand("ping www.npmjs.com")
tt.Equal(e, r)

e = []string{"ls", "-a", "/Applications/Google Chrome.app"}
r = fixCommand("ls -a /Applications/Google\\ Chrome.app")
tt.Equal(e, r)

e = []string{"networksetup", "-setwebproxystate", "USB 10/100/1000 LAN", "on"}
r = fixCommand(`networksetup -setwebproxystate "USB 10/100/1000 LAN" on`)
tt.Equal(e, r)

}

0 comments on commit 124574c

Please sign in to comment.