123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185 |
- "use strict";
- import { die } from './die.js';
- export function getOpt(argObj, config) {
- const optKeys = Object.keys(argObj);
- let argv = process.argv.slice(2)
- let opts = {};
- let notOpts = [];
-
- let bundle = true;
- bundle = config.bundle;
-
- let arg;
- while ((arg = argv.shift())) {
-
- if (!arg.startsWith('-')) {
- notOpts.push(arg);
- continue;
- }
-
-
- if (arg == '--') break;
- let argOpt;
- let argKey;
- if (arg.startsWith('--')) {
- argOpt = arg.slice(2);
- argKey = optKeys.find(k => k == argOpt);
- if (!argKey)
- die(`Unrecognized option: ${arg}`);
- } else {
- argOpt = arg.slice(1);
- const opt = argOpt[0];
- const key = optKeys.find(k => argObj[k].short == opt);
- if (!key)
- die(`Unrecognized option '${argOpt}'`);
- if (Object.keys(opts).includes(key))
- die(`Option '-${opt}' already specified`)
-
- argKey = key;
-
- if (argOpt.length > 1) {
-
-
- if (bundle) {
- let asOpt = '-';
- if (argObj[argKey].type == 'value') asOpt = '';
- argv.unshift(`${asOpt}${argOpt.slice(1)}`);
- } else
- die(`Unrecognized option: '${arg}'`);
- }
- }
-
- const type = argObj[argKey].type;
-
- switch (type) {
- case 'value':
- let val = argv.shift();
-
- const validateFunc = argObj[argKey].validate;
- const convertFunc = argObj[argKey].convert;
- if (convertFunc) val = convertFunc(val)
- if (validateFunc) {
- if (!validateFunc(val)) throw '';
- }
- opts[argKey] = val;
- break;
- case 'flag':
- opts[argKey] = true;
- break;
- default:
- die(`Invalid ${type} for key ${argKey}`);
- }
- }
- if (notOpts.length >= 1)
- process.argv = process.argv.slice(0, 2).concat(notOpts);
-
- Object.keys(argObj).forEach(k => {
- if (!opts[k]) {
- if (argObj[k].default)
- opts[k] = argObj[k].default;
- else opts[k] = null;
- }
- });
- return opts;
- }
|