GitPython: Error in `repo.active_branch` if branch is in DETACHED HEAD state

Error in repo.active_branch if branch is in DETACHED HEAD state:

{TypeError}HEAD is a detached symbolic reference as it points to '0fa1f2a7d9dd9fb63fa775d2d97ad72f56f1d819'

The branch is None in def _get_ref_info(cls, repo, ref_path): because of

# its a commit
        if repo.re_hexsha_only.match(tokens[0]):
            return (tokens[0], None)

def active_branch(self) could return HEAD-{commit-hash} instead like:

    try:
        active_branch = repo.active_branch
    except:
        active_branch = 'DETACHED_' + repo.head.object.hexsha

About this issue

  • Original URL
  • State: open
  • Created 9 years ago
  • Reactions: 24
  • Comments: 16 (8 by maintainers)

Commits related to this issue

Most upvoted comments

3.5 years later and this is still a problem 😦

3 years later and this is still a problem 😦

This comment might help.

I read the last comment, but it was 4 years ago, any new update on this?

Thank you for this follow up, @Byron

My suggestion for the best solution would be this: In order to keep backward compatibility (exception that is) adding a new argument that allows for what OP suggested:

git.Repo(search_parent_directories=True, active_branch_flexible=False)

and then:

if active_branch_flexible:
    try:
        active_branch = repo.active_branch
    except:
        active_branch = 'DETACHED_' + repo.head.object.hexsha

I haven’t looked at the code, so this is totally a pseudocode based on what I saw in this issue.

Of course, if that suggestion resonates, you’d know better what to call it, active_branch_flexible is just a quick idea 😉

Thank you.