From 0ea57e2eedbeae43e03c50b3aca4b890238d639f Mon Sep 17 00:00:00 2001 From: Gavin Mak Date: Tue, 25 Aug 2026 09:02:22 -0700 Subject: [PATCH] project: gate the default-branch query by Git version GIT_DEFAULT_BRANCH support was added to git var in Git 2.35. Skip that guaranteed failure on older supported clients and read init.defaultBranch directly, reducing their fallback from two processes to one. Bug: 553599402 Change-Id: I079e9e6057b56afa41b685317a106fc9cdbad8a2 Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/623907 Tested-by: Gavin Mak Commit-Queue: Gavin Mak Reviewed-by: Brian Gan --- project.py | 8 +++++--- tests/test_project.py | 24 +++++++++++++++++------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/project.py b/project.py index 26f5982da..75f91abbc 100644 --- a/project.py +++ b/project.py @@ -4884,9 +4884,11 @@ def _DefaultBranchFallback() -> str: ) return p.stdout.strip() if p.Wait() == 0 else "" - branch = _git(["var", "GIT_DEFAULT_BRANCH"]) or _git( - ["config", "--get", "init.defaultBranch"] - ) + branch = "" + if git_require((2, 35, 0)): + branch = _git(["var", "GIT_DEFAULT_BRANCH"]) + if not branch: + branch = _git(["config", "--get", "init.defaultBranch"]) return f"refs/heads/{branch or 'master'}" diff --git a/tests/test_project.py b/tests/test_project.py index 3be80c5c2..c2db279dc 100644 --- a/tests/test_project.py +++ b/tests/test_project.py @@ -1708,26 +1708,34 @@ _CONFIG_CMD: List[str] = ["config", "--get", "init.defaultBranch"] @pytest.mark.parametrize( - "responses, expected_ref, expected_calls", + "supports_git_var, responses, expected_ref, expected_calls", ( # git >= 2.35 answers `git var GIT_DEFAULT_BRANCH`. - ({"var": (0, "jellybean\n")}, "refs/heads/jellybean", [_VAR_CMD]), + ( + True, + {"var": (0, "jellybean\n")}, + "refs/heads/jellybean", + [_VAR_CMD], + ), # Older git: `git var` fails, so read init.defaultBranch instead. ( - {"var": (1, ""), "config": (0, "custom\n")}, + False, + {"config": (0, "custom\n")}, "refs/heads/custom", - [_VAR_CMD, _CONFIG_CMD], + [_CONFIG_CMD], ), # Nothing configured anywhere: git's historical built-in default. ( - {"var": (1, ""), "config": (1, "")}, + False, + {"config": (1, "")}, "refs/heads/master", - [_VAR_CMD, _CONFIG_CMD], + [_CONFIG_CMD], ), ), ids=("git_var", "old_git_reads_config", "unconfigured_defaults_to_master"), ) def test_default_branch_fallback( + supports_git_var: bool, responses: Dict[str, Tuple[int, str]], expected_ref: str, expected_calls: List[List[str]], @@ -1750,7 +1758,9 @@ def test_default_branch_fallback( # value) and after (so the mocked value doesn't leak to other tests). project._DefaultBranchFallback.cache_clear() try: - with mock.patch.object(project, "GitCommand", FakeGitCommand): + with mock.patch.object( + project, "git_require", return_value=supports_git_var + ), mock.patch.object(project, "GitCommand", FakeGitCommand): assert project._DefaultBranchFallback() == expected_ref assert seen == expected_calls finally: