Skip to content

clabe.repository

GitRepositoryMetadata

Bases: BaseModel

A serializable snapshot of a Git repository's provenance state.

Paths are relative to the current working directory when the snapshot is made, or absolute when the checkout is on another drive.

GitRepository

GitRepository(*args: Any, **kwargs: Any)

Bases: Repo

A wrapper around the git.Repo class that provides additional methods for managing Git repositories and their submodules.

Extends the functionality of GitPython's Repo class with additional utilities for repository management, submodule handling, and cleanup operations.

Methods:

Name Description
reset_repo

Resets the repository to the last committed state

clean_repo

Cleans the repository by removing untracked files

is_dirty_with_submodules

Checks if the repository or submodules are dirty

uncommitted_changes

Returns a list of uncommitted changes

init_and_update_submodules

Initializes and updates all submodules recursively

submodules_sync

Synchronizes submodules

full_reset

Performs a full reset of the repository and submodules

try_prompt_full_reset

Prompts the user to perform a full reset

Initializes the GitRepository instance and validates the presence of Git.

Parameters:

Name Type Description Default
*args Any

Arguments passed to the parent Repo class

()
**kwargs Any

Keyword arguments passed to the parent Repo class

{}
Example
# Initialize with current directory
repo = GitRepository()

# Initialize with specific path
repo = GitRepository(path="/path/to/repo")
Source code in src/clabe/repository.py
def __init__(self, *args: Any, **kwargs: Any) -> None:
    """
    Initializes the GitRepository instance and validates the presence of Git.

    Args:
        *args: Arguments passed to the parent Repo class
        **kwargs: Keyword arguments passed to the parent Repo class

    Example:
        ```python
        # Initialize with current directory
        repo = GitRepository()

        # Initialize with specific path
        repo = GitRepository(path="/path/to/repo")
        ```
    """
    super().__init__(*args, **kwargs)
    self._validate_git()

reset_repo

reset_repo() -> Self

Resets the repository to the last committed state.

Performs a hard reset to discard all uncommitted changes in the working directory and staging area, reverting to the last commit.

Returns:

Name Type Description
Self Self

The current instance for method chaining.

Example
repo = GitRepository("/path/to/repo")
repo.reset_repo()  # Discards all uncommitted changes
Source code in src/clabe/repository.py
def reset_repo(self) -> Self:
    """
    Resets the repository to the last committed state.

    Performs a hard reset to discard all uncommitted changes in the working directory
    and staging area, reverting to the last commit.

    Returns:
        Self: The current instance for method chaining.

    Example:
        ```python
        repo = GitRepository("/path/to/repo")
        repo.reset_repo()  # Discards all uncommitted changes
        ```
    """
    self.git.reset("--hard")
    return self

clean_repo

clean_repo() -> Self

Cleans the repository by removing untracked files and directories.

Removes all untracked files and directories from the working tree that are not ignored by .gitignore rules.

Returns:

Name Type Description
Self Self

The current instance for method chaining.

Example
repo = GitRepository("/path/to/repo")
repo.clean_repo()  # Removes all untracked files and directories
Source code in src/clabe/repository.py
def clean_repo(self) -> Self:
    """
    Cleans the repository by removing untracked files and directories.

    Removes all untracked files and directories from the working tree that are
    not ignored by .gitignore rules.

    Returns:
        Self: The current instance for method chaining.

    Example:
        ```python
        repo = GitRepository("/path/to/repo")
        repo.clean_repo()  # Removes all untracked files and directories
        ```
    """
    self.git.clean("-fd")
    return self

is_dirty_with_submodules

is_dirty_with_submodules() -> bool

Checks if the repository or any of its submodules is dirty.

A repository is considered dirty if it has uncommitted changes, including untracked files. This method also checks all submodules.

Returns:

Name Type Description
bool bool

True if the repository or any submodules have uncommitted changes.

Example
repo = GitRepository("/path/to/repo")
if repo.is_dirty_with_submodules():
    print("Repository or submodules have uncommitted changes")
Source code in src/clabe/repository.py
def is_dirty_with_submodules(self) -> bool:
    """
    Checks if the repository or any of its submodules is dirty.

    A repository is considered dirty if it has uncommitted changes, including
    untracked files. This method also checks all submodules.

    Returns:
        bool: True if the repository or any submodules have uncommitted changes.

    Example:
        ```python
        repo = GitRepository("/path/to/repo")
        if repo.is_dirty_with_submodules():
            print("Repository or submodules have uncommitted changes")
        ```
    """
    _is_dirty_repo = self.is_dirty(untracked_files=True)
    if _is_dirty_repo:
        return True
    return any(submodule.repo.is_dirty(untracked_files=True) for submodule in self.submodules)

get_metadata

get_metadata() -> GitRepositoryMetadata

Return a serializable snapshot of this repository and its submodules.

The snapshot includes every declared submodule recursively when its parent is initialized. An uninitialized submodule records its configured URL and gitlink commit SHA with is_initialized=False. branch is None when a repository is in a detached-HEAD state, and tag is None when HEAD has no exact tag. describe identifies the nearest reachable tag and the number of commits since it.

Returns:

Name Type Description
GitRepositoryMetadata GitRepositoryMetadata

Repository provenance information suitable for inclusion in experiment or data metadata.

Source code in src/clabe/repository.py
def get_metadata(self) -> GitRepositoryMetadata:
    """Return a serializable snapshot of this repository and its submodules.

    The snapshot includes every declared submodule recursively when its parent
    is initialized. An uninitialized submodule records its configured URL and
    gitlink commit SHA with ``is_initialized=False``. ``branch`` is ``None``
    when a repository is in a detached-HEAD state, and ``tag`` is ``None``
    when HEAD has no exact tag. ``describe`` identifies the nearest reachable
    tag and the number of commits since it.

    Returns:
        GitRepositoryMetadata: Repository provenance information suitable for
            inclusion in experiment or data metadata.
    """
    return self._get_metadata(self)

uncommitted_changes

uncommitted_changes() -> list[str]

Retrieves a list of unstaged and untracked files in the repository and its submodules.

Combines modified files, staged changes, and untracked files from both the main repository and all submodules.

Returns:

Type Description
list[str]

List[str]: A list of file paths with uncommitted changes.

Example
repo = GitRepository("/path/to/repo")
changes = repo.uncommitted_changes()
if changes:
    print(f"Uncommitted changes found: {changes}")
Source code in src/clabe/repository.py
def uncommitted_changes(self) -> list[str]:
    """
    Retrieves a list of unstaged and untracked files in the repository and its submodules.

    Combines modified files, staged changes, and untracked files from both the main
    repository and all submodules.

    Returns:
        List[str]: A list of file paths with uncommitted changes.

    Example:
        ```python
        repo = GitRepository("/path/to/repo")
        changes = repo.uncommitted_changes()
        if changes:
            print(f"Uncommitted changes found: {changes}")
        ```
    """
    untracked_files = self.untracked_files
    changes = self._get_changes(self)
    for submodule in self.submodules:
        changes.extend(self._get_changes(submodule.repo))
        untracked_files.extend(submodule.repo.untracked_files)
    return list(set(changes + untracked_files))

init_and_update_submodules

init_and_update_submodules(force: bool = True) -> Self

Initializes and updates all submodules recursively.

Executes git submodule update --init --recursive to ensure all submodules, including nested ones, are initialized and updated to the commit specified in the parent repository. This is idempotent - if submodules are already up to date, no changes are made.

Parameters:

Name Type Description Default
force bool

If True, passes --force flag to checkout even if local changes would be overwritten in submodules. Defaults to True.

True

Returns:

Name Type Description
Self Self

The current instance for method chaining.

Raises:

Type Description
GitCommandError

If the git command fails (e.g., network error, invalid submodule configuration).

Example
repo = GitRepository("/path/to/repo")
repo.init_and_update_submodules()  # Init and update all submodules
repo.init_and_update_submodules(force=False)  # Without forcing checkout
Source code in src/clabe/repository.py
def init_and_update_submodules(self, force: bool = True) -> Self:
    """
    Initializes and updates all submodules recursively.

    Executes `git submodule update --init --recursive` to ensure all submodules,
    including nested ones, are initialized and updated to the commit specified
    in the parent repository. This is idempotent - if submodules are already
    up to date, no changes are made.

    Args:
        force: If True, passes --force flag to checkout even if local changes
            would be overwritten in submodules. Defaults to True.

    Returns:
        Self: The current instance for method chaining.

    Raises:
        git.GitCommandError: If the git command fails (e.g., network error,
            invalid submodule configuration).

    Example:
        ```python
        repo = GitRepository("/path/to/repo")
        repo.init_and_update_submodules()  # Init and update all submodules
        repo.init_and_update_submodules(force=False)  # Without forcing checkout
        ```
    """
    if not self.submodules:
        logger.debug("No submodules found in repository: %s", self.working_dir)
        return self

    args = ["update", "--init", "--recursive"]
    if force:
        args.append("--force")
    self.git.submodule(*args)
    return self

