index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. 'use strict';
  2. const match = (array, value) =>
  3. array.some(x => (x instanceof RegExp ? x.test(value) : x === value));
  4. const dargs = (object, options) => {
  5. const arguments_ = [];
  6. let extraArguments = [];
  7. let separatedArguments = [];
  8. options = {
  9. useEquals: true,
  10. shortFlag: true,
  11. ...options
  12. };
  13. const makeArguments = (key, value) => {
  14. const prefix = options.shortFlag && key.length === 1 ? '-' : '--';
  15. const theKey = (options.allowCamelCase ?
  16. key :
  17. key.replace(/[A-Z]/g, '-$&').toLowerCase());
  18. key = prefix + theKey;
  19. if (options.useEquals) {
  20. arguments_.push(key + (value ? `=${value}` : ''));
  21. } else {
  22. arguments_.push(key);
  23. if (value) {
  24. arguments_.push(value);
  25. }
  26. }
  27. };
  28. const makeAliasArg = (key, value) => {
  29. arguments_.push(`-${key}`);
  30. if (value) {
  31. arguments_.push(value);
  32. }
  33. };
  34. for (let [key, value] of Object.entries(object)) {
  35. let pushArguments = makeArguments;
  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. pushArguments = 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. separatedArguments = 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. extraArguments = value;
  62. continue;
  63. }
  64. if (value === true) {
  65. pushArguments(key, '');
  66. }
  67. if (value === false && !options.ignoreFalse) {
  68. pushArguments(`no-${key}`);
  69. }
  70. if (typeof value === 'string') {
  71. pushArguments(key, value);
  72. }
  73. if (typeof value === 'number' && !Number.isNaN(value)) {
  74. pushArguments(key, String(value));
  75. }
  76. if (Array.isArray(value)) {
  77. for (const arrayValue of value) {
  78. pushArguments(key, arrayValue);
  79. }
  80. }
  81. }
  82. for (const argument of extraArguments) {
  83. arguments_.push(String(argument));
  84. }
  85. if (separatedArguments.length > 0) {
  86. arguments_.push('--');
  87. }
  88. for (const argument of separatedArguments) {
  89. arguments_.push(String(argument));
  90. }
  91. return arguments_;
  92. };
  93. module.exports = dargs;