tokenize-arg-string.js 829 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. opening = null
  24. continue
  25. } else if ((c === "'" || c === '"') && !opening) {
  26. opening = c
  27. continue
  28. }
  29. if (!args[i]) args[i] = ''
  30. args[i] += c
  31. }
  32. return args
  33. }