-
Notifications
You must be signed in to change notification settings - Fork 2
/
parse.go
144 lines (121 loc) · 2.48 KB
/
parse.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package utils
import (
"errors"
)
type fmsState int
const (
stateArgumentOutside fmsState = iota
stateArgumentStart
stateArgumentEnd
)
var errEndOfLine = errors.New("End of line")
type cmdArgumentParser struct {
s string
i int
length int
state fmsState
startToken byte
shouldEscape bool
currArgument []byte
err error
}
func newCmdArgumentParser(s string) *cmdArgumentParser {
return &cmdArgumentParser{
s: s,
i: -1,
length: len(s),
currArgument: make([]byte, 0, 16),
}
}
func (cap *cmdArgumentParser) parse() (arguments []string) {
for {
cap.next()
if cap.err != nil {
if cap.shouldEscape {
cap.currArgument = append(cap.currArgument, '\\')
}
if len(cap.currArgument) > 0 {
arguments = append(arguments, string(cap.currArgument))
}
return
}
switch cap.state {
case stateArgumentOutside:
cap.detectStartToken()
case stateArgumentStart:
if !cap.detectEnd() {
cap.detectContent()
}
case stateArgumentEnd:
cap.state = stateArgumentOutside
arguments = append(arguments, string(cap.currArgument))
cap.currArgument = cap.currArgument[:0]
}
}
}
func (cap *cmdArgumentParser) previous() {
if cap.i >= 0 {
cap.i--
}
}
func (cap *cmdArgumentParser) next() {
if cap.length-cap.i == 1 {
cap.err = errEndOfLine
return
}
cap.i++
}
func (cap *cmdArgumentParser) detectStartToken() {
c := cap.s[cap.i]
if c == ' ' {
return
}
switch c {
case '\\':
cap.startToken = 0
cap.shouldEscape = true
case '"', '\'':
cap.startToken = c
default:
cap.startToken = 0
cap.previous()
}
cap.state = stateArgumentStart
}
func (cap *cmdArgumentParser) detectContent() {
c := cap.s[cap.i]
if cap.shouldEscape {
switch c {
case ' ', '\\', cap.startToken:
cap.currArgument = append(cap.currArgument, c)
default:
cap.currArgument = append(cap.currArgument, '\\', c)
}
cap.shouldEscape = false
return
}
if c == '\\' {
cap.shouldEscape = true
} else {
cap.currArgument = append(cap.currArgument, c)
}
}
func (cap *cmdArgumentParser) detectEnd() (detected bool) {
c := cap.s[cap.i]
if cap.startToken == 0 {
if c == ' ' && !cap.shouldEscape {
cap.state = stateArgumentEnd
cap.previous()
return true
}
return false
}
if c == cap.startToken && !cap.shouldEscape {
cap.state = stateArgumentEnd
return true
}
return false
}
func ParseCmdArguments(s string) (arguments []string) {
return newCmdArgumentParser(s).parse()
}