-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
43 lines (37 loc) · 886 Bytes
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main
import (
"errors"
"strings"
)
func ParseCommand(text string) (string, []string, error) {
splits := strings.SplitN(text, " ", 2)
cmdText := strings.Replace(splits[0], "!", "", 1)
if len(splits) == 1 {
return cmdText, []string{}, nil
}
cmdArgs := []string{}
currStr := ""
currQuote := ' '
for _, c := range splits[1] {
if c == currQuote {
trimmedStr := strings.TrimSpace(currStr)
if trimmedStr != "" {
cmdArgs = append(cmdArgs, trimmedStr)
}
currStr = ""
currQuote = ' '
} else if c == '"' {
currQuote = '"'
} else if c == '\'' {
currQuote = '\''
} else {
currStr += string(c)
}
}
if currQuote != ' ' {
return "", []string{}, errors.New("unexpected end of arguments")
} else if trimmedStr := strings.TrimSpace(currStr); trimmedStr != "" {
cmdArgs = append(cmdArgs, trimmedStr)
}
return cmdText, cmdArgs, nil
}