DescriptionFileUtils.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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(resolver, directory, filenames, resolveContext, callback) {
  8. (function findDescriptionFile() {
  9. forEachBail(filenames, (filename, callback) => {
  10. const descriptionFilePath = resolver.join(directory, filename);
  11. if(resolver.fileSystem.readJson) {
  12. resolver.fileSystem.readJson(descriptionFilePath, (err, content) => {
  13. if(err) {
  14. if(typeof err.code !== "undefined") return callback();
  15. return onJson(err);
  16. }
  17. onJson(null, content);
  18. });
  19. } else {
  20. resolver.fileSystem.readFile(descriptionFilePath, (err, content) => {
  21. if(err) return callback();
  22. let json;
  23. try {
  24. json = JSON.parse(content);
  25. } catch(e) {
  26. onJson(e);
  27. }
  28. onJson(null, json);
  29. });
  30. }
  31. function onJson(err, content) {
  32. if(err) {
  33. if(resolveContext.log)
  34. resolveContext.log(descriptionFilePath + " (directory description file): " + err);
  35. else
  36. err.message = descriptionFilePath + " (directory description file): " + err;
  37. return callback(err);
  38. }
  39. callback(null, {
  40. content: content,
  41. directory: directory,
  42. path: descriptionFilePath
  43. });
  44. }
  45. }, (err, result) => {
  46. if(err) return callback(err);
  47. if(result) {
  48. return callback(null, result);
  49. } else {
  50. directory = cdUp(directory);
  51. if(!directory) {
  52. return callback();
  53. } else {
  54. return findDescriptionFile();
  55. }
  56. }
  57. });
  58. }());
  59. }
  60. function getField(content, field) {
  61. if(!content) return undefined;
  62. if(Array.isArray(field)) {
  63. let current = content;
  64. for(let j = 0; j < field.length; j++) {
  65. if(current === null || typeof current !== "object") {
  66. current = null;
  67. break;
  68. }
  69. current = current[field[j]];
  70. }
  71. if(typeof current === "object") {
  72. return current;
  73. }
  74. } else {
  75. if(typeof content[field] === "object") {
  76. return content[field];
  77. }
  78. }
  79. }
  80. function cdUp(directory) {
  81. if(directory === "/") return null;
  82. const i = directory.lastIndexOf("/"),
  83. j = directory.lastIndexOf("\\");
  84. const p = i < 0 ? j : j < 0 ? i : i < j ? j : i;
  85. if(p < 0) return null;
  86. return directory.substr(0, p || 1);
  87. }
  88. exports.loadDescriptionFile = loadDescriptionFile;
  89. exports.getField = getField;
  90. exports.cdUp = cdUp;