You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.4 KiB

4 years ago
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const forEachBail = require("./forEachBail");
  7. function loadDescriptionFile(
  8. resolver,
  9. directory,
  10. filenames,
  11. resolveContext,
  12. callback
  13. ) {
  14. (function findDescriptionFile() {
  15. forEachBail(
  16. filenames,
  17. (filename, callback) => {
  18. const descriptionFilePath = resolver.join(directory, filename);
  19. if (resolver.fileSystem.readJson) {
  20. resolver.fileSystem.readJson(descriptionFilePath, (err, content) => {
  21. if (err) {
  22. if (typeof err.code !== "undefined") return callback();
  23. return onJson(err);
  24. }
  25. onJson(null, content);
  26. });
  27. } else {
  28. resolver.fileSystem.readFile(descriptionFilePath, (err, content) => {
  29. if (err) return callback();
  30. let json;
  31. try {
  32. json = JSON.parse(content);
  33. } catch (e) {
  34. onJson(e);
  35. }
  36. onJson(null, json);
  37. });
  38. }
  39. function onJson(err, content) {
  40. if (err) {
  41. if (resolveContext.log)
  42. resolveContext.log(
  43. descriptionFilePath + " (directory description file): " + err
  44. );
  45. else
  46. err.message =
  47. descriptionFilePath + " (directory description file): " + err;
  48. return callback(err);
  49. }
  50. callback(null, {
  51. content: content,
  52. directory: directory,
  53. path: descriptionFilePath
  54. });
  55. }
  56. },
  57. (err, result) => {
  58. if (err) return callback(err);
  59. if (result) {
  60. return callback(null, result);
  61. } else {
  62. directory = cdUp(directory);
  63. if (!directory) {
  64. return callback();
  65. } else {
  66. return findDescriptionFile();
  67. }
  68. }
  69. }
  70. );
  71. })();
  72. }
  73. function getField(content, field) {
  74. if (!content) return undefined;
  75. if (Array.isArray(field)) {
  76. let current = content;
  77. for (let j = 0; j < field.length; j++) {
  78. if (current === null || typeof current !== "object") {
  79. current = null;
  80. break;
  81. }
  82. current = current[field[j]];
  83. }
  84. if (typeof current === "object") {
  85. return current;
  86. }
  87. } else {
  88. if (typeof content[field] === "object") {
  89. return content[field];
  90. }
  91. }
  92. }
  93. function cdUp(directory) {
  94. if (directory === "/") return null;
  95. const i = directory.lastIndexOf("/"),
  96. j = directory.lastIndexOf("\\");
  97. const p = i < 0 ? j : j < 0 ? i : i < j ? j : i;
  98. if (p < 0) return null;
  99. return directory.substr(0, p || 1);
  100. }
  101. exports.loadDescriptionFile = loadDescriptionFile;
  102. exports.getField = getField;
  103. exports.cdUp = cdUp;