ParseCommandLine parses the command line string into an string array
(command string)
| 56 | |
| 57 | // ParseCommandLine parses the command line string into an string array |
| 58 | func ParseCommandLine(command string) ([]string, error) { |
| 59 | var args []string |
| 60 | state := "start" |
| 61 | current := "" |
| 62 | quote := "\"" |
| 63 | escapeNext := true |
| 64 | for i := 0; i < len(command); i++ { |
| 65 | c := command[i] |
| 66 | |
| 67 | if state == "quotes" { |
| 68 | if string(c) != quote { |
| 69 | current += string(c) |
| 70 | } else { |
| 71 | args = append(args, current) |
| 72 | current = "" |
| 73 | state = "start" |
| 74 | } |
| 75 | continue |
| 76 | } |
| 77 | |
| 78 | if escapeNext { |
| 79 | current += string(c) |
| 80 | escapeNext = false |
| 81 | continue |
| 82 | } |
| 83 | |
| 84 | if c == '\\' { |
| 85 | escapeNext = true |
| 86 | continue |
| 87 | } |
| 88 | |
| 89 | if c == '"' || c == '\'' { |
| 90 | state = "quotes" |
| 91 | quote = string(c) |
| 92 | continue |
| 93 | } |
| 94 | |
| 95 | if state == "arg" { |
| 96 | if c == ' ' || c == '\t' { |
| 97 | args = append(args, current) |
| 98 | current = "" |
| 99 | state = "start" |
| 100 | } else { |
| 101 | current += string(c) |
| 102 | } |
| 103 | continue |
| 104 | } |
| 105 | |
| 106 | if c != ' ' && c != '\t' { |
| 107 | state = "arg" |
| 108 | current += string(c) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | if state == "quotes" { |
| 113 | return []string{}, fmt.Errorf("unclosed quote in command line: %s", command) |
| 114 | } |
| 115 |
no test coverage detected