Skip to content

[Question] How to get default branch (HEAD) from remote repository #1118

@rubenwardy

Description

@rubenwardy

Question

Hi,

I have a service which monitors git repos for changes.

I'd like to be able to find out which branch is the default branch without cloning the repo. The way to do this with Git is to check for the HEAD reference, which you can do with one of the following commands:

git ls-remote --symref origin HEAD
git remote show origin | grep "HEAD branch" | cut -d ":" -f 2

Attempt

Here is my current code:

def get_commit_hash(git_url, ref_name=None):
	assert ref_name != ""

	git_dir = os.path.join(tempfile.gettempdir(), randomString(10))

	repo = git.Repo.init(git_dir)
	origin: git.Remote = repo.create_remote("origin", url=git_url)
	assert origin.exists()
	origin.fetch()

	if ref_name:
		ref: git.Reference = origin.refs[ref_name]
	else:
		# How to get default branch here?
		ref: git.Reference = None

	return ref.commit.hexsha

I've tried:

  • origin.refs.HEAD
  • origin.refs.head
  • origin.head

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