From 44f8f328d11d5b285287c88f6d15d5fe7ff795e8 Mon Sep 17 00:00:00 2001
From: Matt Lavin <matt.lavin@gmail.com>
Date: Thu, 9 May 2019 00:43:54 -0400
Subject: [PATCH] fix(bitbucket): Close PRs when deleting branches (#3646)

---
 lib/platform/bitbucket/index.js                    | 12 +++++++++++-
 .../bitbucket/__snapshots__/index.spec.js.snap     | 10 ++++++++++
 test/platform/bitbucket/index.spec.js              | 14 ++++++++++++++
 3 files changed, 35 insertions(+), 1 deletion(-)

diff --git a/lib/platform/bitbucket/index.js b/lib/platform/bitbucket/index.js
index 829693bc54..ce23b84ff0 100644
--- a/lib/platform/bitbucket/index.js
+++ b/lib/platform/bitbucket/index.js
@@ -177,7 +177,17 @@ function getFile(filePath, branchName) {
   return config.storage.getFile(filePath, branchName);
 }
 
-function deleteBranch(branchName) {
+async function deleteBranch(branchName, closePr) {
+  if (closePr) {
+    const pr = await findPr(branchName, null, 'open');
+    if (pr) {
+      await api.post(
+        `/2.0/repositories/${config.repository}/pullrequests/${
+          pr.number
+        }/decline`
+      );
+    }
+  }
   return config.storage.deleteBranch(branchName);
 }
 
diff --git a/test/platform/bitbucket/__snapshots__/index.spec.js.snap b/test/platform/bitbucket/__snapshots__/index.spec.js.snap
index 0c21d78b57..21421c6e37 100644
--- a/test/platform/bitbucket/__snapshots__/index.spec.js.snap
+++ b/test/platform/bitbucket/__snapshots__/index.spec.js.snap
@@ -46,6 +46,16 @@ Array [
 ]
 `;
 
+exports[`platform/bitbucket deleteBranch() should handle closing PRs when none exist 1`] = `Array []`;
+
+exports[`platform/bitbucket deleteBranch() should handle closing PRs when some exist 1`] = `
+Array [
+  Array [
+    "/2.0/repositories/some/repo/pullrequests/5/decline",
+  ],
+]
+`;
+
 exports[`platform/bitbucket ensureIssue() creates new issue 1`] = `
 Array [
   Array [
diff --git a/test/platform/bitbucket/index.spec.js b/test/platform/bitbucket/index.spec.js
index 5f8bde363e..18f6067538 100644
--- a/test/platform/bitbucket/index.spec.js
+++ b/test/platform/bitbucket/index.spec.js
@@ -204,6 +204,20 @@ describe('platform/bitbucket', () => {
         await bitbucket.deleteBranch();
       });
     });
+    it('should handle closing PRs when none exist', async () => {
+      await initRepo();
+      await mocked(async () => {
+        await bitbucket.deleteBranch('some-branch', true);
+        expect(api.post.mock.calls).toMatchSnapshot();
+      });
+    });
+    it('should handle closing PRs when some exist', async () => {
+      await initRepo();
+      await mocked(async () => {
+        await bitbucket.deleteBranch('branch', true);
+        expect(api.post.mock.calls).toMatchSnapshot();
+      });
+    });
   });
 
   describe('mergeBranch()', () => {
-- 
GitLab