1
0

config-builder.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. exports.produceConfigObject = function (root, callback) {
  21. eachConfigFile(root, function (err, filesAndDirs) {
  22. if (err) {
  23. callback(err);
  24. return;
  25. }
  26. var dirExists = {};
  27. var dirs = Object.keys(filesAndDirs.dirs);
  28. for (var i = 0; i < dirs.length; i++) {
  29. dirExists[path.basename(dirs[i])] = true;
  30. }
  31. var result;
  32. var files = Object.keys(filesAndDirs.files);
  33. var firstPass = [], secondPass = [];
  34. for (var i = 0; i < files.length; i++) {
  35. var file = files[i];
  36. var basename = path.basename(file);
  37. var specifier = basename.replace(/\.amd\.json$/, "");
  38. if (specifier == "" || specifier[0] == ".") {
  39. continue;
  40. } else if (specifier == "local") {
  41. firstPass.push(file);
  42. } else if (dirExists[specifier]) {
  43. secondPass.push(file);
  44. } else {
  45. callback(new Error("No location for " + file));
  46. return;
  47. }
  48. }
  49. var bothPasses = [].concat(firstPass).concat(secondPass);
  50. for (var i = 0; i < bothPasses.length; i++) {
  51. var file = bothPasses[i];
  52. result = result || {};
  53. _.merge(result, require(file));
  54. }
  55. if (!result) {
  56. callback(new Error("local.amd.json not found"));
  57. } else {
  58. callback(null, result);
  59. }
  60. })
  61. };