-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
shell_parser.go
74 lines (71 loc) · 1.29 KB
/
shell_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
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
package main
import (
"strings"
"unicode"
)
// This function is meant to split an input string into shell words. For example
//
// "one two" three 'four five six'
//
// would become
//
// []string{"one two", "three", "four five six"}
//
// I'm doing this so that I don't have to resort to hacky solutions like running
// a shell or smoething.
func shellParser(input string) []string {
out := []string{}
var (
buf strings.Builder
escape bool
doubleQuote bool
singleQuote bool
gotWord bool
)
for _, r := range input {
switch {
case escape:
buf.WriteRune(r)
escape = false
continue
case unicode.IsSpace(r):
if singleQuote || doubleQuote {
buf.WriteRune(r)
} else if gotWord {
out = append(out, buf.String())
buf.Reset()
gotWord = false
}
continue
case r == '\\':
if singleQuote {
buf.WriteRune(r)
} else {
escape = true
}
continue
case r == '"':
if !singleQuote {
if doubleQuote {
gotWord = true
}
doubleQuote = !doubleQuote
continue
}
case r == '\'':
if !doubleQuote {
if singleQuote {
gotWord = true
}
singleQuote = !singleQuote
continue
}
}
gotWord = true
buf.WriteRune(r)
}
if buf.Len() > 0 {
out = append(out, buf.String())
}
return out
}