Skip to content

Commit

Permalink
aio.api.github: Improve typing (#2334)
Browse files Browse the repository at this point in the history
Signed-off-by: Ryan Northey <ryan@synca.io>
  • Loading branch information
phlax authored Oct 11, 2024
1 parent a25c513 commit 69b0402
Show file tree
Hide file tree
Showing 10 changed files with 76 additions and 72 deletions.
2 changes: 1 addition & 1 deletion aio.api.github/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.2.8-dev
0.2.8
3 changes: 1 addition & 2 deletions aio.api.github/aio/api/github/abstract/actions/actions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@

from functools import cached_property
from typing import Optional

import abstracts

Expand Down Expand Up @@ -58,7 +57,7 @@ async def dispatch(
app_id: str,
installation_id: str,
key: str,
data: Optional[dict] = None) -> None:
data: dict | None = None) -> None:
access_token_response = await get_installation_access_token(
self.github.api,
installation_id=installation_id,
Expand Down
8 changes: 4 additions & 4 deletions aio.api.github/aio/api/github/abstract/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

from typing import Any, Callable, Dict
from typing import Any, Callable

from aio.api.github import interface

Expand All @@ -10,7 +10,7 @@
class GithubEntity:
"""Base Github entity class."""

def __init__(self, github: interface.IGithubAPI, data: Dict) -> None:
def __init__(self, github: interface.IGithubAPI, data: dict) -> None:
self.data = data
self._github = github

Expand All @@ -20,7 +20,7 @@ def github(self) -> "interface.IGithubAPI":
return self._github

@property
def __data__(self) -> Dict[str, Callable]:
def __data__(self) -> dict[str, Callable]:
"""Dictionary of callables to mangle corresponding `self.data` keys."""
return {}

Expand All @@ -38,7 +38,7 @@ def __getattr__(self, k: str, default: Any = UNSET) -> Any:
class GithubRepoEntity(GithubEntity):
"""Base Github repo entity class."""

def __init__(self, repo: interface.IGithubRepo, data: Dict) -> None:
def __init__(self, repo: interface.IGithubRepo, data: dict) -> None:
self.data = data
self._repo = repo

Expand Down
13 changes: 7 additions & 6 deletions aio.api.github/aio/api/github/abstract/issues/issues.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

import urllib
from functools import cached_property, partial
from typing import Any, Callable, Dict, Optional
from typing import Any, Callable

import gidgethub

Expand Down Expand Up @@ -59,7 +59,7 @@ class AGithubIssues(metaclass=abstracts.Abstraction):
def __init__(
self,
github: interface.IGithubAPI,
repo: Optional[interface.IGithubRepo] = None,
repo: interface.IGithubRepo | None = None,
filter: str = "") -> None:
self._github = github
self.repo = repo
Expand Down Expand Up @@ -97,7 +97,7 @@ async def create(self, title: str, **kwargs) -> interface.IGithubIssue:

def inflater(
self,
repo: Optional[interface.IGithubRepo] = None) -> Callable:
repo: interface.IGithubRepo | None = None) -> Callable:
"""Return default or custom callable to inflate a `GithubIssue`."""
if not (repo := repo or self.repo):
return self._inflate
Expand All @@ -106,8 +106,9 @@ def inflater(
def search(
self,
query: str,
repo: Optional[
interface.IGithubRepo] = None) -> interface.IGithubIterator:
repo: (
interface.IGithubRepo
| None) = None) -> interface.IGithubIterator:
return self.github.getiter(
self.search_query(query),
inflate=self.inflater(repo))
Expand All @@ -117,7 +118,7 @@ def search_query(self, query: str) -> str:
q = urllib.parse.quote(f"{self.filter}{query}")
return f"/search/issues?q={q}"

def _inflate(self, result: Dict) -> interface.IGithubIssue:
def _inflate(self, result: dict) -> interface.IGithubIssue:
"""Inflate an issue, finding the repo from the issue url."""
return self.github.issue_class(
self.github.repo_from_url(result["repository_url"]),
Expand Down
30 changes: 15 additions & 15 deletions aio.api.github/aio/api/github/abstract/issues/tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import re
from functools import cached_property
from typing import (
Any, AsyncGenerator, Dict,
Optional, Pattern, Tuple, Type)
Any, AsyncGenerator,
Pattern, Type)

import abstracts

Expand Down Expand Up @@ -37,19 +37,19 @@ def closing_tpl(self) -> str:
return self.issues.closing_tpl

