Skip to content

Instantly share code, notes, and snippets.

@Roundaround
Last active August 29, 2015 14:27
Show Gist options
  • Save Roundaround/10cd75f02da3f6215586 to your computer and use it in GitHub Desktop.
Save Roundaround/10cd75f02da3f6215586 to your computer and use it in GitHub Desktop.
Command line parser utilizing a fancy RegExp to tokenize.
module.exports = {
Parser: function () {
var self = this;
self.parse = function (str) {
var hash = {
_: [],
_flags: [],
_trailing: ''
};
var quotedTrail = false;
// https://regex101.com/r/dC5cB3
var tokenizer = /(?:^| )((?:(?:-([a-z]+))|(?:--([a-z0-9]\w+)(?: (?:"((?:\\.|[^"\\])*)")|(?: (\w+)))?))|(?:"((?:\\.|[^"\\])*)")|(?:\w+))/ig;
var match;
while ((match = tokenizer.exec(str)) !== null) {
if (match.index === tokenizer.lastIndex)
tokenizer.lastIndex++;
// Determine which pattern simply by checking which capture groups are undefined.
if (match[3] === undefined && match[4] === undefined && match[5] === undefined) {
// Single token or flagset.
if (match[2] === undefined) {
// Single token.
if (match[6] === undefined) {
// *** Single word.
hash._.push(match[1]);
if (!quotedTrail)
hash._trailing += (hash._trailing.length ? ' ' : '') + match[1];
else
hash._trailing = match[1];
quotedTrail = false;
} else {
// *** Quoted token.
hash._.push(match[6]);
hash._trailing = match[6];
quotedTrail = true;
}
} else {
// *** Flagset.
for (var i = 0; i < match[2].length; i++) {
hash._flags.push(match[2][i]);
if (hash[match[2][i]] === undefined)
hash[match[2][i]] = true;
else if (typeof hash[match[2][i]] === 'boolean')
hash[match[2][i]] = 2;
else
hash[match[2][i]]++;
hash._trailing = '';
quotedTrail = false;
}
}
} else if (match[4] === undefined) {
// *** Single word parameterized.
hash[match[3]] = match[5];
hash._trailing = match[5];
quotedTrail = false;
} else {
// *** Quoted token parameterized.
hash[match[3]] = match[4];
hash._trailing = match[4];
quotedTrail = true;
}
}
return hash;
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment