UNPKG

argument-vector

Version:

Split a string of command line options into and argv(argument vector) array

67 lines (59 loc) 1.23 kB
'use strict'; var debug = require('debug')('argument-vector'); function Parser(options) { if (!(this instanceof Parser)) return new Parser(options); } Parser.prototype.parse = function(line){ debug('parse("%s")', line); var orig = line = line.replace(/\\\n/g, '').trim(); var c, i = 0, len = line.length; var args = [], arg, quot, q; for (; i < len; i++) { c = line.charAt(i); switch (c) { case ' ': if (!quot) { if (arg) { args.push(arg.trim()); arg = null; } } else { arg += c; } break; case '\'': case '\"': if (!quot) { if (i === 0 || line.charAt(i-1) !== '\\') { quot = c; if (arg) { arg += c; } else { arg = c; } } } else { arg += c; if (quot === c && line.charAt(i-1) !== '\\') { quot = null; } } break; default: if (arg) { arg += c; } else { arg = c; } } } if (arg) { args.push(arg.trim()); arg = null; } return args; }; Parser.prototype.stringify = function(array){ return array.join(' '); }; module.exports = Parser;