utils.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. "use strict";
  2. const {
  3. resolve
  4. } = require('path');
  5. const {
  6. statSync
  7. } = require('fs');
  8. const normalizePath = require('normalize-path');
  9. const arrify = require('arrify');
  10. /**
  11. * @param {string|string[]} files
  12. * @param {string} context
  13. * @returns {string[]}
  14. */
  15. function parseFiles(files, context) {
  16. return arrify(files).map((
  17. /** @type {string} */
  18. file) => normalizePath(resolve(context, file)));
  19. }
  20. /**
  21. * @param {string|string[]} patterns
  22. * @param {string|string[]} extensions
  23. * @returns {string[]}
  24. */
  25. function parseFoldersToGlobs(patterns, extensions = []) {
  26. const extensionsList = arrify(extensions);
  27. const [prefix, postfix] = extensionsList.length > 1 ? ['{', '}'] : ['', ''];
  28. const extensionsGlob = extensionsList.map((
  29. /** @type {string} */
  30. extension) => extension.replace(/^\./u, '')).join(',');
  31. return arrify(patterns).map((
  32. /** @type {string} */
  33. pattern) => {
  34. try {
  35. // The patterns are absolute because they are prepended with the context.
  36. const stats = statSync(pattern);
  37. /* istanbul ignore else */
  38. if (stats.isDirectory()) {
  39. return pattern.replace(/[/\\]*?$/u, `/**${extensionsGlob ? `/*.${prefix + extensionsGlob + postfix}` : ''}`);
  40. }
  41. } catch (_) {// Return the pattern as is on error.
  42. }
  43. return pattern;
  44. });
  45. }
  46. /**
  47. *
  48. * @param {string} _ key, but unused
  49. * @param {any} value
  50. */
  51. const jsonStringifyReplacerSortKeys = (_, value) => {
  52. /**
  53. * @param {{ [x: string]: any; }} sorted
  54. * @param {string | number} key
  55. */
  56. const insert = (sorted, key) => {
  57. // eslint-disable-next-line no-param-reassign
  58. sorted[key] = value[key];
  59. return sorted;
  60. };
  61. return value instanceof Object && !(value instanceof Array) ? Object.keys(value).sort().reduce(insert, {}) : value;
  62. };
  63. module.exports = {
  64. parseFiles,
  65. parseFoldersToGlobs,
  66. jsonStringifyReplacerSortKeys
  67. };