MCPcopy
hub / github.com/direnv/direnv / BashEscape

Function BashEscape

internal/cmd/shell_bash.go:105–189  ·  view source on GitHub ↗

BashEscape escapes strings for safe use in Bash. Based on https://github.com/solidsnack/shell-escape/blob/master/Text/ShellEscape/Bash.hs * A Bash escaped string. The strings are wrapped in @$\'...\'@ if any bytes within them must be escaped; otherwise, they are left as is. Newlines and other contro

(str string)

Source from the content-addressed store, hash-verified

103strings will always fit on one line and never contain non-ASCII bytes.
104*/
105func BashEscape(str string) string {
106 if str == "" {
107 return "''"
108 }
109 in := []byte(str)
110 out := ""
111 i := 0
112 l := len(in)
113 escape := false
114
115 hex := func(char byte) {
116 escape = true
117 out += fmt.Sprintf("\\x%02x", char)
118 }
119
120 backslash := func(char byte) {
121 escape = true
122 out += string([]byte{BACKSLASH, char})
123 }
124
125 escaped := func(str string) {
126 escape = true
127 out += str
128 }
129
130 quoted := func(char byte) {
131 escape = true
132 out += string([]byte{char})
133 }
134
135 literal := func(char byte) {
136 out += string([]byte{char})
137 }
138
139 for i < l {
140 char := in[i]
141 switch {
142 case char == ACK:
143 hex(char)
144 case char == TAB:
145 escaped(`\t`)
146 case char == LF:
147 escaped(`\n`)
148 case char == CR:
149 escaped(`\r`)
150 case char <= US:
151 hex(char)
152 case char <= AMPERSTAND:
153 quoted(char)
154 case char == SINGLE_QUOTE:
155 backslash(char)
156 case char <= PLUS:
157 quoted(char)
158 case char <= NINE:
159 literal(char)
160 case char <= QUESTION:
161 quoted(char)
162 case char <= UPPERCASE_Z:

Callers 5

escapeMethod · 0.85
LoadMethod · 0.85
TestBashEscapeFunction · 0.85
cmdEditActionFunction · 0.85
escapeMethod · 0.85

Calls

no outgoing calls

Tested by 1

TestBashEscapeFunction · 0.68