tokenize-arg-string.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * @license
  3. * Copyright (c) 2016, Contributors
  4. * SPDX-License-Identifier: ISC
  5. */
  6. // take an un-split argv string and tokenize it.
  7. export function tokenizeArgString(argString) {
  8. if (Array.isArray(argString)) {
  9. return argString.map(e => typeof e !== 'string' ? e + '' : e);
  10. }
  11. argString = argString.trim();
  12. let i = 0;
  13. let prevC = null;
  14. let c = null;
  15. let opening = null;
  16. const args = [];
  17. for (let ii = 0; ii < argString.length; ii++) {
  18. prevC = c;
  19. c = argString.charAt(ii);
  20. // split on spaces unless we're in quotes.
  21. if (c === ' ' && !opening) {
  22. if (!(prevC === ' ')) {
  23. i++;
  24. }
  25. continue;
  26. }
  27. // don't split the string if we're in matching
  28. // opening or closing single and double quotes.
  29. if (c === opening) {
  30. opening = null;
  31. }
  32. else if ((c === "'" || c === '"') && !opening) {
  33. opening = c;
  34. }
  35. if (!args[i])
  36. args[i] = '';
  37. args[i] += c;
  38. }
  39. return args;
  40. }