Skip to content

utils

Class info

🛈 DocStrings

Module containing helper functions for local repository operations.

create_branch_model

create_branch_model(branch: Reference, is_default: bool = False) -> Branch

Create Branch model from GitPython branch reference.

Parameters:

Name Type Description Default
branch Reference

GitPython branch reference

required
is_default bool

Whether this is the default branch

False

Returns:

Type Description
Branch

Branch model instance

Source code in src/githarbor/providers/local_provider/utils.py
def create_branch_model(branch: git.Reference, is_default: bool = False) -> Branch:
    """Create Branch model from GitPython branch reference.

    Args:
        branch: GitPython branch reference
        is_default: Whether this is the default branch

    Returns:
        Branch model instance
    """
    from datetime import UTC, datetime

    commit = branch.commit
    return Branch(
        name=branch.name,
        sha=commit.hexsha,
        protected=False,  # Local repos don't have branch protection
        default=is_default,
        last_commit_date=datetime.fromtimestamp(commit.committed_date, UTC),
        last_commit_message=commit.message
        if isinstance(commit.message, str)
        else commit.message.decode(),
        last_commit_author=create_user_model(commit.author),
    )

create_commit_model

create_commit_model(commit: Commit) -> Commit

Create Commit model from GitPython commit.

Parameters:

Name Type Description Default
commit Commit

GitPython commit object

required

Returns:

Type Description
Commit

Commit model instance

Source code in src/githarbor/providers/local_provider/utils.py
def create_commit_model(commit: git.Commit) -> Commit:
    """Create Commit model from GitPython commit.

    Args:
        commit: GitPython commit object

    Returns:
        Commit model instance
    """
    from datetime import UTC, datetime

    msg = commit.message if isinstance(commit.message, str) else commit.message.decode()
    return Commit(
        sha=commit.hexsha,
        message=msg,
        author=create_user_model(commit.author),
        created_at=datetime.fromtimestamp(commit.committed_date, UTC),
        committer=create_user_model(commit.committer),
        stats=get_commit_stats(commit),
        parents=[c.hexsha for c in commit.parents],
        files_changed=[str(p) for p in commit.stats.files],
    )

create_tag_model

create_tag_model(tag: TagReference | TagObject, commit: Commit) -> Tag

Create Tag model from GitPython tag reference or annotated tag object.

Parameters:

Name Type Description Default
tag TagReference | TagObject

GitPython TagReference or TagObject

required
commit Commit

Associated commit

required

Returns:

Type Description
Tag

Tag model instance

Source code in src/githarbor/providers/local_provider/utils.py
def create_tag_model(
    tag: git.TagReference | git.TagObject,
    commit: git.Commit,
) -> Tag:
    """Create Tag model from GitPython tag reference or annotated tag object.

    Args:
        tag: GitPython TagReference or TagObject
        commit: Associated commit

    Returns:
        Tag model instance
    """
    from datetime import UTC, datetime

    import git
    from git.refs import TagReference

    # Get author info if tag is annotated
    author = None
    created_at = None
    message = None

    tag_obj = tag.tag if isinstance(tag, TagReference) else tag
    if isinstance(tag_obj, git.TagObject):
        author = create_user_model(tag_obj.tagger)
        created_at = datetime.fromtimestamp(tag_obj.tagged_date, UTC)
        message = tag_obj.message

    return Tag(
        name=tag.name if isinstance(tag, TagReference) else tag.tag,
        sha=commit.hexsha,
        message=message,
        created_at=created_at,
        author=author,
    )

create_user_model

create_user_model(git_actor: Actor) -> User

Create User model from GitPython actor.

Parameters:

Name Type Description Default
git_actor Actor

GitPython actor object

required

Returns:

Type Description
User

User model instance or None if no actor

Source code in src/githarbor/providers/local_provider/utils.py
def create_user_model(git_actor: git.Actor) -> User:
    """Create User model from GitPython actor.

    Args:
        git_actor: GitPython actor object

    Returns:
        User model instance or None if no actor
    """
    return User(
        username=git_actor.name or "unknown",
        name=git_actor.name,
        email=git_actor.email,
    )

filter_commits

filter_commits(
    commits: Iterator[Commit],
    since: datetime | None = None,
    until: datetime | None = None,
    author: str | None = None,
    path: str | None = None,
    max_results: int | None = None,
) -> list[Commit]

Filter commits based on criteria.

Parameters:

Name Type Description Default
commits Iterator[Commit]

Iterator of commits

required
since datetime | None

Include commits after this date

None
until datetime | None

Include commits before this date

None
author str | None

Filter by author name/email

None
path str | None

Filter by file path

None
max_results int | None

Maximum number of commits to return

None

Returns:

Type Description
list[Commit]

List of filtered commits

Source code in src/githarbor/providers/local_provider/utils.py
def filter_commits(
    commits: Iterator[git.Commit],
    since: datetime | None = None,
    until: datetime | None = None,
    author: str | None = None,
    path: str | None = None,
    max_results: int | None = None,
) -> list[git.Commit]:
    """Filter commits based on criteria.

    Args:
        commits: Iterator of commits
        since: Include commits after this date
        until: Include commits before this date
        author: Filter by author name/email
        path: Filter by file path
        max_results: Maximum number of commits to return

    Returns:
        List of filtered commits
    """
    from datetime import UTC, datetime

    since_utc = since.replace(tzinfo=UTC) if since and since.tzinfo is None else since
    until_utc = until.replace(tzinfo=UTC) if until and until.tzinfo is None else until

    filtered = []
    for commit in commits:
        commit_date = datetime.fromtimestamp(commit.committed_date, UTC)

        if since_utc and commit_date < since_utc:
            continue
        if until_utc and commit_date > until_utc:
            continue
        if author and author not in (commit.author.name, commit.author.email):
            continue
        if path and not any(path in str(f) for f in commit.stats.files):
            continue

        filtered.append(commit)
        if max_results and len(filtered) >= max_results:
            break

    return filtered

get_commit_stats

get_commit_stats(commit: Commit) -> dict[str, int]

Extract statistics from a commit.

Parameters:

Name Type Description Default
commit Commit

GitPython commit object

required

Returns:

Type Description
dict[str, int]

Dictionary with commit statistics

Source code in src/githarbor/providers/local_provider/utils.py
def get_commit_stats(commit: git.Commit) -> dict[str, int]:
    """Extract statistics from a commit.

    Args:
        commit: GitPython commit object

    Returns:
        Dictionary with commit statistics
    """
    return {
        "additions": commit.stats.total["insertions"],
        "deletions": commit.stats.total["deletions"],
        "total": commit.stats.total["lines"],
    }

handle_git_errors

handle_git_errors(error_msg_template: str) -> Callable[[Callable[P, T]], Callable[P, T]]

Decorator to handle Git operation exceptions consistently.

Parameters:

Name Type Description Default
error_msg_template str

Message template with format placeholders

required
Example

@handle_git_errors("Could not fetch branch {branch_name}") def get_branch(self, branch_name: str) -> Branch: ...

Source code in src/githarbor/providers/local_provider/utils.py
def handle_git_errors[T, **P](
    error_msg_template: str,
) -> Callable[[Callable[P, T]], Callable[P, T]]:
    """Decorator to handle Git operation exceptions consistently.

    Args:
        error_msg_template: Message template with format placeholders

    Example:
        @handle_git_errors("Could not fetch branch {branch_name}")
        def get_branch(self, branch_name: str) -> Branch:
            ...
    """
    parser = string.Formatter()
    param_names = {
        field_name
        for _, field_name, _, _ in parser.parse(error_msg_template)
        if field_name and field_name != "error"
    }

    def decorator(func: Callable[P, T]) -> Callable[P, T]:
        @functools.wraps(func)
        def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
            from git.exc import GitError
            from gitdb.exc import ODBError

            sig = inspect.signature(func)
            bound_args = sig.bind(*args, **kwargs)
            bound_args.apply_defaults()
            params = {
                name: bound_args.arguments[name]
                for name in param_names
                if name in bound_args.arguments
            }

            try:
                return func(*args, **kwargs)
            except (GitError, ODBError, IndexError) as e:
                msg = error_msg_template.format(**params, error=str(e))
                raise ResourceNotFoundError(msg) from e

        return wrapper

    return decorator