| 1 |
|
| 2 |
|
| 3 |
package main |
| 4 |
|
| 5 |
import ( |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"strings" |
| 9 |
) |
| 10 |
|
| 11 |
func splitCFlagsFromArgs(in []string) (args, cflags []string) { |
| 12 |
for i, arg := range in { |
| 13 |
if arg == "--" { |
| 14 |
return in[:i], in[i+1:] |
| 15 |
} |
| 16 |
} |
| 17 |
|
| 18 |
return in, nil |
| 19 |
} |
| 20 |
|
| 21 |
func splitArguments(in string) ([]string, error) { |
| 22 |
var ( |
| 23 |
result []string |
| 24 |
builder strings.Builder |
| 25 |
escaped bool |
| 26 |
delim = ' ' |
| 27 |
) |
| 28 |
|
| 29 |
for _, r := range strings.TrimSpace(in) { |
| 30 |
if escaped { |
| 31 |
builder.WriteRune(r) |
| 32 |
escaped = false |
| 33 |
continue |
| 34 |
} |
| 35 |
|
| 36 |
switch r { |
| 37 |
case '\\': |
| 38 |
escaped = true |
| 39 |
|
| 40 |
case delim: |
| 41 |
current := builder.String() |
| 42 |
builder.Reset() |
| 43 |
|
| 44 |
if current != "" || delim != ' ' { |
| 45 |
|
| 46 |
|
| 47 |
result = append(result, current) |
| 48 |
} |
| 49 |
delim = ' ' |
| 50 |
|
| 51 |
case '"', '\'', ' ': |
| 52 |
if delim == ' ' { |
| 53 |
delim = r |
| 54 |
continue |
| 55 |
} |
| 56 |
|
| 57 |
fallthrough |
| 58 |
|
| 59 |
default: |
| 60 |
builder.WriteRune(r) |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
if delim != ' ' { |
| 65 |
return nil, fmt.Errorf("missing `%c`", delim) |
| 66 |
} |
| 67 |
|
| 68 |
if escaped { |
| 69 |
return nil, errors.New("unfinished escape") |
| 70 |
} |
| 71 |
|
| 72 |
|
| 73 |
if builder.Len() > 0 { |
| 74 |
result = append(result, builder.String()) |
| 75 |
} |
| 76 |
|
| 77 |
return result, nil |
| 78 |
} |