find-common.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. function oneCall(fn) {
  2. var done = false;
  3. return function () {
  4. if (done) return;
  5. done = true;
  6. return fn.apply(this, arguments);
  7. };
  8. }
  9. module.exports = findCommon;
  10. function findCommon(repo, a, b, callback) {
  11. callback = oneCall(callback);
  12. var ahead = 0, behind = 0;
  13. var aStream, bStream;
  14. var aCommit, bCommit;
  15. if (a === b) return callback(null, ahead, behind);
  16. repo.logWalk(a, onAStream);
  17. repo.logWalk(b, onBStream);
  18. function onAStream(err, stream) {
  19. if (err) return callback(err);
  20. aStream = stream;
  21. aStream.read(onA);
  22. }
  23. function onBStream(err, stream) {
  24. if (err) return callback(err);
  25. bStream = stream;
  26. bStream.read(onB);
  27. }
  28. function onA(err, commit) {
  29. if (!commit) return callback(err || new Error("No common commit"));
  30. aCommit = commit;
  31. if (bCommit) compare();
  32. }
  33. function onB(err, commit) {
  34. if (!commit) return callback(err || new Error("No common commit"));
  35. bCommit = commit;
  36. if (aCommit) compare();
  37. }
  38. function compare() {
  39. if (aCommit.hash === bCommit.hash) return callback(null, ahead, behind);
  40. if (aCommit.author.date.seconds > bCommit.author.date.seconds) {
  41. ahead++;
  42. aStream.read(onA);
  43. }
  44. else {
  45. behind++;
  46. bStream.read(onB);
  47. }
  48. }
  49. }