parser.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. // fancy-pants parsing of argv, originally forked
  2. // from minimist: https://www.npmjs.com/package/minimist
  3. var camelCase = require('camelcase'),
  4. fs = require('fs'),
  5. path = require('path');
  6. module.exports = function (args, opts) {
  7. if (!opts) opts = {};
  8. var flags = { arrays: {}, bools : {}, strings : {}, counts: {}, normalize: {}, configs: {} };
  9. [].concat(opts['array']).filter(Boolean).forEach(function (key) {
  10. flags.arrays[key] = true;
  11. });
  12. [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
  13. flags.bools[key] = true;
  14. });
  15. [].concat(opts.string).filter(Boolean).forEach(function (key) {
  16. flags.strings[key] = true;
  17. });
  18. [].concat(opts.count).filter(Boolean).forEach(function (key) {
  19. flags.counts[key] = true;
  20. });
  21. [].concat(opts.normalize).filter(Boolean).forEach(function (key) {
  22. flags.normalize[key] = true;
  23. });
  24. [].concat(opts.config).filter(Boolean).forEach(function (key) {
  25. flags.configs[key] = true;
  26. });
  27. var aliases = {},
  28. newAliases = {};
  29. extendAliases(opts.key);
  30. extendAliases(opts.alias);
  31. var defaults = opts['default'] || {};
  32. Object.keys(defaults).forEach(function (key) {
  33. if (/-/.test(key) && !opts.alias[key]) {
  34. var c = camelCase(key);
  35. aliases[key] = aliases[key] || [];
  36. // don't allow the same key to be added multiple times.
  37. if (aliases[key].indexOf(c) === -1) {
  38. aliases[key] = (aliases[key] || []).concat(c);
  39. newAliases[c] = true;
  40. }
  41. }
  42. (aliases[key] || []).forEach(function (alias) {
  43. defaults[alias] = defaults[key];
  44. });
  45. });
  46. var argv = { _ : [] };
  47. Object.keys(flags.bools).forEach(function (key) {
  48. setArg(key, !(key in defaults) ? false : defaults[key]);
  49. });
  50. var notFlags = [];
  51. if (args.indexOf('--') !== -1) {
  52. notFlags = args.slice(args.indexOf('--')+1);
  53. args = args.slice(0, args.indexOf('--'));
  54. }
  55. for (var i = 0; i < args.length; i++) {
  56. var arg = args[i];
  57. // -- seperated by =
  58. if (arg.match(/^--.+=/)) {
  59. // Using [\s\S] instead of . because js doesn't support the
  60. // 'dotall' regex modifier. See:
  61. // http://stackoverflow.com/a/1068308/13216
  62. var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
  63. setArg(m[1], m[2]);
  64. }
  65. else if (arg.match(/^--no-.+/)) {
  66. var key = arg.match(/^--no-(.+)/)[1];
  67. setArg(key, false);
  68. }
  69. // -- seperated by space.
  70. else if (arg.match(/^--.+/)) {
  71. var key = arg.match(/^--(.+)/)[1];
  72. if (checkAllAliases(key, opts.narg)) {
  73. i = eatNargs(i, key, args);
  74. } else {
  75. var next = args[i + 1];
  76. if (next !== undefined && !next.match(/^-/)
  77. && !checkAllAliases(key, flags.bools)
  78. && !checkAllAliases(key, flags.counts)) {
  79. setArg(key, next);
  80. i++;
  81. }
  82. else if (/^(true|false)$/.test(next)) {
  83. setArg(key, next);
  84. i++;
  85. }
  86. else {
  87. setArg(key, defaultForType(guessType(key, flags)));
  88. }
  89. }
  90. }
  91. // dot-notation flag seperated by '='.
  92. else if (arg.match(/^-.\..+=/)) {
  93. var m = arg.match(/^-([^=]+)=([\s\S]*)$/);
  94. setArg(m[1], m[2]);
  95. }
  96. // dot-notation flag seperated by space.
  97. else if (arg.match(/^-.\..+/)) {
  98. var key = arg.match(/^-(.\..+)/)[1];
  99. var next = args[i + 1];
  100. if (next !== undefined && !next.match(/^-/)
  101. && !checkAllAliases(key, flags.bools)
  102. && !checkAllAliases(key, flags.counts)) {
  103. setArg(key, next);
  104. i++;
  105. }
  106. else {
  107. setArg(key, defaultForType(guessType(key, flags)));
  108. }
  109. }
  110. else if (arg.match(/^-[^-]+/)) {
  111. var letters = arg.slice(1,-1).split('');
  112. var broken = false;
  113. for (var j = 0; j < letters.length; j++) {
  114. var next = arg.slice(j+2);
  115. if (letters[j+1] && letters[j+1] === '=') {
  116. setArg(letters[j], arg.slice(j+3));
  117. broken = true;
  118. break;
  119. }
  120. if (next === '-') {
  121. setArg(letters[j], next)
  122. continue;
  123. }
  124. if (/[A-Za-z]/.test(letters[j])
  125. && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
  126. setArg(letters[j], next);
  127. broken = true;
  128. break;
  129. }
  130. if (letters[j+1] && letters[j+1].match(/\W/)) {
  131. setArg(letters[j], arg.slice(j+2));
  132. broken = true;
  133. break;
  134. }
  135. else {
  136. setArg(letters[j], defaultForType(guessType(letters[j], flags)));
  137. }
  138. }
  139. var key = arg.slice(-1)[0];
  140. if (!broken && key !== '-') {
  141. if (checkAllAliases(key, opts.narg)) {
  142. i = eatNargs(i, key, args);
  143. } else {
  144. if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
  145. && !checkAllAliases(key, flags.bools)
  146. && !checkAllAliases(key, flags.counts)) {
  147. setArg(key, args[i+1]);
  148. i++;
  149. }
  150. else if (args[i+1] && /true|false/.test(args[i+1])) {
  151. setArg(key, args[i+1]);
  152. i++;
  153. }
  154. else {
  155. setArg(key, defaultForType(guessType(key, flags)));
  156. }
  157. }
  158. }
  159. }
  160. else {
  161. argv._.push(
  162. flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
  163. );
  164. }
  165. }
  166. setConfig(argv);
  167. applyDefaultsAndAliases(argv, aliases, defaults);
  168. Object.keys(flags.counts).forEach(function (key) {
  169. setArg(key, defaults[key]);
  170. });
  171. notFlags.forEach(function(key) {
  172. argv._.push(key);
  173. });
  174. // how many arguments should we consume, based
  175. // on the nargs option?
  176. function eatNargs (i, key, args) {
  177. var toEat = checkAllAliases(key, opts.narg);
  178. if (args.length - (i + 1) < toEat) throw Error('not enough arguments following: ' + key);
  179. for (var ii = i + 1; ii < (toEat + i + 1); ii++) {
  180. setArg(key, args[ii]);
  181. }
  182. return (i + toEat);
  183. }
  184. function setArg (key, val) {
  185. // handle parsing boolean arguments --foo=true --bar false.
  186. if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
  187. if (typeof val === 'string') val = val === 'true';
  188. }
  189. if (/-/.test(key) && !(aliases[key] && aliases[key].length)) {
  190. var c = camelCase(key);
  191. aliases[key] = [c];
  192. newAliases[c] = true;
  193. }
  194. var value = !checkAllAliases(key, flags.strings) && isNumber(val) ? Number(val) : val;
  195. if (checkAllAliases(key, flags.counts)) {
  196. value = function(orig) { return orig !== undefined ? orig + 1 : 0; };
  197. }
  198. var splitKey = key.split('.');
  199. setKey(argv, splitKey, value);
  200. (aliases[splitKey[0]] || []).forEach(function (x) {
  201. x = x.split('.');
  202. // handle populating dot notation for both
  203. // the key and its aliases.
  204. if (splitKey.length > 1) {
  205. var a = [].concat(splitKey);
  206. a.shift(); // nuke the old key.
  207. x = x.concat(a);
  208. }
  209. setKey(argv, x, value);
  210. });
  211. var keys = [key].concat(aliases[key] || []);
  212. for (var i = 0, l = keys.length; i < l; i++) {
  213. if (flags.normalize[keys[i]]) {
  214. keys.forEach(function(key) {
  215. argv.__defineSetter__(key, function(v) {
  216. val = path.normalize(v);
  217. });
  218. argv.__defineGetter__(key, function () {
  219. return typeof val === 'string' ?
  220. path.normalize(val) : val;
  221. });
  222. });
  223. break;
  224. }
  225. }
  226. }
  227. // set args from config.json file, this should be
  228. // applied last so that defaults can be applied.
  229. function setConfig (argv) {
  230. var configLookup = {};
  231. // expand defaults/aliases, in-case any happen to reference
  232. // the config.json file.
  233. applyDefaultsAndAliases(configLookup, aliases, defaults);
  234. Object.keys(flags.configs).forEach(function(configKey) {
  235. var configPath = argv[configKey] || configLookup[configKey];
  236. if (configPath) {
  237. try {
  238. var config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  239. Object.keys(config).forEach(function (key) {
  240. // setting arguments via CLI takes precedence over
  241. // values within the config file.
  242. if (argv[key] === undefined) {
  243. delete argv[key];
  244. setArg(key, config[key]);
  245. }
  246. });
  247. } catch (ex) {
  248. throw Error('invalid json config file: ' + configPath);
  249. }
  250. }
  251. });
  252. }
  253. function applyDefaultsAndAliases(obj, aliases, defaults) {
  254. Object.keys(defaults).forEach(function (key) {
  255. if (!hasKey(obj, key.split('.'))) {
  256. setKey(obj, key.split('.'), defaults[key]);
  257. (aliases[key] || []).forEach(function (x) {
  258. setKey(obj, x.split('.'), defaults[key]);
  259. });
  260. }
  261. });
  262. }
  263. function hasKey (obj, keys) {
  264. var o = obj;
  265. keys.slice(0,-1).forEach(function (key) {
  266. o = (o[key] || {});
  267. });
  268. var key = keys[keys.length - 1];
  269. return key in o;
  270. }
  271. function setKey (obj, keys, value) {
  272. var o = obj;
  273. keys.slice(0,-1).forEach(function (key) {
  274. if (o[key] === undefined) o[key] = {};
  275. o = o[key];
  276. });
  277. var key = keys[keys.length - 1];
  278. if (typeof value === 'function') {
  279. o[key] = value(o[key]);
  280. }
  281. else if (o[key] === undefined && checkAllAliases(key, flags.arrays)) {
  282. o[key] = Array.isArray(value) ? value : [value];
  283. }
  284. else if (o[key] === undefined || typeof o[key] === 'boolean') {
  285. o[key] = value;
  286. }
  287. else if (Array.isArray(o[key])) {
  288. o[key].push(value);
  289. }
  290. else {
  291. o[key] = [ o[key], value ];
  292. }
  293. }
  294. // extend the aliases list with inferred aliases.
  295. function extendAliases (obj) {
  296. Object.keys(obj || {}).forEach(function(key) {
  297. aliases[key] = [].concat(opts.alias[key] || []);
  298. // For "--option-name", also set argv.optionName
  299. aliases[key].concat(key).forEach(function (x) {
  300. if (/-/.test(x)) {
  301. var c = camelCase(x);
  302. aliases[key].push(c);
  303. newAliases[c] = true;
  304. }
  305. });
  306. aliases[key].forEach(function (x) {
  307. aliases[x] = [key].concat(aliases[key].filter(function (y) {
  308. return x !== y;
  309. }));
  310. });
  311. });
  312. }
  313. // check if a flag is set for any of a key's aliases.
  314. function checkAllAliases (key, flag) {
  315. var isSet = false,
  316. toCheck = [].concat(aliases[key] || [], key);
  317. toCheck.forEach(function(key) {
  318. if (flag[key]) isSet = flag[key];
  319. });
  320. return isSet;
  321. };
  322. // return a default value, given the type of a flag.,
  323. // e.g., key of type 'string' will default to '', rather than 'true'.
  324. function defaultForType (type) {
  325. var def = {
  326. boolean: true,
  327. string: '',
  328. array: []
  329. };
  330. return def[type];
  331. }
  332. // given a flag, enforce a default type.
  333. function guessType (key, flags) {
  334. var type = 'boolean';
  335. if (flags.strings && flags.strings[key]) type = 'string';
  336. else if (flags.arrays && flags.arrays[key]) type = 'array';
  337. return type;
  338. }
  339. function isNumber (x) {
  340. if (typeof x === 'number') return true;
  341. if (/^0x[0-9a-f]+$/i.test(x)) return true;
  342. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  343. }
  344. return {
  345. argv: argv,
  346. aliases: aliases,
  347. newAliases: newAliases
  348. };
  349. };