tokenize-arg-string.js 1004 B

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