-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutil.go
More file actions
98 lines (91 loc) · 1.61 KB
/
util.go
File metadata and controls
98 lines (91 loc) · 1.61 KB
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
package commandproxy
import (
"bytes"
"fmt"
"strings"
)
var (
errQuoteNotClose = fmt.Errorf("quote is not closed")
errEmptyCommand = fmt.Errorf("cmd is empty")
)
func SplitCommand(cmd string) ([]string, error) {
cmd = strings.TrimSpace(cmd)
if cmd == "" {
return nil, errEmptyCommand
}
var ss []string
var buf bytes.Buffer
for len(cmd) != 0 {
i := strings.IndexAny(cmd, "'\"\\ \n\t")
if i == -1 {
buf.WriteString(cmd)
break
}
buf.WriteString(cmd[:i])
c := cmd[i]
cmd = cmd[i+1:]
switch c {
case '"':
i := strings.IndexByte(cmd, '"')
if i == -1 {
return nil, errQuoteNotClose
}
buf.WriteString(cmd[:i])
cmd = cmd[i+1:]
case '\'':
i := strings.IndexByte(cmd, '\'')
if i == -1 {
return nil, errQuoteNotClose
}
buf.WriteString(cmd[:i])
cmd = cmd[i+1:]
case '\\':
if len(cmd) == 0 {
break
}
if cmd[0] != '\n' {
buf.WriteByte(cmd[0])
cmd = cmd[:1]
continue
}
fallthrough
case '\t', ' ':
if buf.Len() != 0 {
ss = append(ss, buf.String())
buf.Reset()
}
}
}
if buf.Len() != 0 {
s := buf.String()
if len(ss) == 0 {
return []string{s}, nil
}
ss = append(ss, s)
}
return ss, nil
}
func ReplaceEscape(s string, re map[byte]string) string {
re['%'] = "%"
var buf bytes.Buffer
for len(s) != 0 {
i := strings.IndexByte(s, '%')
if i == -1 || i >= len(s)-1 {
if buf.Len() == 0 {
return s
}
buf.WriteString(s)
break
}
buf.WriteString(s[:i])
s = s[i:]
rep, ok := re[s[1]]
if ok {
buf.WriteString(rep)
} else {
buf.WriteString(s[:2])
}
s = s[2:]
}
return buf.String()
}