Skip to content

providers

Class info

Re-exported classes

Class Module Description
AioGitHubRepository githarbor.providers.aiogithubapi_provider.repository GitHub repository implementation using aiogithubapi.
AzureRepository githarbor.providers.azure_provider.repository Azure DevOps repository implementation.
GitHubRepository githarbor.providers.github_provider.repository GitHub repository implementation.
GitLabRepository githarbor.providers.gitlab_provider.repository GitLab repository implementation.
GiteaRepository githarbor.providers.gitea_provider.repository Gitea repository implementation.
LocalRepository githarbor.providers.local_provider.repository Local Git repository implementation using GitPython.
PyGiteaRepository githarbor.providers.pygitea_provider.repository PyGitea repository implementation using py-gitea library.

🛈 DocStrings

Githarbor providers package.

AioGitHubRepository

Bases: BaseRepository

GitHub repository implementation using aiogithubapi.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
class AioGitHubRepository(BaseRepository):
    """GitHub repository implementation using aiogithubapi."""

    url_patterns: ClassVar[list[str]] = ["github.com"]
    is_async: ClassVar[bool] = True

    def __init__(
        self,
        owner: str,
        name: str,
        token: str | None = None,
    ) -> None:
        """Initialize GitHub API client.

        Args:
            owner: Repository owner
            name: Repository name
            token: GitHub access token
        """
        t = token or os.getenv("GITHUB_TOKEN")
        assert t, "GitHub token is required"
        self._gh_client: GitHubAPI | None = None
        self._token = t
        self._owner = owner
        self._name = name
        self._repo = None

    @property
    def _gh(self) -> GitHubAPI:
        """Lazily create the async GitHubAPI client inside a running event loop."""
        if self._gh_client is None:
            try:
                self._gh_client = GitHubAPI(token=self._token)
            except GitHubAuthenticationException as e:
                msg = f"GitHub authentication failed: {e}"
                raise AuthenticationError(msg) from e
        return self._gh_client

    @classmethod
    def from_url(cls, url: str, **kwargs: Any) -> AioGitHubRepository:
        """Create instance from URL."""
        # Remove .git suffix and trailing slashes
        url = url.removesuffix(".git").rstrip("/")
        path = url.split("github.com/", 1)[1]
        owner, name = path.split("/")
        return cls(owner=owner, name=name, token=kwargs.get("token"))

    async def _ensure_repo(self) -> None:
        """Ensure repository info is loaded."""
        if self._repo is None:
            try:
                response = await self._gh.repos.get(f"{self._owner}/{self._name}")
                self._repo = response.data
            except GitHubNotFoundException as e:
                msg = f"Repository {self._owner}/{self._name} not found"
                raise ResourceNotFoundError(msg) from e

    @property
    def default_branch(self) -> str:
        """Return default branch name."""
        return self._repo.default_branch if self._repo and self._repo.default_branch else "main"

    async def get_repo_user_async(self) -> User:
        """Get repository owner information."""
        try:
            response = await self._gh.users.get(self._owner)
            assert response.data, f"User {self._owner} not found"
            return aiogithubapitools.create_user_model(response.data)
        except GitHubNotFoundException as e:
            msg = f"User {self._owner} not found"
            raise ResourceNotFoundError(msg) from e

    async def get_issue_async(self, issue_id: int) -> Issue:
        """Get issue by number."""
        try:
            repo = f"{self._owner}/{self._name}"
            response = await self._gh.repos.issues.get(repo, issue_id)
            assert response.data, f"Issue #{issue_id} not found"
            return aiogithubapitools.create_issue_model(response.data)
        except GitHubNotFoundException as e:
            msg = f"Issue #{issue_id} not found"
            raise ResourceNotFoundError(msg) from e

    async def list_issues_async(self, state: IssueState = "open") -> list[Issue]:
        """List repository issues."""
        repo = f"{self._owner}/{self._name}"
        response = await self._gh.repos.issues.list(repo, params={"state": state})  # ty: ignore[invalid-argument-type]
        return [aiogithubapitools.create_issue_model(i) for i in response.data or []]

    async def create_issue_async(
        self,
        title: str,
        body: str,
        labels: list[str] | None = None,
        assignees: list[str] | None = None,
    ) -> Issue:
        """Create a new issue."""
        from aiogithubapi.github import HttpMethod

        data = {
            "title": title,
            "body": body,
            "labels": labels or [],
            "assignees": assignees or [],
        }
        kwargs = {GitHubRequestKwarg.METHOD: HttpMethod.POST}
        endpoint = f"/repos/{self._owner}/{self._name}/issues"
        response = await self._gh.generic(endpoint=endpoint, data=data, **kwargs)  # type: ignore
        assert response.data
        return aiogithubapitools.create_issue_model(response.data)

    async def get_pull_request_async(self, number: int) -> PullRequest:
        """Get pull request by number."""
        from aiogithubapi.models.pull_request import GitHubPullRequestModel

        try:
            endpoint = f"/repos/{self._owner}/{self._name}/pulls/{number}"
            response = await self._gh.generic(endpoint=endpoint)
            if not response.data:
                msg = f"Pull request #{number} not found"
                raise ResourceNotFoundError(msg)
            return aiogithubapitools.create_pull_request_model(
                GitHubPullRequestModel(response.data)
            )
        except GitHubException as e:
            msg = f"Failed to get pull request #{number}: {e}"
            raise ResourceNotFoundError(msg) from e

    async def list_pull_requests_async(self, state: PullRequestState = "open") -> list[PullRequest]:
        """List pull requests."""
        repo = f"{self._owner}/{self._name}"
        response = await self._gh.repos.pulls.list(repo, params={"state": state})  # ty: ignore[invalid-argument-type]
        return [aiogithubapitools.create_pull_request_model(pr) for pr in response.data or []]

    # async def list_branches_async(self) -> list[Branch]:
    #     response = await self._gh.repos.branches.list(f"{self._owner}/{self._name}")
    #     assert response.data
    #     return [aiogithubapitools.create_branch_model(b) for b in response.data]

    async def get_latest_release_async(
        self,
        include_drafts: bool = False,
        include_prereleases: bool = False,
    ) -> Release:
        """Get latest release."""
        try:
            response = await self._gh.repos.releases.latest(f"{self._owner}/{self._name}")
            assert response.data, f"Release for {self._owner}/{self._name} not found"
            release = aiogithubapitools.create_release_model(response.data)
            if (not include_drafts and release.draft) or (
                not include_prereleases and release.prerelease
            ):
                msg = "Latest release is draft/prerelease"
                raise ResourceNotFoundError(msg)
        except GitHubNotFoundException as e:
            msg = "No releases found"
            raise ResourceNotFoundError(msg) from e
        else:
            return release

    async def list_releases_async(
        self,
        include_drafts: bool = False,
        include_prereleases: bool = False,
        limit: int | None = None,
    ) -> list[Release]:
        """List releases."""
        response = await self._gh.repos.releases.list(f"{self._owner}/{self._name}")
        releases = []
        for release in response.data or []:
            if not include_drafts and release.draft:
                continue
            if not include_prereleases and release.prerelease:
                continue
            releases.append(aiogithubapitools.create_release_model(release))
            if limit and len(releases) >= limit:
                break
        return releases

    async def list_tags_async(self) -> list[Tag]:
        """List repository tags."""
        await self._ensure_repo()
        response = await self._gh.repos.list_tags(f"{self._owner}/{self._name}")
        return [aiogithubapitools.create_tag_model(tag) for tag in response.data or []]

    async def download_async(
        self,
        path: str | os.PathLike[str],
        destination: JoinablePathLike,
        recursive: bool = False,
    ) -> None:
        """Download repository content."""
        await self._ensure_repo()
        await aiogithubapitools.download_from_github(
            repository=f"{self._owner}/{self._name}",
            path=path,
            destination=destination,
            token=self._token,
            branch=self.default_branch,
            recursive=recursive,
        )

default_branch property

default_branch: str

Return default branch name.

__init__

__init__(owner: str, name: str, token: str | None = None) -> None

Initialize GitHub API client.

Parameters:

Name Type Description Default
owner str

Repository owner

required
name str

Repository name

required
token str | None

GitHub access token

None
Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
def __init__(
    self,
    owner: str,
    name: str,
    token: str | None = None,
) -> None:
    """Initialize GitHub API client.

    Args:
        owner: Repository owner
        name: Repository name
        token: GitHub access token
    """
    t = token or os.getenv("GITHUB_TOKEN")
    assert t, "GitHub token is required"
    self._gh_client: GitHubAPI | None = None
    self._token = t
    self._owner = owner
    self._name = name
    self._repo = None

create_issue_async async

create_issue_async(
    title: str, body: str, labels: list[str] | None = None, assignees: list[str] | None = None
) -> Issue

Create a new issue.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
async def create_issue_async(
    self,
    title: str,
    body: str,
    labels: list[str] | None = None,
    assignees: list[str] | None = None,
) -> Issue:
    """Create a new issue."""
    from aiogithubapi.github import HttpMethod

    data = {
        "title": title,
        "body": body,
        "labels": labels or [],
        "assignees": assignees or [],
    }
    kwargs = {GitHubRequestKwarg.METHOD: HttpMethod.POST}
    endpoint = f"/repos/{self._owner}/{self._name}/issues"
    response = await self._gh.generic(endpoint=endpoint, data=data, **kwargs)  # type: ignore
    assert response.data
    return aiogithubapitools.create_issue_model(response.data)

download_async async

download_async(
    path: str | PathLike[str], destination: JoinablePathLike, recursive: bool = False
) -> None

Download repository content.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
async def download_async(
    self,
    path: str | os.PathLike[str],
    destination: JoinablePathLike,
    recursive: bool = False,
) -> None:
    """Download repository content."""
    await self._ensure_repo()
    await aiogithubapitools.download_from_github(
        repository=f"{self._owner}/{self._name}",
        path=path,
        destination=destination,
        token=self._token,
        branch=self.default_branch,
        recursive=recursive,
    )

from_url classmethod

from_url(url: str, **kwargs: Any) -> AioGitHubRepository

Create instance from URL.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
@classmethod
def from_url(cls, url: str, **kwargs: Any) -> AioGitHubRepository:
    """Create instance from URL."""
    # Remove .git suffix and trailing slashes
    url = url.removesuffix(".git").rstrip("/")
    path = url.split("github.com/", 1)[1]
    owner, name = path.split("/")
    return cls(owner=owner, name=name, token=kwargs.get("token"))

get_issue_async async

get_issue_async(issue_id: int) -> Issue

Get issue by number.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
async def get_issue_async(self, issue_id: int) -> Issue:
    """Get issue by number."""
    try:
        repo = f"{self._owner}/{self._name}"
        response = await self._gh.repos.issues.get(repo, issue_id)
        assert response.data, f"Issue #{issue_id} not found"
        return aiogithubapitools.create_issue_model(response.data)
    except GitHubNotFoundException as e:
        msg = f"Issue #{issue_id} not found"
        raise ResourceNotFoundError(msg) from e

get_latest_release_async async

get_latest_release_async(
    include_drafts: bool = False, include_prereleases: bool = False
) -> Release

Get latest release.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
async def get_latest_release_async(
    self,
    include_drafts: bool = False,
    include_prereleases: bool = False,
) -> Release:
    """Get latest release."""
    try:
        response = await self._gh.repos.releases.latest(f"{self._owner}/{self._name}")
        assert response.data, f"Release for {self._owner}/{self._name} not found"
        release = aiogithubapitools.create_release_model(response.data)
        if (not include_drafts and release.draft) or (
            not include_prereleases and release.prerelease
        ):
            msg = "Latest release is draft/prerelease"
            raise ResourceNotFoundError(msg)
    except GitHubNotFoundException as e:
        msg = "No releases found"
        raise ResourceNotFoundError(msg) from e
    else:
        return release

get_pull_request_async async

get_pull_request_async(number: int) -> PullRequest

Get pull request by number.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
async def get_pull_request_async(self, number: int) -> PullRequest:
    """Get pull request by number."""
    from aiogithubapi.models.pull_request import GitHubPullRequestModel

    try:
        endpoint = f"/repos/{self._owner}/{self._name}/pulls/{number}"
        response = await self._gh.generic(endpoint=endpoint)
        if not response.data:
            msg = f"Pull request #{number} not found"
            raise ResourceNotFoundError(msg)
        return aiogithubapitools.create_pull_request_model(
            GitHubPullRequestModel(response.data)
        )
    except GitHubException as e:
        msg = f"Failed to get pull request #{number}: {e}"
        raise ResourceNotFoundError(msg) from e

get_repo_user_async async

get_repo_user_async() -> User

Get repository owner information.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
async def get_repo_user_async(self) -> User:
    """Get repository owner information."""
    try:
        response = await self._gh.users.get(self._owner)
        assert response.data, f"User {self._owner} not found"
        return aiogithubapitools.create_user_model(response.data)
    except GitHubNotFoundException as e:
        msg = f"User {self._owner} not found"
        raise ResourceNotFoundError(msg) from e

list_issues_async async

list_issues_async(state: IssueState = 'open') -> list[Issue]

List repository issues.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
async def list_issues_async(self, state: IssueState = "open") -> list[Issue]:
    """List repository issues."""
    repo = f"{self._owner}/{self._name}"
    response = await self._gh.repos.issues.list(repo, params={"state": state})  # ty: ignore[invalid-argument-type]
    return [aiogithubapitools.create_issue_model(i) for i in response.data or []]

list_pull_requests_async async

list_pull_requests_async(state: PullRequestState = 'open') -> list[PullRequest]

List pull requests.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
async def list_pull_requests_async(self, state: PullRequestState = "open") -> list[PullRequest]:
    """List pull requests."""
    repo = f"{self._owner}/{self._name}"
    response = await self._gh.repos.pulls.list(repo, params={"state": state})  # ty: ignore[invalid-argument-type]
    return [aiogithubapitools.create_pull_request_model(pr) for pr in response.data or []]

list_releases_async async

list_releases_async(
    include_drafts: bool = False, include_prereleases: bool = False, limit: int | None = None
) -> list[Release]

List releases.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
async def list_releases_async(
    self,
    include_drafts: bool = False,
    include_prereleases: bool = False,
    limit: int | None = None,
) -> list[Release]:
    """List releases."""
    response = await self._gh.repos.releases.list(f"{self._owner}/{self._name}")
    releases = []
    for release in response.data or []:
        if not include_drafts and release.draft:
            continue
        if not include_prereleases and release.prerelease:
            continue
        releases.append(aiogithubapitools.create_release_model(release))
        if limit and len(releases) >= limit:
            break
    return releases

list_tags_async async

list_tags_async() -> list[Tag]

List repository tags.

Source code in src/githarbor/providers/aiogithubapi_provider/repository.py
async def list_tags_async(self) -> list[Tag]:
    """List repository tags."""
    await self._ensure_repo()
    response = await self._gh.repos.list_tags(f"{self._owner}/{self._name}")
    return [aiogithubapitools.create_tag_model(tag) for tag in response.data or []]

AzureRepository

Bases: BaseRepository

Azure DevOps repository implementation.

