From 8e7e41f6a3a59ee76a3087b6703ded1fa368f950 Mon Sep 17 00:00:00 2001
From: Rhys Arkins <rhys@arkins.net>
Date: Mon, 22 Feb 2021 06:45:36 +0100
Subject: [PATCH] fix: rebase if automerging even if rebaseWhen=conflicted
 (#8796)

---
 lib/workers/branch/reuse.spec.ts | 9 +++++----
 lib/workers/branch/reuse.ts      | 7 +++++--
 2 files changed, 10 insertions(+), 6 deletions(-)

diff --git a/lib/workers/branch/reuse.spec.ts b/lib/workers/branch/reuse.spec.ts
index 29564f113d..0d60da376f 100644
--- a/lib/workers/branch/reuse.spec.ts
+++ b/lib/workers/branch/reuse.spec.ts
@@ -159,14 +159,15 @@ describe(getName(__filename), () => {
       expect(git.isBranchModified).not.toHaveBeenCalled();
     });
 
-    it('returns true if automerge, rebaseWhen=conflicted and stale', async () => {
+    it('returns false if automerge, rebaseWhen=conflicted and stale', async () => {
       config.rebaseWhen = 'conflicted';
       config.automerge = true;
       git.branchExists.mockReturnValueOnce(true);
+      git.isBranchStale.mockResolvedValueOnce(true);
       const res = await shouldReuseExistingBranch(config);
-      expect(res.reuseExistingBranch).toBe(true);
-      expect(git.isBranchStale).not.toHaveBeenCalled();
-      expect(git.isBranchModified).not.toHaveBeenCalled();
+      expect(res.reuseExistingBranch).toBe(false);
+      expect(git.isBranchStale).toHaveBeenCalled();
+      expect(git.isBranchModified).toHaveBeenCalled();
     });
   });
 });
diff --git a/lib/workers/branch/reuse.ts b/lib/workers/branch/reuse.ts
index 965188cfd6..33e7663dd3 100644
--- a/lib/workers/branch/reuse.ts
+++ b/lib/workers/branch/reuse.ts
@@ -48,8 +48,8 @@ export async function shouldReuseExistingBranch(
 
   if (
     config.rebaseWhen === 'behind-base-branch' ||
-    (config.rebaseWhen === 'auto' &&
-      (config.automerge === true || (await platform.getRepoForceRebase())))
+    (config.rebaseWhen !== 'never' && config.automerge === true) ||
+    (config.rebaseWhen === 'auto' && (await platform.getRepoForceRebase()))
   ) {
     if (await isBranchStale(branchName)) {
       logger.debug(`Branch is stale and needs rebasing`);
@@ -61,6 +61,9 @@ export async function shouldReuseExistingBranch(
       }
       return { reuseExistingBranch: false };
     }
+    logger.debug('Branch is up-to-date');
+  } else {
+    logger.debug('Skipping stale branch check');
   }
 
   // Now check if PR is unmergeable. If so then we also rebase
-- 
GitLab