Skip to content

Commit

Permalink
Migrate more stuff to context module
Browse files Browse the repository at this point in the history
  • Loading branch information
gizmo385 committed Sep 12, 2024
1 parent 2f2f7e2 commit e1dbe9c
Show file tree
Hide file tree
Showing 6 changed files with 232 additions and 249 deletions.
10 changes: 4 additions & 6 deletions lazy_github/lib/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

from lazy_github.lib.config import Config
from lazy_github.lib.constants import JSON_CONTENT_ACCEPT_TYPE
from lazy_github.lib.github.client import GithubClient, _get_client
from lazy_github.lib.github.auth import token
from lazy_github.lib.github.client import GithubClient
from lazy_github.lib.utils import classproperty


Expand All @@ -22,13 +23,10 @@ def config(cls) -> Config:
def client(cls) -> GithubClient:
# Ideally this is would just be a none check but that doesn't properly type check for some reason
if not isinstance(cls._client, GithubClient):
cls._client = _get_client(config=cls.config)
cls._client = GithubClient(cls.config, token())
return cls._client


def github_headers(accept: str = JSON_CONTENT_ACCEPT_TYPE, cache_duration: Optional[int] = None) -> dict[str, str]:
"""Helper function to build headers for Github API requests"""
headers = {"Accept": accept, "Authorization": f"Bearer {LazyGithubContext.client.access_token}"}
max_age = cache_duration or LazyGithubContext.config.cache.default_ttl
headers["Cache-Control"] = f"max-age={max_age}"
return headers
return LazyGithubContext.client.github_headers(accept, cache_duration)
41 changes: 2 additions & 39 deletions lazy_github/lib/github/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def __init__(self, config: Config, access_token: str) -> None:
self.access_token = access_token
self._user: User | None = None