@property
def key(self) -> Optional[str]:
def key(self) -> str | None:
return self.parsed.get("key")

@property
def number(self) -> int:
return self.issue.number

@property
def parse_vars(self) -> Tuple[str, ...]:
def parse_vars(self) -> tuple[str, ...]:
return ("key", )

@cached_property
def parsed(self) -> Dict[str, str]:
def parsed(self) -> dict[str, str]:
parsed = self.title_re.search(self.title)
return (
{k: parsed.group(i + 1)
Expand Down Expand Up @@ -89,8 +89,8 @@ class AGithubTrackedIssues(metaclass=abstracts.Abstraction):
def __init__(
self,
github: interface.IGithubAPI,
issue_author: Optional[str] = None,
repo_name: Optional[str] = None) -> None:
issue_author: str | None = None,
repo_name: str | None = None) -> None:
self._github = github
self._issue_author = issue_author
self._repo_name = repo_name
Expand Down Expand Up @@ -133,8 +133,8 @@ def issue_class(self) -> Type[interface.IGithubTrackedIssue]:
raise NotImplementedError

@async_property(cache=True)
async def issues(self) -> Dict[str, interface.IGithubTrackedIssue]:
issues: Dict[str, interface.IGithubTrackedIssue] = {}
async def issues(self) -> dict[str, interface.IGithubTrackedIssue]:
issues: dict[str, interface.IGithubTrackedIssue] = {}
for issue in await self.open_issues:
if self.track_issue(issues, issue):
issues[issue.key] = issue
Expand All @@ -147,11 +147,11 @@ def issues_search_tpl(self):

@property # type:ignore
@abstracts.interfacemethod
def labels(self) -> Tuple[str, ...]:
def labels(self) -> tuple[str, ...]:
raise NotImplementedError

@async_property(cache=True)
async def missing_labels(self) -> Tuple[str, ...]:
async def missing_labels(self) -> tuple[str, ...]:
found = []
async for label in self.repo.labels:
if label.name in self.labels:
Expand All @@ -165,7 +165,7 @@ async def missing_labels(self) -> Tuple[str, ...]:
if label not in found)

@async_property(cache=True)
async def open_issues(self) -> Tuple[interface.IGithubTrackedIssue, ...]:
async def open_issues(self) -> tuple[interface.IGithubTrackedIssue, ...]:
issues = []
async for issue in self:
issues.append(issue)
Expand Down Expand Up @@ -202,7 +202,7 @@ def title_tpl(self):
raise NotImplementedError

@async_property(cache=True)
async def titles(self) -> Tuple[str, ...]:
async def titles(self) -> tuple[str, ...]:
return tuple(issue.title for issue in await self.open_issues)

async def create(
Expand Down Expand Up @@ -230,7 +230,7 @@ def iter_issues(self) -> "interface.IGithubIterator":

def track_issue(
self,
issues: Dict[str, interface.IGithubTrackedIssue],
issues: dict[str, interface.IGithubTrackedIssue],
issue: interface.IGithubTrackedIssue) -> bool:
return issue.key not in issues

Expand All @@ -247,5 +247,5 @@ def __getitem__(self, k) -> interface.IGithubTrackedIssues:

@property # type:ignore
@abstracts.interfacemethod
def tracked_issues(self) -> Dict[str, interface.IGithubTrackedIssues]:
def tracked_issues(self) -> dict[str, interface.IGithubTrackedIssues]:
raise NotImplementedError
14 changes: 8 additions & 6 deletions aio.api.github/aio/api/github/abstract/iterator.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

from typing import Any, AsyncGenerator, Dict, Mapping, Tuple
from typing import Any, AsyncGenerator, AsyncIterable, Mapping, TypeVar

import gidgethub.abc
import gidgethub.sansio
Expand All @@ -10,9 +10,11 @@

from aio.api.github import interface

T = TypeVar('T')


@abstracts.implementer(interface.IGithubIterator)
class AGithubIterator(metaclass=abstracts.Abstraction):
class AGithubIterator(AsyncIterable[T], metaclass=abstracts.Abstraction):
"""Async iterator to wrap gidgethub API and provide `total_count`."""

def __init__(
Expand All @@ -27,14 +29,14 @@ def __init__(
self.kwargs = kwargs
self._inflate = kwargs.pop("inflate", None)

async def __aiter__(self) -> AsyncGenerator[Any, None]:
async def __aiter__(self) -> AsyncGenerator[T, None]:
aiter = self.api.getiter(
self.query, *self.args, **self.kwargs)
async for item in aiter:
yield self.inflate(item)

@property
def count_request_headers(self) -> Dict[str, str]:
def count_request_headers(self) -> dict[str, str]:
"""Request headers for API call to get `total_count`."""
request_headers = gidgethub.sansio.create_headers(
self.api.requester,
Expand All @@ -60,7 +62,7 @@ async def total_count(self) -> int:
await self.api._request(
"GET", self.count_url, self.count_request_headers, b''))

def count_from_data(self, data: Dict) -> int:
def count_from_data(self, data: dict) -> int:
"""Get `total_count` from the data."""
return (
int(data["total_count"])
Expand All @@ -79,7 +81,7 @@ def count_from_headers(self, headers: Mapping[str, str]) -> int:

def count_from_response(
self,
response: Tuple[int, Mapping[str, str], bytes]) -> int:
response: tuple[int, Mapping[str, str], bytes]) -> int:
"""Get total count from the headers or data."""

(data,
Expand Down
6 changes: 3 additions & 3 deletions aio.api.github/aio/api/github/abstract/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import pathlib
from datetime import datetime
from functools import cached_property
from typing import AsyncIterator, Callable, Dict, Optional, Type
from typing import AsyncIterator, Callable, Type

from packaging import version

Expand Down Expand Up @@ -38,7 +38,7 @@ async def create(
return cls(repo, data)

@cached_property
def __data__(self) -> Dict[str, Callable]:
def __data__(self) -> dict[str, Callable]:
return dict(
created_at=utils.dt_from_js_isoformat,
published_at=utils.dt_from_js_isoformat)
Expand Down Expand Up @@ -76,7 +76,7 @@ def upload_url(self) -> str:
return self.data["upload_url"]

@cached_property
def version(self) -> Optional[version.Version]:
def version(self) -> version.Version | None:
try:
return version.parse(self.tag_version)
except version.InvalidVersion:
Expand Down
22 changes: 11 additions & 11 deletions aio.api.github/aio/api/github/abstract/repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import pathlib
from datetime import datetime
from functools import cached_property, partial
from typing import Any, Dict, Optional, Type
from typing import Any, Type

import gidgethub

Expand Down Expand Up @@ -61,7 +61,7 @@ async def commit(self, name: str) -> "interface.IGithubCommit":

def commits(
self,
since: Optional[datetime] = None) -> "interface.IGithubIterator":
since: datetime | None = None) -> "interface.IGithubIterator":
query = "commits"
if since is not None:
query = f"{query}?since={utils.dt_to_js_isoformat(since)}"
Expand All @@ -74,14 +74,14 @@ async def create_release(
commitish: str,
tag_name: str,
dry_run: bool = False,
body: Optional[str] = None,
latest: Optional[bool] = False,
generate_release_notes: Optional[bool] = False) -> (
body: str | None = None,
latest: bool | None = False,
generate_release_notes: bool | None = False) -> (
"interface.IGithubRelease"):
if await self.tag_exists(tag_name) and not dry_run:
raise exceptions.TagExistsError(
f"Cannot create tag, already exists: {tag_name}")
url_vars: Dict[str, bool | str] = dict(
url_vars: dict[str, bool | str] = dict(
tag_name=tag_name,
name=tag_name,
target_commitish=commitish,
Expand Down Expand Up @@ -113,8 +113,8 @@ def github_endpoint(self, rel_path: str) -> str:

async def highest_release(
self,
since: Optional[datetime] = None) -> Optional[
"interface.IGithubRelease"]:
since: datetime | None = None) -> (
interface.IGithubRelease | None):
highest_release = None

async for release in self.releases():
Expand All @@ -140,13 +140,13 @@ def iter_entities(
inflate=partial(entity, self),
**kwargs)

async def patch(self, query: str, data: Optional[Dict] = None) -> Any:
async def patch(self, query: str, data: dict | None = None) -> Any:
return await self.github.patch(self.github_endpoint(query), data=data)

async def post(
self,
query: str,
data: Optional[Dict] = None, **kwargs) -> Any:
data: dict | None = None, **kwargs) -> Any:
return await self.github.post(
self.github_endpoint(query),
data=data,
Expand All @@ -155,7 +155,7 @@ async def post(
async def release(
self,
name: str,
data: Optional[dict] = None,
data: dict | None = None,
dry_run: bool = False) -> "interface.IGithubRelease":
if data:
return await self.github.release_class.create(self, data, dry_run)
Expand Down
Loading

0 comments on commit 69b0402

Please sign in to comment.