Spaces:
Running
Running
File size: 38,960 Bytes
78c921d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 |
import camelCase from 'lodash.camelcase';
/**
* Takes any input and guarantees an array back.
*
* - Converts array-like objects (e.g. `arguments`, `Set`) to a real array.
* - Converts `undefined` to an empty array.
* - Converts any another other, singular value (including `null`, objects and iterables other than `Set`) into an array containing that value.
* - Ignores input which is already an array.
*
* @module array-back
* @example
* > const arrayify = require('array-back')
*
* > arrayify(undefined)
* []
*
* > arrayify(null)
* [ null ]
*
* > arrayify(0)
* [ 0 ]
*
* > arrayify([ 1, 2 ])
* [ 1, 2 ]
*
* > arrayify(new Set([ 1, 2 ]))
* [ 1, 2 ]
*
* > function f(){ return arrayify(arguments); }
* > f(1,2,3)
* [ 1, 2, 3 ]
*/
function isObject (input) {
return typeof input === 'object' && input !== null
}
function isArrayLike (input) {
return isObject(input) && typeof input.length === 'number'
}
/**
* @param {*} - The input value to convert to an array
* @returns {Array}
* @alias module:array-back
*/
function arrayify (input) {
if (Array.isArray(input)) {
return input
}
if (input === undefined) {
return []
}
if (isArrayLike(input) || input instanceof Set) {
return Array.from(input)
}
return [ input ]
}
/**
* Takes any input and guarantees an array back.
*
* - converts array-like objects (e.g. `arguments`) to a real array
* - converts `undefined` to an empty array
* - converts any another other, singular value (including `null`) into an array containing that value
* - ignores input which is already an array
*
* @module array-back
* @example
* > const arrayify = require('array-back')
*
* > arrayify(undefined)
* []
*
* > arrayify(null)
* [ null ]
*
* > arrayify(0)
* [ 0 ]
*
* > arrayify([ 1, 2 ])
* [ 1, 2 ]
*
* > function f(){ return arrayify(arguments); }
* > f(1,2,3)
* [ 1, 2, 3 ]
*/
function isObject$1 (input) {
return typeof input === 'object' && input !== null
}
function isArrayLike$1 (input) {
return isObject$1(input) && typeof input.length === 'number'
}
/**
* @param {*} - the input value to convert to an array
* @returns {Array}
* @alias module:array-back
*/
function arrayify$1 (input) {
if (Array.isArray(input)) {
return input
} else {
if (input === undefined) {
return []
} else if (isArrayLike$1(input)) {
return Array.prototype.slice.call(input)
} else {
return [ input ]
}
}
}
/**
* Find and either replace or remove items in an array.
*
* @module find-replace
* @example
* > const findReplace = require('find-replace')
* > const numbers = [ 1, 2, 3]
*
* > findReplace(numbers, n => n === 2, 'two')
* [ 1, 'two', 3 ]
*
* > findReplace(numbers, n => n === 2, [ 'two', 'zwei' ])
* [ 1, [ 'two', 'zwei' ], 3 ]
*
* > findReplace(numbers, n => n === 2, 'two', 'zwei')
* [ 1, 'two', 'zwei', 3 ]
*
* > findReplace(numbers, n => n === 2) // no replacement, so remove
* [ 1, 3 ]
*/
/**
* @param {array} - The input array
* @param {testFn} - A predicate function which, if returning `true` causes the current item to be operated on.
* @param [replaceWith] {...any} - If specified, found values will be replaced with these values, else removed.
* @returns {array}
* @alias module:find-replace
*/
function findReplace (array, testFn) {
const found = [];
const replaceWiths = arrayify$1(arguments);
replaceWiths.splice(0, 2);
arrayify$1(array).forEach((value, index) => {
let expanded = [];
replaceWiths.forEach(replaceWith => {
if (typeof replaceWith === 'function') {
expanded = expanded.concat(replaceWith(value));
} else {
expanded.push(replaceWith);
}
});
if (testFn(value)) {
found.push({
index: index,
replaceWithValue: expanded
});
}
});
found.reverse().forEach(item => {
const spliceArgs = [ item.index, 1 ].concat(item.replaceWithValue);
array.splice.apply(array, spliceArgs);
});
return array
}
/**
* Some useful tools for working with `process.argv`.
*
* @module argv-tools
* @typicalName argvTools
* @example
* const argvTools = require('argv-tools')
*/
/**
* Regular expressions for matching option formats.
* @static
*/
const re = {
short: /^-([^\d-])$/,
long: /^--(\S+)/,
combinedShort: /^-[^\d-]{2,}$/,
optEquals: /^(--\S+?)=(.*)/
};
/**
* Array subclass encapsulating common operations on `process.argv`.
* @static
*/
class ArgvArray extends Array {
/**
* Clears the array has loads the supplied input.
* @param {string[]} argv - The argv list to load. Defaults to `process.argv`.
*/
load (argv) {
this.clear();
if (argv && argv !== process.argv) {
argv = arrayify(argv);
} else {
/* if no argv supplied, assume we are parsing process.argv */
argv = process.argv.slice(0);
const deleteCount = process.execArgv.some(isExecArg) ? 1 : 2;
argv.splice(0, deleteCount);
}
argv.forEach(arg => this.push(String(arg)));
}
/**
* Clear the array.
*/
clear () {
this.length = 0;
}
/**
* expand ``--option=value` style args.
*/
expandOptionEqualsNotation () {
if (this.some(arg => re.optEquals.test(arg))) {
const expandedArgs = [];
this.forEach(arg => {
const matches = arg.match(re.optEquals);
if (matches) {
expandedArgs.push(matches[1], matches[2]);
} else {
expandedArgs.push(arg);
}
});
this.clear();
this.load(expandedArgs);
}
}
/**
* expand getopt-style combinedShort options.
*/
expandGetoptNotation () {
if (this.hasCombinedShortOptions()) {
findReplace(this, re.combinedShort, expandCombinedShortArg);
}
}
/**
* Returns true if the array contains combined short options (e.g. `-ab`).
* @returns {boolean}
*/
hasCombinedShortOptions () {
return this.some(arg => re.combinedShort.test(arg))
}
static from (argv) {
const result = new this();
result.load(argv);
return result
}
}
/**
* Expand a combined short option.
* @param {string} - the string to expand, e.g. `-ab`
* @returns {string[]}
* @static
*/
function expandCombinedShortArg (arg) {
/* remove initial hypen */
arg = arg.slice(1);
return arg.split('').map(letter => '-' + letter)
}
/**
* Returns true if the supplied arg matches `--option=value` notation.
* @param {string} - the arg to test, e.g. `--one=something`
* @returns {boolean}
* @static
*/
function isOptionEqualsNotation (arg) {
return re.optEquals.test(arg)
}
/**
* Returns true if the supplied arg is in either long (`--one`) or short (`-o`) format.
* @param {string} - the arg to test, e.g. `--one`
* @returns {boolean}
* @static
*/
function isOption (arg) {
return (re.short.test(arg) || re.long.test(arg)) && !re.optEquals.test(arg)
}
/**
* Returns true if the supplied arg is in long (`--one`) format.
* @param {string} - the arg to test, e.g. `--one`
* @returns {boolean}
* @static
*/
function isLongOption (arg) {
return re.long.test(arg) && !isOptionEqualsNotation(arg)
}
/**
* Returns the name from a long, short or `--options=value` arg.
* @param {string} - the arg to inspect, e.g. `--one`
* @returns {string}
* @static
*/
function getOptionName (arg) {
if (re.short.test(arg)) {
return arg.match(re.short)[1]
} else if (isLongOption(arg)) {
return arg.match(re.long)[1]
} else if (isOptionEqualsNotation(arg)) {
return arg.match(re.optEquals)[1].replace(/^--/, '')
} else {
return null
}
}
function isValue (arg) {
return !(isOption(arg) || re.combinedShort.test(arg) || re.optEquals.test(arg))
}
function isExecArg (arg) {
return ['--eval', '-e'].indexOf(arg) > -1 || arg.startsWith('--eval=')
}
/**
* For type-checking Javascript values.
* @module typical
* @typicalname t
* @example
* const t = require('typical')
*/
/**
* Returns true if input is a number
* @param {*} - the input to test
* @returns {boolean}
* @static
* @example
* > t.isNumber(0)
* true
* > t.isNumber(1)
* true
* > t.isNumber(1.1)
* true
* > t.isNumber(0xff)
* true
* > t.isNumber(0644)
* true
* > t.isNumber(6.2e5)
* true
* > t.isNumber(NaN)
* false
* > t.isNumber(Infinity)
* false
*/
function isNumber (n) {
return !isNaN(parseFloat(n)) && isFinite(n)
}
/**
* A plain object is a simple object literal, it is not an instance of a class. Returns true if the input `typeof` is `object` and directly decends from `Object`.
*
* @param {*} - the input to test
* @returns {boolean}
* @static
* @example
* > t.isPlainObject({ something: 'one' })
* true
* > t.isPlainObject(new Date())
* false
* > t.isPlainObject([ 0, 1 ])
* false
* > t.isPlainObject(/test/)
* false
* > t.isPlainObject(1)
* false
* > t.isPlainObject('one')
* false
* > t.isPlainObject(null)
* false
* > t.isPlainObject((function * () {})())
* false
* > t.isPlainObject(function * () {})
* false
*/
function isPlainObject (input) {
return input !== null && typeof input === 'object' && input.constructor === Object
}
/**
* An array-like value has all the properties of an array, but is not an array instance. Examples in the `arguments` object. Returns true if the input value is an object, not null and has a `length` property with a numeric value.
*
* @param {*} - the input to test
* @returns {boolean}
* @static
* @example
* function sum(x, y){
* console.log(t.isArrayLike(arguments))
* // prints `true`
* }
*/
function isArrayLike$2 (input) {
return isObject$2(input) && typeof input.length === 'number'
}
/**
* returns true if the typeof input is `'object'`, but not null!
* @param {*} - the input to test
* @returns {boolean}
* @static
*/
function isObject$2 (input) {
return typeof input === 'object' && input !== null
}
/**
* Returns true if the input value is defined
* @param {*} - the input to test
* @returns {boolean}
* @static
*/
function isDefined (input) {
return typeof input !== 'undefined'
}
/**
* Returns true if the input value is a string
* @param {*} - the input to test
* @returns {boolean}
* @static
*/
function isString (input) {
return typeof input === 'string'
}
/**
* Returns true if the input value is a boolean
* @param {*} - the input to test
* @returns {boolean}
* @static
*/
function isBoolean (input) {
return typeof input === 'boolean'
}
/**
* Returns true if the input value is a function
* @param {*} - the input to test
* @returns {boolean}
* @static
*/
function isFunction (input) {
return typeof input === 'function'
}
/**
* Returns true if the input value is an es2015 `class`.
* @param {*} - the input to test
* @returns {boolean}
* @static
*/
function isClass (input) {
if (isFunction(input)) {
return /^class /.test(Function.prototype.toString.call(input))
} else {
return false
}
}
/**
* Returns true if the input is a string, number, symbol, boolean, null or undefined value.
* @param {*} - the input to test
* @returns {boolean}
* @static
*/
function isPrimitive (input) {
if (input === null) return true
switch (typeof input) {
case 'string':
case 'number':
case 'symbol':
case 'undefined':
case 'boolean':
return true
default:
return false
}
}
/**
* Returns true if the input is a Promise.
* @param {*} - the input to test
* @returns {boolean}
* @static
*/
function isPromise (input) {
if (input) {
const isPromise = isDefined(Promise) && input instanceof Promise;
const isThenable = input.then && typeof input.then === 'function';
return !!(isPromise || isThenable)
} else {
return false
}
}
/**
* Returns true if the input is an iterable (`Map`, `Set`, `Array`, Generator etc.).
* @param {*} - the input to test
* @returns {boolean}
* @static
* @example
* > t.isIterable('string')
* true
* > t.isIterable(new Map())
* true
* > t.isIterable([])
* true
* > t.isIterable((function * () {})())
* true
* > t.isIterable(Promise.resolve())
* false
* > t.isIterable(Promise)
* false
* > t.isIterable(true)
* false
* > t.isIterable({})
* false
* > t.isIterable(0)
* false
* > t.isIterable(1.1)
* false
* > t.isIterable(NaN)
* false
* > t.isIterable(Infinity)
* false
* > t.isIterable(function () {})
* false
* > t.isIterable(Date)
* false
* > t.isIterable()
* false
* > t.isIterable({ then: function () {} })
* false
*/
function isIterable (input) {
if (input === null || !isDefined(input)) {
return false
} else {
return (
typeof input[Symbol.iterator] === 'function' ||
typeof input[Symbol.asyncIterator] === 'function'
)
}
}
var t = {
isNumber,
isString,
isBoolean,
isPlainObject,
isArrayLike: isArrayLike$2,
isObject: isObject$2,
isDefined,
isFunction,
isClass,
isPrimitive,
isPromise,
isIterable
};
/**
* @module option-definition
*/
/**
* Describes a command-line option. Additionally, if generating a usage guide with [command-line-usage](https://github.com/75lb/command-line-usage) you could optionally add `description` and `typeLabel` properties to each definition.
*
* @alias module:option-definition
* @typicalname option
*/
class OptionDefinition {
constructor (definition) {
/**
* The only required definition property is `name`, so the simplest working example is
* ```js
* const optionDefinitions = [
* { name: 'file' },
* { name: 'depth' }
* ]
* ```
*
* Where a `type` property is not specified it will default to `String`.
*
* | # | argv input | commandLineArgs() output |
* | --- | -------------------- | ------------ |
* | 1 | `--file` | `{ file: null }` |
* | 2 | `--file lib.js` | `{ file: 'lib.js' }` |
* | 3 | `--depth 2` | `{ depth: '2' }` |
*
* Unicode option names and aliases are valid, for example:
* ```js
* const optionDefinitions = [
* { name: 'один' },
* { name: '两' },
* { name: 'три', alias: 'т' }
* ]
* ```
* @type {string}
*/
this.name = definition.name;
/**
* The `type` value is a setter function (you receive the output from this), enabling you to be specific about the type and value received.
*
* The most common values used are `String` (the default), `Number` and `Boolean` but you can use a custom function, for example:
*
* ```js
* const fs = require('fs')
*
* class FileDetails {
* constructor (filename) {
* this.filename = filename
* this.exists = fs.existsSync(filename)
* }
* }
*
* const cli = commandLineArgs([
* { name: 'file', type: filename => new FileDetails(filename) },
* { name: 'depth', type: Number }
* ])
* ```
*
* | # | argv input | commandLineArgs() output |
* | --- | ----------------- | ------------ |
* | 1 | `--file asdf.txt` | `{ file: { filename: 'asdf.txt', exists: false } }` |
*
* The `--depth` option expects a `Number`. If no value was set, you will receive `null`.
*
* | # | argv input | commandLineArgs() output |
* | --- | ----------------- | ------------ |
* | 2 | `--depth` | `{ depth: null }` |
* | 3 | `--depth 2` | `{ depth: 2 }` |
*
* @type {function}
* @default String
*/
this.type = definition.type || String;
/**
* getopt-style short option names. Can be any single character (unicode included) except a digit or hyphen.
*
* ```js
* const optionDefinitions = [
* { name: 'hot', alias: 'h', type: Boolean },
* { name: 'discount', alias: 'd', type: Boolean },
* { name: 'courses', alias: 'c' , type: Number }
* ]
* ```
*
* | # | argv input | commandLineArgs() output |
* | --- | ------------ | ------------ |
* | 1 | `-hcd` | `{ hot: true, courses: null, discount: true }` |
* | 2 | `-hdc 3` | `{ hot: true, discount: true, courses: 3 }` |
*
* @type {string}
*/
this.alias = definition.alias;
/**
* Set this flag if the option takes a list of values. You will receive an array of values, each passed through the `type` function (if specified).
*
* ```js
* const optionDefinitions = [
* { name: 'files', type: String, multiple: true }
* ]
* ```
*
* Note, examples 1 and 3 below demonstrate "greedy" parsing which can be disabled by using `lazyMultiple`.
*
* | # | argv input | commandLineArgs() output |
* | --- | ------------ | ------------ |
* | 1 | `--files one.js two.js` | `{ files: [ 'one.js', 'two.js' ] }` |
* | 2 | `--files one.js --files two.js` | `{ files: [ 'one.js', 'two.js' ] }` |
* | 3 | `--files *` | `{ files: [ 'one.js', 'two.js' ] }` |
*
* @type {boolean}
*/
this.multiple = definition.multiple;
/**
* Identical to `multiple` but with greedy parsing disabled.
*
* ```js
* const optionDefinitions = [
* { name: 'files', lazyMultiple: true },
* { name: 'verbose', alias: 'v', type: Boolean, lazyMultiple: true }
* ]
* ```
*
* | # | argv input | commandLineArgs() output |
* | --- | ------------ | ------------ |
* | 1 | `--files one.js --files two.js` | `{ files: [ 'one.js', 'two.js' ] }` |
* | 2 | `-vvv` | `{ verbose: [ true, true, true ] }` |
*
* @type {boolean}
*/
this.lazyMultiple = definition.lazyMultiple;
/**
* Any values unaccounted for by an option definition will be set on the `defaultOption`. This flag is typically set on the most commonly-used option to make for more concise usage (i.e. `$ example *.js` instead of `$ example --files *.js`).
*
* ```js
* const optionDefinitions = [
* { name: 'files', multiple: true, defaultOption: true }
* ]
* ```
*
* | # | argv input | commandLineArgs() output |
* | --- | ------------ | ------------ |
* | 1 | `--files one.js two.js` | `{ files: [ 'one.js', 'two.js' ] }` |
* | 2 | `one.js two.js` | `{ files: [ 'one.js', 'two.js' ] }` |
* | 3 | `*` | `{ files: [ 'one.js', 'two.js' ] }` |
*
* @type {boolean}
*/
this.defaultOption = definition.defaultOption;
/**
* An initial value for the option.
*
* ```js
* const optionDefinitions = [
* { name: 'files', multiple: true, defaultValue: [ 'one.js' ] },
* { name: 'max', type: Number, defaultValue: 3 }
* ]
* ```
*
* | # | argv input | commandLineArgs() output |
* | --- | ------------ | ------------ |
* | 1 | | `{ files: [ 'one.js' ], max: 3 }` |
* | 2 | `--files two.js` | `{ files: [ 'two.js' ], max: 3 }` |
* | 3 | `--max 4` | `{ files: [ 'one.js' ], max: 4 }` |
*
* @type {*}
*/
this.defaultValue = definition.defaultValue;
/**
* When your app has a large amount of options it makes sense to organise them in groups.
*
* There are two automatic groups: `_all` (contains all options) and `_none` (contains options without a `group` specified in their definition).
*
* ```js
* const optionDefinitions = [
* { name: 'verbose', group: 'standard' },
* { name: 'help', group: [ 'standard', 'main' ] },
* { name: 'compress', group: [ 'server', 'main' ] },
* { name: 'static', group: 'server' },
* { name: 'debug' }
* ]
* ```
*
*<table>
* <tr>
* <th>#</th><th>Command Line</th><th>commandLineArgs() output</th>
* </tr>
* <tr>
* <td>1</td><td><code>--verbose</code></td><td><pre><code>
*{
* _all: { verbose: true },
* standard: { verbose: true }
*}
*</code></pre></td>
* </tr>
* <tr>
* <td>2</td><td><code>--debug</code></td><td><pre><code>
*{
* _all: { debug: true },
* _none: { debug: true }
*}
*</code></pre></td>
* </tr>
* <tr>
* <td>3</td><td><code>--verbose --debug --compress</code></td><td><pre><code>
*{
* _all: {
* verbose: true,
* debug: true,
* compress: true
* },
* standard: { verbose: true },
* server: { compress: true },
* main: { compress: true },
* _none: { debug: true }
*}
*</code></pre></td>
* </tr>
* <tr>
* <td>4</td><td><code>--compress</code></td><td><pre><code>
*{
* _all: { compress: true },
* server: { compress: true },
* main: { compress: true }
*}
*</code></pre></td>
* </tr>
*</table>
*
* @type {string|string[]}
*/
this.group = definition.group;
/* pick up any remaining properties */
for (const prop in definition) {
if (!this[prop]) this[prop] = definition[prop];
}
}
isBoolean () {
return this.type === Boolean || (t.isFunction(this.type) && this.type.name === 'Boolean')
}
isMultiple () {
return this.multiple || this.lazyMultiple
}
static create (def) {
const result = new this(def);
return result
}
}
/**
* @module option-definitions
*/
/**
* @alias module:option-definitions
*/
class Definitions extends Array {
/**
* validate option definitions
* @param {boolean} [caseInsensitive=false] - whether arguments will be parsed in a case insensitive manner
* @returns {string}
*/
validate (caseInsensitive) {
const someHaveNoName = this.some(def => !def.name);
if (someHaveNoName) {
halt(
'INVALID_DEFINITIONS',
'Invalid option definitions: the `name` property is required on each definition'
);
}
const someDontHaveFunctionType = this.some(def => def.type && typeof def.type !== 'function');
if (someDontHaveFunctionType) {
halt(
'INVALID_DEFINITIONS',
'Invalid option definitions: the `type` property must be a setter fuction (default: `Boolean`)'
);
}
let invalidOption;
const numericAlias = this.some(def => {
invalidOption = def;
return t.isDefined(def.alias) && t.isNumber(def.alias)
});
if (numericAlias) {
halt(
'INVALID_DEFINITIONS',
'Invalid option definition: to avoid ambiguity an alias cannot be numeric [--' + invalidOption.name + ' alias is -' + invalidOption.alias + ']'
);
}
const multiCharacterAlias = this.some(def => {
invalidOption = def;
return t.isDefined(def.alias) && def.alias.length !== 1
});
if (multiCharacterAlias) {
halt(
'INVALID_DEFINITIONS',
'Invalid option definition: an alias must be a single character'
);
}
const hypenAlias = this.some(def => {
invalidOption = def;
return def.alias === '-'
});
if (hypenAlias) {
halt(
'INVALID_DEFINITIONS',
'Invalid option definition: an alias cannot be "-"'
);
}
const duplicateName = hasDuplicates(this.map(def => caseInsensitive ? def.name.toLowerCase() : def.name));
if (duplicateName) {
halt(
'INVALID_DEFINITIONS',
'Two or more option definitions have the same name'
);
}
const duplicateAlias = hasDuplicates(this.map(def => caseInsensitive && t.isDefined(def.alias) ? def.alias.toLowerCase() : def.alias));
if (duplicateAlias) {
halt(
'INVALID_DEFINITIONS',
'Two or more option definitions have the same alias'
);
}
const duplicateDefaultOption = this.filter(def => def.defaultOption === true).length > 1;
if (duplicateDefaultOption) {
halt(
'INVALID_DEFINITIONS',
'Only one option definition can be the defaultOption'
);
}
const defaultBoolean = this.some(def => {
invalidOption = def;
return def.isBoolean() && def.defaultOption
});
if (defaultBoolean) {
halt(
'INVALID_DEFINITIONS',
`A boolean option ["${invalidOption.name}"] can not also be the defaultOption.`
);
}
}
/**
* Get definition by option arg (e.g. `--one` or `-o`)
* @param {string} [arg] the argument name to get the definition for
* @param {boolean} [caseInsensitive] whether to use case insensitive comparisons when finding the appropriate definition
* @returns {Definition}
*/
get (arg, caseInsensitive) {
if (isOption(arg)) {
if (re.short.test(arg)) {
const shortOptionName = getOptionName(arg);
if (caseInsensitive) {
const lowercaseShortOptionName = shortOptionName.toLowerCase();
return this.find(def => t.isDefined(def.alias) && def.alias.toLowerCase() === lowercaseShortOptionName)
} else {
return this.find(def => def.alias === shortOptionName)
}
} else {
const optionName = getOptionName(arg);
if (caseInsensitive) {
const lowercaseOptionName = optionName.toLowerCase();
return this.find(def => def.name.toLowerCase() === lowercaseOptionName)
} else {
return this.find(def => def.name === optionName)
}
}
} else {
return this.find(def => def.name === arg)
}
}
getDefault () {
return this.find(def => def.defaultOption === true)
}
isGrouped () {
return this.some(def => def.group)
}
whereGrouped () {
return this.filter(containsValidGroup)
}
whereNotGrouped () {
return this.filter(def => !containsValidGroup(def))
}
whereDefaultValueSet () {
return this.filter(def => t.isDefined(def.defaultValue))
}
static from (definitions, caseInsensitive) {
if (definitions instanceof this) return definitions
const result = super.from(arrayify(definitions), def => OptionDefinition.create(def));
result.validate(caseInsensitive);
return result
}
}
function halt (name, message) {
const err = new Error(message);
err.name = name;
throw err
}
function containsValidGroup (def) {
return arrayify(def.group).some(group => group)
}
function hasDuplicates (array) {
const items = {};
for (let i = 0; i < array.length; i++) {
const value = array[i];
if (items[value]) {
return true
} else {
if (t.isDefined(value)) items[value] = true;
}
}
}
/**
* @module argv-parser
*/
/**
* @alias module:argv-parser
*/
class ArgvParser {
/**
* @param {OptionDefinitions} - Definitions array
* @param {object} [options] - Options
* @param {string[]} [options.argv] - Overrides `process.argv`
* @param {boolean} [options.stopAtFirstUnknown] -
* @param {boolean} [options.caseInsensitive] - Arguments will be parsed in a case insensitive manner. Defaults to false.
*/
constructor (definitions, options) {
this.options = Object.assign({}, options);
/**
* Option Definitions
*/
this.definitions = Definitions.from(definitions, this.options.caseInsensitive);
/**
* Argv
*/
this.argv = ArgvArray.from(this.options.argv);
if (this.argv.hasCombinedShortOptions()) {
findReplace(this.argv, re.combinedShort.test.bind(re.combinedShort), arg => {
arg = arg.slice(1);
return arg.split('').map(letter => ({ origArg: `-${arg}`, arg: '-' + letter }))
});
}
}
/**
* Yields one `{ event, name, value, arg, def }` argInfo object for each arg in `process.argv` (or `options.argv`).
*/
* [Symbol.iterator] () {
const definitions = this.definitions;
let def;
let value;
let name;
let event;
let singularDefaultSet = false;
let unknownFound = false;
let origArg;
for (let arg of this.argv) {
if (t.isPlainObject(arg)) {
origArg = arg.origArg;
arg = arg.arg;
}
if (unknownFound && this.options.stopAtFirstUnknown) {
yield { event: 'unknown_value', arg, name: '_unknown', value: undefined };
continue
}
/* handle long or short option */
if (isOption(arg)) {
def = definitions.get(arg, this.options.caseInsensitive);
value = undefined;
if (def) {
value = def.isBoolean() ? true : null;
event = 'set';
} else {
event = 'unknown_option';
}
/* handle --option-value notation */
} else if (isOptionEqualsNotation(arg)) {
const matches = arg.match(re.optEquals);
def = definitions.get(matches[1], this.options.caseInsensitive);
if (def) {
if (def.isBoolean()) {
yield { event: 'unknown_value', arg, name: '_unknown', value, def };
event = 'set';
value = true;
} else {
event = 'set';
value = matches[2];
}
} else {
event = 'unknown_option';
}
/* handle value */
} else if (isValue(arg)) {
if (def) {
value = arg;
event = 'set';
} else {
/* get the defaultOption */
def = this.definitions.getDefault();
if (def && !singularDefaultSet) {
value = arg;
event = 'set';
} else {
event = 'unknown_value';
def = undefined;
}
}
}
name = def ? def.name : '_unknown';
const argInfo = { event, arg, name, value, def };
if (origArg) {
argInfo.subArg = arg;
argInfo.arg = origArg;
}
yield argInfo;
/* unknownFound logic */
if (name === '_unknown') unknownFound = true;
/* singularDefaultSet logic */
if (def && def.defaultOption && !def.isMultiple() && event === 'set') singularDefaultSet = true;
/* reset values once consumed and yielded */
if (def && def.isBoolean()) def = undefined;
/* reset the def if it's a singular which has been set */
if (def && !def.multiple && t.isDefined(value) && value !== null) {
def = undefined;
}
value = undefined;
event = undefined;
name = undefined;
origArg = undefined;
}
}
}
const _value = new WeakMap();
/**
* Encapsulates behaviour (defined by an OptionDefinition) when setting values
*/
class Option {
constructor (definition) {
this.definition = new OptionDefinition(definition);
this.state = null; /* set or default */
this.resetToDefault();
}
get () {
return _value.get(this)
}
set (val) {
this._set(val, 'set');
}
_set (val, state) {
const def = this.definition;
if (def.isMultiple()) {
/* don't add null or undefined to a multiple */
if (val !== null && val !== undefined) {
const arr = this.get();
if (this.state === 'default') arr.length = 0;
arr.push(def.type(val));
this.state = state;
}
} else {
/* throw if already set on a singlar defaultOption */
if (!def.isMultiple() && this.state === 'set') {
const err = new Error(`Singular option already set [${this.definition.name}=${this.get()}]`);
err.name = 'ALREADY_SET';
err.value = val;
err.optionName = def.name;
throw err
} else if (val === null || val === undefined) {
_value.set(this, val);
// /* required to make 'partial: defaultOption with value equal to defaultValue 2' pass */
// if (!(def.defaultOption && !def.isMultiple())) {
// this.state = state
// }
} else {
_value.set(this, def.type(val));
this.state = state;
}
}
}
resetToDefault () {
if (t.isDefined(this.definition.defaultValue)) {
if (this.definition.isMultiple()) {
_value.set(this, arrayify(this.definition.defaultValue).slice());
} else {
_value.set(this, this.definition.defaultValue);
}
} else {
if (this.definition.isMultiple()) {
_value.set(this, []);
} else {
_value.set(this, null);
}
}
this.state = 'default';
}
static create (definition) {
definition = new OptionDefinition(definition);
if (definition.isBoolean()) {
return FlagOption.create(definition)
} else {
return new this(definition)
}
}
}
class FlagOption extends Option {
set (val) {
super.set(true);
}
static create (def) {
return new this(def)
}
}
/**
* A map of { DefinitionNameString: Option }. By default, an Output has an `_unknown` property and any options with defaultValues.
*/
class Output extends Map {
constructor (definitions) {
super();
/**
* @type {OptionDefinitions}
*/
this.definitions = Definitions.from(definitions);
/* by default, an Output has an `_unknown` property and any options with defaultValues */
this.set('_unknown', Option.create({ name: '_unknown', multiple: true }));
for (const def of this.definitions.whereDefaultValueSet()) {
this.set(def.name, Option.create(def));
}
}
toObject (options) {
options = options || {};
const output = {};
for (const item of this) {
const name = options.camelCase && item[0] !== '_unknown' ? camelCase(item[0]) : item[0];
const option = item[1];
if (name === '_unknown' && !option.get().length) continue
output[name] = option.get();
}
if (options.skipUnknown) delete output._unknown;
return output
}
}
class GroupedOutput extends Output {
toObject (options) {
const superOutputNoCamel = super.toObject({ skipUnknown: options.skipUnknown });
const superOutput = super.toObject(options);
const unknown = superOutput._unknown;
delete superOutput._unknown;
const grouped = {
_all: superOutput
};
if (unknown && unknown.length) grouped._unknown = unknown;
this.definitions.whereGrouped().forEach(def => {
const name = options.camelCase ? camelCase(def.name) : def.name;
const outputValue = superOutputNoCamel[def.name];
for (const groupName of arrayify(def.group)) {
grouped[groupName] = grouped[groupName] || {};
if (t.isDefined(outputValue)) {
grouped[groupName][name] = outputValue;
}
}
});
this.definitions.whereNotGrouped().forEach(def => {
const name = options.camelCase ? camelCase(def.name) : def.name;
const outputValue = superOutputNoCamel[def.name];
if (t.isDefined(outputValue)) {
if (!grouped._none) grouped._none = {};
grouped._none[name] = outputValue;
}
});
return grouped
}
}
/**
* @module command-line-args
*/
/**
* Returns an object containing all option values set on the command line. By default it parses the global [`process.argv`](https://nodejs.org/api/process.html#process_process_argv) array.
*
* Parsing is strict by default - an exception is thrown if the user sets a singular option more than once or sets an unknown value or option (one without a valid [definition](https://github.com/75lb/command-line-args/blob/master/doc/option-definition.md)). To be more permissive, enabling [partial](https://github.com/75lb/command-line-args/wiki/Partial-mode-example) or [stopAtFirstUnknown](https://github.com/75lb/command-line-args/wiki/stopAtFirstUnknown) modes will return known options in the usual manner while collecting unknown arguments in a separate `_unknown` property.
*
* @param {Array<OptionDefinition>} - An array of [OptionDefinition](https://github.com/75lb/command-line-args/blob/master/doc/option-definition.md) objects
* @param {object} [options] - Options.
* @param {string[]} [options.argv] - An array of strings which, if present will be parsed instead of `process.argv`.
* @param {boolean} [options.partial] - If `true`, an array of unknown arguments is returned in the `_unknown` property of the output.
* @param {boolean} [options.stopAtFirstUnknown] - If `true`, parsing will stop at the first unknown argument and the remaining arguments returned in `_unknown`. When set, `partial: true` is also implied.
* @param {boolean} [options.camelCase] - If `true`, options with hypenated names (e.g. `move-to`) will be returned in camel-case (e.g. `moveTo`).
* @param {boolean} [options.caseInsensitive] - If `true`, the case of each option name or alias parsed is insignificant. In other words, both `--Verbose` and `--verbose`, `-V` and `-v` would be equivalent. Defaults to false.
* @returns {object}
* @throws `UNKNOWN_OPTION` If `options.partial` is false and the user set an undefined option. The `err.optionName` property contains the arg that specified an unknown option, e.g. `--one`.
* @throws `UNKNOWN_VALUE` If `options.partial` is false and the user set a value unaccounted for by an option definition. The `err.value` property contains the unknown value, e.g. `5`.
* @throws `ALREADY_SET` If a user sets a singular, non-multiple option more than once. The `err.optionName` property contains the option name that has already been set, e.g. `one`.
* @throws `INVALID_DEFINITIONS`
* - If an option definition is missing the required `name` property
* - If an option definition has a `type` value that's not a function
* - If an alias is numeric, a hyphen or a length other than 1
* - If an option definition name was used more than once
* - If an option definition alias was used more than once
* - If more than one option definition has `defaultOption: true`
* - If a `Boolean` option is also set as the `defaultOption`.
* @alias module:command-line-args
*/
function commandLineArgs (optionDefinitions, options) {
options = options || {};
if (options.stopAtFirstUnknown) options.partial = true;
optionDefinitions = Definitions.from(optionDefinitions, options.caseInsensitive);
const parser = new ArgvParser(optionDefinitions, {
argv: options.argv,
stopAtFirstUnknown: options.stopAtFirstUnknown,
caseInsensitive: options.caseInsensitive
});
const OutputClass = optionDefinitions.isGrouped() ? GroupedOutput : Output;
const output = new OutputClass(optionDefinitions);
/* Iterate the parser setting each known value to the output. Optionally, throw on unknowns. */
for (const argInfo of parser) {
const arg = argInfo.subArg || argInfo.arg;
if (!options.partial) {
if (argInfo.event === 'unknown_value') {
const err = new Error(`Unknown value: ${arg}`);
err.name = 'UNKNOWN_VALUE';
err.value = arg;
throw err
} else if (argInfo.event === 'unknown_option') {
const err = new Error(`Unknown option: ${arg}`);
err.name = 'UNKNOWN_OPTION';
err.optionName = arg;
throw err
}
}
let option;
if (output.has(argInfo.name)) {
option = output.get(argInfo.name);
} else {
option = Option.create(argInfo.def);
output.set(argInfo.name, option);
}
if (argInfo.name === '_unknown') {
option.set(arg);
} else {
option.set(argInfo.value);
}
}
return output.toObject({ skipUnknown: !options.partial, camelCase: options.camelCase })
}
export default commandLineArgs;
|