-
Notifications
You must be signed in to change notification settings - Fork 472
/
maybeshellquote.go
61 lines (56 loc) · 1.36 KB
/
maybeshellquote.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
package chezmoi
import (
"regexp"
"strings"
)
var needShellQuoteRegexp = regexp.MustCompile(`[^+\-./0-9=A-Z_a-z]`)
const (
backslash = '\\'
singleQuote = '\''
)
// MaybeShellQuote returns s quoted as a shell argument, if necessary.
func MaybeShellQuote(s string) string {
switch {
case s == "":
return "''"
case needShellQuoteRegexp.MatchString(s):
result := make([]byte, 0, 2+len(s))
inSingleQuotes := false
for _, b := range []byte(s) {
switch b {
case backslash:
if !inSingleQuotes {
result = append(result, singleQuote)
inSingleQuotes = true
}
result = append(result, backslash, backslash)
case singleQuote:
if inSingleQuotes {
result = append(result, singleQuote)
inSingleQuotes = false
}
result = append(result, backslash, singleQuote)
default:
if !inSingleQuotes {
result = append(result, singleQuote)
inSingleQuotes = true
}
result = append(result, b)
}
}
if inSingleQuotes {
result = append(result, singleQuote)
}
return string(result)
default:
return s
}
}
// ShellQuoteArgs returs args shell quoted and joined into a single string.
func ShellQuoteArgs(args []string) string {
shellQuotedArgs := make([]string, 0, len(args))
for _, arg := range args {
shellQuotedArgs = append(shellQuotedArgs, MaybeShellQuote(arg))
}
return strings.Join(shellQuotedArgs, " ")
}