Reset git_cache mirror when HEAD points to master

master->main branch migration left the cache in some builders to have its HEAD still pointing to refs/heads/master. This causes bot_update to fail. If in this state, delete the cache and force bootstrap.

Bug: 1418866
Change-Id: Id716a013833d459ee37306d27b369099faf846ab
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/4310522
Commit-Queue: Aravind Vasudevan <aravindvasudev@google.com>
Reviewed-by: Josip Sokcevic <sokcevic@chromium.org>
Reviewed-by: Fumitoshi Ukai <ukai@google.com>
diff --git a/git_cache.py b/git_cache.py
index a402fc2..a990c1f 100755
--- a/git_cache.py
+++ b/git_cache.py
@@ -390,6 +390,29 @@
       self.print('%s has %d .pack files, re-bootstrapping if >%d or ==0' %
                 (self.mirror_path, len(pack_files), GC_AUTOPACKLIMIT))
 
+    # master->main branch migration left the cache in some builders to have its
+    # HEAD still pointing to refs/heads/master. This causes bot_update to fail.
+    # If in this state, delete the cache and force bootstrap.
+    try:
+      with open(os.path.join(self.mirror_path, 'HEAD')) as f:
+        head_ref = f.read()
+    except FileNotFoundError:
+      head_ref = ''
+
+    # Check only when HEAD points to master.
+    if 'master' in head_ref:
+      # Some repos could still have master so verify if the ref exists first.
+      show_ref_master_cmd = subprocess.run(
+          [Mirror.git_exe, 'show-ref', '--verify', 'refs/heads/master'],
+          cwd=self.mirror_path)
+
+      if show_ref_master_cmd.returncode != 0:
+        # Remove mirror
+        gclient_utils.rmtree(self.mirror_path)
+
+        # force bootstrap
+        force = True
+
     should_bootstrap = (force or
                         not self.exists() or
                         len(pack_files) > GC_AUTOPACKLIMIT or