Skip to content

Exception on repo().active_branch.name #1479

Description

@grumpyp

Setup

Running on GitPython==3.1.27

MacOS monterey, Python 3.10.5

Reproduce the bug

git checkout <commit> -> leads to a detached HEAD

from pathlib import Path
from git import Repo

def repo() -> 'Repo':
    from git import Repo  # type: ignore
    return Repo(Path(__file__).parent, search_parent_directories=True)

repository = repo()
repository.active_branch.name    

Error log

❯ python3 test.py
Traceback (most recent call last):
  File "/test.py", line 9, in <module>
    repository.active_branch.name
  File "/venv/lib/python3.10/site-packages/git/repo/base.py", line 797, in active_branch
    return self.head.reference
  File "/venv/lib/python3.10/site-packages/git/refs/symbolic.py", line 294, in _get_reference
    raise TypeError("%s is a detached symbolic reference as it points to %r" % (self, sha))
TypeError: HEAD is a detached symbolic reference as it points to '7sfaslkhfuhajkfnjaksdhfc4ede32c'

visual proof

image

Activity

  1. Byron commented on Aug 20, 2022

    @Byron
    Member

    This is intended behaviour, despite not being 'nice'.

    The exception is not just any exception, but it states exactly why there is no active branch:

    TypeError: HEAD is a detached symbolic reference as it points to '7sfaslkhfuhajkfnjaksdhfc4ede32c'
    

    At this point, there is no way to fix this property, but in case you would like to add a new one, like try_active_branch or something that returns None instead, PRs are always welcome.

  2. grumpyp commented on Aug 20, 2022

    @grumpyp
    Author

    Hi @Byron, probably a fix in the documentation would help users as well.

    I was looking for an error in my code for a while until I noticed that it's not my fault.

    Thanks.

  3. Byron commented on Aug 20, 2022

    @Byron
    Member

    Definitely, if exceptions are used to communicate errors they should be documented, and a PR for that is welcome as well.

  4. grumpyp commented on Aug 20, 2022

    @grumpyp
    Author

    @Byron opened a PR here

    For everyone else:

    You can prevent the execution of the Exception by doing something like this:

    if repo().head.is_detached:
       print("foo")
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions