index.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var Fs = require("fs"),
  2. Package = require("./package.json"),
  3. version = module.exports.version = Package.version,
  4. Path = require("path"),
  5. DIRNAME = __dirname,
  6. read = function (p) {
  7. var content = Fs.readFileSync(p, 'utf-8');
  8. if (content.charAt(content.length - 1) !== '\n') {
  9. throw new Error("file at " + p + " did not end with a newline character");
  10. }
  11. return JSON.parse(content);
  12. },
  13. P = module.exports.peers = (function () {
  14. var pathFromArray = function (A) {
  15. return A.reduce(function (a, b) { return Path.join(a, b); }, '');
  16. };
  17. var isDir = function (fullPath) {
  18. return Fs.lstatSync(fullPath).isDirectory();
  19. };
  20. var getDir = function (A, f) {
  21. var p = pathFromArray(A);
  22. return Fs.readdirSync(p).filter(function (name) {
  23. var fullPath = pathFromArray([p, name]);
  24. return f(fullPath, A, name);
  25. });
  26. };
  27. var find = function (map, path) {
  28. /* safely search for nested values in an object via a path */
  29. return (map && path.reduce(function (p, n) {
  30. return typeof p[n] !== 'undefined' && p[n];
  31. }, map)) || undefined;
  32. }
  33. var peers = {};
  34. var walk = function (A) {
  35. getDir(A, function (fullPath, A, name) {
  36. if (/^\./.test(name)) {
  37. // ignore hidden files
  38. } else if (isDir(fullPath)) {
  39. find(peers, A.slice(1))[name] = {};
  40. walk(A.concat(name));
  41. } else if (/\.k$/.test(name)) {
  42. var obj = find(peers, A.slice(1))[name] = read(fullPath);
  43. // embed the location in the object
  44. obj.location = A.slice(1);
  45. }
  46. });
  47. };
  48. walk([DIRNAME]);
  49. return peers;
  50. }()),
  51. map = module.exports.map = function (f) {
  52. var L = [];
  53. // t/f is the object a credential
  54. var isCred = function (k) {
  55. // creds end in .k
  56. return /\.k/.test(k);
  57. };
  58. var walk = function (o, p, f) {
  59. // walk the tree of objects
  60. if (typeof(o) === 'object') {
  61. // for each key in o, walk the key
  62. Object.keys(o).forEach(function (k) {
  63. var path = p.slice(0).concat(k);
  64. if (isCred(k)) {
  65. L.push(f(o[k], path));
  66. }
  67. walk(o[k], path, f);
  68. });
  69. }
  70. };
  71. walk(P, [], f);
  72. return L;
  73. },
  74. filter = module.exports.filter = function (f) {
  75. var L = [];
  76. map(function (x, p) {
  77. if (f(x,p)) { L.push(x); }
  78. });
  79. return L;
  80. };