Branches

class pygit2.Repository(path: str | None = None, flags: RepositoryOpenFlag = RepositoryOpenFlag.DEFAULT)
branches
lookup_branch(branch_name: str, branch_type: BranchType = BranchType.LOCAL) Branch

Returns the Git reference for the given branch name (local or remote). If branch_type is BranchType.REMOTE, you must include the remote name in the branch name (eg ‘origin/master’).

raw_listall_branches(flag: BranchType = BranchType.LOCAL) list[bytes]

Return a list with all the branches in the repository.

The flag may be:

  • BranchType.LOCAL - return all local branches (set by default)

  • BranchType.REMOTE - return all remote-tracking branches

  • BranchType.ALL - return local branches and remote-tracking branches

Branches inherit from References, and additionally provide specialized accessors for some unique features.

class pygit2.repository.Branches(repository: BaseRepository, flag: BranchType = BranchType.ALL, commit=None)
__contains__(name)
__getitem__(name: str)
__iter__()
create(name: str, commit, force=False)
delete(name: str)
get(key: str)
with_commit(commit)

Example:

>>> # Listing all branches
>>> branches_list = list(repo.branches)
>>> # Local only
>>> local_branches = list(repo.branches.local)
>>> # Remote only
>>> remote_branches = list(repo.branches.remote)

>>> # Get a branch
>>> branch = repo.branches['master']
>>> other_branch = repo.branches['does-not-exist']  # Will raise a KeyError
>>> other_branch = repo.branches.get('does-not-exist')  # Returns None

>>> remote_branch = repo.branches.remote['upstream/feature']

>>> # Create a local branch
>>> new_branch = repo.branches.local.create('new-branch')

>>> And delete it
>>> repo.branches.delete('new-branch')

The Branch type

class pygit2.Branch

Branch.

branch_name

The name of the local or remote branch.

delete()

Delete this branch. It will no longer be valid!

is_checked_out() bool

True if branch is checked out by any repo connected to the current one, False otherwise.

is_head() bool

True if HEAD points at the branch, False otherwise.

raw_branch_name

The name of the local or remote branch (bytes).

remote_name

Find the remote name of a remote-tracking branch.

This will return the name of the remote whose fetch refspec is matching the given branch. E.g. given a branch ‘refs/remotes/test/master’, it will extract the ‘test’ part. If refspecs from multiple remotes match, the function will raise ValueError.

rename(name: str, force: bool = False)

Move/rename an existing local branch reference. The new branch name will be checked for validity. Returns the new branch.

upstream

The branch’s upstream branch or None if this branch does not have an upstream set. Set to None to unset the upstream configuration.

upstream_name

The name of the reference set to be the upstream of this one