path-to-entry.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var cache = require('./mem-cache').cache;
  2. var modes = require('../lib/modes');
  3. module.exports = function (repo) {
  4. repo.pathToEntry = pathToEntry;
  5. };
  6. function pathToEntry(rootTree, path, callback) {
  7. if (!callback) return pathToEntry.bind(this, rootTree, path);
  8. var repo = this;
  9. var mode = modes.tree;
  10. var hash = rootTree;
  11. var parts = path.split("/").filter(Boolean);
  12. var index = 0;
  13. var cached;
  14. loop();
  15. function loop() {
  16. while (index < parts.length) {
  17. if (mode === modes.tree) {
  18. cached = cache[hash];
  19. if (!cached) return repo.loadAs("tree", hash, onLoad);
  20. var entry = cached[parts[index]];
  21. if (!entry) return callback();
  22. mode = entry.mode;
  23. hash = entry.hash;
  24. index++;
  25. continue;
  26. }
  27. if (modes.isFile(mode)) return callback();
  28. return callback(null, {
  29. last: {
  30. mode: mode,
  31. hash: hash,
  32. path: parts.slice(0, index).join("/"),
  33. rest: parts.slice(index).join("/"),
  34. }
  35. });
  36. }
  37. callback(null, {
  38. mode: mode,
  39. hash: hash
  40. });
  41. }
  42. function onLoad(err, value) {
  43. if (!value) return callback(err || new Error("Missing object: " + hash));
  44. cache[hash] = value;
  45. loop();
  46. }
  47. }