wait-for-merge-commit.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const MAX_WAIT_MS = 10 * 1000; // 10s
  2. const WAIT_PERIOD = 0.5 * 1000; // 0.5s
  3. function wait(interval) {
  4. return new Promise(resolve => {
  5. setTimeout(resolve, interval);
  6. });
  7. }
  8. async function waitForMergeCommit({github, context, core}) {
  9. const pullRequest = context.payload.pull_request;
  10. const pullNumber = pullRequest.number;
  11. let timedOut = false;
  12. let mergeable = false;
  13. let mergeCommitSha = null;
  14. const start = new Date().getTime();
  15. // eslint-disable-next-line no-constant-condition
  16. while (true) {
  17. const response = await github.rest.pulls.get({
  18. ...context.repo,
  19. pull_number: pullNumber,
  20. });
  21. if (response.status === 200 && response.data.mergeable !== null) {
  22. // If mergable is false, that means there is merge conflict
  23. // or the PR cannot be merged so we want to break.
  24. mergeable = response.data.mergeable;
  25. if (mergeable) {
  26. mergeCommitSha = response.data.merge_commit_sha;
  27. }
  28. break;
  29. } else {
  30. core.info('Non 200 response or PR is not mergeable: ', response);
  31. }
  32. await wait(WAIT_PERIOD);
  33. const now = new Date().getTime();
  34. if (now - start > MAX_WAIT_MS) {
  35. timedOut = true;
  36. break;
  37. }
  38. }
  39. core.setOutput('timedOut', timedOut);
  40. core.setOutput('mergeable', mergeable);
  41. core.setOutput('mergeCommitSha', mergeCommitSha);
  42. core.startGroup('Finished waiting for merge commit.');
  43. core.info(`Timed out: ${timedOut}`);
  44. core.info(`Mergeable: ${mergeable}`);
  45. core.info(`Merge commit SHA: ${mergeCommitSha}`);
  46. core.info(`PR head SHA: ${pullRequest.head.sha}`);
  47. core.endGroup();
  48. if (!mergeable) {
  49. // setFailed will cause the action to fail
  50. core.setFailed(`PR #${pullNumber} is not mergeable`);
  51. }
  52. }
  53. module.exports = {
  54. waitForMergeCommit,
  55. };