Rewrite shell cmd parser

This commit is contained in:
Alex X
2023-10-25 16:49:01 +03:00
parent 041ce885c7
commit f291f1d827
2 changed files with 36 additions and 25 deletions

View File

@@ -14,35 +14,28 @@ func QuoteSplit(s string) []string {
var a []string var a []string
for len(s) > 0 { for len(s) > 0 {
is := strings.IndexByte(s, ' ') switch c := s[0]; c {
if is >= 0 { case '\t', '\n', '\r', ' ': // unicode.IsSpace
// skip prefix and double spaces
if is == 0 {
// goto next symbol
s = s[1:] s = s[1:]
continue case '"', '\'': // quote chars
} if i := strings.IndexByte(s[1:], c); i > 0 {
a = append(a, s[1:i+1])
// check if quote in word s = s[i+2:]
if i := strings.IndexByte(s[:is], '"'); i >= 0 {
// search quote end
if is = strings.Index(s, `" `); is > 0 {
is += 1
} else { } else {
is = -1 return nil // error
} }
} default:
} i := strings.IndexAny(s, "\t\n\r ")
if i > 0 {
if is >= 0 { a = append(a, s[:i])
a = append(a, strings.ReplaceAll(s[:is], `"`, "")) s = s[i:]
s = s[is+1:]
} else { } else {
//add last word
a = append(a, s) a = append(a, s)
break s = ""
} }
} }
}
return a return a
} }

18
pkg/shell/shell_test.go Normal file
View File

@@ -0,0 +1,18 @@
package shell
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestQuoteSplit(t *testing.T) {
s := `
python "-c" 'import time
print("time", time.time())'
`
require.Equal(t, []string{"python", "-c", "import time\nprint(\"time\", time.time())"}, QuoteSplit(s))
s = `ffmpeg -i video="0" -i "DeckLink SDI (2)"`
require.Equal(t, []string{"ffmpeg", "-i", "video=\"0\"", "-i", "DeckLink SDI (2)"}, QuoteSplit(s))
}