-
Notifications
You must be signed in to change notification settings - Fork 13
/
shellescape.go
63 lines (55 loc) · 1.7 KB
/
shellescape.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
package osutils
import (
"regexp"
"strings"
)
// ShellEscape serve to escape arguments passed to shell commands
type ShellEscape struct {
wordPattern *regexp.Regexp
escapePattern *regexp.Regexp
escapeWith string
}
//NewBashEscaper creates a new instance of ShellEscape that's configured for escaping bash style arguments
func NewBashEscaper() *ShellEscape {
return &ShellEscape{
regexp.MustCompile(`^[\w]+$`),
regexp.MustCompile(`(\\|"|\$)`),
`\$1`,
}
}
// NewBatchEscaper creates a new instance of ShellEscape that's configured for escaping batch style arguments
func NewBatchEscaper() *ShellEscape {
return &ShellEscape{
regexp.MustCompile(`^[\w]+$`),
regexp.MustCompile(`"`),
`""`,
}
}
// NewCmdEscaper creates a new instance of ShellEscape that's configured for escaping cmd arguments
func NewCmdEscaper() *ShellEscape {
return &ShellEscape{
regexp.MustCompile(`^[^ &()\[\]{}^=;!'+,~]+$`), // cmd.exe /? lists these characters as requiring quotes
regexp.MustCompile(`"`),
`""`,
}
}
// EscapeLineEnd will escape any line end characters that require escaping for the purpose of quoting
func (s *ShellEscape) EscapeLineEnd(value string) string {
value = strings.Replace(value, "\n", `\n`, -1)
value = strings.Replace(value, "\r", `\r`, -1)
return value
}
// Escape will escape any characters that require escaping for the purpose of quoting
func (s *ShellEscape) Escape(value string) string {
return s.escapePattern.ReplaceAllString(value, s.escapeWith)
}
// Quote implements SubShell.Quote
func (s *ShellEscape) Quote(value string) string {
if len(value) == 0 {
return `""`
}
if s.wordPattern.MatchString(value) {
return value
}
return `"` + s.EscapeLineEnd(s.Escape(value)) + `"`
}