Skip to content

AioGitHubOwner

Base classes

Name Children Inherits
BaseOwner
githarbor.core.base
Base class for repository owners.

⋔ Inheritance diagram

graph TD
  2696370964["owner.AioGitHubOwner"]
  697273899["base.BaseOwner"]
  2751680898["builtins.object"]
  697273899 --> 2696370964
  2751680898 --> 697273899

🛈 DocStrings

Bases: BaseOwner

Owner implementation using aiogithubapi.

Source code in src/githarbor/providers/aiogithubapi_provider/owner.py
class AioGitHubOwner(BaseOwner):
    """Owner implementation using aiogithubapi."""

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

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

        Args:
            username: Username of the owner
            token: GitHub access token
        """
        t = token or os.getenv("GITHUB_TOKEN")
        if not t:
            msg = "GitHub token is required"
            raise ValueError(msg)
        self._token = t
        self._gh_client: Any = None
        self._name = username

    @property
    def _gh(self) -> Any:
        """Lazily create the async GitHubAPI client inside a running event loop."""
        if self._gh_client is None:
            from aiogithubapi import GitHubAPI
            from aiogithubapi.exceptions import GitHubAuthenticationException

            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

    @property
    def name(self) -> str:
        """The name of the owner."""
        return self._name

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

        Args:
            url: URL like "https://github.com/octocat"
            **kwargs: Additional arguments including token
        """
        # Remove trailing slashes and handle both user & org URLs
        url = url.rstrip("/")
        username = url.split("/")[-1]
        return cls(username=username, token=kwargs.get("token"))

    async def list_repositories_async(self) -> list[BaseRepository]:
        """List all repositories owned by this user."""
        from aiogithubapi.exceptions import GitHubAuthenticationException

        try:
            response = await self._gh.users.repos(self._name)
            assert response.data
            return [create_repository(r.html_url) for r in response.data if r.html_url]
        except GitHubAuthenticationException as e:
            msg = f"Failed to list repositories: {e}"
            raise ResourceNotFoundError(msg) from e

    async def create_repository_async(
        self,
        name: str,
        description: str = "",
        private: bool = False,
    ) -> BaseRepository:
        """Create a new repository.

        Args:
            name: Repository name
            description: Repository description
            private: Whether to create a private repository

        Returns:
            Newly created repository
        """
        from aiogithubapi import GitHubRequestKwarg
        from aiogithubapi.exceptions import GitHubAuthenticationException
        from aiogithubapi.github import HttpMethod

        try:
            data = {"name": name, "description": description, "private": private}
            kwargs: dict[Any, Any] = {GitHubRequestKwarg.METHOD: HttpMethod.POST}
            ep = "/user/repos"
            response = await self._gh.generic(endpoint=ep, data=data, **kwargs)
            assert response.data
            return create_repository(response.data["html_url"])
        except GitHubAuthenticationException as e:
            msg = f"Failed to create repository: {e}"
            raise ResourceNotFoundError(msg) from e

    async def get_user_async(self) -> User:
        """Get user information."""
        from aiogithubapi.exceptions import GitHubAuthenticationException

        try:
            response = await self._gh.users.get(self._name)
            assert response.data
            return aiogithubapitools.create_user_model(response.data)
        except GitHubAuthenticationException as e:
            msg = f"Failed to get user info: {e}"
            raise ResourceNotFoundError(msg) from e

    async def delete_repository_async(self, name: str) -> None:
        """Delete a repository.

        Args:
            name: Name of repository to delete
        """
        from aiogithubapi import GitHubRequestKwarg
        from aiogithubapi.exceptions import GitHubAuthenticationException
        from aiogithubapi.github import HttpMethod

        try:
            kwargs = {GitHubRequestKwarg.METHOD: HttpMethod.DELETE}
            ep = f"/repos/{self._name}/{name}"
            await self._gh.generic(endpoint=ep, **kwargs)
        except GitHubAuthenticationException as e:
            msg = f"Failed to delete repository: {e}"
            raise ResourceNotFoundError(msg) from e

name property

name: str

The name of the owner.

__init__

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

Initialize GitHub API client.

Parameters:

Name Type Description Default
username str

Username of the owner

required
token str | None

