| 1 |
// Copyright 2019 The Kubernetes Authors. |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package execplugin |
| 5 |
|
| 6 |
import ( |
| 7 |
"fmt" |
| 8 |
"strings" |
| 9 |
"unicode" |
| 10 |
) |
| 11 |
|
| 12 |
// ShlexSplit splits a string into a slice of strings using shell-style rules for quoting and commenting |
| 13 |
// Similar to Python's shlex.split with comments enabled |
| 14 |
func ShlexSplit(s string) ([]string, error) { |
| 15 |
return shlexSplit(s) |
| 16 |
} |
| 17 |
|
| 18 |
func shlexSplit(s string) ([]string, error) { |
| 19 |
result := []string{} |
| 20 |
|
| 21 |
// noQuote is used to track if we are not in a quoted |
| 22 |
const noQuote = 0 |
| 23 |
|
| 24 |
var current strings.Builder |
| 25 |
var quote rune = noQuote |
| 26 |
var escaped bool |
| 27 |
|
| 28 |
for _, r := range s { |
| 29 |
switch { |
| 30 |
case escaped: |
| 31 |
current.WriteRune(r) |
| 32 |
escaped = false |
| 33 |
case r == '\\' && quote != '\'': |
| 34 |
escaped = true |
| 35 |
case (r == '\'' || r == '"') && quote == noQuote: |
| 36 |
quote = r |
| 37 |
case r == quote: |
| 38 |
quote = noQuote |
| 39 |
case r == '#' && quote == noQuote: |
| 40 |
// Comment starts, ignore the rest of the line |
| 41 |
if current.Len() > 0 { |
| 42 |
result = append(result, current.String()) |
| 43 |
} |
| 44 |
return result, nil |
| 45 |
case unicode.IsSpace(r) && quote == noQuote: |
| 46 |
if current.Len() > 0 { |
| 47 |
result = append(result, current.String()) |
| 48 |
current.Reset() |
| 49 |
} |
| 50 |
default: |
| 51 |
current.WriteRune(r) |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
if quote != noQuote { |
| 56 |
return nil, fmt.Errorf("unclosed quote in string") |
| 57 |
} |
| 58 |
if current.Len() > 0 { |
| 59 |
result = append(result, current.String()) |
| 60 |
} |
| 61 |
return result, nil |
| 62 |
} |