Skip to content

Commit 4735bee

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 caused false positives (e.g. pattern 'main' matching 'main-old', 'main-staging', etc.). This was the root cause of the CI false positive in PR #19. 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 4735bee

2 files changed

Lines changed: 101 additions & 10 deletions

File tree

‎commit_check/engine.py‎

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -440,21 +440,47 @@ 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
445456
import re
446457

458+
# Strip common regex anchors to obtain a clean branch name
459+
branch_name = re.sub(r"^\^+|\$+$", "", pattern).strip()
460+
if not branch_name:
461+
return None
462+
463+
# Try local branch first
447464
try:
448-
all_branches = subprocess.check_output(
449-
["git", "branch", "-a"], encoding="utf-8"
450-
).splitlines()
465+
subprocess.run(
466+
["git", "rev-parse", "--verify", branch_name],
467+
stdout=subprocess.DEVNULL,
468+
stderr=subprocess.DEVNULL,
469+
check=True,
470+
)
471+
return branch_name
472+
except subprocess.CalledProcessError:
473+
pass
451474

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
475+
# Try remote tracking branch under origin/
476+
try:
477+
subprocess.run(
478+
["git", "rev-parse", "--verify", f"origin/{branch_name}"],
479+
stdout=subprocess.DEVNULL,
480+
stderr=subprocess.DEVNULL,
481+
check=True,
482+
)
483+
return branch_name
458484
except subprocess.CalledProcessError:
459485
pass
460486

‎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+
"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+
"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] == "main"
909+
845910

846911
class TestValidationEngine:
847912
@pytest.mark.benchmark

0 commit comments

Comments
 (0)