Coverage for polar/integrations/github/client.py: 66%
27 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-12-05 16:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2025-12-05 16:17 +0000
1from enum import StrEnum 1a
2from typing import Any 1a
4from githubkit import ( 1a
5 AppAuthStrategy,
6 AppInstallationAuthStrategy,
7 GitHub,
8 Response,
9 TokenAuthStrategy,
10)
12from polar.config import settings 1a
15class UnexpectedStatusCode(Exception): ... 1a
18class AuthenticationRequired(UnexpectedStatusCode): ... 1a
21class Forbidden(UnexpectedStatusCode): ... 1a
24class NotFound(UnexpectedStatusCode): ... 1a
27class ValidationFailed(UnexpectedStatusCode): ... 1a
30class GitHubApp(StrEnum): 1a
31 repository_benefit = "repository_benefit" 1a
34HTTP_EXCEPTIONS = { 1a
35 401: AuthenticationRequired,
36 403: Forbidden,
37 404: NotFound,
38 422: ValidationFailed,
39}
41###############################################################################
42# GITHUB API HELPERS
43###############################################################################
46def ensure_expected_response( 1a
47 response: Response[Any], accepted: set[int] = {200, 304}
48) -> bool:
49 status_code = response.status_code
50 if status_code in accepted:
51 return True
53 http_exception = HTTP_EXCEPTIONS.get(status_code, UnexpectedStatusCode)
54 raise http_exception()
57###############################################################################
58# GITHUB API CLIENTS
59###############################################################################
62def get_client(access_token: str) -> GitHub[TokenAuthStrategy]: 1a
63 return GitHub(access_token, http_cache=False)
66def get_app_client( 1a
67 app: GitHubApp = GitHubApp.repository_benefit,
68) -> GitHub[AppAuthStrategy]:
69 return GitHub(
70 AppAuthStrategy(
71 app_id=settings.GITHUB_REPOSITORY_BENEFITS_APP_IDENTIFIER,
72 private_key=settings.GITHUB_REPOSITORY_BENEFITS_APP_PRIVATE_KEY,
73 client_id=settings.GITHUB_REPOSITORY_BENEFITS_CLIENT_ID,
74 client_secret=settings.GITHUB_REPOSITORY_BENEFITS_CLIENT_SECRET,
75 ),
76 http_cache=False,
77 )
80def get_app_installation_client( 1a
81 installation_id: int,
82 *,
83 app: GitHubApp = GitHubApp.repository_benefit,
84) -> GitHub[AppInstallationAuthStrategy]:
85 if not installation_id:
86 raise Exception("unable to create github client: no installation_id provided")
88 return GitHub(
89 AppInstallationAuthStrategy(
90 app_id=settings.GITHUB_REPOSITORY_BENEFITS_APP_IDENTIFIER,
91 private_key=settings.GITHUB_REPOSITORY_BENEFITS_APP_PRIVATE_KEY,
92 client_id=settings.GITHUB_REPOSITORY_BENEFITS_CLIENT_ID,
93 client_secret=settings.GITHUB_REPOSITORY_BENEFITS_CLIENT_SECRET,
94 installation_id=installation_id,
95 ),
96 http_cache=False,
97 )
100__all__ = [ 1a
101 "get_client",
102 "get_app_client",
103 "get_app_installation_client",
104 "GitHub",
105 "AppInstallationAuthStrategy",
106 "TokenAuthStrategy",
107 "Response",
108]