Refactor SplitShellStrings
This commit is contained in:
parent
345b6c4694
commit
34f27edc03
3 changed files with 26 additions and 33 deletions
|
@ -41,8 +41,8 @@ func (s *shellSplitter) isSplitChar(c rune) bool {
|
|||
return c == '\\' || unicode.IsSpace(c)
|
||||
}
|
||||
|
||||
// SplitShellArgs returns the list of arguments from a shell command string.
|
||||
func SplitShellArgs(data string) (cmd string, args []string, err error) {
|
||||
// SplitShellStrings returns the list of shell strings from a shell command string.
|
||||
func SplitShellStrings(data string) (strs []string, err error) {
|
||||
s := &shellSplitter{}
|
||||
|
||||
// derived from strings.SplitFunc
|
||||
|
@ -50,7 +50,7 @@ func SplitShellArgs(data string) (cmd string, args []string, err error) {
|
|||
for i, rune := range data {
|
||||
if s.isSplitChar(rune) {
|
||||
if fieldStart >= 0 {
|
||||
args = append(args, data[fieldStart:i])
|
||||
strs = append(strs, data[fieldStart:i])
|
||||
fieldStart = -1
|
||||
}
|
||||
} else if fieldStart == -1 {
|
||||
|
@ -58,21 +58,19 @@ func SplitShellArgs(data string) (cmd string, args []string, err error) {
|
|||
}
|
||||
}
|
||||
if fieldStart >= 0 { // Last field might end at EOF.
|
||||
args = append(args, data[fieldStart:])
|
||||
strs = append(strs, data[fieldStart:])
|
||||
}
|
||||
|
||||
switch s.quote {
|
||||
case '\'':
|
||||
return "", nil, errors.New("single-quoted string not terminated")
|
||||
return nil, errors.New("single-quoted string not terminated")
|
||||
case '"':
|
||||
return "", nil, errors.New("double-quoted string not terminated")
|
||||
return nil, errors.New("double-quoted string not terminated")
|
||||
}
|
||||
|
||||
if len(args) == 0 {
|
||||
return "", nil, errors.New("command string is empty")
|
||||
if len(strs) == 0 {
|
||||
return nil, errors.New("command string is empty")
|
||||
}
|
||||
|
||||
cmd, args = args[0], args[1:]
|
||||
|
||||
return cmd, args, nil
|
||||
return strs, nil
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue