Skip to content

GitHubKitOwner

Base classes

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

â‹” Inheritance diagram

graph TD
  498046126["owner.GitHubKitOwner"]
  697273899["base.BaseOwner"]
  2751680898["builtins.object"]
  697273899 --> 498046126
  2751680898 --> 697273899

🛈 DocStrings

Bases: BaseOwner

Owner implementation using GitHubKit.

Source code in src/githarbor/providers/githubkit_provider/owner.py
class GitHubKitOwner(BaseOwner):
    """Owner implementation using GitHubKit."""

    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
        """
        from githubkit import GitHub
        from githubkit.exception import GitHubException

        try:
            t = token or os.getenv("GITHUB_TOKEN")
            if not t:
                msg = "GitHub token is required"
                raise ValueError(msg)
            self._token = t
            self._gh = GitHub(t)
            self._name = username
            self._user = self._gh.rest.users.get_authenticated().parsed_data

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

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

    @classmethod
    def from_url(cls, url: str, **kwargs: Any) -> GitHubKitOwner:
        """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_repos_owned_by_user(
        self, headers: dict[str, str] | None = None
    ) -> list[dict[str, Any]]:
        """List repositories owned by user.

        Args:
            headers: Optional additional headers to pass

        Returns:
            List of repository data
        """
        import aiohttp

        base_headers = {
            "Accept": "application/vnd.github.v3+json",
            "Authorization": f"Bearer {self._token}",
        }
        if headers:
            base_headers.update(headers)

        url = f"https://api.github.com/users/{self._name}/repos"

        async with aiohttp.ClientSession() as session:  # noqa: SIM117
            async with session.get(url, headers=base_headers) as response:
                if response.status == 200:  # noqa: PLR2004
                    return await response.json()
                msg = f"Failed to list repositories: {response.status}"
                raise ResourceNotFoundError(msg)

    async def list_repositories_async(self) -> list[BaseRepository]:
        """List all repositories owned by this user."""
        try:
            repos = await self.list_repos_owned_by_user()
            return [create_repository(repo["html_url"]) for repo in repos if repo.get("html_url")]
        except Exception as e:
            msg = f"Failed to list repositories: {e!s}"
            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 githubkit.exception import GitHubException

        try:
            resp = await self._gh.rest.repos.async_create_for_authenticated_user(
                name=name,
                description=description,
                private=private,
            )
            return create_repository(resp.parsed_data.html_url)
        except GitHubException as e:
            msg = f"Failed to create repository: {e!s}"
            raise ResourceNotFoundError(msg) from e

    async def get_user_async(self) -> User:
        """Get user information."""
        from githubkit.exception import GitHubException

        try:
            resp = await self._gh.rest.users.async_get_by_username(self._name)
            return githubkittools.create_user_model(resp.parsed_data)
        except GitHubException as e:
            msg = f"Failed to get user info: {e!s}"
            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 githubkit.exception import GitHubException

        try:
            await self._gh.rest.repos.async_delete(self._name, name)
        except GitHubException as e:
            msg = f"Failed to delete repository: {e!s}"
            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/githubkit_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
    """
    from githubkit import GitHub
    from githubkit.exception import GitHubException

    try:
        t = token or os.getenv("GITHUB_TOKEN")
        if not t:
            msg = "GitHub token is required"
            raise ValueError(msg)
        self._token = t
        self._gh = GitHub(t)
        self._name = username
        self._user = self._gh.rest.users.get_authenticated().parsed_data

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

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/githubkit_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 githubkit.exception import GitHubException

    try:
        resp = await self._gh.rest.repos.async_create_for_authenticated_user(
            name=name,
            description=description,
            private=private,
        )
        return create_repository(resp.parsed_data.html_url)
    except GitHubException as e:
        msg = f"Failed to create repository: {e!s}"
        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/githubkit_provider/owner.py
async def delete_repository_async(self, name: str) -> None:
    """Delete a repository.

    Args:
        name: Name of repository to delete
    """
    from githubkit.exception import GitHubException

    try:
        await self._gh.rest.repos.async_delete(self._name, name)
    except GitHubException as e:
        msg = f"Failed to delete repository: {e!s}"
        raise ResourceNotFoundError(msg) from e

from_url classmethod

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

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/githubkit_provider/owner.py
@classmethod
def from_url(cls, url: str, **kwargs: Any) -> GitHubKitOwner:
    """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/githubkit_provider/owner.py
async def get_user_async(self) -> User:
    """Get user information."""
    from githubkit.exception import GitHubException

    try:
        resp = await self._gh.rest.users.async_get_by_username(self._name)
        return githubkittools.create_user_model(resp.parsed_data)
    except GitHubException as e:
        msg = f"Failed to get user info: {e!s}"
        raise ResourceNotFoundError(msg) from e

list_repos_owned_by_user async

list_repos_owned_by_user(headers: dict[str, str] | None = None) -> list[dict[str, Any]]

List repositories owned by user.

Parameters:

Name Type Description Default
headers dict[str, str] | None

Optional additional headers to pass

None

Returns:

Type Description
list[dict[str, Any]]

List of repository data

Source code in src/githarbor/providers/githubkit_provider/owner.py
async def list_repos_owned_by_user(
    self, headers: dict[str, str] | None = None
) -> list[dict[str, Any]]:
    """List repositories owned by user.

    Args:
        headers: Optional additional headers to pass

    Returns:
        List of repository data
    """
    import aiohttp

    base_headers = {
        "Accept": "application/vnd.github.v3+json",
        "Authorization": f"Bearer {self._token}",
    }
    if headers:
        base_headers.update(headers)

    url = f"https://api.github.com/users/{self._name}/repos"

    async with aiohttp.ClientSession() as session:  # noqa: SIM117
        async with session.get(url, headers=base_headers) as response:
            if response.status == 200:  # noqa: PLR2004
                return await response.json()
            msg = f"Failed to list repositories: {response.status}"
            raise ResourceNotFoundError(msg)

list_repositories_async async

list_repositories_async() -> list[BaseRepository]

List all repositories owned by this user.

Source code in src/githarbor/providers/githubkit_provider/owner.py
async def list_repositories_async(self) -> list[BaseRepository]:
    """List all repositories owned by this user."""
    try:
        repos = await self.list_repos_owned_by_user()
        return [create_repository(repo["html_url"]) for repo in repos if repo.get("html_url")]
    except Exception as e:
        msg = f"Failed to list repositories: {e!s}"
        raise ResourceNotFoundError(msg) from e

:fa-brands-github: Show source on GitHub