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 <gavinmak@google.com>
Commit-Queue: Gavin Mak <gavinmak@google.com>
Reviewed-by: Brian Gan <brgan@google.com>
This commit is contained in:
Gavin Mak authored and gerrit-scoped@luci-project-accounts.iam.gserviceaccount.com committed 2026-09-02 17:46:23 -07:00
1 parent ba8ddf396c
commit 0ea57e2eed
2 files changed
+22 -10

No files matched your search

+5 -3
View File
@@ -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'}"
+17 -7
View File
@@ -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: