tokenize-arg-string.js 862 B

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