5
0
mirror of https://github.com/cwinfo/hyperboria-peers.git synced 2024-11-09 15:30:26 +00:00
hyperboria-peers/index.js

92 lines
2.8 KiB
JavaScript
Raw Normal View History

var Fs = require("fs"),
2016-10-25 05:58:05 +00:00
Package = require("./package.json"),
version = module.exports.version = Package.version,
Path = require("path"),
2016-06-19 08:13:09 +00:00
DIRNAME = __dirname,
read = function (p) {
2016-06-12 09:52:46 +00:00
var content = Fs.readFileSync(p, 'utf-8');
if (content.charAt(content.length - 1) !== '\n') {
throw new Error("file at " + p + " did not end with a newline character");
}
return JSON.parse(content);
},
P = module.exports.peers = (function () {
var pathFromArray = function (A) {
return A.reduce(function (a, b) { return Path.join(a, b); }, '');
};
var isDir = function (fullPath) {
return Fs.lstatSync(fullPath).isDirectory();
};
var getDir = function (A, f) {
var p = pathFromArray(A);
return Fs.readdirSync(p).filter(function (name) {
var fullPath = pathFromArray([p, name]);
return f(fullPath, A, name);
});
};
var find = function (map, path) {
/* safely search for nested values in an object via a path */
return (map && path.reduce(function (p, n) {
return typeof p[n] !== 'undefined' && p[n];
}, map)) || undefined;
}
var peers = {};
var walk = function (A) {
getDir(A, function (fullPath, A, name) {
if (/^\./.test(name)) {
// ignore hidden files
} else if (isDir(fullPath)) {
find(peers, A.slice(1))[name] = {};
walk(A.concat(name));
} else if (/\.k$/.test(name)) {
var obj = find(peers, A.slice(1))[name] = read(fullPath);
// embed the location in the object
obj.location = A.slice(1);
}
});
};
2016-06-19 08:13:09 +00:00
walk([DIRNAME]);
return peers;
}()),
2016-06-12 09:52:46 +00:00
map = module.exports.map = function (f) {
var L = [];
// t/f is the object a credential
var isCred = function (k) {
// creds end in .k
return /\.k/.test(k);
};
var walk = function (o, p, f) {
// walk the tree of objects
if (typeof(o) === 'object') {
// for each key in o, walk the key
Object.keys(o).forEach(function (k) {
var path = p.slice(0).concat(k);
2016-06-12 09:52:46 +00:00
if (isCred(k)) {
L.push(f(o[k], path));
}
walk(o[k], path, f);
});
}
};
walk(P, [], f);
return L;
},
filter = module.exports.filter = function (f) {
var L = [];
map(function (x, p) {
if (f(x,p)) { L.push(x); }
});
return L;
};