Source code in src/githarbor/providers/azure_provider/repository.py
class AzureRepository(BaseRepository):
    """Azure DevOps repository implementation."""

    url_patterns: ClassVar[list[str]] = ["dev.azure.com", "visualstudio.com"]

    def __init__(
        self,
        organization: str,
        project: str,
        name: str,
        token: str | None = None,
    ) -> None:
        """Initialize Azure DevOps repository.

        Args:
            organization: Azure DevOps organization name
            project: Project name
            name: Repository name
            token: Personal access token for authentication

        Raises:
            AuthenticationError: If authentication fails
            ValueError: If token is missing
        """
        from azure.devops.connection import Connection
        from msrest.authentication import BasicAuthentication

        t = token or os.getenv("AZURE_DEVOPS_PAT")
        if not t:
            msg = "Azure DevOps PAT token is required"
            raise ValueError(msg)
        try:
            credentials = BasicAuthentication("", t)
            organization_url = f"https://dev.azure.com/{organization}"
            self._connection = Connection(base_url=organization_url, creds=credentials)

            self._client: GitClient = self._connection.clients.get_git_client()
            self._work_client: WorkItemTrackingClient = (
                self._connection.clients.get_work_item_tracking_client()
            )
            self._build_client: BuildClient = self._connection.clients.get_build_client()

            self._project = project
            self._name = name
            self._owner = organization
            self._token = t
            self._repo: GitRepository = self._client.get_repository(name, project=project)

        except Exception as e:
            msg = f"Azure DevOps authentication failed: {e!s}"
            raise AuthenticationError(msg) from e

    @classmethod
    def from_url(cls, url: str, **kwargs: Any) -> AzureRepository:
        """Create from URL.

        Example URL: 'https://dev.azure.com/org/project/_git/repo'
        """
        parsed = urlparse(url)
        parts = parsed.path.strip("/").split("/")

        if len(parts) < 4:  # noqa: PLR2004
            msg = f"Invalid Azure DevOps URL: {url}"
            raise ValueError(msg)

        org = parts[0]
        project = parts[1]
        repo_name = parts[3]  # After '_git'
        token = kwargs.get("token")
        return cls(organization=org, project=project, name=repo_name, token=token)

    @property
    def default_branch(self) -> str:
        """Default branch name."""
        return (self._repo.default_branch or "main").removeprefix("refs/heads/")

    @azuretools.handle_azure_errors("Failed to get user {username}")
    def get_user(self, username: str | None = None) -> User:
        """Get user information.

        Args:
            username: Username to look up (defaults to repository owner/organization).

        Returns:
            User model with user information.
        """
        identity_client = self._connection.clients.get_identity_client()
        target = username or self._owner
        filter_ = f"General,localAccount,{target}"
        user_descriptor = identity_client.read_identities(search_filter=filter_)
        if not user_descriptor or not user_descriptor[0]:
            msg = f"User {target} not found"
            raise ResourceNotFoundError(msg)
        user_info = user_descriptor[0]
        props = getattr(user_info, "properties", None) or {}
        return User(
            username=props.get("Account", getattr(user_info, "unique_name", target)),
            name=getattr(user_info, "display_name", None) or target,
            email=props.get("Mail", ""),
            avatar_url=props.get("Avatar", ""),
        )

    def get_repo_user(self) -> User:
        """Get repository owner information."""
        return self.get_user(self._owner)

    @azuretools.handle_azure_errors("Failed to get branch {name}")
    def get_branch(self, name: str) -> Branch:
        """Get branch information."""
        branch = self._client.get_branch(self._repo.id, name=name, project=self._project)
        commit = self._client.get_commit(
            branch.commit.commit_id,
            self._repo.id,
            project=self._project,
        )
        return Branch(
            name=branch.name,
            sha=branch.commit.commit_id,
            protected=False,  # Azure DevOps handles branch protection differently
            default=branch.name == self.default_branch,
            created_at=None,  # Not provided by Azure API
            updated_at=None,  # Not provided by Azure API
            last_commit_date=commit.author.date,
            last_commit_message=commit.comment,
            last_commit_author=azuretools.create_user_model(commit.author),
        )

    @azuretools.handle_azure_errors("Failed to get pull request {number}")
    def get_pull_request(self, number: int) -> PullRequest:
        """Get pull request by number."""
        pr: GitPullRequest = self._client.get_pull_request_by_id(number, self._project)
        return azuretools.create_pull_request_model(pr)

    @azuretools.handle_azure_errors("Failed to list pull requests")
    def list_pull_requests(self, state: PullRequestState = "open") -> list[PullRequest]:
        """List pull requests."""
        # Map state to Azure DevOps status
        from azure.devops.v7_1.git.models import GitPullRequestSearchCriteria

        status_map = {"open": "active", "closed": "completed", "all": "all"}
        azure_status = status_map.get(state, "active")
        criteria = GitPullRequestSearchCriteria(status=azure_status)
        prs = self._client.get_pull_requests(
            self._repo.id, search_criteria=criteria, project=self._project
        )
        return [azuretools.create_pull_request_model(pr) for pr in prs]

    # @azuretools.handle_azure_errors("Failed to list branches")
    # def list_branches(self) -> list[Branch]:
    #     branches = self._client.get_branches(self._repo.id, project=self._project)
    #     return [azuretools.create_branch_model(branch) for branch in branches]

    @azuretools.handle_azure_errors("Failed to get issue {issue_id}")
    def get_issue(self, issue_id: int) -> Issue:
        """Get issue by ID (work item in Azure DevOps)."""
        work_item = self._work_client.get_work_item(issue_id, self._project)
        return azuretools.create_issue_model(work_item)

    @azuretools.handle_azure_errors("Failed to list issues")
    def list_issues(self, state: IssueState = "open") -> list[Issue]:
        """List issues (work items in Azure DevOps)."""
        from azure.devops.v7_1.work_item_tracking.models import Wiql

        # Build WIQL query based on state
        state_map = {"open": "Active", "closed": "Closed", "all": ""}
        azure_state = state_map.get(state, "Active")
        state_clause = f"AND [System.State] = '{azure_state}'" if azure_state else ""
        wiql = (
            f"SELECT [System.Id] FROM WorkItems "
            f"WHERE [System.TeamProject] = '{self._project}' "
            f"{state_clause} ORDER BY [System.ChangedDate] DESC"
        )
        wiql_result = self._work_client.query_by_wiql(Wiql(query=wiql))
        if not wiql_result.work_items:
            return []

        work_items = self._work_client.get_work_items(
            [wi.id for wi in wiql_result.work_items],
        )
        return [azuretools.create_issue_model(wi) for wi in work_items]

    @azuretools.handle_azure_errors("Failed to create issue")
    def create_issue(
        self,
        title: str,
        body: str,
        labels: list[str] | None = None,
        assignees: list[str] | None = None,
    ) -> Issue:
        """Create a new issue."""
        from azure.devops.v7_1.work_item_tracking.models import JsonPatchOperation

        doc = [
            JsonPatchOperation(op="add", path="/fields/System.Title", value=title),
            JsonPatchOperation(op="add", path="/fields/System.Description", value=body),
        ]
        if labels:
            doc.append(
                JsonPatchOperation(op="add", path="/fields/System.Tags", value="; ".join(labels))
            )
        if assignees:
            doc.append(
                JsonPatchOperation(op="add", path="/fields/System.AssignedTo", value=assignees[0])
            )
        work_item = self._work_client.create_work_item(doc, self._project, type="Issue")
        return azuretools.create_issue_model(work_item)

    @azuretools.handle_azure_errors("Failed to get commit {sha}")
    def get_commit(self, sha: str) -> Commit:
        """Get commit by SHA."""
        commit: GitCommit = self._client.get_commit(
            commit_id=sha,
            repository_id=self._repo.id,
            project=self._project,
        )
        return azuretools.create_commit_model(commit)

    @azuretools.handle_azure_errors("Failed to list commits")
    def list_commits(
        self,
        branch: str | None = None,
        since: datetime | None = None,
        until: datetime | None = None,
        author: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        """List repository commits with optional filters."""
        from azure.devops.v7_1.git.models import GitQueryCommitsCriteria, GitVersionDescriptor

        item_version = (
            GitVersionDescriptor(version=branch, version_type="branch") if branch else None
        )
        criteria = GitQueryCommitsCriteria(
            item_version=item_version,
            from_date=since.isoformat() if since else None,
            to_date=until.isoformat() if until else None,
            author=author,
            item_path=path,
        )
        commits = self._client.get_commits(
            repository_id=self._repo.id,
            search_criteria=criteria,
            project=self._project,
            top=max_results,
        )
        return [azuretools.create_commit_model(c) for c in commits]

    @azuretools.handle_azure_errors("Failed to download file {path}")
    def download(self, path: str, destination: JoinablePathLike, recursive: bool = False):
        """Download file(s) from repository."""
        return azuretools.download_from_azure(
            organization=self._owner,
            project=self._project,
            repo=self._repo.id,  # type: ignore
            path=path,
            destination=destination,
            token=self._token,
            recursive=recursive,
        )

    @azuretools.handle_azure_errors("Failed to list files for {path}")
    def iter_files(
        self,
        path: str = "",
        ref: str | None = None,
        pattern: str | None = None,
    ) -> Iterator[str]:
        """Iterate over repository files."""
        from azure.devops.v7_1.git.models import GitVersionDescriptor

        version_desc = GitVersionDescriptor(version=ref) if ref else None
        items = self._client.get_items(
            repository_id=self._repo.id,
            project=self._project,
            scope_path=path or None,
            recursion_level="full",
            version_descriptor=version_desc,
        )
        for item in items:
            if item.is_folder:
                continue
            if not pattern or fnmatch.fnmatch(item.path, pattern):
                yield item.path

    # @azuretools.handle_azure_errors("Failed to get latest release")
    # def get_latest_release(
    #     self,
    #     include_drafts: bool = False,
    #     include_prereleases: bool = False,
    # ) -> Release:
    #     """Get latest release (mapped from Git tags)."""
    #     tags = self._client.get_tags(
    #         repository_id=self._repo.id,
    #         project=self._project,
    #     )
    #     if not tags:
    #         msg = "No releases found"
    #         raise ResourceNotFoundError(msg)

    #     latest_tags = sorted(tags, key=lambda t: t.commit.committer.date, reverse=True)
    #     latest_tag = latest_tags[0]
    #     return azuretools.create_release_model(latest_tag)

    @azuretools.handle_azure_errors("Failed to create pull request")
    def create_pull_request(
        self,
        title: str,
        body: str,
        head_branch: str,
        base_branch: str,
        draft: bool = False,
    ) -> PullRequest:
        """Create a pull request."""
        from azure.devops.v7_1.git.models import GitPullRequest

        request = GitPullRequest(
            source_ref_name=f"refs/heads/{head_branch}",
            target_ref_name=f"refs/heads/{base_branch}",
            title=title,
            description=body,
            is_draft=draft,
        )
        pr = self._client.create_pull_request(
            request,
            repository_id=self._repo.id,
            project=self._project,
        )
        return azuretools.create_pull_request_model(pr)

    @azuretools.handle_azure_errors("Failed to add pull request comment")
    def add_pull_request_comment(
        self,
        number: int,
        body: str,
    ) -> Comment:
        from azure.devops.v7_1.git.models import Comment, GitPullRequestCommentThread

        comment = Comment(content=body)
        thread = GitPullRequestCommentThread(comments=[comment], status="active")
        result = self._client.create_thread(
            comment_thread=thread,
            repository_id=self._repo.id,
            pull_request_id=number,
            project=self._project,
        )
        return azuretools.create_comment_model(result.comments[0])

    @azuretools.handle_azure_errors("Failed to add pull request review comment")
    def add_pull_request_review_comment(
        self,
        number: int,
        body: str,
        commit_id: str,
        path: str,
        position: int,
    ) -> Comment:
        from azure.devops.v7_1.git.models import (
            Comment,
            CommentThreadContext,
            GitPullRequestCommentThread,
        )

        ctx = CommentThreadContext(
            file_path=path,
            right_file_start={"line": position, "offset": 0},
            right_file_end={"line": position, "offset": 0},
        )
        thread = GitPullRequestCommentThread(
            comments=[Comment(content=body)],
            status="active",
            thread_context=ctx,
        )
        result = self._client.create_thread(
            comment_thread=thread,
            repository_id=self._repo.id,
            pull_request_id=number,
            project=self._project,
        )
        return azuretools.create_comment_model(result.comments[0])

default_branch property

default_branch: str

Default branch name.

__init__

__init__(organization: str, project: str, name: str, token: str | None = None) -> None

Initialize Azure DevOps repository.

Parameters:

Name Type Description Default
organization str

Azure DevOps organization name

required
project str

Project name

required
name str

Repository name

required
token str | None

Personal access token for authentication

None

Raises:

Type Description
AuthenticationError

If authentication fails

ValueError

If token is missing

Source code in src/githarbor/providers/azure_provider/repository.py
def __init__(
    self,
    organization: str,
    project: str,
    name: str,
    token: str | None = None,
) -> None:
    """Initialize Azure DevOps repository.

    Args:
        organization: Azure DevOps organization name
        project: Project name
        name: Repository name
        token: Personal access token for authentication

    Raises:
        AuthenticationError: If authentication fails
        ValueError: If token is missing
    """
    from azure.devops.connection import Connection
    from msrest.authentication import BasicAuthentication

    t = token or os.getenv("AZURE_DEVOPS_PAT")
    if not t:
        msg = "Azure DevOps PAT token is required"
        raise ValueError(msg)
    try:
        credentials = BasicAuthentication("", t)
        organization_url = f"https://dev.azure.com/{organization}"
        self._connection = Connection(base_url=organization_url, creds=credentials)

        self._client: GitClient = self._connection.clients.get_git_client()
        self._work_client: WorkItemTrackingClient = (
            self._connection.clients.get_work_item_tracking_client()
        )
        self._build_client: BuildClient = self._connection.clients.get_build_client()

        self._project = project
        self._name = name
        self._owner = organization
        self._token = t
        self._repo: GitRepository = self._client.get_repository(name, project=project)

    except Exception as e:
        msg = f"Azure DevOps authentication failed: {e!s}"
        raise AuthenticationError(msg) from e

create_issue

create_issue(
    title: str, body: str, labels: list[str] | None = None, assignees: list[str] | None = None
) -> Issue

Create a new issue.

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to create issue")
def create_issue(
    self,
    title: str,
    body: str,
    labels: list[str] | None = None,
    assignees: list[str] | None = None,
) -> Issue:
    """Create a new issue."""
    from azure.devops.v7_1.work_item_tracking.models import JsonPatchOperation

    doc = [
        JsonPatchOperation(op="add", path="/fields/System.Title", value=title),
        JsonPatchOperation(op="add", path="/fields/System.Description", value=body),
    ]
    if labels:
        doc.append(
            JsonPatchOperation(op="add", path="/fields/System.Tags", value="; ".join(labels))
        )
    if assignees:
        doc.append(
            JsonPatchOperation(op="add", path="/fields/System.AssignedTo", value=assignees[0])
        )
    work_item = self._work_client.create_work_item(doc, self._project, type="Issue")
    return azuretools.create_issue_model(work_item)

create_pull_request

create_pull_request(
    title: str, body: str, head_branch: str, base_branch: str, draft: bool = False
) -> PullRequest

Create a pull request.

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to create pull request")
def create_pull_request(
    self,
    title: str,
    body: str,
    head_branch: str,
    base_branch: str,
    draft: bool = False,
) -> PullRequest:
    """Create a pull request."""
    from azure.devops.v7_1.git.models import GitPullRequest

    request = GitPullRequest(
        source_ref_name=f"refs/heads/{head_branch}",
        target_ref_name=f"refs/heads/{base_branch}",
        title=title,
        description=body,
        is_draft=draft,
    )
    pr = self._client.create_pull_request(
        request,
        repository_id=self._repo.id,
        project=self._project,
    )
    return azuretools.create_pull_request_model(pr)

download

download(path: str, destination: JoinablePathLike, recursive: bool = False)

Download file(s) from repository.

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to download file {path}")
def download(self, path: str, destination: JoinablePathLike, recursive: bool = False):
    """Download file(s) from repository."""
    return azuretools.download_from_azure(
        organization=self._owner,
        project=self._project,
        repo=self._repo.id,  # type: ignore
        path=path,
        destination=destination,
        token=self._token,
        recursive=recursive,
    )

from_url classmethod

from_url(url: str, **kwargs: Any) -> AzureRepository

Create from URL.

Example URL: 'https://dev.azure.com/org/project/_git/repo'

Source code in src/githarbor/providers/azure_provider/repository.py
@classmethod
def from_url(cls, url: str, **kwargs: Any) -> AzureRepository:
    """Create from URL.

    Example URL: 'https://dev.azure.com/org/project/_git/repo'
    """
    parsed = urlparse(url)
    parts = parsed.path.strip("/").split("/")

    if len(parts) < 4:  # noqa: PLR2004
        msg = f"Invalid Azure DevOps URL: {url}"
        raise ValueError(msg)

    org = parts[0]
    project = parts[1]
    repo_name = parts[3]  # After '_git'
    token = kwargs.get("token")
    return cls(organization=org, project=project, name=repo_name, token=token)

get_branch

get_branch(name: str) -> Branch

Get branch information.

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to get branch {name}")
def get_branch(self, name: str) -> Branch:
    """Get branch information."""
    branch = self._client.get_branch(self._repo.id, name=name, project=self._project)
    commit = self._client.get_commit(
        branch.commit.commit_id,
        self._repo.id,
        project=self._project,
    )
    return Branch(
        name=branch.name,
        sha=branch.commit.commit_id,
        protected=False,  # Azure DevOps handles branch protection differently
        default=branch.name == self.default_branch,
        created_at=None,  # Not provided by Azure API
        updated_at=None,  # Not provided by Azure API
        last_commit_date=commit.author.date,
        last_commit_message=commit.comment,
        last_commit_author=azuretools.create_user_model(commit.author),
    )

get_commit

get_commit(sha: str) -> Commit

Get commit by SHA.

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to get commit {sha}")
def get_commit(self, sha: str) -> Commit:
    """Get commit by SHA."""
    commit: GitCommit = self._client.get_commit(
        commit_id=sha,
        repository_id=self._repo.id,
        project=self._project,
    )
    return azuretools.create_commit_model(commit)

get_issue

get_issue(issue_id: int) -> Issue

Get issue by ID (work item in Azure DevOps).

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to get issue {issue_id}")
def get_issue(self, issue_id: int) -> Issue:
    """Get issue by ID (work item in Azure DevOps)."""
    work_item = self._work_client.get_work_item(issue_id, self._project)
    return azuretools.create_issue_model(work_item)

get_pull_request

get_pull_request(number: int) -> PullRequest

Get pull request by number.

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to get pull request {number}")
def get_pull_request(self, number: int) -> PullRequest:
    """Get pull request by number."""
    pr: GitPullRequest = self._client.get_pull_request_by_id(number, self._project)
    return azuretools.create_pull_request_model(pr)

get_repo_user

get_repo_user() -> User

Get repository owner information.

Source code in src/githarbor/providers/azure_provider/repository.py
def get_repo_user(self) -> User:
    """Get repository owner information."""
    return self.get_user(self._owner)

get_user

get_user(username: str | None = None) -> User

Get user information.

Parameters:

Name Type Description Default
username str | None

Username to look up (defaults to repository owner/organization).

None

Returns:

Type Description
User

User model with user information.

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to get user {username}")
def get_user(self, username: str | None = None) -> User:
    """Get user information.

    Args:
        username: Username to look up (defaults to repository owner/organization).

    Returns:
        User model with user information.
    """
    identity_client = self._connection.clients.get_identity_client()
    target = username or self._owner
    filter_ = f"General,localAccount,{target}"
    user_descriptor = identity_client.read_identities(search_filter=filter_)
    if not user_descriptor or not user_descriptor[0]:
        msg = f"User {target} not found"
        raise ResourceNotFoundError(msg)
    user_info = user_descriptor[0]
    props = getattr(user_info, "properties", None) or {}
    return User(
        username=props.get("Account", getattr(user_info, "unique_name", target)),
        name=getattr(user_info, "display_name", None) or target,
        email=props.get("Mail", ""),
        avatar_url=props.get("Avatar", ""),
    )

iter_files

iter_files(path: str = '', ref: str | None = None, pattern: str | None = None) -> Iterator[str]

Iterate over repository files.

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to list files for {path}")
def iter_files(
    self,
    path: str = "",
    ref: str | None = None,
    pattern: str | None = None,
) -> Iterator[str]:
    """Iterate over repository files."""
    from azure.devops.v7_1.git.models import GitVersionDescriptor

    version_desc = GitVersionDescriptor(version=ref) if ref else None
    items = self._client.get_items(
        repository_id=self._repo.id,
        project=self._project,
        scope_path=path or None,
        recursion_level="full",
        version_descriptor=version_desc,
    )
    for item in items:
        if item.is_folder:
            continue
        if not pattern or fnmatch.fnmatch(item.path, pattern):
            yield item.path

list_commits

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

List repository commits with optional filters.

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to list commits")
def list_commits(
    self,
    branch: str | None = None,
    since: datetime | None = None,
    until: datetime | None = None,
    author: str | None = None,
    path: str | None = None,
    max_results: int | None = None,
) -> list[Commit]:
    """List repository commits with optional filters."""
    from azure.devops.v7_1.git.models import GitQueryCommitsCriteria, GitVersionDescriptor

    item_version = (
        GitVersionDescriptor(version=branch, version_type="branch") if branch else None
    )
    criteria = GitQueryCommitsCriteria(
        item_version=item_version,
        from_date=since.isoformat() if since else None,
        to_date=until.isoformat() if until else None,
        author=author,
        item_path=path,
    )
    commits = self._client.get_commits(
        repository_id=self._repo.id,
        search_criteria=criteria,
        project=self._project,
        top=max_results,
    )
    return [azuretools.create_commit_model(c) for c in commits]

list_issues

list_issues(state: IssueState = 'open') -> list[Issue]

List issues (work items in Azure DevOps).

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to list issues")
def list_issues(self, state: IssueState = "open") -> list[Issue]:
    """List issues (work items in Azure DevOps)."""
    from azure.devops.v7_1.work_item_tracking.models import Wiql

    # Build WIQL query based on state
    state_map = {"open": "Active", "closed": "Closed", "all": ""}
    azure_state = state_map.get(state, "Active")
    state_clause = f"AND [System.State] = '{azure_state}'" if azure_state else ""
    wiql = (
        f"SELECT [System.Id] FROM WorkItems "
        f"WHERE [System.TeamProject] = '{self._project}' "
        f"{state_clause} ORDER BY [System.ChangedDate] DESC"
    )
    wiql_result = self._work_client.query_by_wiql(Wiql(query=wiql))
    if not wiql_result.work_items:
        return []

    work_items = self._work_client.get_work_items(
        [wi.id for wi in wiql_result.work_items],
    )
    return [azuretools.create_issue_model(wi) for wi in work_items]

list_pull_requests

list_pull_requests(state: PullRequestState = 'open') -> list[PullRequest]

List pull requests.

Source code in src/githarbor/providers/azure_provider/repository.py
@azuretools.handle_azure_errors("Failed to list pull requests")
def list_pull_requests(self, state: PullRequestState = "open") -> list[PullRequest]:
    """List pull requests."""
    # Map state to Azure DevOps status
    from azure.devops.v7_1.git.models import GitPullRequestSearchCriteria

    status_map = {"open": "active", "closed": "completed", "all": "all"}
    azure_status = status_map.get(state, "active")
    criteria = GitPullRequestSearchCriteria(status=azure_status)
    prs = self._client.get_pull_requests(
        self._repo.id, search_criteria=criteria, project=self._project
    )
    return [azuretools.create_pull_request_model(pr) for pr in prs]

GitHubKitRepository

Bases: BaseRepository

GitHub repository implementation using GitHubKit.

Source code in src/githarbor/providers/githubkit_provider/repository.py
class GitHubKitRepository(BaseRepository):
    """GitHub repository implementation using GitHubKit."""

    url_patterns: ClassVar[list[str]] = ["github.com"]
    is_async: ClassVar[bool] = True

    def __init__(
        self,
        owner: str,
        name: str,
        token: str | None = None,
    ) -> None:
        """Initialize GitHub API client.

        Args:
            owner: Repository owner
            name: Repository name
            token: GitHub access token

        Raises:
            AuthenticationError: If authentication fails
        """
        from githubkit import GitHub

        t = token or os.getenv("GITHUB_TOKEN")
        if not t:
            msg = "GitHub token is required"
            raise ValueError(msg)
        self._gh = GitHub(t)
        self._owner = owner
        self._name = name
        self._repo: FullRepository | None = None

    async def _ensure_repo(self) -> None:
        """Ensure repository info is loaded."""
        from githubkit.exception import GitHubException

        if self._repo is None:
            try:
                resp = await self._gh.rest.repos.async_get(self._owner, self._name)
                self._repo = resp.parsed_data
            except GitHubException as e:
                msg = f"Repository {self._owner}/{self._name} not found"
                raise ResourceNotFoundError(msg) from e

    @classmethod
    def from_url(cls, url: str, **kwargs: Any) -> GitHubKitRepository:
        """Create instance from URL."""
        # Remove .git suffix and trailing slashes
        url = url.removesuffix(".git").rstrip("/")
        path = url.split("github.com/", 1)[1]
        owner, name = path.split("/")
        return cls(owner=owner, name=name, token=kwargs.get("token"))

    @property
    def default_branch(self) -> str:
        """Return default branch name."""
        if not self._repo:
            return "main"
        return self._repo.default_branch

    @property
    def edit_base_uri(self) -> str:
        """Return base URI for editing files."""
        return f"edit/{self.default_branch}/"

    @githubkittools.handle_githubkit_errors("Failed to get user info")
    async def get_repo_user_async(self) -> User:
        """Get repository owner information."""
        resp = await self._gh.rest.users.async_get_by_username(self._owner)
        return githubkittools.create_user_model(resp.parsed_data)

    @githubkittools.handle_githubkit_errors("Failed to get branch {name}")
    async def get_branch_async(self, name: str) -> Branch:
        """Get branch information."""
        resp = await self._gh.rest.repos.async_get_branch(self._owner, self._name, name)
        branch = githubkittools.create_branch_model(resp.parsed_data)
        branch.default = name == self.default_branch
        return branch

    @githubkittools.handle_githubkit_errors("Failed to get pull request {number}")
    async def get_pull_request_async(self, number: int) -> PullRequest:
        """Get pull request by number."""
        resp = await self._gh.rest.pulls.async_get(self._owner, self._name, number)
        return githubkittools.create_pull_request_model(resp.parsed_data)

    @githubkittools.handle_githubkit_errors("Failed to list pull requests")
    async def list_pull_requests_async(self, state: PullRequestState = "open") -> list[PullRequest]:
        """List pull requests."""
        resp = await self._gh.rest.pulls.async_list(self._owner, self._name, state=state)
        data = resp.parsed_data
        return [githubkittools.create_pull_request_model(pr) for pr in data]

    @githubkittools.handle_githubkit_errors("Failed to list branches")
    async def list_branches_async(self) -> list[Branch]:
        resp = await self._gh.rest.repos.async_list_branches(self._owner, self._name)
        return [githubkittools.create_branch_model(branch) for branch in resp.parsed_data]

    @githubkittools.handle_githubkit_errors("Failed to get issue {issue_id}")
    async def get_issue_async(self, issue_id: int) -> Issue:
        """Get issue by ID."""
        resp = await self._gh.rest.issues.async_get(self._owner, self._name, issue_id)
        return githubkittools.create_issue_model(resp.parsed_data)

    @githubkittools.handle_githubkit_errors("Failed to list issues")
    async def list_issues_async(self, state: IssueState = "open") -> list[Issue]:
        """List repository issues."""
        resp = await self._gh.rest.issues.async_list_for_repo(
            self._owner,
            self._name,
            state=state,
        )
        data = resp.parsed_data
        return [githubkittools.create_issue_model(issue) for issue in data]

    @githubkittools.handle_githubkit_errors("Failed to create issue")
    async def create_issue_async(
        self,
        title: str,
        body: str,
        labels: list[str] | None = None,
        assignees: list[str] | None = None,
    ) -> Issue:
        """Create a new issue."""
        response = await self._gh.rest.issues.async_create(
            owner=self._owner,
            repo=self._name,
            title=title,
            body=body,
            labels=labels or [],
            assignees=assignees,
        )
        return githubkittools.create_issue_model(response.parsed_data)

    @githubkittools.handle_githubkit_errors("Failed to get commit {sha}")
    async def get_commit_async(self, sha: str) -> Commit:
        """Get commit by SHA."""
        resp = await self._gh.rest.repos.async_get_commit(self._owner, self._name, sha)
        return githubkittools.create_commit_model(resp.parsed_data)

    @githubkittools.handle_githubkit_errors("Failed to list commits")
    async def list_commits_async(
        self,
        branch: str | None = None,
        since: datetime | None = None,
        until: datetime | None = None,
        author: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        """List repository commits."""
        kwargs: dict[str, Any] = {"sha": branch} if branch else {}
        if since:
            kwargs["since"] = since.isoformat()
        if until:
            kwargs["until"] = until.isoformat()
        if author:
            kwargs["author"] = author
        if path:
            kwargs["path"] = path
        if max_results:
            kwargs["per_page"] = max_results

        resp = await self._gh.rest.repos.async_list_commits(self._owner, self._name, **kwargs)
        return [githubkittools.create_commit_model(c) for c in resp.parsed_data]

    @githubkittools.handle_githubkit_errors("Failed to download {path}")
    async def download_async(
        self,
        path: str | os.PathLike[str],
        destination: JoinablePathLike,
        recursive: bool = False,
    ) -> None:
        """Download repository content."""
        from upathtools import to_upath

        dest = to_upath(destination)
        dest.mkdir(exist_ok=True, parents=True)

        resp = await self._gh.rest.repos.async_get_content(
            self._owner,
            self._name,
            str(path),
            headers={"Accept": "application/vnd.github.raw"},
        )
        file_dest = dest / to_upath(path).name
        file_dest.write_bytes(resp.content)

    @githubkittools.handle_githubkit_errors("Failed to search commits")
    async def search_commits_async(
        self,
        query: str,
        branch: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        """Search repository commits."""
        search_query = f"repo:{self._owner}/{self._name} {query}"
        if branch:
            search_query += f" ref:{branch}"
        if path:
            search_query += f" path:{path}"

        kwargs: dict[str, Any] = {"q": search_query}
        if max_results:
            kwargs["per_page"] = max_results
        resp = await self._gh.rest.search.async_commits(**kwargs)
        return [githubkittools.create_commit_model(c.commit) for c in resp.parsed_data.items]

    @githubkittools.handle_githubkit_errors("Failed to get languages")
    async def get_languages_async(self) -> dict[str, int]:
        """Get repository language statistics."""
        resp = await self._gh.rest.repos.async_list_languages(self._owner, self._name)
        return resp.parsed_data.model_dump()

    @githubkittools.handle_githubkit_errors("Failed to compare branches")
    async def compare_branches_async(
        self,
        base: str,
        head: str,
        include_commits: bool = True,
        include_files: bool = True,
        include_stats: bool = True,
    ) -> dict[str, Any]:
        """Compare two branches."""
        # Create the basehead string in the format "base...head"
        basehead = f"{base}...{head}"

        resp = await self._gh.rest.repos.async_compare_commits(
            self._owner,
            self._name,
            basehead,  # Single parameter combining base and head
        )
        comparison = resp.parsed_data
        result: dict[str, Any] = {
            "ahead_by": comparison.ahead_by,
            "behind_by": comparison.behind_by,
        }

        if include_commits:
            result["commits"] = [githubkittools.create_commit_model(c) for c in comparison.commits]
        files = comparison.files or []
        if include_files:
            result["files"] = [f.filename for f in files]
        if include_stats:
            result["stats"] = {
                "additions": sum(f.additions for f in files),
                "deletions": sum(f.deletions for f in files),
                "changes": len(files),
            }
        return result

    @githubkittools.handle_githubkit_errors("Failed to get latest release")
    async def get_latest_release_async(
        self,
        include_drafts: bool = False,
        include_prereleases: bool = False,
    ) -> Release:
        """Get latest release."""
        from githubkit.exception import GitHubException

        try:
            resp = await self._gh.rest.repos.async_get_latest_release(self._owner, self._name)
            release = resp.parsed_data
            if (not include_drafts and release.draft) or (
                not include_prereleases and release.prerelease
            ):
                msg = "Latest release is draft/prerelease"
                raise ResourceNotFoundError(msg)
            return githubkittools.create_release_model(release)
        except GitHubException as e:
            msg = "No releases found"
            raise ResourceNotFoundError(msg) from e

    @githubkittools.handle_githubkit_errors("Failed to list releases")
    async def list_releases_async(
        self,
        include_drafts: bool = False,
        include_prereleases: bool = False,
        limit: int | None = None,
    ) -> list[Release]:
        """List releases."""
        resp = await self._gh.rest.repos.async_list_releases(self._owner, self._name)
        releases = []
        for release in resp.parsed_data:
            if not include_drafts and release.draft:
                continue
            if not include_prereleases and release.prerelease:
                continue
            releases.append(githubkittools.create_release_model(release))
            if limit and len(releases) >= limit:
                break
        return releases

    @githubkittools.handle_githubkit_errors("Failed to get release {tag}")
    async def get_release_async(self, tag: str) -> Release:
        """Get release by tag."""
        resp = await self._gh.rest.repos.async_get_release_by_tag(self._owner, self._name, tag)
        return githubkittools.create_release_model(resp.parsed_data)

    @githubkittools.handle_githubkit_errors("Failed to get tag {name}")
    async def get_tag_async(self, name: str) -> Tag:
        """Get tag by name."""
        from githarbor.core.models import Tag

        ref_resp = await self._gh.rest.git.async_get_ref(self._owner, self._name, f"tags/{name}")
        obj = ref_resp.parsed_data.object_
        if obj.type == "tag":
            resp = await self._gh.rest.git.async_get_tag(self._owner, self._name, obj.sha)
            return githubkittools.create_tag_model(resp.parsed_data)
        return Tag(name=name, sha=obj.sha, url=obj.url)

    @githubkittools.handle_githubkit_errors("Failed to list tags")
    async def list_tags_async(self) -> list[Tag]:
        """List repository tags."""
        resp = await self._gh.rest.repos.async_list_tags(self._owner, self._name)
        return [githubkittools.create_tag_model(tag) for tag in resp.parsed_data]

    @githubkittools.handle_githubkit_errors("Failed to create pull request")
    async def create_pull_request_async(
        self,
        title: str,
        body: str,
        head_branch: str,
        base_branch: str,
        draft: bool = False,
    ) -> PullRequest:
        response = await self._gh.rest.pulls.async_create(
            owner=self._owner,
            repo=self._name,
            title=title,
            body=body,
            head=head_branch,
            base=base_branch,
            draft=draft,
        )
        return githubkittools.create_pull_request_model(response.parsed_data)

    @githubkittools.handle_githubkit_errors("Failed to create branch")
    async def create_branch_async(
        self,
        name: str,
        base_commit: str,
    ) -> Branch:
        """Create a new branch at the specified commit."""
        await self._gh.rest.git.async_create_ref(
            owner=self._owner,
            repo=self._name,
            ref=f"refs/heads/{name}",
            sha=base_commit,
        )
        # Get the branch to return proper Branch model
        response = await self._gh.rest.repos.async_get_branch(
            owner=self._owner,
            repo=self._name,
            branch=name,
        )
        return githubkittools.create_branch_model(response.parsed_data)

    @githubkittools.handle_githubkit_errors("Failed to add pull request comment")
    async def add_pull_request_comment_async(
        self,
        number: int,
        body: str,
    ) -> Comment:
        response = await self._gh.rest.issues.async_create_comment(
            owner=self._owner,
            repo=self._name,
            issue_number=number,
            body=body,
        )
        return githubkittools.create_comment_model(response.parsed_data)

    @githubkittools.handle_githubkit_errors("Failed to add pull request review comment")
    async def add_pull_request_review_comment_async(
        self,
        number: int,
        body: str,
        commit_id: str,
        path: str,
        position: int,
    ) -> Comment:
        response = await self._gh.rest.pulls.async_create_review_comment(
            owner=self._owner,
            repo=self._name,
            pull_number=number,
            body=body,
            commit_id=commit_id,
            path=path,
            line=position,  # Using line instead of position as per API docs
        )
        return githubkittools.create_comment_model(response.parsed_data)

default_branch property

default_branch: str

Return default branch name.

edit_base_uri property

edit_base_uri: str

Return base URI for editing files.

__init__

__init__(owner: str, name: str, token: str | None = None) -> None

Initialize GitHub API client.

Parameters:

Name Type Description Default
owner str

Repository owner

required
name str

Repository name

required
token str | None

GitHub access token

None

Raises:

Type Description
AuthenticationError

If authentication fails

Source code in src/githarbor/providers/githubkit_provider/repository.py
def __init__(
    self,
    owner: str,
    name: str,
    token: str | None = None,
) -> None:
    """Initialize GitHub API client.

    Args:
        owner: Repository owner
        name: Repository name
        token: GitHub access token

    Raises:
        AuthenticationError: If authentication fails
    """
    from githubkit import GitHub

    t = token or os.getenv("GITHUB_TOKEN")
    if not t:
        msg = "GitHub token is required"
        raise ValueError(msg)
    self._gh = GitHub(t)
    self._owner = owner
    self._name = name
    self._repo: FullRepository | None = None

compare_branches_async async

compare_branches_async(
    base: str,
    head: str,
    include_commits: bool = True,
    include_files: bool = True,
    include_stats: bool = True,
) -> dict[str, Any]

Compare two branches.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to compare branches")
async def compare_branches_async(
    self,
    base: str,
    head: str,
    include_commits: bool = True,
    include_files: bool = True,
    include_stats: bool = True,
) -> dict[str, Any]:
    """Compare two branches."""
    # Create the basehead string in the format "base...head"
    basehead = f"{base}...{head}"

    resp = await self._gh.rest.repos.async_compare_commits(
        self._owner,
        self._name,
        basehead,  # Single parameter combining base and head
    )
    comparison = resp.parsed_data
    result: dict[str, Any] = {
        "ahead_by": comparison.ahead_by,
        "behind_by": comparison.behind_by,
    }

    if include_commits:
        result["commits"] = [githubkittools.create_commit_model(c) for c in comparison.commits]
    files = comparison.files or []
    if include_files:
        result["files"] = [f.filename for f in files]
    if include_stats:
        result["stats"] = {
            "additions": sum(f.additions for f in files),
            "deletions": sum(f.deletions for f in files),
            "changes": len(files),
        }
    return result

create_branch_async async

create_branch_async(name: str, base_commit: str) -> Branch

Create a new branch at the specified commit.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to create branch")
async def create_branch_async(
    self,
    name: str,
    base_commit: str,
) -> Branch:
    """Create a new branch at the specified commit."""
    await self._gh.rest.git.async_create_ref(
        owner=self._owner,
        repo=self._name,
        ref=f"refs/heads/{name}",
        sha=base_commit,
    )
    # Get the branch to return proper Branch model
    response = await self._gh.rest.repos.async_get_branch(
        owner=self._owner,
        repo=self._name,
        branch=name,
    )
    return githubkittools.create_branch_model(response.parsed_data)

create_issue_async async

create_issue_async(
    title: str, body: str, labels: list[str] | None = None, assignees: list[str] | None = None
) -> Issue

Create a new issue.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to create issue")
async def create_issue_async(
    self,
    title: str,
    body: str,
    labels: list[str] | None = None,
    assignees: list[str] | None = None,
) -> Issue:
    """Create a new issue."""
    response = await self._gh.rest.issues.async_create(
        owner=self._owner,
        repo=self._name,
        title=title,
        body=body,
        labels=labels or [],
        assignees=assignees,
    )
    return githubkittools.create_issue_model(response.parsed_data)

download_async async

download_async(
    path: str | PathLike[str], destination: JoinablePathLike, recursive: bool = False
) -> None

Download repository content.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to download {path}")
async def download_async(
    self,
    path: str | os.PathLike[str],
    destination: JoinablePathLike,
    recursive: bool = False,
) -> None:
    """Download repository content."""
    from upathtools import to_upath

    dest = to_upath(destination)
    dest.mkdir(exist_ok=True, parents=True)

    resp = await self._gh.rest.repos.async_get_content(
        self._owner,
        self._name,
        str(path),
        headers={"Accept": "application/vnd.github.raw"},
    )
    file_dest = dest / to_upath(path).name
    file_dest.write_bytes(resp.content)

from_url classmethod

from_url(url: str, **kwargs: Any) -> GitHubKitRepository

Create instance from URL.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@classmethod
def from_url(cls, url: str, **kwargs: Any) -> GitHubKitRepository:
    """Create instance from URL."""
    # Remove .git suffix and trailing slashes
    url = url.removesuffix(".git").rstrip("/")
    path = url.split("github.com/", 1)[1]
    owner, name = path.split("/")
    return cls(owner=owner, name=name, token=kwargs.get("token"))

get_branch_async async

get_branch_async(name: str) -> Branch

Get branch information.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to get branch {name}")
async def get_branch_async(self, name: str) -> Branch:
    """Get branch information."""
    resp = await self._gh.rest.repos.async_get_branch(self._owner, self._name, name)
    branch = githubkittools.create_branch_model(resp.parsed_data)
    branch.default = name == self.default_branch
    return branch

get_commit_async async

get_commit_async(sha: str) -> Commit

Get commit by SHA.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to get commit {sha}")
async def get_commit_async(self, sha: str) -> Commit:
    """Get commit by SHA."""
    resp = await self._gh.rest.repos.async_get_commit(self._owner, self._name, sha)
    return githubkittools.create_commit_model(resp.parsed_data)

get_issue_async async

get_issue_async(issue_id: int) -> Issue

Get issue by ID.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to get issue {issue_id}")
async def get_issue_async(self, issue_id: int) -> Issue:
    """Get issue by ID."""
    resp = await self._gh.rest.issues.async_get(self._owner, self._name, issue_id)
    return githubkittools.create_issue_model(resp.parsed_data)

get_languages_async async

get_languages_async() -> dict[str, int]

Get repository language statistics.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to get languages")
async def get_languages_async(self) -> dict[str, int]:
    """Get repository language statistics."""
    resp = await self._gh.rest.repos.async_list_languages(self._owner, self._name)
    return resp.parsed_data.model_dump()

get_latest_release_async async

get_latest_release_async(
    include_drafts: bool = False, include_prereleases: bool = False
) -> Release

Get latest release.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to get latest release")
async def get_latest_release_async(
    self,
    include_drafts: bool = False,
    include_prereleases: bool = False,
) -> Release:
    """Get latest release."""
    from githubkit.exception import GitHubException

    try:
        resp = await self._gh.rest.repos.async_get_latest_release(self._owner, self._name)
        release = resp.parsed_data
        if (not include_drafts and release.draft) or (
            not include_prereleases and release.prerelease
        ):
            msg = "Latest release is draft/prerelease"
            raise ResourceNotFoundError(msg)
        return githubkittools.create_release_model(release)
    except GitHubException as e:
        msg = "No releases found"
        raise ResourceNotFoundError(msg) from e

get_pull_request_async async

get_pull_request_async(number: int) -> PullRequest

Get pull request by number.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to get pull request {number}")
async def get_pull_request_async(self, number: int) -> PullRequest:
    """Get pull request by number."""
    resp = await self._gh.rest.pulls.async_get(self._owner, self._name, number)
    return githubkittools.create_pull_request_model(resp.parsed_data)

get_release_async async

get_release_async(tag: str) -> Release

Get release by tag.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to get release {tag}")
async def get_release_async(self, tag: str) -> Release:
    """Get release by tag."""
    resp = await self._gh.rest.repos.async_get_release_by_tag(self._owner, self._name, tag)
    return githubkittools.create_release_model(resp.parsed_data)

get_repo_user_async async

get_repo_user_async() -> User

Get repository owner information.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to get user info")
async def get_repo_user_async(self) -> User:
    """Get repository owner information."""
    resp = await self._gh.rest.users.async_get_by_username(self._owner)
    return githubkittools.create_user_model(resp.parsed_data)

get_tag_async async

get_tag_async(name: str) -> Tag

Get tag by name.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to get tag {name}")
async def get_tag_async(self, name: str) -> Tag:
    """Get tag by name."""
    from githarbor.core.models import Tag

    ref_resp = await self._gh.rest.git.async_get_ref(self._owner, self._name, f"tags/{name}")
    obj = ref_resp.parsed_data.object_
    if obj.type == "tag":
        resp = await self._gh.rest.git.async_get_tag(self._owner, self._name, obj.sha)
        return githubkittools.create_tag_model(resp.parsed_data)
    return Tag(name=name, sha=obj.sha, url=obj.url)

list_commits_async async

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

List repository commits.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to list commits")
async def list_commits_async(
    self,
    branch: str | None = None,
    since: datetime | None = None,
    until: datetime | None = None,
    author: str | None = None,
    path: str | None = None,
    max_results: int | None = None,
) -> list[Commit]:
    """List repository commits."""
    kwargs: dict[str, Any] = {"sha": branch} if branch else {}
    if since:
        kwargs["since"] = since.isoformat()
    if until:
        kwargs["until"] = until.isoformat()
    if author:
        kwargs["author"] = author
    if path:
        kwargs["path"] = path
    if max_results:
        kwargs["per_page"] = max_results

    resp = await self._gh.rest.repos.async_list_commits(self._owner, self._name, **kwargs)
    return [githubkittools.create_commit_model(c) for c in resp.parsed_data]

list_issues_async async

list_issues_async(state: IssueState = 'open') -> list[Issue]

List repository issues.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to list issues")
async def list_issues_async(self, state: IssueState = "open") -> list[Issue]:
    """List repository issues."""
    resp = await self._gh.rest.issues.async_list_for_repo(
        self._owner,
        self._name,
        state=state,
    )
    data = resp.parsed_data
    return [githubkittools.create_issue_model(issue) for issue in data]

list_pull_requests_async async

list_pull_requests_async(state: PullRequestState = 'open') -> list[PullRequest]

List pull requests.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to list pull requests")
async def list_pull_requests_async(self, state: PullRequestState = "open") -> list[PullRequest]:
    """List pull requests."""
    resp = await self._gh.rest.pulls.async_list(self._owner, self._name, state=state)
    data = resp.parsed_data
    return [githubkittools.create_pull_request_model(pr) for pr in data]

list_releases_async async

list_releases_async(
    include_drafts: bool = False, include_prereleases: bool = False, limit: int | None = None
) -> list[Release]

List releases.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to list releases")
async def list_releases_async(
    self,
    include_drafts: bool = False,
    include_prereleases: bool = False,
    limit: int | None = None,
) -> list[Release]:
    """List releases."""
    resp = await self._gh.rest.repos.async_list_releases(self._owner, self._name)
    releases = []
    for release in resp.parsed_data:
        if not include_drafts and release.draft:
            continue
        if not include_prereleases and release.prerelease:
            continue
        releases.append(githubkittools.create_release_model(release))
        if limit and len(releases) >= limit:
            break
    return releases

list_tags_async async

list_tags_async() -> list[Tag]

List repository tags.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to list tags")
async def list_tags_async(self) -> list[Tag]:
    """List repository tags."""
    resp = await self._gh.rest.repos.async_list_tags(self._owner, self._name)
    return [githubkittools.create_tag_model(tag) for tag in resp.parsed_data]

search_commits_async async

search_commits_async(
    query: str, branch: str | None = None, path: str | None = None, max_results: int | None = None
) -> list[Commit]

Search repository commits.

Source code in src/githarbor/providers/githubkit_provider/repository.py
@githubkittools.handle_githubkit_errors("Failed to search commits")
async def search_commits_async(
    self,
    query: str,
    branch: str | None = None,
    path: str | None = None,
    max_results: int | None = None,
) -> list[Commit]:
    """Search repository commits."""
    search_query = f"repo:{self._owner}/{self._name} {query}"
    if branch:
        search_query += f" ref:{branch}"
    if path:
        search_query += f" path:{path}"

    kwargs: dict[str, Any] = {"q": search_query}
    if max_results:
        kwargs["per_page"] = max_results
    resp = await self._gh.rest.search.async_commits(**kwargs)
    return [githubkittools.create_commit_model(c.commit) for c in resp.parsed_data.items]

GitHubRepository

Bases: BaseRepository

GitHub repository implementation.

Source code in src/githarbor/providers/github_provider/repository.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
class GitHubRepository(BaseRepository):
    """GitHub repository implementation."""

    url_patterns: ClassVar[list[str]] = ["github.com"]
    raw_prefix: ClassVar[str] = "https://raw.githubusercontent.com/{owner}/{name}/{branch}/{path}"

    def __init__(self, owner: str, name: str, token: str | None = None):
        """Initialize GitHub repository."""
        from github import Auth, Github
        from github.GithubException import GithubException

        try:
            t = token or TOKEN
            if t is None:
                logger.info("No GitHub token provided. Stricter rate limit.")
            auth = Auth.Token(t) if t else None
            self._gh = Github(auth=auth)
            self._token = t
            self._repo = self._gh.get_repo(f"{owner}/{name}")
            self._owner = owner
            self._name = name
            self.user: NamedUser.NamedUser = self._gh.get_user(owner)
        except GithubException as e:
            msg = f"GitHub authentication failed: {e!s}"
            raise AuthenticationError(msg) from e

    @classmethod
    def from_url(cls, url: str, **kwargs: Any) -> GitHubRepository:
        """Create from URL like 'https://github.com/owner/repo'."""
        parsed = urlparse(url)
        parts = parsed.path.strip("/").split("/")
        if len(parts) < 2:  # noqa: PLR2004
            msg = f"Invalid GitHub URL: {url}"
            raise ValueError(msg)

        return cls(parts[0], parts[1].removesuffix(".git"), token=kwargs.get("token"))

    @property
    def default_branch(self) -> str:
        return self._repo.default_branch

    @property
    def edit_base_uri(self) -> str:
        return f"edit/{self.default_branch}/"

    @githubtools.handle_github_errors("Failed to get branch {name}")
    def get_branch(self, name: str) -> Branch:
        branch = self._repo.get_branch(name)
        model = githubtools.create_branch_model(branch)
        model.default = branch.name == self.default_branch
        return model

    @githubtools.handle_github_errors("Failed to get pull request {number}")
    def get_pull_request(self, number: int) -> PullRequest:
        pr = self._repo.get_pull(number)
        return githubtools.create_pull_request_model(pr)

    @githubtools.handle_github_errors("Failed to list branches")
    def list_branches(self) -> list[Branch]:
        branches = self._repo.get_branches()
        return [githubtools.create_branch_model(branch) for branch in branches]

    @githubtools.handle_github_errors("Failed to list pull requests")
    def list_pull_requests(self, state: PullRequestState = "open") -> list[PullRequest]:
        prs = self._repo.get_pulls(state=state)
        return [githubtools.create_pull_request_model(pr) for pr in prs]

    @githubtools.handle_github_errors("Failed to get issue {issue_id}")
    def get_issue(self, issue_id: int) -> Issue:
        issue = self._repo.get_issue(issue_id)
        return githubtools.create_issue_model(issue)

    @githubtools.handle_github_errors("Failed to list issues")
    def list_issues(self, state: IssueState = "open") -> list[Issue]:
        issues = self._repo.get_issues(state=state)
        return [githubtools.create_issue_model(issue) for issue in issues]

    @githubtools.handle_github_errors("Failed to create issue")
    def create_issue(
        self,
        title: str,
        body: str,
        labels: list[str] | None = None,
        assignees: list[str] | None = None,
    ) -> Issue:
        """Create a new issue."""
        issue = self._repo.create_issue(
            title=title,
            body=body,
            labels=labels or [],
            assignees=assignees or [],
        )
        return githubtools.create_issue_model(issue)

    @githubtools.handle_github_errors("Failed to get commit {sha}")
    def get_commit(self, sha: str) -> Commit:
        commit = self._repo.get_commit(sha)
        return githubtools.create_commit_model(commit)

    @githubtools.handle_github_errors("Failed to list commits")
    def list_commits(
        self,
        branch: str | None = None,
        since: datetime | None = None,
        until: datetime | None = None,
        author: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        kwargs = {
            "since": since,
            "until": until,
            "author": author,
            "path": path,
            "sha": branch,
        }
        # Filter out None values
        kwargs = {k: v for k, v in kwargs.items() if v is not None}
        commits = self._repo.get_commits(**kwargs)  # type: ignore
        results = commits[:max_results] if max_results else commits
        return [githubtools.create_commit_model(c) for c in results]

    @githubtools.handle_github_errors("Failed to get workflow {workflow_id}")
    def get_workflow(self, workflow_id: str) -> Workflow:
        workflow = self._repo.get_workflow(workflow_id)
        return githubtools.create_workflow_model(workflow)

    @githubtools.handle_github_errors("Failed to list workflows")
    def list_workflows(self) -> list[Workflow]:
        workflows = self._repo.get_workflows()
        return [githubtools.create_workflow_model(w) for w in workflows]

    @githubtools.handle_github_errors("Failed to get workflow run {run_id}")
    def get_workflow_run(self, run_id: str) -> WorkflowRun:
        run = self._repo.get_workflow_run(int(run_id))
        return githubtools.create_workflow_run_model(run)

    @githubtools.handle_github_errors("Failed to download file {path}")
    def download(self, path: str, destination: JoinablePathLike, recursive: bool = False):
        user_name = self._gh.get_user().login if self._token else None
        return githubtools.download_from_github(
            org=self._owner,
            repo=self._name,
            path=path,
            destination=destination,
            username=user_name,
            token=self._token,
            recursive=recursive,
        )

    @githubtools.handle_github_errors("Failed to search commits")
    def search_commits(
        self,
        query: str,
        branch: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        # Build the search query
        from github.Commit import CommitSearchResult

        search_query = f"{query} repo:{self._owner}/{self._name}"
        # Add branch qualifier if specified
        if branch:
            search_query += f" ref:{branch}"
        # Add path qualifier if specified
        if path:
            search_query += f" path:{path}"
        kwargs = {"query": search_query}
        # kwargs = {"query": f"{self._owner}/{self._name}+{query}"}
        # if branch:
        #     kwargs["ref"] = branch
        # if path:
        #     kwargs["path"] = path
        results = self._gh.search_commits(**kwargs)
        return [
            self.get_commit(c.sha) for c in cast(list[CommitSearchResult], results[:max_results])
        ]

    @githubtools.handle_github_errors("Failed to list files for {path}")
    def iter_files(
        self,
        path: str = "",
        ref: str | None = None,
        pattern: str | None = None,
    ) -> Iterator[str]:
        contents = self._repo.get_contents(path, ref=ref or self.default_branch)
        assert isinstance(contents, list)
        kwargs = {"ref": ref} if ref else {}
        while contents:
            content = contents.pop(0)
            if content.type == "dir":
                c = self._repo.get_contents(content.path, **kwargs)
                assert isinstance(c, list)
                contents.extend(c)
            elif not pattern or fnmatch.fnmatch(content.path, pattern):
                yield content.path

    @githubtools.handle_github_errors("Failed to get repository owner info")
    def get_repo_user(self) -> User:
        """Get user (repository owner) information."""
        return githubtools.create_user_model(self.user)

    @githubtools.handle_github_errors("Failed to get contributors")
    def get_contributors(
        self,
        sort_by: Literal["commits", "name", "date"] = "commits",
        limit: int | None = None,
    ) -> list[User]:
        contributors = list(self._repo.get_contributors())
        if sort_by == "name":
            contributors = sorted(contributors, key=lambda c: c.login)
        elif sort_by == "date":
            from datetime import UTC, datetime

            contributors = sorted(
                contributors,
                key=lambda c: c.created_at or datetime.min.replace(tzinfo=UTC),
            )
        contributors = contributors[:limit] if limit else contributors
        return [u for c in contributors if (u := githubtools.create_user_model(c))]

    @githubtools.handle_github_errors("Failed to get languages")
    def get_languages(self) -> dict[str, int]:
        # PyGithub includes the API "url" in the raw response; keep only byte counts.
        return {k: v for k, v in self._repo.get_languages().items() if isinstance(v, int)}

    @githubtools.handle_github_errors("Failed to compare branches")
    def compare_branches(
        self,
        base: str,
        head: str,
        include_commits: bool = True,
        include_files: bool = True,
        include_stats: bool = True,
    ) -> dict[str, Any]:
        comp = self._repo.compare(base, head)
        result: dict[str, Any] = {"ahead_by": comp.ahead_by, "behind_by": comp.behind_by}
        if include_commits:
            result["commits"] = [self.get_commit(c.sha) for c in comp.commits]
        if include_files:
            result["files"] = [f.filename for f in comp.files]
        if include_stats:
            result["stats"] = {
                "additions": sum(f.additions for f in comp.files),
                "deletions": sum(f.deletions for f in comp.files),
                "changes": len(comp.files),
            }
        return result

    @githubtools.handle_github_errors("Failed to get latest release")
    def get_latest_release(
        self,
        include_drafts: bool = False,
        include_prereleases: bool = False,
    ) -> Release:  # Changed from dict[str, Any] to Release
        releases = self._repo.get_releases()
        # Filter releases based on parameters
        filtered = [
            release
            for release in releases
            if (include_drafts or not release.draft)
            and (include_prereleases or not release.prerelease)
        ]
        if not filtered:
            msg = "No matching releases found"
            raise ResourceNotFoundError(msg)
        latest = filtered[0]  # Releases are returned in chronological order
        return githubtools.create_release_model(latest)

    @githubtools.handle_github_errors("Failed to list releases")
    def list_releases(
        self,
        include_drafts: bool = False,
        include_prereleases: bool = False,
        limit: int | None = None,
    ) -> list[Release]:
        filtered_releases = (
            release
            for release in self._repo.get_releases()
            if (include_drafts or not release.draft)
            and (include_prereleases or not release.prerelease)
        )
        return [
            githubtools.create_release_model(release)
            for release in (list(filtered_releases)[:limit] if limit else filtered_releases)
        ]

    @githubtools.handle_github_errors("Failed to get release {tag}")
    def get_release(self, tag: str) -> Release:
        release = self._repo.get_release(tag)
        return githubtools.create_release_model(release)

    @githubtools.handle_github_errors("Failed to get tag {name}")
    def get_tag(self, name: str) -> Tag:
        """Get a specific tag by name."""
        from github.GithubException import GithubException

        try:
            tag = self._repo.get_git_ref(f"tags/{name}")
            tag_obj = self._repo.get_git_tag(tag.object.sha)
            return githubtools.create_tag_model(tag_obj)
        except GithubException as e:
            if e.status == HTML_ERROR_CODE:  # Might be lightweight tag
                commit = self._repo.get_commit(name)
                return githubtools.create_tag_model(commit, name=name)
            raise

    @githubtools.handle_github_errors("Failed to list tags")
    def list_tags(self) -> list[Tag]:
        """List all repository tags."""
        return [githubtools.create_tag_model(tag) for tag in self._repo.get_tags()]

    @githubtools.handle_github_errors("Failed to create pull request")
    def create_pull_request(
        self,
        title: str,
        body: str,
        head_branch: str,
        base_branch: str,
        draft: bool = False,
    ) -> PullRequest:
        pr = self._repo.create_pull(
            title=title,
            body=body,
            head=head_branch,
            base=base_branch,
            draft=draft,
        )
        return githubtools.create_pull_request_model(pr)

    @githubtools.handle_github_errors("Failed to create pull request from diff")
    def create_pull_request_from_diff(
        self,
        title: str,
        body: str,
        base_branch: str,
        diff: str,
        head_branch: str | None = None,
        draft: bool = False,
    ) -> PullRequest:
        """Create a pull request from a diff string."""
        from datetime import datetime
        import uuid

        from github import InputGitTreeElement
        from github.GithubException import GithubException

        from githarbor.core.filechanges import parse_diff
        from githarbor.exceptions import GitHarborError

        # Generate unique branch name if not provided
        if head_branch is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            unique_id = str(uuid.uuid4())[:8]
            head_branch = f"patch/{timestamp}_{unique_id}"

        # Get the base branch's last commit
        base_ref = self._repo.get_git_ref(f"heads/{base_branch}")
        base_commit = self._repo.get_git_commit(base_ref.object.sha)

        # Create a new branch
        try:
            head_ref = self._repo.get_git_ref(f"heads/{head_branch}")
            msg = f"Branch {head_branch} already exists"
            raise GitHarborError(msg)
        except GithubException:
            ref = f"refs/heads/{head_branch}"
            head_ref = self._repo.create_git_ref(ref=ref, sha=base_ref.object.sha)

        # Parse the diff and apply changes
        changes = parse_diff(diff)

        # Create blobs and trees for the changes
        new_tree: list[InputGitTreeElement] = []
        for change in changes:
            if change.mode == "delete":
                # For deletions, we add a null SHA
                elem = InputGitTreeElement(
                    path=change.path,
                    mode="100644",
                    type="blob",
                    sha=None,
                )
                new_tree.append(elem)
                continue

            if change.content is not None:
                # Create blob for the file content
                blob = self._repo.create_git_blob(content=change.content, encoding="utf-8")

                if change.old_path:
                    # For renamed files, we need to remove the old path
                    elem = InputGitTreeElement(
                        path=change.old_path,
                        mode="100644",
                        type="blob",
                        sha=None,
                    )
                    new_tree.append(elem)

                elem = InputGitTreeElement(
                    path=change.path,
                    mode="100644",
                    type="blob",
                    sha=blob.sha,
                )
                new_tree.append(elem)

        # Create a new tree
        base_tree = self._repo.get_git_tree(base_commit.tree.sha)
        tree = self._repo.create_git_tree(new_tree, base_tree)

        # Create a commit
        msg = f"Changes for {title}"
        commit = self._repo.create_git_commit(msg, tree=tree, parents=[base_commit])

        # Update the reference
        head_ref.edit(commit.sha, force=True)

        # Create the pull request
        pr = self._repo.create_pull(
            title=title,
            body=body,
            base=base_branch,
            head=head_branch,
            draft=draft,
        )
        return githubtools.create_pull_request_model(pr)

    @githubtools.handle_github_errors("Failed to create branch")
    def create_branch(
        self,
        name: str,
        base_commit: str,
    ) -> Branch:
        """Create a new branch at the specified commit."""
        # Create reference with full ref name
        _ref = self._repo.create_git_ref(
            ref=f"refs/heads/{name}",
            sha=base_commit,
        )
        # Get the branch to return proper Branch model
        branch = self._repo.get_branch(name)
        return githubtools.create_branch_model(branch)

    @githubtools.handle_github_errors("Failed to add pull request comment")
    def add_pull_request_comment(
        self,
        number: int,
        body: str,
    ) -> Comment:
        pr = self._repo.get_pull(number)
        comment = pr.create_issue_comment(body)
        return githubtools.create_comment_model(comment)

    @githubtools.handle_github_errors("Failed to add pull request review comment")
    def add_pull_request_review_comment(
        self,
        number: int,
        body: str,
        commit_id: str,
        path: str,
        position: int,
    ) -> Comment:
        pr = self._repo.get_pull(number)
        commit = self._repo.get_commit(commit_id)
        comment = pr.create_review_comment(body, commit, path, line=position)
        return githubtools.create_comment_model(comment)

__init__

__init__(owner: str, name: str, token: str | None = None)

Initialize GitHub repository.

Source code in src/githarbor/providers/github_provider/repository.py
def __init__(self, owner: str, name: str, token: str | None = None):
    """Initialize GitHub repository."""
    from github import Auth, Github
    from github.GithubException import GithubException

    try:
        t = token or TOKEN
        if t is None:
            logger.info("No GitHub token provided. Stricter rate limit.")
        auth = Auth.Token(t) if t else None
        self._gh = Github(auth=auth)
        self._token = t
        self._repo = self._gh.get_repo(f"{owner}/{name}")
        self._owner = owner
        self._name = name
        self.user: NamedUser.NamedUser = self._gh.get_user(owner)
    except GithubException as e:
        msg = f"GitHub authentication failed: {e!s}"
        raise AuthenticationError(msg) from e

create_branch

create_branch(name: str, base_commit: str) -> Branch

Create a new branch at the specified commit.

Source code in src/githarbor/providers/github_provider/repository.py
@githubtools.handle_github_errors("Failed to create branch")
def create_branch(
    self,
    name: str,
    base_commit: str,
) -> Branch:
    """Create a new branch at the specified commit."""
    # Create reference with full ref name
    _ref = self._repo.create_git_ref(
        ref=f"refs/heads/{name}",
        sha=base_commit,
    )
    # Get the branch to return proper Branch model
    branch = self._repo.get_branch(name)
    return githubtools.create_branch_model(branch)

create_issue

create_issue(
    title: str, body: str, labels: list[str] | None = None, assignees: list[str] | None = None
) -> Issue

Create a new issue.

Source code in src/githarbor/providers/github_provider/repository.py
@githubtools.handle_github_errors("Failed to create issue")
def create_issue(
    self,
    title: str,
    body: str,
    labels: list[str] | None = None,
    assignees: list[str] | None = None,
) -> Issue:
    """Create a new issue."""
    issue = self._repo.create_issue(
        title=title,
        body=body,
        labels=labels or [],
        assignees=assignees or [],
    )
    return githubtools.create_issue_model(issue)

create_pull_request_from_diff

create_pull_request_from_diff(
    title: str,
    body: str,
    base_branch: str,
    diff: str,
    head_branch: str | None = None,
    draft: bool = False,
) -> PullRequest

Create a pull request from a diff string.

Source code in src/githarbor/providers/github_provider/repository.py
@githubtools.handle_github_errors("Failed to create pull request from diff")
def create_pull_request_from_diff(
    self,
    title: str,
    body: str,
    base_branch: str,
    diff: str,
    head_branch: str | None = None,
    draft: bool = False,
) -> PullRequest:
    """Create a pull request from a diff string."""
    from datetime import datetime
    import uuid

    from github import InputGitTreeElement
    from github.GithubException import GithubException

    from githarbor.core.filechanges import parse_diff
    from githarbor.exceptions import GitHarborError

    # Generate unique branch name if not provided
    if head_branch is None:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        unique_id = str(uuid.uuid4())[:8]
        head_branch = f"patch/{timestamp}_{unique_id}"

    # Get the base branch's last commit
    base_ref = self._repo.get_git_ref(f"heads/{base_branch}")
    base_commit = self._repo.get_git_commit(base_ref.object.sha)

    # Create a new branch
    try:
        head_ref = self._repo.get_git_ref(f"heads/{head_branch}")
        msg = f"Branch {head_branch} already exists"
        raise GitHarborError(msg)
    except GithubException:
        ref = f"refs/heads/{head_branch}"
        head_ref = self._repo.create_git_ref(ref=ref, sha=base_ref.object.sha)

    # Parse the diff and apply changes
    changes = parse_diff(diff)

    # Create blobs and trees for the changes
    new_tree: list[InputGitTreeElement] = []
    for change in changes:
        if change.mode == "delete":
            # For deletions, we add a null SHA
            elem = InputGitTreeElement(
                path=change.path,
                mode="100644",
                type="blob",
                sha=None,
            )
            new_tree.append(elem)
            continue

        if change.content is not None:
            # Create blob for the file content
            blob = self._repo.create_git_blob(content=change.content, encoding="utf-8")

            if change.old_path:
                # For renamed files, we need to remove the old path
                elem = InputGitTreeElement(
                    path=change.old_path,
                    mode="100644",
                    type="blob",
                    sha=None,
                )
                new_tree.append(elem)

            elem = InputGitTreeElement(
                path=change.path,
                mode="100644",
                type="blob",
                sha=blob.sha,
            )
            new_tree.append(elem)

    # Create a new tree
    base_tree = self._repo.get_git_tree(base_commit.tree.sha)
    tree = self._repo.create_git_tree(new_tree, base_tree)

    # Create a commit
    msg = f"Changes for {title}"
    commit = self._repo.create_git_commit(msg, tree=tree, parents=[base_commit])

    # Update the reference
    head_ref.edit(commit.sha, force=True)

    # Create the pull request
    pr = self._repo.create_pull(
        title=title,
        body=body,
        base=base_branch,
        head=head_branch,
        draft=draft,
    )
    return githubtools.create_pull_request_model(pr)

from_url classmethod

from_url(url: str, **kwargs: Any) -> GitHubRepository

Create from URL like 'https://github.com/owner/repo'.

Source code in src/githarbor/providers/github_provider/repository.py
@classmethod
def from_url(cls, url: str, **kwargs: Any) -> GitHubRepository:
    """Create from URL like 'https://github.com/owner/repo'."""
    parsed = urlparse(url)
    parts = parsed.path.strip("/").split("/")
    if len(parts) < 2:  # noqa: PLR2004
        msg = f"Invalid GitHub URL: {url}"
        raise ValueError(msg)

    return cls(parts[0], parts[1].removesuffix(".git"), token=kwargs.get("token"))

get_repo_user

get_repo_user() -> User

Get user (repository owner) information.

Source code in src/githarbor/providers/github_provider/repository.py
@githubtools.handle_github_errors("Failed to get repository owner info")
def get_repo_user(self) -> User:
    """Get user (repository owner) information."""
    return githubtools.create_user_model(self.user)

get_tag

get_tag(name: str) -> Tag

Get a specific tag by name.

Source code in src/githarbor/providers/github_provider/repository.py
@githubtools.handle_github_errors("Failed to get tag {name}")
def get_tag(self, name: str) -> Tag:
    """Get a specific tag by name."""
    from github.GithubException import GithubException

    try:
        tag = self._repo.get_git_ref(f"tags/{name}")
        tag_obj = self._repo.get_git_tag(tag.object.sha)
        return githubtools.create_tag_model(tag_obj)
    except GithubException as e:
        if e.status == HTML_ERROR_CODE:  # Might be lightweight tag
            commit = self._repo.get_commit(name)
            return githubtools.create_tag_model(commit, name=name)
        raise

list_tags

list_tags() -> list[Tag]

List all repository tags.

Source code in src/githarbor/providers/github_provider/repository.py
@githubtools.handle_github_errors("Failed to list tags")
def list_tags(self) -> list[Tag]:
    """List all repository tags."""
    return [githubtools.create_tag_model(tag) for tag in self._repo.get_tags()]

GitLabRepository

Bases: BaseRepository

GitLab repository implementation.

Source code in src/githarbor/providers/gitlab_provider/repository.py
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
class GitLabRepository(BaseRepository):
    """GitLab repository implementation."""

    url_patterns: ClassVar[list[str]] = ["gitlab.com"]

    def __init__(
        self,
        owner: str,
        name: str,
        token: str | None = None,
        url: str = "https://gitlab.com",
    ):
        import gitlab
        from gitlab.exceptions import GitlabAuthenticationError

        try:
            t = token or os.getenv("GITLAB_TOKEN")
            if not t:
                msg = "GitLab token is required"
                raise ValueError(msg)

            self._gl = gitlab.Gitlab(url=url, private_token=t)
            self._gl.auth()
            self._repo = self._gl.projects.get(f"{owner}/{name}")
            self._owner = owner
            self._name = name

        except GitlabAuthenticationError as e:
            msg = f"GitLab authentication failed: {e!s}"
            raise AuthenticationError(msg) from e

    @classmethod
    def from_url(cls, url: str, **kwargs: Any) -> GitLabRepository:
        """Create from URL like 'https://gitlab.com/owner/repo'."""
        parsed = urlparse(url)
        parts = parsed.path.strip("/").split("/")
        if len(parts) < 2:  # noqa: PLR2004
            msg = f"Invalid GitLab URL: {url}"
            raise ValueError(msg)
        url_ = f"{parsed.scheme}://{parsed.netloc}"
        return cls(owner=parts[0], name=parts[1], token=kwargs.get("token"), url=url_)

    @property
    def default_branch(self) -> str:
        return self._repo.default_branch

    @property
    def edit_base_uri(self) -> str:
        return f"edit/{self.default_branch}/"

    @gitlabtools.handle_gitlab_errors("Failed to get user info")
    def get_repo_user(self) -> User:
        """Get user (repository owner) information."""
        users = self._gl.users.list(username=self._owner)
        if not users:
            msg = f"User {self._owner!r} not found"
            raise ResourceNotFoundError(msg)
        return gitlabtools.create_user_model(users[0])

    @gitlabtools.handle_gitlab_errors("Branch {name} not found")
    def get_branch(self, name: str) -> Branch:
        branch = self._repo.branches.get(name)
        return Branch(
            name=branch.name,
            sha=branch.commit["id"],
            protected=branch.protected,
            created_at=None,  # GitLab doesn't provide branch creation date
            updated_at=None,  # GitLab doesn't provide branch update date
        )

    @gitlabtools.handle_gitlab_errors("Merge request #{number} not found")
    def get_pull_request(self, number: int) -> PullRequest:
        mr = self._repo.mergerequests.get(number)
        return gitlabtools.create_pull_request_model(mr)

    @gitlabtools.handle_gitlab_errors("Failed to list merge requests")
    def list_pull_requests(self, state: PullRequestState = "open") -> list[PullRequest]:
        gl_state = "opened" if state == "open" else state
        mrs = self._repo.mergerequests.list(state=gl_state, get_all=True)
        return [gitlabtools.create_pull_request_model(mr) for mr in mrs]

    @gitlabtools.handle_gitlab_errors("Failed to list branches")
    def list_branches(self) -> list[Branch]:
        branches = self._repo.branches.list(get_all=True)
        return [gitlabtools.create_branch_model(branch) for branch in branches]

    @gitlabtools.handle_gitlab_errors("Issue #{issue_id} not found")
    def get_issue(self, issue_id: int) -> Issue:
        issue = self._repo.issues.get(issue_id)
        return gitlabtools.create_issue_model(issue)

    @gitlabtools.handle_gitlab_errors("Failed to list issues")
    def list_issues(self, state: IssueState = "open") -> list[Issue]:
        gl_state = "opened" if state == "open" else state
        issues = self._repo.issues.list(state=gl_state, get_all=True)
        return [gitlabtools.create_issue_model(issue) for issue in issues]

    @gitlabtools.handle_gitlab_errors("Failed to create issue")
    def create_issue(
        self,
        title: str,
        body: str,
        labels: list[str] | None = None,
        assignees: list[str] | None = None,
    ) -> Issue:
        """Create a new issue."""
        data: dict[str, Any] = {"title": title, "description": body}
        if labels:
            data["labels"] = ",".join(labels)
        if assignees:
            # GitLab API expects assignee_ids
            ids_ = [self._gl.users.list(username=n)[0].id for n in assignees]
            data["assignee_ids"] = ids_

        issue = self._repo.issues.create(data)
        return gitlabtools.create_issue_model(issue)

    @gitlabtools.handle_gitlab_errors("Commit {sha} not found")
    def get_commit(self, sha: str) -> Commit:
        commit = self._repo.commits.get(sha)
        return gitlabtools.create_commit_model(commit)

    @gitlabtools.handle_gitlab_errors("Failed to list commits")
    def list_commits(
        self,
        branch: str | None = None,
        since: datetime | None = None,
        until: datetime | None = None,
        author: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        kwargs: dict[str, Any] = {}
        if branch:
            kwargs["ref_name"] = branch
        if since:
            kwargs["since"] = since.isoformat()
        if until:
            kwargs["until"] = until.isoformat()
        if path:
            kwargs["path"] = path
        if author:
            kwargs["author"] = author
        if max_results:
            kwargs["per_page"] = max_results
            kwargs["page"] = 1
        else:
            kwargs["get_all"] = True

        commits = self._repo.commits.list(**kwargs)
        # Convert to list to materialize the results
        commits = list(commits)
        return [gitlabtools.create_commit_model(commit) for commit in commits]

    @gitlabtools.handle_gitlab_errors("Pipeline {workflow_id} not found")
    def get_workflow(self, workflow_id: str) -> Workflow:
        pipeline = self._repo.pipelines.get(workflow_id)
        return gitlabtools.create_workflow_model(pipeline)

    @gitlabtools.handle_gitlab_errors("Failed to list pipelines")
    def list_workflows(self) -> list[Workflow]:
        pipelines = self._repo.pipelines.list()
        return [gitlabtools.create_workflow_model(pipeline) for pipeline in pipelines]

    @gitlabtools.handle_gitlab_errors("Job {run_id} not found")
    def get_workflow_run(self, run_id: str) -> WorkflowRun:
        job = self._repo.jobs.get(run_id)
        return gitlabtools.create_workflow_run_model(job)

    @gitlabtools.handle_gitlab_errors("Failed to download {path}")
    def download(self, path: str, destination: JoinablePathLike, recursive: bool = False) -> None:
        dest = to_upath(destination)
        dest.mkdir(exist_ok=True, parents=True)

        if recursive:
            # For recursive downloads, we need to get all files in the directory
            items = self._repo.repository_tree(path=str(path), recursive=True)
            for item in items:
                if item["type"] == "blob":  # Only download files, not directories
                    file_path = item["path"]
                    content = self._repo.files.get(file_path=file_path, ref=self.default_branch)
                    # Create subdirectories if needed
                    file_dest = dest / file_path
                    file_dest.parent.mkdir(exist_ok=True, parents=True)
                    # Save the file content
                    file_dest.write_bytes(content.decode())
        else:
            # For single file download
            content = self._repo.files.get(file_path=str(path), ref=self.default_branch)
            file_dest = dest / to_upath(path).name
            file_dest.write_bytes(content.decode())

    @gitlabtools.handle_gitlab_errors("Failed to search commits")
    def search_commits(
        self,
        query: str,
        branch: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        kwargs: dict[str, Any] = {}
        if branch:
            kwargs["ref_name"] = branch
        if path:
            kwargs["path"] = path
        if max_results:
            kwargs["per_page"] = max_results
            kwargs["page"] = 1
        else:
            kwargs["get_all"] = True
        commits = list(self._repo.commits.list(search=query, **kwargs))
        if max_results:
            commits = commits[:max_results]
        return [gitlabtools.create_commit_model(commit) for commit in commits]

    @gitlabtools.handle_gitlab_errors("Failed to iter files from {path}")
    def iter_files(
        self,
        path: str = "",
        ref: str | None = None,
        pattern: str | None = None,
    ) -> Iterator[str]:
        ref_ = ref or self.default_branch
        items = self._repo.repository_tree(path=path, ref=ref_, recursive=True)
        for item in items:
            if item["type"] == "blob" and (not pattern or fnmatch.fnmatch(item["path"], pattern)):
                yield item["path"]

    @gitlabtools.handle_gitlab_errors("Failed to get contributors")
    def get_contributors(
        self,
        sort_by: Literal["commits", "name", "date"] = "commits",
        limit: int | None = None,
    ) -> list[User]:
        order_by = "name" if sort_by == "name" else "commits"
        sort_dir = "asc" if sort_by == "name" else "desc"
        contributors = self._repo.repository_contributors(
            order_by=order_by,
            sort=sort_dir,
            get_all=True,
        )
        assert isinstance(contributors, list)
        if limit:
            contributors = contributors[:limit]
        return [
            User(
                username=c["name"],
                name=c["name"],
                email=c.get("email"),
            )
            for c in contributors
        ]

    @gitlabtools.handle_gitlab_errors("Failed to get languages")
    def get_languages(self) -> dict[str, int]:
        response = self._repo.languages()
        return response if isinstance(response, dict) else response.json()

    @gitlabtools.handle_gitlab_errors("Failed to compare branches {base} and {head}")
    def compare_branches(
        self,
        base: str,
        head: str,
        include_commits: bool = True,
        include_files: bool = True,
        include_stats: bool = True,
    ) -> dict[str, Any]:
        comparison = self._repo.repository_compare(base, head)
        assert isinstance(comparison, dict)
        result: dict[str, Any] = {"ahead_by": len(comparison["commits"])}
        if include_commits:
            result["commits"] = [
                Commit(
                    sha=c["id"],
                    message=c["message"],
                    created_at=gitlabtools.parse_timestamp(c["created_at"]),
                    author=User(
                        username=c["author_name"],
                        email=c["author_email"],
                        name=c["author_name"],
                    ),
                    url=c["web_url"],
                )
                for c in comparison["commits"]
            ]
        if include_files:
            result["files"] = [f["new_path"] for f in comparison["diffs"]]
        if include_stats:
            # Parse diff strings to count additions/deletions
            additions = deletions = 0
            for diff in comparison["diffs"]:
                diff_text = diff["diff"]
                for line in diff_text.splitlines():
                    if line.startswith("+") and not line.startswith("+++"):
                        additions += 1
                    elif line.startswith("-") and not line.startswith("---"):
                        deletions += 1
            result["stats"] = {
                "additions": additions,
                "deletions": deletions,
                "changes": len(comparison["diffs"]),
            }
        return result

    @gitlabtools.handle_gitlab_errors("Failed to get latest release")
    def get_latest_release(
        self,
        include_drafts: bool = False,
        include_prereleases: bool = False,
    ) -> Release:
        releases = self._repo.releases.list()

        if not releases:
            msg = "No releases found"
            raise ResourceNotFoundError(msg)

        # Filter releases
        filtered: list[RESTObject] = []
        for release in releases:
            # GitLab doesn't have draft releases
            if not include_prereleases and release.tag_name.startswith(PRE_TAGS):
                continue
            filtered.append(release)

        if not filtered:
            msg = "No matching releases found"
            raise ResourceNotFoundError(msg)

        latest = filtered[0]  # GitLab returns in descending order
        return gitlabtools.create_release_model(latest)

    @gitlabtools.handle_gitlab_errors("Failed to list releases")
    def list_releases(
        self,
        include_drafts: bool = False,
        include_prereleases: bool = False,
        limit: int | None = None,
    ) -> list[Release]:
        releases: list[Release] = []
        for release in self._repo.releases.list():
            if not include_prereleases and release.tag_name.startswith(PRE_TAGS):
                continue
            releases.append(gitlabtools.create_release_model(release))
            if limit and len(releases) >= limit:
                break
        return releases

    @gitlabtools.handle_gitlab_errors("Release with tag {tag} not found")
    def get_release(self, tag: str) -> Release:
        release = self._repo.releases.get(tag)
        return gitlabtools.create_release_model(release)

    @gitlabtools.handle_gitlab_errors("Failed to get tag {name}")
    def get_tag(self, name: str) -> Tag:
        """Get a specific tag by name."""
        tag = self._repo.tags.get(name)
        return gitlabtools.create_tag_model(tag)

    @gitlabtools.handle_gitlab_errors("Failed to list tags")
    def list_tags(self) -> list[Tag]:
        """List all repository tags."""
        return [gitlabtools.create_tag_model(tag) for tag in self._repo.tags.list()]

    @gitlabtools.handle_gitlab_errors("Failed to create merge request")
    def create_pull_request(
        self,
        title: str,
        body: str,
        head_branch: str,
        base_branch: str,
        draft: bool = False,
    ) -> PullRequest:
        mr_title = f"Draft: {title}" if draft and not title.startswith("Draft:") else title
        mr = self._repo.mergerequests.create({
            "title": mr_title,
            "description": body,
            "source_branch": head_branch,
            "target_branch": base_branch,
        })
        return gitlabtools.create_pull_request_model(mr)

    @gitlabtools.handle_gitlab_errors("Failed to create branch")
    def create_branch(self, name: str, base_commit: str) -> Branch:
        """Create a new branch at the specified commit."""
        branch = self._repo.branches.create({"branch": name, "ref": base_commit})
        return gitlabtools.create_branch_model(branch)

    @gitlabtools.handle_gitlab_errors("Failed to add merge request comment")
    def add_pull_request_comment(self, number: int, body: str) -> Comment:
        mr = self._repo.mergerequests.get(number)
        note = mr.notes.create({"body": body})
        return gitlabtools.create_comment_model(note)

    @gitlabtools.handle_gitlab_errors("Failed to add merge request review comment")
    def add_pull_request_review_comment(
        self,
        number: int,
        body: str,
        commit_id: str,
        path: str,
        position: int,
    ) -> Comment:
        mr = self._repo.mergerequests.get(number)
        pos = {
            "position_type": "text",
            "new_path": path,
            "new_line": position,
            "head_sha": commit_id,
            # GitLab requires these, we'll use the same commit SHA
            "base_sha": commit_id,
            "start_sha": commit_id,
        }
        discussion = mr.discussions.create({"body": body, "position": pos})
        # Discussion contains the note as first element
        return gitlabtools.create_comment_model(discussion.attributes["notes"][0])

create_branch

create_branch(name: str, base_commit: str) -> Branch

Create a new branch at the specified commit.

Source code in src/githarbor/providers/gitlab_provider/repository.py
@gitlabtools.handle_gitlab_errors("Failed to create branch")
def create_branch(self, name: str, base_commit: str) -> Branch:
    """Create a new branch at the specified commit."""
    branch = self._repo.branches.create({"branch": name, "ref": base_commit})
    return gitlabtools.create_branch_model(branch)

create_issue

create_issue(
    title: str, body: str, labels: list[str] | None = None, assignees: list[str] | None = None
) -> Issue

Create a new issue.

Source code in src/githarbor/providers/gitlab_provider/repository.py
@gitlabtools.handle_gitlab_errors("Failed to create issue")
def create_issue(
    self,
    title: str,
    body: str,
    labels: list[str] | None = None,
    assignees: list[str] | None = None,
) -> Issue:
    """Create a new issue."""
    data: dict[str, Any] = {"title": title, "description": body}
    if labels:
        data["labels"] = ",".join(labels)
    if assignees:
        # GitLab API expects assignee_ids
        ids_ = [self._gl.users.list(username=n)[0].id for n in assignees]
        data["assignee_ids"] = ids_

    issue = self._repo.issues.create(data)
    return gitlabtools.create_issue_model(issue)

from_url classmethod

from_url(url: str, **kwargs: Any) -> GitLabRepository

Create from URL like 'https://gitlab.com/owner/repo'.

Source code in src/githarbor/providers/gitlab_provider/repository.py
@classmethod
def from_url(cls, url: str, **kwargs: Any) -> GitLabRepository:
    """Create from URL like 'https://gitlab.com/owner/repo'."""
    parsed = urlparse(url)
    parts = parsed.path.strip("/").split("/")
    if len(parts) < 2:  # noqa: PLR2004
        msg = f"Invalid GitLab URL: {url}"
        raise ValueError(msg)
    url_ = f"{parsed.scheme}://{parsed.netloc}"
    return cls(owner=parts[0], name=parts[1], token=kwargs.get("token"), url=url_)

get_repo_user

get_repo_user() -> User

Get user (repository owner) information.

Source code in src/githarbor/providers/gitlab_provider/repository.py
@gitlabtools.handle_gitlab_errors("Failed to get user info")
def get_repo_user(self) -> User:
    """Get user (repository owner) information."""
    users = self._gl.users.list(username=self._owner)
    if not users:
        msg = f"User {self._owner!r} not found"
        raise ResourceNotFoundError(msg)
    return gitlabtools.create_user_model(users[0])

get_tag

get_tag(name: str) -> Tag

Get a specific tag by name.

Source code in src/githarbor/providers/gitlab_provider/repository.py
@gitlabtools.handle_gitlab_errors("Failed to get tag {name}")
def get_tag(self, name: str) -> Tag:
    """Get a specific tag by name."""
    tag = self._repo.tags.get(name)
    return gitlabtools.create_tag_model(tag)

list_tags

list_tags() -> list[Tag]

List all repository tags.

Source code in src/githarbor/providers/gitlab_provider/repository.py
@gitlabtools.handle_gitlab_errors("Failed to list tags")
def list_tags(self) -> list[Tag]:
    """List all repository tags."""
    return [gitlabtools.create_tag_model(tag) for tag in self._repo.tags.list()]

GiteaRepository

Bases: BaseRepository

Gitea repository implementation.

Source code in src/githarbor/providers/gitea_provider/repository.py
class GiteaRepository(BaseRepository):
    """Gitea repository implementation."""

    url_patterns: ClassVar[list[str]] = [
        "gitea.com",
        "codeberg.org",
    ]  # Add your Gitea instances here

    def __init__(
        self,
        owner: str,
        name: str,
        token: str | None = None,
        url: str = "https://gitea.com",
    ):
        import giteapy
        from giteapy.rest import ApiException

        t = token or os.getenv("GITEA_TOKEN")
        if not t:
            msg = "Gitea token is required"
            raise ValueError(msg)
        configuration = giteapy.Configuration()
        configuration.host = url.rstrip("/") + "/api/v1"
        configuration.api_key["token"] = t
        # configuration.temp_folder_path = ...
        self._owner = owner
        self._name = name
        try:
            self._api = giteapy.ApiClient(configuration)
            self._org_api = giteapy.OrganizationApi(self._api)
            self._repo_api = giteapy.RepositoryApi(self._api)
            self._issues_api = giteapy.IssueApi(self._api)
            self._user_api = giteapy.UserApi(self._api)
            # Verify access and get repo info
            self._repo: giteapy.Repository = self._repo_api.repo_get(owner, name)
        except ApiException as e:
            msg = f"Gitea authentication failed: {e!s}"
            raise AuthenticationError(msg) from e

    @classmethod
    def from_url(cls, url: str, **kwargs: Any) -> GiteaRepository:
        """Create from URL like 'https://gitea.com/owner/repo'."""
        parsed = urlparse(url)
        parts = parsed.path.strip("/").split("/")
        if len(parts) < 2:  # noqa: PLR2004
            msg = f"Invalid Gitea URL: {url}"
            raise ValueError(msg)
        url = f"{parsed.scheme}://{parsed.netloc}"
        return cls(owner=parts[0], name=parts[1], token=kwargs.get("token"), url=url)

    @property
    def default_branch(self) -> str:
        return self._repo.default_branch

    @property
    def edit_base_uri(self) -> str:
        return f"_edit/{self.default_branch}/"

    @giteatools.handle_api_errors("Failed to get branch")
    def get_branch(self, name: str) -> Branch:
        """Get a specific branch by name."""
        branch = self._repo_api.repo_get_branch(self._owner, self._name, name)
        return giteatools.create_branch_model(branch)

    @giteatools.handle_api_errors("Failed to get repository owner info")
    def get_repo_user(self) -> User:
        """Get user (repository owner) information."""
        user = self._user_api.user_get(self._owner)
        return giteatools.create_user_model(user)

    @giteatools.handle_api_errors("Failed to get pull request")
    def get_pull_request(self, number: int) -> PullRequest:
        """Get a specific pull request by number."""
        pr = self._repo_api.repo_get_pull_request(self._owner, self._name, number)
        return giteatools.create_pull_request_model(pr)

    @giteatools.handle_api_errors("Failed to list pull requests")
    def list_pull_requests(self, state: PullRequestState = "open") -> list[PullRequest]:
        """List pull requests."""
        prs = self._repo_api.repo_list_pull_requests(
            self._owner,
            self._name,
            state=state,
        )
        assert isinstance(prs, list)
        return [giteatools.create_pull_request_model(pr) for pr in prs]  # pyright: ignore

    @giteatools.handle_api_errors("Failed to list branches")
    def list_branches(self) -> list[Branch]:
        branches = self._repo_api.repo_list_branches(self._owner, self._name)
        assert isinstance(branches, list)
        return [giteatools.create_branch_model(branch) for branch in branches]  # pyright: ignore

    @giteatools.handle_api_errors("Failed to get issue")
    def get_issue(self, issue_id: int) -> Issue:
        """Get a specific issue by ID."""
        issue: giteapy.Issue = self._issues_api.issue_get_issue(self._owner, self._name, issue_id)
        return giteatools.create_issue_model(issue)

    @giteatools.handle_api_errors("Failed to list issues")
    def list_issues(self, state: IssueState = "open") -> list[Issue]:
        """List repository issues."""
        issues: list[giteapy.Issue] = self._issues_api.issue_list_issues(
            self._owner,
            self._name,
            state=state,
        )
        return [giteatools.create_issue_model(issue) for issue in issues]

    @giteatools.handle_api_errors("Failed to create issue")
    def create_issue(
        self,
        title: str,
        body: str,
        labels: list[str] | None = None,
        assignees: list[str] | None = None,
    ) -> Issue:
        """Create a new issue."""
        params: dict[str, Any] = {
            "title": title,
            "body": body,
        }
        if labels:
            params["labels"] = labels
        if assignees:
            params["assignees"] = assignees

        issue = self._issues_api.issue_create_issue(
            owner=self._owner,
            repo=self._name,
            body=params,
        )
        return giteatools.create_issue_model(issue)

    @giteatools.handle_api_errors("Failed to get commit")
    def get_commit(self, sha: str) -> Commit:
        """Get a specific commit by SHA."""
        commit: giteapy.Commit = self._repo_api.repo_get_single_commit(self._owner, self._name, sha)
        return giteatools.create_commit_model(commit)

    @giteatools.handle_api_errors("Failed to list commits")
    def list_commits(
        self,
        branch: str | None = None,
        since: datetime | None = None,
        until: datetime | None = None,
        author: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        """List repository commits with optional filters."""
        if path:
            msg = "Filtering commits by path is not supported for Gitea"
            raise FeatureNotSupportedError(msg)
        kwargs: dict[str, Any] = {}
        if branch:
            kwargs["sha"] = branch

        commits = self._repo_api.repo_get_all_commits(self._owner, self._name, **kwargs)
        assert isinstance(commits, list)

        models = [giteatools.create_commit_model(commit) for commit in commits]
        if since:
            models = [m for m in models if m.created_at and m.created_at >= since]
        if until:
            models = [m for m in models if m.created_at and m.created_at <= until]
        if author:
            models = [
                m
                for m in models
                if m.author
                and (author in (m.author.name or "") or author in (m.author.email or ""))
            ]
        if max_results:
            models = models[:max_results]

        return models

    @giteatools.handle_api_errors("Failed to download file")
    def download(self, path: str, destination: JoinablePathLike, recursive: bool = False) -> None:
        """Download repository contents."""
        import base64

        from upathtools import to_upath

        dest = to_upath(destination)
        dest.mkdir(exist_ok=True, parents=True)

        def _decode_content(file_content: Any) -> bytes:
            raw = file_content.content or ""
            if getattr(file_content, "encoding", "base64") == "base64":
                return base64.b64decode(raw)
            return raw.encode()

        if recursive:
            contents = self._list_contents(str(path), self.default_branch)

            for content in contents:
                if content.type == "file":
                    file_content = self._repo_api.repo_get_contents(
                        self._owner,
                        self._name,
                        content.path,
                        ref=self.default_branch,
                    )
                    file_dest = dest / content.path
                    file_dest.parent.mkdir(exist_ok=True, parents=True)
                    file_dest.write_bytes(_decode_content(file_content))
        else:
            content = self._repo_api.repo_get_contents(
                self._owner,
                self._name,
                str(path),
                ref=self.default_branch,
            )
            file_dest = dest / to_upath(path).name
            file_dest.write_bytes(_decode_content(content))

    @giteatools.handle_api_errors("Failed to search commits")
    def search_commits(
        self,
        query: str,
        branch: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        """Search repository commits."""
        # giteapy has no commit search endpoint, so filter commit messages client-side.
        if path:
            msg = "Filtering commit search by path is not supported for Gitea"
            raise FeatureNotSupportedError(msg)
        kwargs = {"sha": branch} if branch else {}
        commits = self._repo_api.repo_get_all_commits(self._owner, self._name, **kwargs)
        query_lower = query.lower()
        matches = [c for c in commits if query_lower in (c.commit.message or "").lower()]
        if max_results:
            matches = matches[:max_results]
        return [giteatools.create_commit_model(commit) for commit in matches]

    def _list_contents(self, path: str, ref: str) -> list[Any]:
        """List the entries of a directory (giteapy only supports the root dir)."""
        path = path.strip("/")
        if not path:
            return self._repo_api.repo_get_contents_list(self._owner, self._name, ref=ref)
        return self._api.call_api(
            "/repos/{owner}/{repo}/contents/{filepath}",
            "GET",
            {"owner": self._owner, "repo": self._name, "filepath": path},
            [("ref", ref)],
            {"Accept": "application/json"},
            response_type="list[ContentsResponse]",
            auth_settings=["AccessToken", "AuthorizationHeaderToken", "BasicAuth", "Token"],
            _return_http_data_only=True,
        )

    @giteatools.handle_api_errors("Failed to list files")
    def iter_files(
        self,
        path: str = "",
        ref: str | None = None,
        pattern: str | None = None,
    ) -> Iterator[str]:
        """Iterate over repository files."""
        ref_ = ref or self.default_branch
        entries = self._list_contents(path, ref_)
        for entry in entries:
            if entry.type == "file":
                if not pattern or fnmatch.fnmatch(entry.path, pattern):
                    yield entry.path
            elif entry.type == "dir":
                yield from self.iter_files(entry.path, ref, pattern)

    @giteatools.handle_api_errors("Failed to get contributors")
    def get_contributors(
        self,
        sort_by: Literal["commits", "name", "date"] = "commits",
        limit: int | None = None,
    ) -> list[User]:
        """Get repository contributors."""
        commits = self._repo_api.repo_get_all_commits(self._owner, self._name)
        assert isinstance(commits, list)

        # Build contributor stats from commits
        contributors: dict[str, dict[str, Any]] = {}
        for commit in commits:
            author = commit.author
            if not author:
                continue

            if author.login not in contributors:
                contributors[author.login] = {"user": author, "commits": 0}
            contributors[author.login]["commits"] += 1

        # Convert to list and sort
        contributor_list = list(contributors.values())
        if sort_by == "name":
            contributor_list.sort(key=lambda c: c["user"].login)
        elif sort_by == "commits":
            contributor_list.sort(key=lambda c: c["commits"], reverse=True)
        if limit:
            contributor_list = contributor_list[:limit]

        return [giteatools.create_user_model(c["user"]) for c in contributor_list]

    @giteatools.handle_api_errors("Failed to get latest release")
    def get_latest_release(
        self,
        include_drafts: bool = False,
        include_prereleases: bool = False,
    ) -> Release:
        """Get the latest repository release."""
        releases = self.list_releases(
            include_drafts=include_drafts,
            include_prereleases=include_prereleases,
            limit=1,
        )
        if not releases:
            msg = "No matching releases found"
            raise ResourceNotFoundError(msg)
        return releases[0]

    @giteatools.handle_api_errors("Failed to list releases")
    def list_releases(
        self,
        include_drafts: bool = False,
        include_prereleases: bool = False,
        limit: int | None = None,
    ) -> list[Release]:
        """List repository releases."""
        results = self._repo_api.repo_list_releases(self._owner, self._name)
        assert isinstance(results, list)
        filtered = [
            giteatools.create_release_model(release)
            for release in results
            if (include_drafts or not release.draft)
            and (include_prereleases or not release.prerelease)
        ]
        return filtered[:limit] if limit else filtered

    @giteatools.handle_api_errors("Failed to get release")
    def get_release(self, tag: str) -> Release:
        """Get a specific release by tag."""
        results = self._repo_api.repo_list_releases(self._owner, self._name)
        assert isinstance(results, list)
        for release in results:
            if release.tag_name == tag:
                return giteatools.create_release_model(release)
        msg = f"Release with tag {tag!r} not found"
        raise ResourceNotFoundError(msg)

    @giteatools.handle_api_errors("Failed to list tags")
    def list_tags(self) -> list[Tag]:
        """List all repository tags."""
        tags = self._repo_api.repo_list_tags(self._owner, self._name)
        return [giteatools.create_tag_model(tag) for tag in tags]

    @giteatools.handle_api_errors("Failed to get tag {name}")
    def get_tag(self, name: str) -> Tag:
        """Get a specific repository tag."""
        tags = self._repo_api.repo_list_tags(self._owner, self._name)
        for tag in tags:
            if tag.name == name:
                return giteatools.create_tag_model(tag)
        msg = f"Tag {name!r} not found"
        raise ResourceNotFoundError(msg)

    @giteatools.handle_api_errors("Failed to create pull request")
    def create_pull_request(
        self,
        title: str,
        body: str,
        head_branch: str,
        base_branch: str,
        draft: bool = False,
    ) -> PullRequest:
        # Gitea doesn't support draft PRs, so we'll ignore that parameter
        if draft:
            logger.warning("Gitea does not support draft pull requests")

        pr = self._repo_api.repo_create_pull_request(
            owner=self._owner,
            repo=self._name,
            body={"title": title, "body": body, "head": head_branch, "base": base_branch},
        )
        return giteatools.create_pull_request_model(pr)

create_issue

create_issue(
    title: str, body: str, labels: list[str] | None = None, assignees: list[str] | None = None
) -> Issue

Create a new issue.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to create issue")
def create_issue(
    self,
    title: str,
    body: str,
    labels: list[str] | None = None,
    assignees: list[str] | None = None,
) -> Issue:
    """Create a new issue."""
    params: dict[str, Any] = {
        "title": title,
        "body": body,
    }
    if labels:
        params["labels"] = labels
    if assignees:
        params["assignees"] = assignees

    issue = self._issues_api.issue_create_issue(
        owner=self._owner,
        repo=self._name,
        body=params,
    )
    return giteatools.create_issue_model(issue)

download

download(path: str, destination: JoinablePathLike, recursive: bool = False) -> None

Download repository contents.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to download file")
def download(self, path: str, destination: JoinablePathLike, recursive: bool = False) -> None:
    """Download repository contents."""
    import base64

    from upathtools import to_upath

    dest = to_upath(destination)
    dest.mkdir(exist_ok=True, parents=True)

    def _decode_content(file_content: Any) -> bytes:
        raw = file_content.content or ""
        if getattr(file_content, "encoding", "base64") == "base64":
            return base64.b64decode(raw)
        return raw.encode()

    if recursive:
        contents = self._list_contents(str(path), self.default_branch)

        for content in contents:
            if content.type == "file":
                file_content = self._repo_api.repo_get_contents(
                    self._owner,
                    self._name,
                    content.path,
                    ref=self.default_branch,
                )
                file_dest = dest / content.path
                file_dest.parent.mkdir(exist_ok=True, parents=True)
                file_dest.write_bytes(_decode_content(file_content))
    else:
        content = self._repo_api.repo_get_contents(
            self._owner,
            self._name,
            str(path),
            ref=self.default_branch,
        )
        file_dest = dest / to_upath(path).name
        file_dest.write_bytes(_decode_content(content))

from_url classmethod

from_url(url: str, **kwargs: Any) -> GiteaRepository

Create from URL like 'https://gitea.com/owner/repo'.

Source code in src/githarbor/providers/gitea_provider/repository.py
@classmethod
def from_url(cls, url: str, **kwargs: Any) -> GiteaRepository:
    """Create from URL like 'https://gitea.com/owner/repo'."""
    parsed = urlparse(url)
    parts = parsed.path.strip("/").split("/")
    if len(parts) < 2:  # noqa: PLR2004
        msg = f"Invalid Gitea URL: {url}"
        raise ValueError(msg)
    url = f"{parsed.scheme}://{parsed.netloc}"
    return cls(owner=parts[0], name=parts[1], token=kwargs.get("token"), url=url)

get_branch

get_branch(name: str) -> Branch

Get a specific branch by name.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to get branch")
def get_branch(self, name: str) -> Branch:
    """Get a specific branch by name."""
    branch = self._repo_api.repo_get_branch(self._owner, self._name, name)
    return giteatools.create_branch_model(branch)

get_commit

get_commit(sha: str) -> Commit

Get a specific commit by SHA.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to get commit")
def get_commit(self, sha: str) -> Commit:
    """Get a specific commit by SHA."""
    commit: giteapy.Commit = self._repo_api.repo_get_single_commit(self._owner, self._name, sha)
    return giteatools.create_commit_model(commit)

get_contributors

get_contributors(
    sort_by: Literal["commits", "name", "date"] = "commits", limit: int | None = None
) -> list[User]

Get repository contributors.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to get contributors")
def get_contributors(
    self,
    sort_by: Literal["commits", "name", "date"] = "commits",
    limit: int | None = None,
) -> list[User]:
    """Get repository contributors."""
    commits = self._repo_api.repo_get_all_commits(self._owner, self._name)
    assert isinstance(commits, list)

    # Build contributor stats from commits
    contributors: dict[str, dict[str, Any]] = {}
    for commit in commits:
        author = commit.author
        if not author:
            continue

        if author.login not in contributors:
            contributors[author.login] = {"user": author, "commits": 0}
        contributors[author.login]["commits"] += 1

    # Convert to list and sort
    contributor_list = list(contributors.values())
    if sort_by == "name":
        contributor_list.sort(key=lambda c: c["user"].login)
    elif sort_by == "commits":
        contributor_list.sort(key=lambda c: c["commits"], reverse=True)
    if limit:
        contributor_list = contributor_list[:limit]

    return [giteatools.create_user_model(c["user"]) for c in contributor_list]

get_issue

get_issue(issue_id: int) -> Issue

Get a specific issue by ID.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to get issue")
def get_issue(self, issue_id: int) -> Issue:
    """Get a specific issue by ID."""
    issue: giteapy.Issue = self._issues_api.issue_get_issue(self._owner, self._name, issue_id)
    return giteatools.create_issue_model(issue)

get_latest_release

get_latest_release(include_drafts: bool = False, include_prereleases: bool = False) -> Release

Get the latest repository release.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to get latest release")
def get_latest_release(
    self,
    include_drafts: bool = False,
    include_prereleases: bool = False,
) -> Release:
    """Get the latest repository release."""
    releases = self.list_releases(
        include_drafts=include_drafts,
        include_prereleases=include_prereleases,
        limit=1,
    )
    if not releases:
        msg = "No matching releases found"
        raise ResourceNotFoundError(msg)
    return releases[0]

get_pull_request

get_pull_request(number: int) -> PullRequest

Get a specific pull request by number.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to get pull request")
def get_pull_request(self, number: int) -> PullRequest:
    """Get a specific pull request by number."""
    pr = self._repo_api.repo_get_pull_request(self._owner, self._name, number)
    return giteatools.create_pull_request_model(pr)

get_release

get_release(tag: str) -> Release

Get a specific release by tag.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to get release")
def get_release(self, tag: str) -> Release:
    """Get a specific release by tag."""
    results = self._repo_api.repo_list_releases(self._owner, self._name)
    assert isinstance(results, list)
    for release in results:
        if release.tag_name == tag:
            return giteatools.create_release_model(release)
    msg = f"Release with tag {tag!r} not found"
    raise ResourceNotFoundError(msg)

get_repo_user

get_repo_user() -> User

Get user (repository owner) information.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to get repository owner info")
def get_repo_user(self) -> User:
    """Get user (repository owner) information."""
    user = self._user_api.user_get(self._owner)
    return giteatools.create_user_model(user)

get_tag

get_tag(name: str) -> Tag

Get a specific repository tag.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to get tag {name}")
def get_tag(self, name: str) -> Tag:
    """Get a specific repository tag."""
    tags = self._repo_api.repo_list_tags(self._owner, self._name)
    for tag in tags:
        if tag.name == name:
            return giteatools.create_tag_model(tag)
    msg = f"Tag {name!r} not found"
    raise ResourceNotFoundError(msg)

iter_files

iter_files(path: str = '', ref: str | None = None, pattern: str | None = None) -> Iterator[str]

Iterate over repository files.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to list files")
def iter_files(
    self,
    path: str = "",
    ref: str | None = None,
    pattern: str | None = None,
) -> Iterator[str]:
    """Iterate over repository files."""
    ref_ = ref or self.default_branch
    entries = self._list_contents(path, ref_)
    for entry in entries:
        if entry.type == "file":
            if not pattern or fnmatch.fnmatch(entry.path, pattern):
                yield entry.path
        elif entry.type == "dir":
            yield from self.iter_files(entry.path, ref, pattern)

list_commits

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

List repository commits with optional filters.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to list commits")
def list_commits(
    self,
    branch: str | None = None,
    since: datetime | None = None,
    until: datetime | None = None,
    author: str | None = None,
    path: str | None = None,
    max_results: int | None = None,
) -> list[Commit]:
    """List repository commits with optional filters."""
    if path:
        msg = "Filtering commits by path is not supported for Gitea"
        raise FeatureNotSupportedError(msg)
    kwargs: dict[str, Any] = {}
    if branch:
        kwargs["sha"] = branch

    commits = self._repo_api.repo_get_all_commits(self._owner, self._name, **kwargs)
    assert isinstance(commits, list)

    models = [giteatools.create_commit_model(commit) for commit in commits]
    if since:
        models = [m for m in models if m.created_at and m.created_at >= since]
    if until:
        models = [m for m in models if m.created_at and m.created_at <= until]
    if author:
        models = [
            m
            for m in models
            if m.author
            and (author in (m.author.name or "") or author in (m.author.email or ""))
        ]
    if max_results:
        models = models[:max_results]

    return models

list_issues

list_issues(state: IssueState = 'open') -> list[Issue]

List repository issues.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to list issues")
def list_issues(self, state: IssueState = "open") -> list[Issue]:
    """List repository issues."""
    issues: list[giteapy.Issue] = self._issues_api.issue_list_issues(
        self._owner,
        self._name,
        state=state,
    )
    return [giteatools.create_issue_model(issue) for issue in issues]

list_pull_requests

list_pull_requests(state: PullRequestState = 'open') -> list[PullRequest]

List pull requests.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to list pull requests")
def list_pull_requests(self, state: PullRequestState = "open") -> list[PullRequest]:
    """List pull requests."""
    prs = self._repo_api.repo_list_pull_requests(
        self._owner,
        self._name,
        state=state,
    )
    assert isinstance(prs, list)
    return [giteatools.create_pull_request_model(pr) for pr in prs]  # pyright: ignore

list_releases

list_releases(
    include_drafts: bool = False, include_prereleases: bool = False, limit: int | None = None
) -> list[Release]

List repository releases.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to list releases")
def list_releases(
    self,
    include_drafts: bool = False,
    include_prereleases: bool = False,
    limit: int | None = None,
) -> list[Release]:
    """List repository releases."""
    results = self._repo_api.repo_list_releases(self._owner, self._name)
    assert isinstance(results, list)
    filtered = [
        giteatools.create_release_model(release)
        for release in results
        if (include_drafts or not release.draft)
        and (include_prereleases or not release.prerelease)
    ]
    return filtered[:limit] if limit else filtered

list_tags

list_tags() -> list[Tag]

List all repository tags.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to list tags")
def list_tags(self) -> list[Tag]:
    """List all repository tags."""
    tags = self._repo_api.repo_list_tags(self._owner, self._name)
    return [giteatools.create_tag_model(tag) for tag in tags]

search_commits

search_commits(
    query: str, branch: str | None = None, path: str | None = None, max_results: int | None = None
) -> list[Commit]

Search repository commits.

Source code in src/githarbor/providers/gitea_provider/repository.py
@giteatools.handle_api_errors("Failed to search commits")
def search_commits(
    self,
    query: str,
    branch: str | None = None,
    path: str | None = None,
    max_results: int | None = None,
) -> list[Commit]:
    """Search repository commits."""
    # giteapy has no commit search endpoint, so filter commit messages client-side.
    if path:
        msg = "Filtering commit search by path is not supported for Gitea"
        raise FeatureNotSupportedError(msg)
    kwargs = {"sha": branch} if branch else {}
    commits = self._repo_api.repo_get_all_commits(self._owner, self._name, **kwargs)
    query_lower = query.lower()
    matches = [c for c in commits if query_lower in (c.commit.message or "").lower()]
    if max_results:
        matches = matches[:max_results]
    return [giteatools.create_commit_model(commit) for commit in matches]

LocalRepository

Bases: BaseRepository

Local Git repository implementation using GitPython.

Source code in src/githarbor/providers/local_provider/repository.py
class LocalRepository(BaseRepository):
    """Local Git repository implementation using GitPython."""

    url_patterns: ClassVar[list[str]] = []  # Local repos don't have URL patterns

    def __init__(self, path: str | os.PathLike[str]) -> None:
        import git

        try:
            self.path = pathlib.Path(path)
            self.repo = git.Repo(self.path)
            self._name = self.path.name
            self._owner = self.path.parent.name  # or None?
        except (git.InvalidGitRepositoryError, git.NoSuchPathError) as e:
            msg = f"Not a valid git repository: {path}"
            raise ResourceNotFoundError(msg) from e

    @classmethod
    def from_url(cls, url: str, **_: Any) -> LocalRepository:
        return cls(url)

    @classmethod
    def supports_url(cls, url: str) -> bool:
        return pathlib.Path(url).exists()

    @property
    def default_branch(self) -> str:
        return self.repo.active_branch.name

    @localtools.handle_git_errors("Failed to get branch {name}")
    def get_branch(self, name: str) -> Branch:
        branch = self.repo.heads[name]
        is_default = branch.name == self.default_branch
        return localtools.create_branch_model(branch, is_default=is_default)

    @localtools.handle_git_errors("Failed to list branches")
    def list_branches(self) -> list[Branch]:
        return [
            localtools.create_branch_model(b, is_default=b.name == self.default_branch)
            for b in self.repo.heads
        ]

    @localtools.handle_git_errors("Failed to get commit {sha}")
    def get_commit(self, sha: str) -> Commit:
        commit = self.repo.commit(sha)
        return localtools.create_commit_model(commit)

    @localtools.handle_git_errors("Failed to list commits")
    def list_commits(
        self,
        branch: str | None = None,
        since: datetime | None = None,
        until: datetime | None = None,
        author: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        commits = self.repo.iter_commits(rev=branch or self.default_branch)
        filtered = localtools.filter_commits(
            commits,
            since=since,
            until=until,
            author=author,
            path=path,
            max_results=max_results,
        )
        return [localtools.create_commit_model(commit) for commit in filtered]

    @localtools.handle_git_errors("Failed to iterate files")
    def iter_files(
        self,
        path: str = "",
        ref: str | None = None,
        pattern: str | None = None,
    ) -> Iterator[str]:
        tree = self.repo.head.commit.tree if ref is None else self.repo.commit(ref).tree
        for blob in tree.traverse():
            # Skip dirs
            if blob.type != "blob":  # type: ignore
                continue
            file_path = str(blob.path)  # type: ignore
            if (not pattern or fnmatch.fnmatch(file_path, pattern)) and (
                not path or file_path.startswith(path)
            ):
                yield file_path

    @localtools.handle_git_errors("Failed to get tag {name}")
    def get_tag(self, name: str) -> Tag:
        tag = self.repo.tags[name]
        return localtools.create_tag_model(tag, tag.commit)

    @localtools.handle_git_errors("Failed to list tags")
    def list_tags(self) -> list[Tag]:
        return [localtools.create_tag_model(tag, tag.commit) for tag in self.repo.tags]

    @functools.cached_property
    def remote_repository(self) -> Repository:
        """Get the remote code repository."""
        from githarbor import create_repository

        return create_repository(self.repo.remotes.origin.url)

remote_repository cached property

remote_repository: Repository

Get the remote code repository.

PyGiteaRepository

Bases: BaseRepository

PyGitea repository implementation using py-gitea library.

Source code in src/githarbor/providers/pygitea_provider/repository.py
class PyGiteaRepository(BaseRepository):
    """PyGitea repository implementation using py-gitea library."""

    url_patterns: ClassVar[list[str]] = [
        "gitea.com",
        "codeberg.org",
    ]  # Add your Gitea instances here

    def __init__(
        self,
        owner: str,
        name: str,
        token: str | None = None,
        url: str = "https://gitea.com",
    ):
        try:
            import gitea
        except ImportError as e:
            msg = "py-gitea library is required for PyGiteaRepository"
            raise ImportError(msg) from e

        t = token or os.getenv("GITEA_TOKEN")
        if not t:
            msg = "Gitea token is required"
            raise ValueError(msg)

        self._owner = owner
        self._name = name
        self._base_url = url.rstrip("/")

        try:
            # Initialize Gitea client
            self._gitea = gitea.Gitea(self._base_url, t)

            # Test connection and get repository info
            self._repo = gitea.Repository.request(self._gitea, owner, name)

        except Exception as e:
            msg = f"PyGitea authentication failed: {e!s}"
            raise AuthenticationError(msg) from e

    @classmethod
    def from_url(cls, url: str, **kwargs: Any) -> PyGiteaRepository:
        """Create from URL like 'https://gitea.com/owner/repo'."""
        parsed = urlparse(url)
        parts = parsed.path.strip("/").split("/")
        if len(parts) < 2:  # noqa: PLR2004
            msg = f"Invalid Gitea URL: {url}"
            raise ValueError(msg)
        base_url = f"{parsed.scheme}://{parsed.netloc}"
        return cls(owner=parts[0], name=parts[1], token=kwargs.get("token"), url=base_url)

    @property
    def default_branch(self) -> str:
        return self._repo.default_branch

    @property
    def edit_base_uri(self):
        return f"_edit/{self.default_branch}/"

    @pygiteatools.handle_api_errors("Failed to get branch")
    def get_branch(self, name: str) -> Branch:
        """Get a specific branch by name."""
        import gitea

        branch = gitea.Branch.request(self._gitea, self._owner, self._name, name)
        return pygiteatools.create_branch_model(branch)

    @pygiteatools.handle_api_errors("Failed to get repository owner info")
    def get_repo_user(self) -> User:
        """Get user (repository owner) information."""
        import gitea

        user = gitea.User.request(self._gitea, self._owner)
        return pygiteatools.create_user_model(user)

    def _get_issues_by_state(self, state: str) -> list[Any]:
        """Fetch issues for open, closed, or all states."""
        if state == "all":
            return self._repo.get_issues_state("open") + self._repo.get_issues_state("closed")
        return self._repo.get_issues_state(state)

    @pygiteatools.handle_api_errors("Failed to get pull request")
    def get_pull_request(self, number: int) -> PullRequest:
        """Get a specific pull request by number."""
        prs = self._get_issues_by_state("all")
        for pr in prs:
            if pr.pull_request and pr.number == number:
                return pygiteatools.create_pull_request_model(pr)
        msg = f"Pull request #{number} not found"
        raise ResourceNotFoundError(msg)

    @pygiteatools.handle_api_errors("Failed to list pull requests")
    def list_pull_requests(self, state: PullRequestState = "open") -> list[PullRequest]:
        """List pull requests."""
        issues = self._get_issues_by_state(state)
        prs = [issue for issue in issues if issue.pull_request]
        return [pygiteatools.create_pull_request_model(pr) for pr in prs]

    @pygiteatools.handle_api_errors("Failed to list branches")
    def list_branches(self) -> list[Branch]:
        """List repository branches."""
        branches = self._repo.get_branches()
        return [pygiteatools.create_branch_model(branch) for branch in branches]

    @pygiteatools.handle_api_errors("Failed to get issue")
    def get_issue(self, issue_id: int) -> Issue:
        """Get a specific issue by ID."""
        import gitea

        issue = gitea.Issue.request(self._gitea, self._owner, self._name, str(issue_id))
        return pygiteatools.create_issue_model(issue)

    @pygiteatools.handle_api_errors("Failed to list issues")
    def list_issues(self, state: IssueState = "open") -> list[Issue]:
        """List repository issues."""
        issues = self._get_issues_by_state(state)
        return [pygiteatools.create_issue_model(issue) for issue in issues]

    @pygiteatools.handle_api_errors("Failed to create issue")
    def create_issue(
        self,
        title: str,
        body: str,
        labels: list[str] | None = None,
        assignees: list[str] | None = None,
    ) -> Issue:
        """Create a new issue."""
        import gitea

        assignee_users = (
            {gitea.User.request(self._gitea, username) for username in assignees}
            if assignees
            else None
        )
        issue = self._repo.create_issue(
            title=title,
            description=body,
            assignees=assignee_users,
        )
        return pygiteatools.create_issue_model(issue)

    @pygiteatools.handle_api_errors("Failed to get commit")
    def get_commit(self, sha: str) -> Commit:
        """Get a specific commit by SHA."""
        commits = self._repo.get_commits()
        for commit in commits:
            if commit.sha == sha:
                return pygiteatools.create_commit_model(commit)
        msg = f"Commit {sha} not found"
        raise ResourceNotFoundError(msg)

    @pygiteatools.handle_api_errors("Failed to list commits")
    def list_commits(
        self,
        branch: str | None = None,
        since: datetime | None = None,
        until: datetime | None = None,
        author: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        """List repository commits with optional filters."""
        commits = self._repo.get_commits()

        # Apply filters
        if author:
            commits = [
                c
                for c in commits
                if c.author and (author in c.author.username or author in c.author.email)
            ]

        if max_results:
            commits = commits[:max_results]

        return [pygiteatools.create_commit_model(commit) for commit in commits]

    @pygiteatools.handle_api_errors("Failed to download file")
    def download(self, path: str, destination: JoinablePathLike, recursive: bool = False):
        """Download repository contents."""
        import base64

        from upathtools import to_upath

        dest = to_upath(destination)
        dest.mkdir(exist_ok=True, parents=True)

        content = self._repo.get_git_content()

        def _write_file(file_dest: Any, file_data: Any) -> None:
            if not isinstance(file_data, str):
                msg = f"Unexpected directory or non-file content for {file_dest}"
                raise ResourceNotFoundError(msg)
            try:
                content_bytes = base64.b64decode(file_data)
                file_dest.write_bytes(content_bytes)
            except Exception:  # noqa: BLE001
                file_dest.write_text(file_data)

        if recursive:
            for file_content in content:
                if file_content.type == "file":
                    file_data = self._repo.get_file_content(file_content)
                    file_dest = dest / file_content.path
                    file_dest.parent.mkdir(exist_ok=True, parents=True)
                    _write_file(file_dest, file_data)
        else:
            target_file = next((fc for fc in content if fc.path == path), None)
            if not target_file:
                msg = f"File {path!r} not found"
                raise ResourceNotFoundError(msg)
            file_data = self._repo.get_file_content(target_file)
            file_dest = dest / to_upath(path).name
            _write_file(file_dest, file_data)

    @pygiteatools.handle_api_errors("Failed to search commits")
    def search_commits(
        self,
        query: str,
        branch: str | None = None,
        path: str | None = None,
        max_results: int | None = None,
    ) -> list[Commit]:
        """Search repository commits - limited support in py-gitea."""
        commits = self._repo.get_commits()

        # Simple text search in commit messages
        matching_commits = []
        for commit in commits:
            commit_data = commit.inner_commit if hasattr(commit, "inner_commit") else {}
            message = commit_data.get("message", "")
            if query.lower() in message.lower():
                matching_commits.append(commit)
                if max_results and len(matching_commits) >= max_results:
                    break

        return [pygiteatools.create_commit_model(commit) for commit in matching_commits]

    @pygiteatools.handle_api_errors("Failed to list files")
    def iter_files(
        self,
        path: str = "",
        ref: str | None = None,
        pattern: str | None = None,
    ) -> Iterator[str]:
        """Iterate over repository files."""
        try:
            content = self._repo.get_git_content()
            for file_content in content:
                if file_content.type == "file":
                    file_path = file_content.path
                    if not pattern or fnmatch.fnmatch(file_path, pattern):
                        yield file_path
        except Exception as e:  # noqa: BLE001
            logger.warning("Failed to iterate files: %s", e)

    @pygiteatools.handle_api_errors("Failed to get contributors")
    def get_contributors(
        self,
        sort_by: Literal["commits", "name", "date"] = "commits",
        limit: int | None = None,
    ) -> list[User]:
        """Get repository contributors."""
        commits = self._repo.get_commits()

        # Build contributor stats from commits
        contributors: dict[str, dict[str, Any]] = {}
        for commit in commits:
            if commit.author:
                username = commit.author.username
                if not username:
                    continue
                if username not in contributors:
                    contributors[username] = {"user": commit.author, "commits": 0}
                contributors[username]["commits"] += 1

        # Convert to list and sort
        contributor_list = list(contributors.values())
        if sort_by == "name":
            contributor_list.sort(key=lambda c: c["user"].username)
        elif sort_by == "commits":
            contributor_list.sort(key=lambda c: c["commits"], reverse=True)

        if limit:
            contributor_list = contributor_list[:limit]

        return [pygiteatools.create_user_model(c["user"]) for c in contributor_list]

    @pygiteatools.handle_api_errors("Failed to list tags")
    def list_tags(self) -> list[Tag]:
        """List all repository tags."""
        tags = self._repo.get_tags()
        return [pygiteatools.create_tag_model(tag) for tag in tags]

    @pygiteatools.handle_api_errors("Failed to get tag")
    def get_tag(self, name: str) -> Tag:
        """Get a specific repository tag."""
        tags = self.list_tags()
        for tag in tags:
            if tag.name == name:
                return tag
        msg = f"Tag '{name}' not found"
        raise ResourceNotFoundError(msg)

    @pygiteatools.handle_api_errors("Failed to create branch")
    def create_branch(
        self,
        name: str,
        base_commit: str,
    ) -> Branch:
        """Create a new branch."""
        branches = self._repo.get_branches()
        base_branch = None
        for branch in branches:
            if branch.commit and branch.commit.get("id") == base_commit:
                base_branch = branch
                break

        if not base_branch:
            msg = f"Base commit {base_commit} not found in any branch"
            raise ResourceNotFoundError(msg)

        new_branch = self._repo.add_branch(base_branch, name)
        return pygiteatools.create_branch_model(new_branch)

create_branch

create_branch(name: str, base_commit: str) -> Branch

Create a new branch.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to create branch")
def create_branch(
    self,
    name: str,
    base_commit: str,
) -> Branch:
    """Create a new branch."""
    branches = self._repo.get_branches()
    base_branch = None
    for branch in branches:
        if branch.commit and branch.commit.get("id") == base_commit:
            base_branch = branch
            break

    if not base_branch:
        msg = f"Base commit {base_commit} not found in any branch"
        raise ResourceNotFoundError(msg)

    new_branch = self._repo.add_branch(base_branch, name)
    return pygiteatools.create_branch_model(new_branch)

create_issue

create_issue(
    title: str, body: str, labels: list[str] | None = None, assignees: list[str] | None = None
) -> Issue

Create a new issue.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to create issue")
def create_issue(
    self,
    title: str,
    body: str,
    labels: list[str] | None = None,
    assignees: list[str] | None = None,
) -> Issue:
    """Create a new issue."""
    import gitea

    assignee_users = (
        {gitea.User.request(self._gitea, username) for username in assignees}
        if assignees
        else None
    )
    issue = self._repo.create_issue(
        title=title,
        description=body,
        assignees=assignee_users,
    )
    return pygiteatools.create_issue_model(issue)

download

download(path: str, destination: JoinablePathLike, recursive: bool = False)

Download repository contents.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to download file")
def download(self, path: str, destination: JoinablePathLike, recursive: bool = False):
    """Download repository contents."""
    import base64

    from upathtools import to_upath

    dest = to_upath(destination)
    dest.mkdir(exist_ok=True, parents=True)

    content = self._repo.get_git_content()

    def _write_file(file_dest: Any, file_data: Any) -> None:
        if not isinstance(file_data, str):
            msg = f"Unexpected directory or non-file content for {file_dest}"
            raise ResourceNotFoundError(msg)
        try:
            content_bytes = base64.b64decode(file_data)
            file_dest.write_bytes(content_bytes)
        except Exception:  # noqa: BLE001
            file_dest.write_text(file_data)

    if recursive:
        for file_content in content:
            if file_content.type == "file":
                file_data = self._repo.get_file_content(file_content)
                file_dest = dest / file_content.path
                file_dest.parent.mkdir(exist_ok=True, parents=True)
                _write_file(file_dest, file_data)
    else:
        target_file = next((fc for fc in content if fc.path == path), None)
        if not target_file:
            msg = f"File {path!r} not found"
            raise ResourceNotFoundError(msg)
        file_data = self._repo.get_file_content(target_file)
        file_dest = dest / to_upath(path).name
        _write_file(file_dest, file_data)

from_url classmethod

from_url(url: str, **kwargs: Any) -> PyGiteaRepository

Create from URL like 'https://gitea.com/owner/repo'.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@classmethod
def from_url(cls, url: str, **kwargs: Any) -> PyGiteaRepository:
    """Create from URL like 'https://gitea.com/owner/repo'."""
    parsed = urlparse(url)
    parts = parsed.path.strip("/").split("/")
    if len(parts) < 2:  # noqa: PLR2004
        msg = f"Invalid Gitea URL: {url}"
        raise ValueError(msg)
    base_url = f"{parsed.scheme}://{parsed.netloc}"
    return cls(owner=parts[0], name=parts[1], token=kwargs.get("token"), url=base_url)

get_branch

get_branch(name: str) -> Branch

Get a specific branch by name.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to get branch")
def get_branch(self, name: str) -> Branch:
    """Get a specific branch by name."""
    import gitea

    branch = gitea.Branch.request(self._gitea, self._owner, self._name, name)
    return pygiteatools.create_branch_model(branch)

get_commit

get_commit(sha: str) -> Commit

Get a specific commit by SHA.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to get commit")
def get_commit(self, sha: str) -> Commit:
    """Get a specific commit by SHA."""
    commits = self._repo.get_commits()
    for commit in commits:
        if commit.sha == sha:
            return pygiteatools.create_commit_model(commit)
    msg = f"Commit {sha} not found"
    raise ResourceNotFoundError(msg)

get_contributors

get_contributors(
    sort_by: Literal["commits", "name", "date"] = "commits", limit: int | None = None
) -> list[User]

Get repository contributors.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to get contributors")
def get_contributors(
    self,
    sort_by: Literal["commits", "name", "date"] = "commits",
    limit: int | None = None,
) -> list[User]:
    """Get repository contributors."""
    commits = self._repo.get_commits()

    # Build contributor stats from commits
    contributors: dict[str, dict[str, Any]] = {}
    for commit in commits:
        if commit.author:
            username = commit.author.username
            if not username:
                continue
            if username not in contributors:
                contributors[username] = {"user": commit.author, "commits": 0}
            contributors[username]["commits"] += 1

    # Convert to list and sort
    contributor_list = list(contributors.values())
    if sort_by == "name":
        contributor_list.sort(key=lambda c: c["user"].username)
    elif sort_by == "commits":
        contributor_list.sort(key=lambda c: c["commits"], reverse=True)

    if limit:
        contributor_list = contributor_list[:limit]

    return [pygiteatools.create_user_model(c["user"]) for c in contributor_list]

get_issue

get_issue(issue_id: int) -> Issue

Get a specific issue by ID.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to get issue")
def get_issue(self, issue_id: int) -> Issue:
    """Get a specific issue by ID."""
    import gitea

    issue = gitea.Issue.request(self._gitea, self._owner, self._name, str(issue_id))
    return pygiteatools.create_issue_model(issue)

get_pull_request

get_pull_request(number: int) -> PullRequest

Get a specific pull request by number.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to get pull request")
def get_pull_request(self, number: int) -> PullRequest:
    """Get a specific pull request by number."""
    prs = self._get_issues_by_state("all")
    for pr in prs:
        if pr.pull_request and pr.number == number:
            return pygiteatools.create_pull_request_model(pr)
    msg = f"Pull request #{number} not found"
    raise ResourceNotFoundError(msg)

get_repo_user

get_repo_user() -> User

Get user (repository owner) information.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to get repository owner info")
def get_repo_user(self) -> User:
    """Get user (repository owner) information."""
    import gitea

    user = gitea.User.request(self._gitea, self._owner)
    return pygiteatools.create_user_model(user)

get_tag

get_tag(name: str) -> Tag

Get a specific repository tag.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to get tag")
def get_tag(self, name: str) -> Tag:
    """Get a specific repository tag."""
    tags = self.list_tags()
    for tag in tags:
        if tag.name == name:
            return tag
    msg = f"Tag '{name}' not found"
    raise ResourceNotFoundError(msg)

iter_files

iter_files(path: str = '', ref: str | None = None, pattern: str | None = None) -> Iterator[str]

Iterate over repository files.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to list files")
def iter_files(
    self,
    path: str = "",
    ref: str | None = None,
    pattern: str | None = None,
) -> Iterator[str]:
    """Iterate over repository files."""
    try:
        content = self._repo.get_git_content()
        for file_content in content:
            if file_content.type == "file":
                file_path = file_content.path
                if not pattern or fnmatch.fnmatch(file_path, pattern):
                    yield file_path
    except Exception as e:  # noqa: BLE001
        logger.warning("Failed to iterate files: %s", e)

list_branches

list_branches() -> list[Branch]

List repository branches.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to list branches")
def list_branches(self) -> list[Branch]:
    """List repository branches."""
    branches = self._repo.get_branches()
    return [pygiteatools.create_branch_model(branch) for branch in branches]

list_commits

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

List repository commits with optional filters.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to list commits")
def list_commits(
    self,
    branch: str | None = None,
    since: datetime | None = None,
    until: datetime | None = None,
    author: str | None = None,
    path: str | None = None,
    max_results: int | None = None,
) -> list[Commit]:
    """List repository commits with optional filters."""
    commits = self._repo.get_commits()

    # Apply filters
    if author:
        commits = [
            c
            for c in commits
            if c.author and (author in c.author.username or author in c.author.email)
        ]

    if max_results:
        commits = commits[:max_results]

    return [pygiteatools.create_commit_model(commit) for commit in commits]

list_issues

list_issues(state: IssueState = 'open') -> list[Issue]

List repository issues.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to list issues")
def list_issues(self, state: IssueState = "open") -> list[Issue]:
    """List repository issues."""
    issues = self._get_issues_by_state(state)
    return [pygiteatools.create_issue_model(issue) for issue in issues]

list_pull_requests

list_pull_requests(state: PullRequestState = 'open') -> list[PullRequest]

List pull requests.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to list pull requests")
def list_pull_requests(self, state: PullRequestState = "open") -> list[PullRequest]:
    """List pull requests."""
    issues = self._get_issues_by_state(state)
    prs = [issue for issue in issues if issue.pull_request]
    return [pygiteatools.create_pull_request_model(pr) for pr in prs]

list_tags

list_tags() -> list[Tag]

List all repository tags.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to list tags")
def list_tags(self) -> list[Tag]:
    """List all repository tags."""
    tags = self._repo.get_tags()
    return [pygiteatools.create_tag_model(tag) for tag in tags]

search_commits

search_commits(
    query: str, branch: str | None = None, path: str | None = None, max_results: int | None = None
) -> list[Commit]

Search repository commits - limited support in py-gitea.

Source code in src/githarbor/providers/pygitea_provider/repository.py
@pygiteatools.handle_api_errors("Failed to search commits")
def search_commits(
    self,
    query: str,
    branch: str | None = None,
    path: str | None = None,
    max_results: int | None = None,
) -> list[Commit]:
    """Search repository commits - limited support in py-gitea."""
    commits = self._repo.get_commits()

    # Simple text search in commit messages
    matching_commits = []
    for commit in commits:
        commit_data = commit.inner_commit if hasattr(commit, "inner_commit") else {}
        message = commit_data.get("message", "")
        if query.lower() in message.lower():
            matching_commits.append(commit)
            if max_results and len(matching_commits) >= max_results:
                break

    return [pygiteatools.create_commit_model(commit) for commit in matching_commits]