DescriptionFileUtils.js 2.4 KB

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