config-builder.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 files = Object.keys(filesAndDirs.files);
  32. var firstPass = [], secondPass = [];
  33. for (var i = 0; i < files.length; i++) {
  34. var file = files[i];
  35. var basename = path.basename(file);
  36. var specifier = basename.replace(/\.amd\.json$/, "");
  37. if (specifier == "" || specifier[0] == ".") {
  38. continue;
  39. } else if (specifier == "local") {
  40. firstPass.push(file);
  41. } else if (dirExists[specifier]) {
  42. secondPass.push(file);
  43. } else {
  44. callback(new Error("No location for " + file));
  45. return;
  46. }
  47. }
  48. var bothPasses = [].concat(firstPass).concat(secondPass);
  49. if (!bothPasses.length) {
  50. callback(new Error("No .amd.json-type file found"));
  51. return;
  52. }
  53. var result = {};
  54. for (var i = 0; i < bothPasses.length; i++) {
  55. var file = bothPasses[i];
  56. _.merge(result, require(file));
  57. }
  58. callback(null, result);
  59. })
  60. };