index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. 'use strict';
  2. const match = (array, value) =>
  3. array.some(x => (x instanceof RegExp ? x.test(value) : x === value));
  4. const dargs = (input, options) => {
  5. const args = [];
  6. let extraArgs = [];
  7. let separatedArgs = [];
  8. options = Object.assign({
  9. useEquals: true
  10. }, options);
  11. const makeArg = (key, value) => {
  12. key =
  13. '--' +
  14. (options.allowCamelCase ?
  15. key :
  16. key.replace(/[A-Z]/g, '-$&').toLowerCase());
  17. if (options.useEquals) {
  18. args.push(key + (value ? `=${value}` : ''));
  19. } else {
  20. args.push(key);
  21. if (value) {
  22. args.push(value);
  23. }
  24. }
  25. };
  26. const makeAliasArg = (key, value) => {
  27. args.push(`-${key}`);
  28. if (value) {
  29. args.push(value);
  30. }
  31. };
  32. // TODO: Use Object.entries() when targeting Node.js 8
  33. for (let key of Object.keys(input)) {
  34. const value = input[key];
  35. let pushArg = makeArg;
  36. if (Array.isArray(options.excludes) && match(options.excludes, key)) {
  37. continue;
  38. }
  39. if (Array.isArray(options.includes) && !match(options.includes, key)) {
  40. continue;
  41. }
  42. if (typeof options.aliases === 'object' && options.aliases[key]) {
  43. key = options.aliases[key];
  44. pushArg = makeAliasArg;
  45. }
  46. if (key === '--') {
  47. if (!Array.isArray(value)) {
  48. throw new TypeError(
  49. `Expected key \`--\` to be Array, got ${typeof value}`
  50. );
  51. }
  52. separatedArgs = value;
  53. continue;
  54. }
  55. if (key === '_') {
  56. if (!Array.isArray(value)) {
  57. throw new TypeError(
  58. `Expected key \`_\` to be Array, got ${typeof value}`
  59. );
  60. }
  61. extraArgs = value;
  62. continue;
  63. }
  64. if (value === true) {
  65. pushArg(key, '');
  66. }
  67. if (value === false && !options.ignoreFalse) {
  68. pushArg(`no-${key}`);
  69. }
  70. if (typeof value === 'string') {
  71. pushArg(key, value);
  72. }
  73. if (typeof value === 'number' && !Number.isNaN(value)) {
  74. pushArg(key, String(value));
  75. }
  76. if (Array.isArray(value)) {
  77. for (const arrayValue of value) {
  78. pushArg(key, arrayValue);
  79. }
  80. }
  81. }
  82. for (const x of extraArgs) {
  83. args.push(String(x));
  84. }
  85. if (separatedArgs.length > 0) {
  86. args.push('--');
  87. }
  88. for (const x of separatedArgs) {
  89. args.push(String(x));
  90. }
  91. return args;
  92. };
  93. module.exports = dargs;