From e804fda25f2899d7260e317977c5b4ebee8d421c Mon Sep 17 00:00:00 2001
From: Rhys Arkins <rhys@arkins.net>
Date: Sun, 19 Mar 2023 09:21:28 +0100
Subject: [PATCH] refactor(git): cache list of branches per-sha per repo
 (#20839)

---
 lib/util/git/index.ts | 18 +++++++++++-------
 lib/util/git/types.ts |  1 +
 2 files changed, 12 insertions(+), 7 deletions(-)

diff --git a/lib/util/git/index.ts b/lib/util/git/index.ts
index d92e594550..a8593e5622 100644
--- a/lib/util/git/index.ts
+++ b/lib/util/git/index.ts
@@ -242,6 +242,7 @@ export async function initRepo(args: StorageConfig): Promise<void> {
   config.ignoredAuthors = [];
   config.additionalBranches = [];
   config.branchIsModified = {};
+  config.commitBranches = {};
   const { localDir } = GlobalConfig.get();
   git = simpleGit(localDir, simpleGitConfig()).env({
     ...process.env,
@@ -587,13 +588,16 @@ export async function isBranchBehindBase(
   await syncGit();
   try {
     const { currentBranchSha, currentBranch } = config;
-    const branches = await git.branch([
-      '--remotes',
-      '--verbose',
-      '--contains',
-      config.currentBranchSha,
-    ]);
-    isBehind = !branches.all.map(localName).includes(branchName);
+    config.commitBranches[config.currentBranchSha] ??= (
+      await git.branch([
+        '--remotes',
+        '--verbose',
+        '--contains',
+        config.currentBranchSha,
+      ])
+    ).all.map(localName);
+    isBehind =
+      !config.commitBranches[config.currentBranchSha].includes(branchName);
     logger.debug(
       { currentBranch, currentBranchSha },
       `branch.isBehindBase(): ${isBehind}`
diff --git a/lib/util/git/types.ts b/lib/util/git/types.ts
index ef0e18e86c..bacf172951 100644
--- a/lib/util/git/types.ts
+++ b/lib/util/git/types.ts
@@ -25,6 +25,7 @@ export interface LocalConfig extends StorageConfig {
   currentBranchSha: string;
   branchCommits: Record<string, CommitSha>;
   branchIsModified: Record<string, boolean>;
+  commitBranches: Record<string, string[]>;
   ignoredAuthors: string[];
   gitAuthorName?: string | null;
   gitAuthorEmail?: string;
-- 
GitLab