From 4e6c7e2ef5f532b58351fddc67daffed28531dec Mon Sep 17 00:00:00 2001
From: Rhys Arkins <rhys@keylocation.sg>
Date: Sun, 3 Sep 2017 10:02:48 +0200
Subject: [PATCH] feat: delete branch if PR creation fails (#774)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This will help “self heal” in cases where the branch becomes invalid and PR creation continually fails.

Closes #773
---
 lib/workers/pr/index.js       |  9 ++++++++-
 test/workers/pr/index.spec.js | 12 ++++++++++++
 2 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/lib/workers/pr/index.js b/lib/workers/pr/index.js
index b1dc63afd5..2a09224292 100644
--- a/lib/workers/pr/index.js
+++ b/lib/workers/pr/index.js
@@ -151,7 +151,14 @@ async function ensurePr(prConfig) {
       return existingPr;
     }
     logger.debug({ prTitle }, `Creating PR for branch ${branchName}`);
-    const pr = await config.api.createPr(branchName, prTitle, prBody);
+    let pr;
+    try {
+      pr = await config.api.createPr(branchName, prTitle, prBody);
+    } catch (err) {
+      logger.warn({ err }, `Failed to create PR - deleting branch`);
+      await config.api.deleteBranch(branchName);
+      return null;
+    }
     if (config.labels.length > 0) {
       await config.api.addLabels(pr.number, config.labels);
     }
diff --git a/test/workers/pr/index.spec.js b/test/workers/pr/index.spec.js
index 07a0b758ec..0d6b9671fe 100644
--- a/test/workers/pr/index.spec.js
+++ b/test/workers/pr/index.spec.js
@@ -137,6 +137,18 @@ describe('workers/pr', () => {
       const pr = await prWorker.ensurePr(config);
       expect(pr).toMatchObject({ displayNumber: 'New Pull Request' });
     });
+    it('should delete branch and return null if creating PR fails', async () => {
+      config.api.getBranchStatus = jest.fn(() => 'success');
+      config.api.getBranchPr = jest.fn();
+      config.api.createPr = jest.fn(() => {
+        throw new Error('failed to create PR');
+      });
+      config.api.deleteBranch = jest.fn();
+      config.prCreation = 'status-success';
+      const pr = await prWorker.ensurePr(config);
+      expect(config.api.deleteBranch.mock.calls).toHaveLength(1);
+      expect(pr).toBe(null);
+    });
     it('should return null if waiting for not pending', async () => {
       config.api.getBranchStatus = jest.fn(() => 'pending');
       config.api.getBranchLastCommitTime = jest.fn(() => new Date());
-- 
GitLab