From 47305e6031b7001ea5f27f562f3a352988e8b261 Mon Sep 17 00:00:00 2001
From: Rhys Arkins <rhys@arkins.net>
Date: Sat, 2 Feb 2019 03:02:12 +0100
Subject: [PATCH] fix(github): catch 404 when committing files

---
 lib/platform/github/storage.js | 43 +++++++++++++++-------------------
 1 file changed, 19 insertions(+), 24 deletions(-)

diff --git a/lib/platform/github/storage.js b/lib/platform/github/storage.js
index d0825b5b79..d0dbe8ad9c 100644
--- a/lib/platform/github/storage.js
+++ b/lib/platform/github/storage.js
@@ -275,23 +275,23 @@ class Storage {
       logger.debug(
         `commitFilesToBranch('${branchName}', files, message, '${parentBranch})'`
       );
-      delete branchFiles[branchName];
-      const parentCommit = await getBranchCommit(parentBranch);
-      const parentTree = await getCommitTree(parentCommit);
-      const fileBlobs = [];
-      // Create blobs
-      for (const file of files) {
-        const blob = await createBlob(file.contents);
-        fileBlobs.push({
-          name: file.name,
-          blob,
-        });
-      }
-      // Create tree
-      const tree = await createTree(parentTree, fileBlobs);
-      const commit = await createCommit(parentCommit, tree, message);
-      const isBranchExisting = await branchExists(branchName);
       try {
+        delete branchFiles[branchName];
+        const parentCommit = await getBranchCommit(parentBranch);
+        const parentTree = await getCommitTree(parentCommit);
+        const fileBlobs = [];
+        // Create blobs
+        for (const file of files) {
+          const blob = await createBlob(file.contents);
+          fileBlobs.push({
+            name: file.name,
+            blob,
+          });
+        }
+        // Create tree
+        const tree = await createTree(parentTree, fileBlobs);
+        const commit = await createCommit(parentCommit, tree, message);
+        const isBranchExisting = await branchExists(branchName);
         if (isBranchExisting) {
           await updateBranch(branchName, commit);
           logger.debug({ branch: branchName }, 'Branch updated');
@@ -305,14 +305,9 @@ class Storage {
         }
         return 'created';
       } catch (err) /* istanbul ignore next */ {
-        logger.debug({
-          files: files.filter(
-            file =>
-              !file.name.endsWith('package-lock.json') &&
-              !file.name.endsWith('npm-shrinkwrap.json') &&
-              !file.name.endsWith('yarn.lock')
-          ),
-        });
+        if (err.statusCode === 404) {
+          throw new Error('repository-changed');
+        }
         throw err;
       }
     }
-- 
GitLab