Skip to content

fix: use git branch --show-current to get branch name #252

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions commit_check/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ def get_branch_name() -> str:
:returns: A `str` describing the current branch name.
"""
try:
commands = ['git', 'rev-parse', '--abbrev-ref', 'HEAD']
branch_name = cmd_output(commands)
# Git 2.22 and above supports `git branch --show-current`
commands = ['git', 'branch', '--show-current']
Comment on lines +25 to +26
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify compatibility and behavioral differences with the new Git command.

The change from git rev-parse --abbrev-ref HEAD to git branch --show-current introduces a Git version dependency (2.22+) and potential behavioral differences:

  1. Git version compatibility: Environments with Git < 2.22 will experience failures
  2. Detached HEAD behavior: git rev-parse --abbrev-ref HEAD returns "HEAD" in detached HEAD state, while git branch --show-current returns an empty string

Please verify the behavioral compatibility:


🏁 Script executed:

#!/bin/bash
# Check Git version compatibility and behavioral differences

echo "=== Git Version Check ==="
git --version

echo "=== Testing normal branch behavior ==="
# Create a test repository and branch
mkdir -p /tmp/git-test && cd /tmp/git-test
git init
git config user.email "test@example.com"
git config user.name "Test User"
echo "test" > test.txt
git add test.txt
git commit -m "Initial commit"
git checkout -b feature-branch

echo "Current branch with old command:"
git rev-parse --abbrev-ref HEAD

echo "Current branch with new command:"
git branch --show-current

echo "=== Testing detached HEAD behavior ==="
# Test detached HEAD state
git checkout HEAD~0 2>/dev/null || echo "No previous commits to detach to"

echo "Detached HEAD with old command:"
git rev-parse --abbrev-ref HEAD

echo "Detached HEAD with new command:"
git branch --show-current

# Clean up
cd / && rm -rf /tmp/git-test

Length of output: 1756


Fix Git command fallback for detached HEAD and enforce Git ≥ 2.22

The new git branch --show-current works as expected on a normal branch but:

  • In a detached HEAD state it returns an empty string (whereas git rev-parse --abbrev-ref HEAD returns "HEAD").
  • It requires Git 2.22 or newer, so older environments will fail outright.

Please update commit_check/util.py to:

  • Check git --version (or otherwise ensure Git ≥ 2.22) before using --show-current, or
  • Fall back to the old command when:
    • The version is older than 2.22, or
    • git branch --show-current yields an empty string

For example:

--- a/commit_check/util.py
+++ b/commit_check/util.py
@@ -23,7 +23,15 @@ def get_branch_name():
     """
-    # Git 2.22 and above supports `git branch --show-current`
-    commands = ['git', 'branch', '--show-current']
+    # Prefer `--show-current` on Git ≥2.22, but fallback for older versions or detached HEAD
+    def git_version_tuple():
+        v = run_cmd(['git', '--version']).strip().split()[-1]
+        return tuple(int(x) for x in v.split('.')[:2])
+
+    version = git_version_tuple()
+    cmd = ['git', 'branch', '--show-current'] if version >= (2, 22) else ['git', 'rev-parse', '--abbrev-ref', 'HEAD']
+    branch = run_cmd(cmd).strip()
+    if not branch:
+        # detached HEAD or empty result → fall back
+        branch = run_cmd(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip()
 
     if not branch:
         raise RuntimeError("Unable to determine Git branch name")
  • Verify parsing of git --version handles major.minor correctly.
  • Ensure existing error handling remains in place.
  • Add tests for detached HEAD to confirm desired behavior.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Git 2.22 and above supports `git branch --show-current`
commands = ['git', 'branch', '--show-current']
"""
# Prefer `--show-current` on Git ≥2.22, but fallback for older versions or detached HEAD
def git_version_tuple():
v = run_cmd(['git', '--version']).strip().split()[-1]
return tuple(int(x) for x in v.split('.')[:2])
version = git_version_tuple()
cmd = ['git', 'branch', '--show-current'] if version >= (2, 22) else ['git', 'rev-parse', '--abbrev-ref', 'HEAD']
branch = run_cmd(cmd).strip()
if not branch:
# detached HEAD or empty result → fall back
branch = run_cmd(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip()
if not branch:
raise RuntimeError("Unable to determine Git branch name")
🤖 Prompt for AI Agents
In commit_check/util.py around lines 25-26, the current use of 'git branch
--show-current' does not handle detached HEAD states and requires Git version
2.22 or newer. Modify the code to first check the installed Git version by
running 'git --version' and parsing the major and minor version numbers. Use
'git branch --show-current' only if the version is 2.22 or higher; otherwise,
fall back to 'git rev-parse --abbrev-ref HEAD'. Additionally, if 'git branch
--show-current' returns an empty string (indicating detached HEAD), also fall
back to the older command. Maintain existing error handling and add tests to
verify behavior in detached HEAD states.

branch_name = cmd_output(commands) or "HEAD"
except CalledProcessError:
branch_name = ''
return branch_name.strip()
Expand Down
4 changes: 2 additions & 2 deletions tests/util_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def test_get_branch_name(self, mocker):
retval = get_branch_name()
assert m_cmd_output.call_count == 1
assert m_cmd_output.call_args[0][0] == [
"git", "rev-parse", "--abbrev-ref", "HEAD"
"git", "branch", "--show-current"
]
assert retval == "fake_branch_name"

Expand All @@ -45,7 +45,7 @@ def test_get_branch_name_with_exception(self, mocker):
retval = get_branch_name()
assert m_cmd_output.call_count == 1
assert m_cmd_output.call_args[0][0] == [
"git", "rev-parse", "--abbrev-ref", "HEAD"
"git", "branch", "--show-current"
]
assert retval == ""

Expand Down
Loading