command.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Main logic for `execaCommand()`
  2. export const mapCommandAsync = ({file, commandArguments}) => parseCommand(file, commandArguments);
  3. // Main logic for `execaCommandSync()`
  4. export const mapCommandSync = ({file, commandArguments}) => ({...parseCommand(file, commandArguments), isSync: true});
  5. // Convert `execaCommand(command)` into `execa(file, ...commandArguments)`
  6. const parseCommand = (command, unusedArguments) => {
  7. if (unusedArguments.length > 0) {
  8. throw new TypeError(`The command and its arguments must be passed as a single string: ${command} ${unusedArguments}.`);
  9. }
  10. const [file, ...commandArguments] = parseCommandString(command);
  11. return {file, commandArguments};
  12. };
  13. // Convert `command` string into an array of file or arguments to pass to $`${...fileOrCommandArguments}`
  14. export const parseCommandString = command => {
  15. if (typeof command !== 'string') {
  16. throw new TypeError(`The command must be a string: ${String(command)}.`);
  17. }
  18. const trimmedCommand = command.trim();
  19. if (trimmedCommand === '') {
  20. return [];
  21. }
  22. const tokens = [];
  23. for (const token of trimmedCommand.split(SPACES_REGEXP)) {
  24. // Allow spaces to be escaped by a backslash if not meant as a delimiter
  25. const previousToken = tokens.at(-1);
  26. if (previousToken && previousToken.endsWith('\\')) {
  27. // Merge previous token with current one
  28. tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;
  29. } else {
  30. tokens.push(token);
  31. }
  32. }
  33. return tokens;
  34. };
  35. const SPACES_REGEXP = / +/g;