parse-args.js 635 B

123456789101112131415161718192021222324252627
  1. /**
  2. * @param {string} args
  3. */
  4. exports.parseArgs = function (args) {
  5. const parts = args.split(/\s+/)
  6. const result = []
  7. let arg
  8. let index = 0
  9. for (const part of parts) {
  10. const l = part.length
  11. if (!arg && part.charAt(0) === '"') {
  12. arg = part.substr(1)
  13. } else if (part.charAt(l - 1) === '"' && (
  14. l === 1 || part.charAt(l - 2) !== '\\'
  15. )) {
  16. arg += args.charAt(index - 1) + part.substr(0, l - 1)
  17. result.push(arg)
  18. arg = null
  19. } else if (arg) {
  20. arg += args.charAt(index - 1) + part
  21. } else {
  22. result.push(part)
  23. }
  24. index += part.length + 1
  25. }
  26. return result
  27. }