From b1da837da150be277ddfa2b6ea16b6d1e31ce45b Mon Sep 17 00:00:00 2001
From: Rhys Arkins <rhys@arkins.net>
Date: Fri, 9 Feb 2018 13:29:47 +0100
Subject: [PATCH] fix: create Pr if prNotPending hours exceeded for branch
 automerge

---
 lib/workers/pr/index.js       | 13 +++++++++++++
 test/workers/pr/index.spec.js | 11 +++++++++++
 2 files changed, 24 insertions(+)

diff --git a/lib/workers/pr/index.js b/lib/workers/pr/index.js
index e53ac499b6..a1b2482208 100644
--- a/lib/workers/pr/index.js
+++ b/lib/workers/pr/index.js
@@ -30,6 +30,19 @@ async function ensurePr(prConfig) {
     logger.debug(
       `Branch is configured for branch automerge, branchStatus is: ${branchStatus}`
     );
+    if (branchStatus === 'pending' || branchStatus === 'running') {
+      logger.debug('Checking how long this branch has been pending');
+      const lastCommitTime = await platform.getBranchLastCommitTime(branchName);
+      const currentTime = new Date();
+      const millisecondsPerHour = 1000 * 60 * 60;
+      const elapsedHours = Math.round(
+        (currentTime.getTime() - lastCommitTime.getTime()) / millisecondsPerHour
+      );
+      if (elapsedHours >= config.prNotPendingHours) {
+        logger.info('Branch exceeds prNotPending hours - forcing PR creation');
+        config.forcePr = true;
+      }
+    }
     if (config.forcePr || branchStatus === 'failure') {
       logger.debug(`Branch tests failed, so will create PR`);
     } else {
diff --git a/test/workers/pr/index.spec.js b/test/workers/pr/index.spec.js
index 0355c5b85e..8f6c684d32 100644
--- a/test/workers/pr/index.spec.js
+++ b/test/workers/pr/index.spec.js
@@ -300,9 +300,20 @@ describe('workers/pr', () => {
       config.automerge = true;
       config.automergeType = 'branch-push';
       platform.getBranchStatus.mockReturnValueOnce('pending');
+      platform.getBranchLastCommitTime.mockReturnValueOnce(new Date());
       const pr = await prWorker.ensurePr(config);
       expect(pr).toBe(null);
     });
+    it('should not return null if branch automerging taking too long', async () => {
+      config.automerge = true;
+      config.automergeType = 'branch-push';
+      platform.getBranchStatus.mockReturnValueOnce('pending');
+      platform.getBranchLastCommitTime.mockReturnValueOnce(
+        new Date('2018-01-01')
+      );
+      const pr = await prWorker.ensurePr(config);
+      expect(pr).not.toBe(null);
+    });
     it('handles duplicate upgrades', async () => {
       config.upgrades.push(config.upgrades[0]);
       const pr = await prWorker.ensurePr(config);
-- 
GitLab