| 168 | * @example getCommandRoot("git status && npm test") returns "git" |
| 169 | */ |
| 170 | export function getCommandRoot(command: string): string | undefined { |
| 171 | const trimmedCommand = command.trim(); |
| 172 | if (!trimmedCommand) { |
| 173 | return undefined; |
| 174 | } |
| 175 | |
| 176 | // This regex is designed to find the first "word" of a command, |
| 177 | // while respecting quotes. It looks for a sequence of non-whitespace |
| 178 | // characters that are not inside quotes. |
| 179 | const match = trimmedCommand.match(/^"([^"]+)"|^'([^']+)'|^(\S+)/); |
| 180 | if (match) { |
| 181 | // The first element in the match array is the full match. |
| 182 | // The subsequent elements are the capture groups. |
| 183 | // We prefer a captured group because it will be unquoted. |
| 184 | const commandRoot = match[1] || match[2] || match[3]; |
| 185 | if (commandRoot) { |
| 186 | // If the command is a path, return the last component. |
| 187 | return commandRoot.split(/[\\/]/).pop(); |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | return undefined; |
| 192 | } |
| 193 | |
| 194 | export function getCommandRoots(command: string): string[] { |
| 195 | if (!command) { |