submodules_sync

submodules_sync() -> Self

Synchronizes submodule URLs with the parent repository.

Updates the submodule URLs to match those defined in the parent repository's .gitmodules file.

Returns:

Name Type Description
Self Self

The current instance for method chaining.

Example
repo = GitRepository("/path/to/repo")
repo.submodules_sync()  # Synchronizes submodule URLs
Source code in src/clabe/repository.py
def submodules_sync(self) -> Self:
    """
    Synchronizes submodule URLs with the parent repository.

    Updates the submodule URLs to match those defined in the parent repository's
    .gitmodules file.

    Returns:
        Self: The current instance for method chaining.

    Example:
        ```python
        repo = GitRepository("/path/to/repo")
        repo.submodules_sync()  # Synchronizes submodule URLs
        ```
    """
    self.git.submodule("sync", "--recursive")
    return self

full_reset

full_reset() -> Self

Performs a full reset of the repository and its submodules.

Executes a complete cleanup including resetting the repository, synchronizing submodules, updating them, and cleaning untracked files. Also recursively resets all submodules.

Returns:

Name Type Description
Self Self

The current instance for method chaining.

Example
repo = GitRepository("/path/to/repo")
repo.full_reset()  # Complete cleanup of repo and submodules
Source code in src/clabe/repository.py
def full_reset(self) -> Self:
    """
    Performs a full reset of the repository and its submodules.

    Executes a complete cleanup including resetting the repository, synchronizing
    submodules, updating them, and cleaning untracked files. Also recursively
    resets all submodules.

    Returns:
        Self: The current instance for method chaining.

    Example:
        ```python
        repo = GitRepository("/path/to/repo")
        repo.full_reset()  # Complete cleanup of repo and submodules
        ```
    """
    self.reset_repo().submodules_sync().init_and_update_submodules().clean_repo()
    _ = [GitRepository(str(sub.abspath)).full_reset() for sub in self.submodules]
    return self

try_prompt_full_reset

try_prompt_full_reset(force_reset: bool = False) -> Self

Prompts the user to perform a full reset if the repository is dirty.

Checks if the repository has uncommitted changes and either asks the user (through the active clabe.ui session) or automatically performs a full reset based on force_reset.

Parameters:

Name Type Description Default
force_reset bool

Whether to skip the prompt and force a reset

False

Returns:

Name Type Description
Self Self

The current instance for method chaining.

Example
repo = GitRepository("/path/to/repo")
repo.try_prompt_full_reset()  # Asks the user if dirty
repo.try_prompt_full_reset(force_reset=True)  # Forces reset
Source code in src/clabe/repository.py
def try_prompt_full_reset(self, force_reset: bool = False) -> Self:
    """
    Prompts the user to perform a full reset if the repository is dirty.

    Checks if the repository has uncommitted changes and either asks the user (through the active
    [`clabe.ui`][clabe.ui] session) or automatically performs a full reset based on ``force_reset``.

    Args:
        force_reset: Whether to skip the prompt and force a reset

    Returns:
        Self: The current instance for method chaining.

    Example:
        ```python
        repo = GitRepository("/path/to/repo")
        repo.try_prompt_full_reset()  # Asks the user if dirty
        repo.try_prompt_full_reset(force_reset=True)  # Forces reset
        ```
    """
    if force_reset:
        self.full_reset()
        return self
    if self.is_dirty_with_submodules():
        logger.info("Repository is dirty! %s", self.working_dir)
        logger.info("Uncommitted files: %s", self.uncommitted_changes())
        if not force_reset:
            is_reset = ui.confirm("Do you want to reset the repository?")
        else:
            is_reset = True
        if is_reset:
            logger.info("Full reset of repository and submodules: %s", self.working_dir)
            self.full_reset()
    return self