config-builder.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. var path = require('path'),
  2. _ = require('lodash'),
  3. findit = require('findit'),
  4. fs = require('fs');
  5. function eachConfigFile(root, callback) {
  6. var result = {files: [], dirs: []};
  7. var find = findit(root, {followSymlinks: true});
  8. find.on('file', function (file, stat) {
  9. if (file.match(/\.amd\.json$/)) {
  10. result.files[file] = stat;
  11. }
  12. });
  13. find.on('directory', function (dir, stat, stop) {
  14. result.dirs[dir] = stat;
  15. });
  16. find.on('end', function () {
  17. callback(null, result);
  18. });
  19. }
  20. function transformShimDeps(json) {
  21. var shimmedList = json.shim && Object.keys(json.shim);
  22. if (!shimmedList) return;
  23. for (var i = 0; i < shimmedList.length; i++) {
  24. var shim = json.shim[shimmedList[i]];
  25. if (Array.isArray(shim)) {
  26. json.shim[shimmedList[i]] = {deps: shim};
  27. }
  28. }
  29. }
  30. exports.produceConfigObject = function (root, callback) {
  31. eachConfigFile(root, function (err, filesAndDirs) {
  32. if (err) {
  33. callback(err);
  34. return;
  35. }
  36. var dirExists = {};
  37. var dirs = Object.keys(filesAndDirs.dirs);
  38. for (var i = 0; i < dirs.length; i++) {
  39. dirExists[path.basename(dirs[i])] = true;
  40. }
  41. var files = Object.keys(filesAndDirs.files);
  42. var firstPass = [], secondPass = [];
  43. for (var i = 0; i < files.length; i++) {
  44. var file = files[i];
  45. var basename = path.basename(file);
  46. var specifier = basename.replace(/\.amd\.json$/, "");
  47. if (specifier == "" || specifier[0] == ".") {
  48. continue;
  49. } else if (specifier == "local") {
  50. firstPass.push(file);
  51. } else if (dirExists[specifier]) {
  52. secondPass.push(file);
  53. } else {
  54. callback(new Error("No location for " + file));
  55. return;
  56. }
  57. }
  58. var bothPasses = [].concat(firstPass).concat(secondPass);
  59. if (!bothPasses.length) {
  60. callback(new Error("No .amd.json-type file found"));
  61. return;
  62. }
  63. var result = {};
  64. for (var i = 0; i < bothPasses.length; i++) {
  65. var json = require(bothPasses[i]);
  66. transformShimDeps(json);
  67. _.merge(result, json, function(a, b) {
  68. return _.isArray(a) ? a.concat(b) : undefined;
  69. });
  70. }
  71. callback(null, result);
  72. })
  73. };