tokenize-arg-string.js 854 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // take an un-split argv string and tokenize it.
  2. module.exports = function (argString) {
  3. if (Array.isArray(argString)) {
  4. return argString.map(e => typeof e !== 'string' ? e + '' : e)
  5. }
  6. argString = argString.trim()
  7. var i = 0
  8. var prevC = null
  9. var c = null
  10. var opening = null
  11. var args = []
  12. for (var 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. } else if ((c === "'" || c === '"') && !opening) {
  27. opening = c
  28. }
  29. if (!args[i]) args[i] = ''
  30. args[i] += c
  31. }
  32. return args
  33. }