GitHub access token

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

    Args:
        username: Username of the owner
        token: GitHub access token
    """
    t = token or os.getenv("GITHUB_TOKEN")
    if not t:
        msg = "GitHub token is required"
        raise ValueError(msg)
    self._token = t
    self._gh_client: Any = None
    self._name = username

create_repository_async async

create_repository_async(name: str, description: str = '', private: bool = False) -> BaseRepository

Create a new repository.

Parameters:

Name Type Description Default
name str

Repository name

required
description str

Repository description

''
private bool

Whether to create a private repository

False

Returns:

Type Description
BaseRepository

Newly created repository

Source code in src/githarbor/providers/aiogithubapi_provider/owner.py
async def create_repository_async(
    self,
    name: str,
    description: str = "",
    private: bool = False,
) -> BaseRepository:
    """Create a new repository.

    Args:
        name: Repository name
        description: Repository description
        private: Whether to create a private repository

    Returns:
        Newly created repository
    """
    from aiogithubapi import GitHubRequestKwarg
    from aiogithubapi.exceptions import GitHubAuthenticationException
    from aiogithubapi.github import HttpMethod

    try:
        data = {"name": name, "description": description, "private": private}
        kwargs: dict[Any, Any] = {GitHubRequestKwarg.METHOD: HttpMethod.POST}
        ep = "/user/repos"
        response = await self._gh.generic(endpoint=ep, data=data, **kwargs)
        assert response.data
        return create_repository(response.data["html_url"])
    except GitHubAuthenticationException as e:
        msg = f"Failed to create repository: {e}"
        raise ResourceNotFoundError(msg) from e

delete_repository_async async

delete_repository_async(name: str) -> None

Delete a repository.

Parameters:

Name Type Description Default
name str

Name of repository to delete

required
Source code in src/githarbor/providers/aiogithubapi_provider/owner.py
async def delete_repository_async(self, name: str) -> None:
    """Delete a repository.

    Args:
        name: Name of repository to delete
    """
    from aiogithubapi import GitHubRequestKwarg
    from aiogithubapi.exceptions import GitHubAuthenticationException
    from aiogithubapi.github import HttpMethod

    try:
        kwargs = {GitHubRequestKwarg.METHOD: HttpMethod.DELETE}
        ep = f"/repos/{self._name}/{name}"
        await self._gh.generic(endpoint=ep, **kwargs)
    except GitHubAuthenticationException as e:
        msg = f"Failed to delete repository: {e}"
        raise ResourceNotFoundError(msg) from e

from_url classmethod

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

Create instance from URL.

Parameters:

Name Type Description Default
url str

URL like "https://github.com/octocat"

required
**kwargs Any

Additional arguments including token

{}
Source code in src/githarbor/providers/aiogithubapi_provider/owner.py
@classmethod
def from_url(cls, url: str, **kwargs: Any) -> AioGitHubOwner:
    """Create instance from URL.

    Args:
        url: URL like "https://github.com/octocat"
        **kwargs: Additional arguments including token
    """
    # Remove trailing slashes and handle both user & org URLs
    url = url.rstrip("/")
    username = url.split("/")[-1]
    return cls(username=username, token=kwargs.get("token"))

get_user_async async

get_user_async() -> User

Get user information.

Source code in src/githarbor/providers/aiogithubapi_provider/owner.py
async def get_user_async(self) -> User:
    """Get user information."""
    from aiogithubapi.exceptions import GitHubAuthenticationException

    try:
        response = await self._gh.users.get(self._name)
        assert response.data
        return aiogithubapitools.create_user_model(response.data)
    except GitHubAuthenticationException as e:
        msg = f"Failed to get user info: {e}"
        raise ResourceNotFoundError(msg) from e

list_repositories_async async

list_repositories_async() -> list[BaseRepository]

List all repositories owned by this user.

Source code in src/githarbor/providers/aiogithubapi_provider/owner.py
async def list_repositories_async(self) -> list[BaseRepository]:
    """List all repositories owned by this user."""
    from aiogithubapi.exceptions import GitHubAuthenticationException

    try:
        response = await self._gh.users.repos(self._name)
        assert response.data
        return [create_repository(r.html_url) for r in response.data if r.html_url]
    except GitHubAuthenticationException as e:
        msg = f"Failed to list repositories: {e}"
        raise ResourceNotFoundError(msg) from e

:fa-brands-github: Show source on GitHub