utils.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { join, dirname, readJson } = require("../util/fs");
  7. /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
  8. /**
  9. * @param {string} str maybe required version
  10. * @returns {boolean} true, if it looks like a version
  11. */
  12. exports.isRequiredVersion = str => {
  13. return /^([\d^=v<>~]|[*xX]$)/.test(str);
  14. };
  15. /**
  16. *
  17. * @param {InputFileSystem} fs file system
  18. * @param {string} directory directory to start looking into
  19. * @param {string[]} descriptionFiles possible description filenames
  20. * @param {function((Error | null)=, {data: object, path: string}=): void} callback callback
  21. */
  22. const getDescriptionFile = (fs, directory, descriptionFiles, callback) => {
  23. let i = 0;
  24. const tryLoadCurrent = () => {
  25. if (i >= descriptionFiles.length) {
  26. const parentDirectory = dirname(fs, directory);
  27. if (!parentDirectory || parentDirectory === directory) return callback();
  28. return getDescriptionFile(
  29. fs,
  30. parentDirectory,
  31. descriptionFiles,
  32. callback
  33. );
  34. }
  35. const filePath = join(fs, directory, descriptionFiles[i]);
  36. readJson(fs, filePath, (err, data) => {
  37. if (err) {
  38. if ("code" in err && err.code === "ENOENT") {
  39. i++;
  40. return tryLoadCurrent();
  41. }
  42. return callback(err);
  43. }
  44. if (!data || typeof data !== "object" || Array.isArray(data)) {
  45. return callback(
  46. new Error(`Description file ${filePath} is not an object`)
  47. );
  48. }
  49. callback(null, { data, path: filePath });
  50. });
  51. };
  52. tryLoadCurrent();
  53. };
  54. exports.getDescriptionFile = getDescriptionFile;
  55. exports.getRequiredVersionFromDescriptionFile = (data, packageName) => {
  56. if (
  57. data.optionalDependencies &&
  58. typeof data.optionalDependencies === "object" &&
  59. packageName in data.optionalDependencies
  60. ) {
  61. return data.optionalDependencies[packageName];
  62. }
  63. if (
  64. data.dependencies &&
  65. typeof data.dependencies === "object" &&
  66. packageName in data.dependencies
  67. ) {
  68. return data.dependencies[packageName];
  69. }
  70. if (
  71. data.peerDependencies &&
  72. typeof data.peerDependencies === "object" &&
  73. packageName in data.peerDependencies
  74. ) {
  75. return data.peerDependencies[packageName];
  76. }
  77. if (
  78. data.devDependencies &&
  79. typeof data.devDependencies === "object" &&
  80. packageName in data.devDependencies
  81. ) {
  82. return data.devDependencies[packageName];
  83. }
  84. };