is-behind-upstream.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. const log = require("npmlog");
  3. const childProcess = require("@lerna/child-process");
  4. module.exports.isBehindUpstream = isBehindUpstream;
  5. /**
  6. * @param {string} gitRemote
  7. * @param {string} branch
  8. * @param {import("@lerna/child-process").ExecOpts} opts
  9. */
  10. function isBehindUpstream(gitRemote, branch, opts) {
  11. log.silly("isBehindUpstream");
  12. updateRemote(opts);
  13. const remoteBranch = `${gitRemote}/${branch}`;
  14. const [behind, ahead] = countLeftRight(`${remoteBranch}...${branch}`, opts);
  15. log.silly(
  16. "isBehindUpstream",
  17. `${branch} is behind ${remoteBranch} by ${behind} commit(s) and ahead by ${ahead}`
  18. );
  19. return Boolean(behind);
  20. }
  21. /**
  22. * @param {import("@lerna/command").ExecOpts} opts
  23. */
  24. function updateRemote(opts) {
  25. // git fetch, but for everything
  26. childProcess.execSync("git", ["remote", "update"], opts);
  27. }
  28. /**
  29. * @param {string} symmetricDifference
  30. * @param {import("@lerna/command").ExecOpts} opts
  31. */
  32. function countLeftRight(symmetricDifference, opts) {
  33. const stdout = childProcess.execSync(
  34. "git",
  35. ["rev-list", "--left-right", "--count", symmetricDifference],
  36. opts
  37. );
  38. return stdout.split("\t").map((val) => parseInt(val, 10));
  39. }