| 1 |
package imagebuilder |
| 2 |
|
| 3 |
// This will take a single word and an array of env variables and |
| 4 |
// process all quotes (" and ') as well as $xxx and ${xxx} env variable |
| 5 |
// tokens. Tries to mimic bash shell process. |
| 6 |
// It doesn't support all flavors of ${xx:...} formats but new ones can |
| 7 |
// be added by adding code to the "special ${} format processing" section |
| 8 |
|
| 9 |
import ( |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
"path" |
| 13 |
"strings" |
| 14 |
"text/scanner" |
| 15 |
"unicode" |
| 16 |
) |
| 17 |
|
| 18 |
type shellWord struct { |
| 19 |
word string |
| 20 |
scanner scanner.Scanner |
| 21 |
envs []string |
| 22 |
pos int |
| 23 |
} |
| 24 |
|
| 25 |
// ProcessWord will use the 'env' list of environment variables, |
| 26 |
// and replace any env var references in 'word'. |
| 27 |
func ProcessWord(word string, env []string) (string, error) { |
| 28 |
sw := &shellWord{ |
| 29 |
word: word, |
| 30 |
envs: env, |
| 31 |
pos: 0, |
| 32 |
} |
| 33 |
sw.scanner.Init(strings.NewReader(word)) |
| 34 |
word, _, err := sw.process() |
| 35 |
return word, err |
| 36 |
} |
| 37 |
|
| 38 |
// ProcessWords will use the 'env' list of environment variables, |
| 39 |
// and replace any env var references in 'word' then it will also |
| 40 |
// return a slice of strings which represents the 'word' |
| 41 |
// split up based on spaces - taking into account quotes. Note that |
| 42 |
// this splitting is done **after** the env var substitutions are done. |
| 43 |
// Note, each one is trimmed to remove leading and trailing spaces (unless |
| 44 |
// they are quoted", but ProcessWord retains spaces between words. |
| 45 |
func ProcessWords(word string, env []string) ([]string, error) { |
| 46 |
sw := &shellWord{ |
| 47 |
word: word, |
| 48 |
envs: env, |
| 49 |
pos: 0, |
| 50 |
} |
| 51 |
sw.scanner.Init(strings.NewReader(word)) |
| 52 |
_, words, err := sw.process() |
| 53 |
return words, err |
| 54 |
} |
| 55 |
|
| 56 |
func (sw *shellWord) process() (string, []string, error) { |
| 57 |
return sw.processStopOn(scanner.EOF) |
| 58 |
} |
| 59 |
|
| 60 |
type wordsStruct struct { |
| 61 |
word string |
| 62 |
words []string |
| 63 |
inWord bool |
| 64 |
} |
| 65 |
|
| 66 |
func (w *wordsStruct) addChar(ch rune) { |
| 67 |
if unicode.IsSpace(ch) && w.inWord { |
| 68 |
if len(w.word) != 0 { |
| 69 |
w.words = append(w.words, w.word) |
| 70 |
w.word = "" |
| 71 |
w.inWord = false |
| 72 |
} |
| 73 |
} else if !unicode.IsSpace(ch) { |
| 74 |
w.addRawChar(ch) |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
func (w *wordsStruct) addRawChar(ch rune) { |
| 79 |
w.word += string(ch) |
| 80 |
w.inWord = true |
| 81 |
} |
| 82 |
|
| 83 |
func (w *wordsStruct) addString(str string) { |
| 84 |
var scan scanner.Scanner |
| 85 |
scan.Init(strings.NewReader(str)) |
| 86 |
for scan.Peek() != scanner.EOF { |
| 87 |
w.addChar(scan.Next()) |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
func (w *wordsStruct) addRawString(str string) { |
| 92 |
w.word += str |
| 93 |
w.inWord = true |
| 94 |
} |
| 95 |
|
| 96 |
func (w *wordsStruct) getWords() []string { |
| 97 |
if len(w.word) > 0 { |
| 98 |
w.words = append(w.words, w.word) |
| 99 |
|
| 100 |
// Just in case we're called again by mistake |
| 101 |
w.word = "" |
| 102 |
w.inWord = false |
| 103 |
} |
| 104 |
return w.words |
| 105 |
} |
| 106 |
|
| 107 |
func (sw *shellWord) processStopOn(stopChar rune) (string, []string, error) { |
| 108 |
_, result, words, err := sw.processStopOnAny([]rune{stopChar}) |
| 109 |
return result, words, err |
| 110 |
} |
| 111 |
|
| 112 |
// Process the word, starting at 'pos', and stop when we get to the |
| 113 |
// end of the word or the 'stopChar' character |
| 114 |
func (sw *shellWord) processStopOnAny(stopChars []rune) (rune, string, []string, error) { |
| 115 |
var result string |
| 116 |
var words wordsStruct |
| 117 |
|
| 118 |
var charFuncMapping = map[rune]func() (string, error){ |
| 119 |
'\'': sw.processSingleQuote, |
| 120 |
'"': sw.processDoubleQuote, |
| 121 |
'$': sw.processDollar, |
| 122 |
} |
| 123 |
|
| 124 |
sliceContains := func(slice []rune, value rune) bool { |
| 125 |
for _, r := range slice { |
| 126 |
if r == value { |
| 127 |
return true |
| 128 |
} |
| 129 |
} |
| 130 |
return false |
| 131 |
} |
| 132 |
for sw.scanner.Peek() != scanner.EOF { |
| 133 |
ch := sw.scanner.Peek() |
| 134 |
|
| 135 |
if sliceContains(stopChars, ch) { |
| 136 |
sw.scanner.Next() // skip over ch |
| 137 |
return ch, result, words.getWords(), nil |
| 138 |
} |
| 139 |
if fn, ok := charFuncMapping[ch]; ok { |
| 140 |
// Call special processing func for certain chars |
| 141 |
tmp, err := fn() |
| 142 |
if err != nil { |
| 143 |
return ch, "", []string{}, err |
| 144 |
} |
| 145 |
result += tmp |
| 146 |
|
| 147 |
if ch == rune('$') { |
| 148 |
words.addString(tmp) |
| 149 |
} else { |
| 150 |
words.addRawString(tmp) |
| 151 |
} |
| 152 |
} else { |
| 153 |
// Not special, just add it to the result |
| 154 |
ch = sw.scanner.Next() |
| 155 |
|
| 156 |
if ch == '\\' { |
| 157 |
// '\' escapes, except end of line |
| 158 |
|
| 159 |
ch = sw.scanner.Next() |
| 160 |
|
| 161 |
if ch == scanner.EOF { |
| 162 |
break |
| 163 |
} |
| 164 |
|
| 165 |
words.addRawChar(ch) |
| 166 |
} else { |
| 167 |
words.addChar(ch) |
| 168 |
} |
| 169 |
|
| 170 |
result += string(ch) |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
if !sliceContains(stopChars, scanner.EOF) { |
| 175 |
return scanner.EOF, "", []string{}, fmt.Errorf("unexpected end of statement while looking for matching %s", string(stopChars)) |
| 176 |
} |
| 177 |
|
| 178 |
return scanner.EOF, result, words.getWords(), nil |
| 179 |
} |
| 180 |
|
| 181 |
func (sw *shellWord) processSingleQuote() (string, error) { |
| 182 |
// All chars between single quotes are taken as-is |
| 183 |
// Note, you can't escape ' |
| 184 |
var result string |
| 185 |
|
| 186 |
sw.scanner.Next() |
| 187 |
|
| 188 |
for { |
| 189 |
ch := sw.scanner.Next() |
| 190 |
if ch == '\'' { |
| 191 |
break |
| 192 |
} |
| 193 |
if ch == scanner.EOF { |
| 194 |
return "", errors.New("unexpected end of statement while looking for matching single-quote") |
| 195 |
} |
| 196 |
result += string(ch) |
| 197 |
} |
| 198 |
|
| 199 |
return result, nil |
| 200 |
} |
| 201 |
|
| 202 |
func (sw *shellWord) processDoubleQuote() (string, error) { |
| 203 |
// All chars up to the next " are taken as-is, even ', except any $ chars |
| 204 |
// But you can escape " with a \ |
| 205 |
var result string |
| 206 |
|
| 207 |
sw.scanner.Next() |
| 208 |
|
| 209 |
for { |
| 210 |
ch := sw.scanner.Peek() |
| 211 |
if ch == '"' { |
| 212 |
sw.scanner.Next() |
| 213 |
break |
| 214 |
} |
| 215 |
if ch == scanner.EOF { |
| 216 |
return "", errors.New("unexpected end of statement while looking for matching double-quote") |
| 217 |
} |
| 218 |
if ch == '$' { |
| 219 |
tmp, err := sw.processDollar() |
| 220 |
if err != nil { |
| 221 |
return "", err |
| 222 |
} |
| 223 |
result += tmp |
| 224 |
} else { |
| 225 |
ch = sw.scanner.Next() |
| 226 |
if ch == '\\' { |
| 227 |
chNext := sw.scanner.Peek() |
| 228 |
|
| 229 |
if chNext == scanner.EOF { |
| 230 |
// Ignore \ at end of word |
| 231 |
continue |
| 232 |
} |
| 233 |
|
| 234 |
if chNext == '"' || chNext == '$' || chNext == '\\' { |
| 235 |
// \" and \$ and \\ can be escaped, all other \'s are left as-is |
| 236 |
ch = sw.scanner.Next() |
| 237 |
} |
| 238 |
} |
| 239 |
result += string(ch) |
| 240 |
} |
| 241 |
} |
| 242 |
|
| 243 |
return result, nil |
| 244 |
} |
| 245 |
|
| 246 |
func (sw *shellWord) processDollar() (string, error) { |
| 247 |
sw.scanner.Next() |
| 248 |
ch := sw.scanner.Peek() |
| 249 |
if ch == '{' { |
| 250 |
sw.scanner.Next() |
| 251 |
name := sw.processName() |
| 252 |
ch = sw.scanner.Peek() |
| 253 |
if ch == '}' { |
| 254 |
// Normal ${xx} case |
| 255 |
sw.scanner.Next() |
| 256 |
return sw.getEnv(name), nil |
| 257 |
} |
| 258 |
if ch == ':' { |
| 259 |
// Special ${xx:...} format processing |
| 260 |
// Yes it allows for recursive $'s in the ... spot |
| 261 |
|
| 262 |
sw.scanner.Next() // skip over : |
| 263 |
modifier := sw.scanner.Next() |
| 264 |
|
| 265 |
word, _, err := sw.processStopOn('}') |
| 266 |
if err != nil { |
| 267 |
return "", err |
| 268 |
} |
| 269 |
|
| 270 |
// Grab the current value of the variable in question so we |
| 271 |
// can use it to determine what to do based on the modifier |
| 272 |
newValue := sw.getEnv(name) |
| 273 |
|
| 274 |
switch modifier { |
| 275 |
case '+': |
| 276 |
if newValue != "" { |
| 277 |
newValue = word |
| 278 |
} |
| 279 |
return newValue, nil |
| 280 |
|
| 281 |
case '-': |
| 282 |
if newValue == "" { |
| 283 |
newValue = word |
| 284 |
} |
| 285 |
return newValue, nil |
| 286 |
case '?': |
| 287 |
if newValue == "" { |
| 288 |
newValue = word |
| 289 |
} |
| 290 |
if newValue == "" { |
| 291 |
return "", fmt.Errorf("Failed to process `%s`: %s is not allowed to be unset", sw.word, name) |
| 292 |
} |
| 293 |
return newValue, nil |
| 294 |
default: |
| 295 |
return "", fmt.Errorf("Unsupported modifier (%c) in substitution: %s", modifier, sw.word) |
| 296 |
} |
| 297 |
} |
| 298 |
if ch == '#' || ch == '%' { // strip a prefix or suffix |
| 299 |
sw.scanner.Next() // skip over # or % |
| 300 |
greedy := false |
| 301 |
if sw.scanner.Peek() == ch { |
| 302 |
sw.scanner.Next() // skip over second # or % |
| 303 |
greedy = true |
| 304 |
} |
| 305 |
word, _, err := sw.processStopOn('}') |
| 306 |
if err != nil { |
| 307 |
return "", err |
| 308 |
} |
| 309 |
value := sw.getEnv(name) |
| 310 |
switch ch { |
| 311 |
case '#': // strip a prefix |
| 312 |
if word == "" { |
| 313 |
return "", fmt.Errorf("%s#: no prefix to remove", name) |
| 314 |
} |
| 315 |
if greedy { |
| 316 |
for i := len(value) - 1; i >= 0; i-- { |
| 317 |
if matches, err := path.Match(word, value[:i]); err == nil && matches { |
| 318 |
return value[i:], nil |
| 319 |
} |
| 320 |
} |
| 321 |
} else { |
| 322 |
for i := 0; i < len(value)-1; i++ { |
| 323 |
if matches, err := path.Match(word, value[:i]); err == nil && matches { |
| 324 |
return value[i:], nil |
| 325 |
} |
| 326 |
} |
| 327 |
} |
| 328 |
return value, nil |
| 329 |
case '%': // strip a suffix |
| 330 |
if word == "" { |
| 331 |
return "", fmt.Errorf("%s%%: no suffix to remove", name) |
| 332 |
} |
| 333 |
if greedy { |
| 334 |
for i := 0; i < len(value)-1; i++ { |
| 335 |
if matches, err := path.Match(word, value[i:]); err == nil && matches { |
| 336 |
return value[:i], nil |
| 337 |
} |
| 338 |
} |
| 339 |
} else { |
| 340 |
for i := len(value) - 1; i >= 0; i-- { |
| 341 |
if matches, err := path.Match(word, value[i:]); err == nil && matches { |
| 342 |
return value[:i], nil |
| 343 |
} |
| 344 |
} |
| 345 |
} |
| 346 |
return value, nil |
| 347 |
} |
| 348 |
} |
| 349 |
if ch == '/' { // perform substitution |
| 350 |
sw.scanner.Next() // skip over / |
| 351 |
all, begin, end := false, false, false |
| 352 |
switch sw.scanner.Peek() { |
| 353 |
case ch: |
| 354 |
sw.scanner.Next() // skip over second / |
| 355 |
all = true // replace all instances |
| 356 |
case '#': |
| 357 |
sw.scanner.Next() // skip over # |
| 358 |
begin = true // replace only an prefix instance |
| 359 |
case '%': |
| 360 |
sw.scanner.Next() // skip over % |
| 361 |
end = true // replace only a fuffix instance |
| 362 |
} |
| 363 |
// the '/', and the replacement pattern that follows |
| 364 |
// it, can be omitted if the replacement pattern is "", |
| 365 |
// so the pattern-to-replace can end at either a '/' or |
| 366 |
// a '}' |
| 367 |
ch, pattern, _, err := sw.processStopOnAny([]rune{'/', '}'}) |
| 368 |
if err != nil { |
| 369 |
return "", err |
| 370 |
} |
| 371 |
if pattern == "" { // pattern to replace needs to not be empty |
| 372 |
return "", fmt.Errorf("%s/: no pattern to replace", name) |
| 373 |
} |
| 374 |
var replacement string |
| 375 |
if ch == '/' { // patter to replace it with was specified |
| 376 |
replacement, _, err = sw.processStopOn('}') |
| 377 |
if err != nil { |
| 378 |
return "", err |
| 379 |
} |
| 380 |
} |
| 381 |
value := sw.getEnv(name) |
| 382 |
i := 0 |
| 383 |
for { |
| 384 |
if i >= len(value) { |
| 385 |
break |
| 386 |
} |
| 387 |
for j := len(value); j > i; j-- { |
| 388 |
if begin && i != 0 { |
| 389 |
continue |
| 390 |
} |
| 391 |
if end && j != len(value) { |
| 392 |
continue |
| 393 |
} |
| 394 |
matches, err := path.Match(pattern, value[i:j]) |
| 395 |
if err == nil && matches { |
| 396 |
value = value[:i] + replacement + value[j:] |
| 397 |
if !all { |
| 398 |
return value, nil |
| 399 |
} |
| 400 |
i += (len(replacement) - 1) |
| 401 |
break |
| 402 |
} |
| 403 |
} |
| 404 |
i++ |
| 405 |
} |
| 406 |
return value, nil |
| 407 |
} |
| 408 |
return "", fmt.Errorf("Missing ':' or '#' or '%%' or '/' in substitution: %s", sw.word) |
| 409 |
} |
| 410 |
// $xxx case |
| 411 |
name := sw.processName() |
| 412 |
if name == "" { |
| 413 |
return "$", nil |
| 414 |
} |
| 415 |
return sw.getEnv(name), nil |
| 416 |
} |
| 417 |
|
| 418 |
func (sw *shellWord) processName() string { |
| 419 |
// Read in a name (alphanumeric or _) |
| 420 |
// If it starts with a numeric then just return $# |
| 421 |
var name string |
| 422 |
|
| 423 |
for sw.scanner.Peek() != scanner.EOF { |
| 424 |
ch := sw.scanner.Peek() |
| 425 |
if len(name) == 0 && unicode.IsDigit(ch) { |
| 426 |
ch = sw.scanner.Next() |
| 427 |
return string(ch) |
| 428 |
} |
| 429 |
if !unicode.IsLetter(ch) && !unicode.IsDigit(ch) && ch != '_' { |
| 430 |
break |
| 431 |
} |
| 432 |
ch = sw.scanner.Next() |
| 433 |
name += string(ch) |
| 434 |
} |
| 435 |
|
| 436 |
return name |
| 437 |
} |
| 438 |
|
| 439 |
func (sw *shellWord) getEnv(name string) string { |
| 440 |
for _, env := range sw.envs { |
| 441 |
i := strings.Index(env, "=") |
| 442 |
if i < 0 { |
| 443 |
if name == env { |
| 444 |
// Should probably never get here, but just in case treat |
| 445 |
// it like "var" and "var=" are the same |
| 446 |
return "" |
| 447 |
} |
| 448 |
continue |
| 449 |
} |
| 450 |
if name != env[:i] { |
| 451 |
continue |
| 452 |
} |
| 453 |
return env[i+1:] |
| 454 |
} |
| 455 |
return "" |
| 456 |
} |