def headers_with_auth_accept(
def github_headers(
self, accept: str = JSON_CONTENT_ACCEPT_TYPE, cache_duration: Optional[int] = None
) -> dict[str, str]:
"""Helper function to build a request with specific headers"""
Expand All @@ -31,43 +31,6 @@ def headers_with_auth_accept(
async def user(self) -> User:
"""Returns the authed user for this client"""
if self._user is None:
response = await self.get("/user", headers=self.headers_with_auth_accept())
response = await self.get("/user", headers=self.github_headers())
self._user = User(**response.json())
return self._user


_GITHUB_CLIENT: GithubClient | None = None


def _get_client(config: Config | None = None) -> GithubClient:
global _GITHUB_CLIENT
if not _GITHUB_CLIENT:
_GITHUB_CLIENT = GithubClient(config or Config.load_config(), token())
return _GITHUB_CLIENT


def get(
url: URL | str,
headers: HeaderTypes | None = None,
params: QueryParamTypes | None = None,
follow_redirects: bool = True,
) -> Coroutine[Any, Any, Response]:
return _get_client().get(url, headers=headers, params=params, follow_redirects=follow_redirects)


def post(url: URL | str, json: Any | None = None, headers: HeaderTypes | None = None) -> Coroutine[Any, Any, Response]:
return _get_client().post(url, json=json, headers=headers)


def patch(url: URL | str, json: Any | None, headers: HeaderTypes | None = None) -> Coroutine[Any, Any, Response]:
return _get_client().patch(url, json=json, headers=headers)


def headers_with_auth_accept(
accept: str = JSON_CONTENT_ACCEPT_TYPE, cache_duration: Optional[int] = None
) -> dict[str, str]:
return _get_client().headers_with_auth_accept(accept, cache_duration)


async def user() -> User:
return await _get_client().user()
16 changes: 6 additions & 10 deletions lazy_github/lib/github/pull_requests.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from lazy_github.lib.config import Config
from lazy_github.lib.constants import DIFF_CONTENT_ACCEPT_TYPE
from lazy_github.lib.context import LazyGithubContext
from lazy_github.lib.context import LazyGithubContext, github_headers
from lazy_github.lib.github.issues import list_issues
from lazy_github.models.github import (
FullPullRequest,
Expand All @@ -24,32 +24,29 @@ async def list_for_repo(repo: Repository) -> list[PartialPullRequest]:
async def get_full_pull_request(partial_pr: PartialPullRequest) -> FullPullRequest:
"""Converts a partial pull request into a full pull request"""
url = f"/repos/{partial_pr.repo.owner.login}/{partial_pr.repo.name}/pulls/{partial_pr.number}"
headers = LazyGithubContext.client.headers_with_auth_accept()
response = await LazyGithubContext.client.get(url, headers=headers)
response = await LazyGithubContext.client.get(url, headers=github_headers())
response.raise_for_status()
return FullPullRequest(**response.json(), repo=partial_pr.repo)


async def get_diff(pr: FullPullRequest) -> str:
"""Fetches the raw diff for an individual pull request"""
headers = LazyGithubContext.client.headers_with_auth_accept(DIFF_CONTENT_ACCEPT_TYPE)
headers = github_headers(DIFF_CONTENT_ACCEPT_TYPE)
response = await LazyGithubContext.client.get(pr.diff_url, headers=headers, follow_redirects=True)
response.raise_for_status()
return response.text


async def get_review_comments(pr: FullPullRequest, review: Review) -> list[ReviewComment]:
url = f"/repos/{pr.repo.owner.login}/{pr.repo.name}/pulls/{pr.number}/reviews/{review.id}/comments"
headers = LazyGithubContext.client.headers_with_auth_accept()
response = await LazyGithubContext.client.get(url, headers=headers)
response = await LazyGithubContext.client.get(url, headers=github_headers())
response.raise_for_status()
return [ReviewComment(**c) for c in response.json()]


async def get_reviews(pr: FullPullRequest, with_comments: bool = True) -> list[Review]:
url = url = f"/repos/{pr.repo.owner.login}/{pr.repo.name}/pulls/{pr.number}/reviews"
headers = LazyGithubContext.client.headers_with_auth_accept()
response = await LazyGithubContext.client.get(url, headers=headers)
response = await LazyGithubContext.client.get(url, headers=github_headers())
response.raise_for_status()
reviews: list[Review] = []
for raw_review in response.json():
Expand All @@ -64,8 +61,7 @@ async def reply_to_review_comment(
repo: Repository, issue: Issue, comment: ReviewComment, comment_body: str
) -> ReviewComment:
url = f"/repos/{repo.owner.login}/{repo.name}/pulls/{issue.number}/comments/{comment.id}/replies"
headers = LazyGithubContext.client.headers_with_auth_accept()
response = await LazyGithubContext.client.post(url, headers=headers, json={"body": comment_body})
response = await LazyGithubContext.client.post(url, headers=github_headers(), json={"body": comment_body})
response.raise_for_status()
return ReviewComment(**response.json())

Expand Down
6 changes: 3 additions & 3 deletions lazy_github/lib/github/repositories.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from functools import partial
from typing import Literal

import lazy_github.lib.github.client as github
from lazy_github.lib.context import LazyGithubContext, github_headers
from lazy_github.lib.config import Config
from lazy_github.models.github import Repository

Expand All @@ -22,10 +22,10 @@ async def _list_for_page(
) -> tuple[list[Repository], bool]:
"""Retrieves a single page of Github repos matching the specified criteria"""
config = Config.load_config()
headers = github.headers_with_auth_accept(cache_duration=config.cache.list_repos_ttl)
headers = github_headers(cache_duration=config.cache.list_repos_ttl)
query_params = {"type": repo_types, "direction": direction, "sort": sort, "page": page, "per_page": per_page}

response = await github.get("/user/repos", headers=headers, params=query_params)
response = await LazyGithubContext.client.get("/user/repos", headers=headers, params=query_params)
response.raise_for_status()

link_header = response.headers.get("link")
Expand Down
4 changes: 2 additions & 2 deletions lazy_github/ui/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from textual import log
from textual.app import App

from lazy_github.lib.context import LazyGithubContext
from lazy_github.lib.github.auth import GithubAuthenticationRequired
import lazy_github.lib.github.client as github
from lazy_github.ui.screens.auth import AuthenticationModal
from lazy_github.ui.screens.primary import LazyGithubMainScreen

Expand All @@ -13,7 +13,7 @@ class LazyGithub(App):
async def authenticate_with_github(self):
try:
# We pull the user here to validate auth
_ = await github.user()
_ = await LazyGithubContext.client.user()
self.push_screen(LazyGithubMainScreen())
except GithubAuthenticationRequired:
log("Triggering auth with github")
Expand Down
Loading

0 comments on commit e1dbe9c

Please sign in to comment.