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

Conversation

shenxianpeng
Copy link
Contributor

@shenxianpeng shenxianpeng commented Jul 9, 2025

closes #249

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability of branch name detection by updating the underlying Git command used.
  • Tests
    • Updated tests to align with the new method for retrieving the current branch name.

@shenxianpeng shenxianpeng added the bug Something isn't working label Jul 9, 2025
Copy link
Contributor

coderabbitai bot commented Jul 9, 2025

Walkthrough

The get_branch_name() function in commit_check/util.py was updated to use the git branch --show-current command instead of git rev-parse --abbrev-ref HEAD for determining the current branch name. Corresponding updates were made in the tests to expect the new command.

Changes

File(s) Change Summary
commit_check/util.py Updated get_branch_name() to use git branch --show-current for branch detection, with a note on Git version requirement and defaulting output to "HEAD" if empty.
tests/util_test.py Modified tests to expect git branch --show-current instead of git rev-parse --abbrev-ref HEAD in both normal and exception cases.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant get_branch_name()
    participant Git

    User->>get_branch_name(): Call function
    get_branch_name()->>Git: Run 'git branch --show-current'
    Git-->>get_branch_name(): Return branch name or error
    get_branch_name()-->>User: Return branch name or None
Loading

Assessment against linked issues

Objective Addressed Explanation
Fix check-branch not working on first commit by updating branch detection logic (#249)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Poem

In the warren of code, a branch name we seek,
With a hop and a skip, we fixed a technique.
No more HEAD confusion, no more git dread,
Now the first commit works, just like bunny said!
🐇🌱


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 89249ec and 88ba1e4.

📒 Files selected for processing (1)
  • commit_check/util.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • commit_check/util.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Analyze (actions)
  • GitHub Check: Analyze (python)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@shenxianpeng shenxianpeng marked this pull request as ready for review July 9, 2025 20:43
@shenxianpeng shenxianpeng requested a review from a team as a code owner July 9, 2025 20:43
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 54738e6 and 89249ec.

📒 Files selected for processing (2)
  • commit_check/util.py (1 hunks)
  • tests/util_test.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Run benchmarks
🔇 Additional comments (3)
commit_check/util.py (1)

16-30: Good documentation and error handling maintained.

The docstring appropriately documents the Git version requirement and provides a link for users to report issues. The error handling logic remains robust with proper exception handling for CalledProcessError.

tests/util_test.py (2)

27-29: Test properly updated for new Git command.

The test assertion correctly expects the new git branch --show-current command. The test structure and expected behavior remain consistent.


47-49: Exception handling test properly updated.

The test for exception handling correctly expects the new Git command while maintaining the same error handling logic and assertions.

Comment on lines +25 to +26
# Git 2.22 and above supports `git branch --show-current`
commands = ['git', 'branch', '--show-current']
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.

Copy link

codspeed-hq bot commented Jul 9, 2025

CodSpeed Performance Report

Merging #252 will not alter performance

Comparing bugfix/update-get-branch-name (88ba1e4) with main (5a2b5e5)

Summary

✅ 93 untouched benchmarks

Copy link

sonarqubecloud bot commented Jul 9, 2025

Copy link

codecov bot commented Jul 9, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (54738e6) to head (88ba1e4).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #252   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            7         7           
  Lines          298       298           
=========================================
  Hits           298       298           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@shenxianpeng shenxianpeng merged commit cf9d245 into main Jul 9, 2025
29 checks passed
@shenxianpeng shenxianpeng deleted the bugfix/update-get-branch-name branch July 9, 2025 20:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] check-branch not working when first commit
1 participant