Skip to content

Commit be6a2c3

Browse files
committed
fix: replace git branch -a regex with rev-parse in MergeBaseValidator
The old _find_target_branch method scanned all branches via git branch -a and used a loose regex match, which could cause false positives: a pattern like 'main' could match 'main-old', 'main-staging', etc. depending on the order git branch -a outputs branches. The new approach: 1. Strips common regex anchors (^, $) from the pattern to get a clean name 2. Uses git rev-parse --verify <name> for exact local ref resolution 3. Falls back to git rev-parse --verify origin/<name> for remote tracking This makes require_rebase_target safe to recommend to users.
1 parent ac1e9a9 commit be6a2c3

2 files changed

Lines changed: 101 additions & 11 deletions

File tree

‎commit_check/engine.py‎

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -440,21 +440,46 @@ def validate(self, context: ValidationContext) -> ValidationResult:
440440
return ValidationResult.FAIL
441441

442442
def _find_target_branch(self, pattern: str) -> str | None:
443-
"""Find target branch matching the pattern."""
443+
"""Find target branch by verifying refs directly.
444+
445+
Uses ``git rev-parse --verify`` for exact ref resolution instead of
446+
scanning ``git branch -a`` output with a regex. Strips common regex
447+
anchors (``^``, ``$``) from the pattern to obtain a branch name,
448+
then attempts to verify it as a local ref first, falling back to
449+
the remote tracking ref under ``origin/``.
450+
451+
:param pattern: The raw regex pattern from the rule config (e.g.
452+
``"^main$"`` or ``"main"``).
453+
:returns: The resolved branch name if verified, ``None`` otherwise.
454+
"""
444455
import subprocess
445-
import re
446456

457+
# Strip common regex anchors to obtain a clean branch name
458+
branch_name = pattern.lstrip("^").rstrip("$").strip()
459+
if not branch_name:
460+
return None
461+
462+
# Try local branch first (refs/heads/ avoids ambiguity with tags)
447463
try:
448-
all_branches = subprocess.check_output(
449-
["git", "branch", "-a"], encoding="utf-8"
450-
).splitlines()
464+
subprocess.run(
465+
["git", "rev-parse", "--verify", f"refs/heads/{branch_name}"],
466+
stdout=subprocess.DEVNULL,
467+
stderr=subprocess.DEVNULL,
468+
check=True,
469+
)
470+
return branch_name
471+
except subprocess.CalledProcessError:
472+
pass
451473

452-
for branch in all_branches:
453-
clean_branch = (
454-
branch.strip().replace("* ", "").replace("remotes/origin/", "")
455-
)
456-
if re.match(pattern, clean_branch):
457-
return clean_branch
474+
# Try remote tracking branch under origin/
475+
try:
476+
subprocess.run(
477+
["git", "rev-parse", "--verify", f"refs/remotes/origin/{branch_name}"],
478+
stdout=subprocess.DEVNULL,
479+
stderr=subprocess.DEVNULL,
480+
check=True,
481+
)
482+
return branch_name
458483
except subprocess.CalledProcessError:
459484
pass
460485

‎tests/engine_test.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Tests for commit_check.engine module."""
22

3+
import subprocess
34
import pytest
45
import tempfile
56
import os
@@ -842,6 +843,70 @@ def test_validate_with_merge_base_skip_conditions(self):
842843
result = validator.validate(context)
843844
assert result == ValidationResult.PASS # Skipped
844845

846+
# ------------------------------------------------------------------ #
847+
# _find_target_branch —— unit tests for the new impl
848+
# ------------------------------------------------------------------ #
849+
850+
@patch("subprocess.run")
851+
def test_find_target_branch_local_found(self, mock_run):
852+
"""Local branch exists: returns the stripped branch name."""
853+
mock_run.return_value = subprocess.CompletedProcess(args=[], returncode=0)
854+
validator = MergeBaseValidator(ValidationRule(check="merge_base"))
855+
result = validator._find_target_branch("^main$")
856+
assert result == "main"
857+
# First call: local branch verification
858+
assert mock_run.call_args_list[0][0][0][:4] == [
859+
"git",
860+
"rev-parse",
861+
"--verify",
862+
"refs/heads/main",
863+
]
864+
865+
@patch("subprocess.run")
866+
def test_find_target_branch_local_missing_remote_found(self, mock_run):
867+
"""Local missing, remote tracking exists: returns the stripped branch name."""
868+
mock_run.side_effect = [
869+
subprocess.CalledProcessError(1, []), # local fails
870+
subprocess.CompletedProcess(args=[], returncode=0), # remote succeeds
871+
]
872+
validator = MergeBaseValidator(ValidationRule(check="merge_base"))
873+
result = validator._find_target_branch("develop")
874+
assert result == "develop"
875+
assert mock_run.call_args_list[1][0][0][:5] == [
876+
"git",
877+
"rev-parse",
878+
"--verify",
879+
"refs/remotes/origin/develop",
880+
]
881+
882+
@patch("subprocess.run")
883+
def test_find_target_branch_not_found(self, mock_run):
884+
"""Neither local nor remote exists: returns None."""
885+
mock_run.side_effect = [
886+
subprocess.CalledProcessError(1, []),
887+
subprocess.CalledProcessError(1, []),
888+
]
889+
validator = MergeBaseValidator(ValidationRule(check="merge_base"))
890+
result = validator._find_target_branch("nonexistent-branch")
891+
assert result is None
892+
893+
@patch("subprocess.run")
894+
def test_find_target_branch_empty_pattern(self, mock_run):
895+
"""Empty or anchor-only pattern: returns None without calling subprocess."""
896+
validator = MergeBaseValidator(ValidationRule(check="merge_base"))
897+
result = validator._find_target_branch("")
898+
assert result is None
899+
mock_run.assert_not_called()
900+
901+
@patch("subprocess.run")
902+
def test_find_target_branch_plain_name(self, mock_run):
903+
"""Plain branch name (no regex anchors) works correctly."""
904+
mock_run.return_value = subprocess.CompletedProcess(args=[], returncode=0)
905+
validator = MergeBaseValidator(ValidationRule(check="merge_base"))
906+
result = validator._find_target_branch("main")
907+
assert result == "main"
908+
assert mock_run.call_args_list[0][0][0][3] == "refs/heads/main"
909+
845910

846911
class TestValidationEngine:
847912
@pytest.mark.benchmark

0 commit comments

Comments
 (0)