Skip to content

Reference for ultralytics/utils/git.py

Note

This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/utils/git.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!


ultralytics.utils.git.GitRepo

GitRepo(path: Path = Path(__file__).resolve())

Represent a local Git repository and expose branch, commit, and remote metadata.

This class discovers the repository root by searching for a .git entry from the given path upward, resolves the actual .git directory (including worktrees), and reads Git metadata directly from on-disk files. It does not invoke the git binary and therefore works in restricted environments. All metadata properties are resolved lazily and cached; construct a new instance to refresh state.

Attributes:

Name Type Description
root Path | None

Repository root directory containing the .git entry; None if not in a repository.

gitdir Path | None

Resolved .git directory path; handles worktrees; None if unresolved.

head str | None

Raw contents of HEAD; a SHA for detached HEAD or "ref: " for branch heads.

is_repo bool

Whether the provided path resides inside a Git repository.

branch str | None

Current branch name when HEAD points to a branch; None for detached HEAD or non-repo.

commit str | None

Current commit SHA for HEAD; None if not determinable.

origin str | None

URL of the "origin" remote as read from gitdir/config; None if unset or unavailable.

Examples:

Initialize from the current working directory and read metadata

>>> from pathlib import Path
>>> repo = GitRepo(Path.cwd())
>>> repo.is_repo
True
>>> repo.branch, repo.commit[:7], repo.origin
('main', '1a2b3c4', 'https://example.com/owner/repo.git')
Notes
  • Resolves metadata by reading files: HEAD, packed-refs, and config; no subprocess calls are used.
  • Caches properties on first access using cached_property; recreate the object to reflect repository changes.

Parameters:

Name Type Description Default
path Path

File or directory path used as the starting point to locate the repository root.

resolve()
Source code in ultralytics/utils/git.py
41
42
43
44
45
46
47
48
49
def __init__(self, path: Path = Path(__file__).resolve()):
    """
    Initialize a Git repository context by discovering the repository root from a starting path.

    Args:
        path (Path, optional): File or directory path used as the starting point to locate the repository root.
    """
    self.root = self._find_root(path)
    self.gitdir = self._gitdir(self.root) if self.root else None

branch cached property

branch: str | None

Current branch or None.

commit cached property

commit: str | None

Current commit SHA or None.

head cached property

head: str | None

HEAD file contents.

is_repo property

is_repo: bool

True if inside a git repo.

origin cached property

origin: str | None

Origin URL or None.





📅 Created 0 days ago ✏️ Updated 0 days ago