index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. const match = (arr, val) => arr.some(x => x instanceof RegExp ? x.test(val) : x === val);
  3. module.exports = (input, opts) => {
  4. const args = [];
  5. let extraArgs = [];
  6. opts = Object.assign({
  7. useEquals: true
  8. }, opts);
  9. const makeArg = (key, val) => {
  10. key = '--' + (opts.allowCamelCase ? key : key.replace(/[A-Z]/g, '-$&').toLowerCase());
  11. if (opts.useEquals) {
  12. args.push(key + (val ? `=${val}` : ''));
  13. } else {
  14. args.push(key);
  15. if (val) {
  16. args.push(val);
  17. }
  18. }
  19. };
  20. const makeAliasArg = (key, val) => {
  21. args.push(`-${key}`);
  22. if (val) {
  23. args.push(val);
  24. }
  25. };
  26. // TODO: use for-of loop and Object.entries when targeting Node.js 6
  27. Object.keys(input).forEach(key => {
  28. const val = input[key];
  29. let pushArg = makeArg;
  30. if (Array.isArray(opts.excludes) && match(opts.excludes, key)) {
  31. return;
  32. }
  33. if (Array.isArray(opts.includes) && !match(opts.includes, key)) {
  34. return;
  35. }
  36. if (typeof opts.aliases === 'object' && opts.aliases[key]) {
  37. key = opts.aliases[key];
  38. pushArg = makeAliasArg;
  39. }
  40. if (key === '_') {
  41. if (!Array.isArray(val)) {
  42. throw new TypeError(`Expected key \`_\` to be Array, got ${typeof val}`);
  43. }
  44. extraArgs = val;
  45. return;
  46. }
  47. if (val === true) {
  48. pushArg(key, '');
  49. }
  50. if (val === false && !opts.ignoreFalse) {
  51. pushArg(`no-${key}`);
  52. }
  53. if (typeof val === 'string') {
  54. pushArg(key, val);
  55. }
  56. if (typeof val === 'number' && !Number.isNaN(val)) {
  57. pushArg(key, String(val));
  58. }
  59. if (Array.isArray(val)) {
  60. val.forEach(arrVal => {
  61. pushArg(key, arrVal);
  62. });
  63. }
  64. });
  65. for (const x of extraArgs) {
  66. args.push(String(x));
  67. }
  68. return args;
  69. };