ã¤ã®ãªã¹ã®MRCè³ãããã¯ã¼ã¯ãã¤ããã¯ã¹ã¦ãããã¨ãªãã¯ã¹ãã©ã¼ã大å¦ã«ããç 究ã§ãè³ã®å¦ç¿åçã人工ç¥è½ã®ãã®ã¨ã¯æ ¹æ¬çã«ç°ãªã£ã¦ããã¨ã示ããã¦ãã¾ãã
è³ã®å¦ç¿åçã¯äººå·¥ç¥è½ã®ãã®ã¨ã¯æ ¹æ¬çã«ç°ãªã£ã¦ãã - GIGAZINE
ç 究ãã¼ã ã¯ãå¦ç¿ä¸ã®è³ã®ãã¥ã¼ãã³ã®æåãã·ããã¹çµåã®å¤åã説æããæ å ±å¦çã¢ãã«ã調ã¹ã¦åæãã·ãã¥ã¬ã¼ããã人工ã®ãã¥ã¼ã©ã«ãããã¯ã¼ã¯ã¨ã¯æ ¹æ¬çã«ç°ãªãåçã§ãããã¨ãçºè¦ãã¾ããã
è³ã®å¦ç¿åçã¯äººå·¥ç¥è½ã®ãã®ã¨ã¯æ ¹æ¬çã«ç°ãªã£ã¦ãã - GIGAZINE
â§ æ ¹æ¬çã«ç°ãªãã§ããããã¨ã¯èª°ããæã£ã¦ããã§ããããã©ã漸ããç§å¦çã«æ¤è¨¼ãããæããªãã§ããã
人éã®è³ã®ç 究ãé²ãã¨è¯ãã§ããªã
PyGitHubã¨ã¯
è·å ´ã®æ¹ã«æãã¦ããã ãããPyGitHubãã¨ããã©ã¤ãã©ãªã®åå¨ãç¥ã£ãã®ã§ãåå¿é²ã¨ãã¦ã
å ¬å¼ã®ããã¥ã¡ã³ãã«ããã¾ãã¨ã
PyGitHub is a Python library to access the GitHub REST API. This library enables you to manage GitHub resources such as repositories, user profiles, and organizations in your Python applications.
â§ãGitHubãã®ãREST APIãããPythonãããå®è¡ã§ããããã«ãã¦ããã©ã¤ãã©ãªã§ããã¨ã
ãGitHub Appãã®ãInstallation Access Tokenããåå¾ããã«ã¯ã
â§ãInstallation IDããåå¾å¾ã
⧠ä¸è¨ã®ã¡ã½ãããå¼ã¶ãã¨ã«ãªããã ã¨æãããã®ã ããå¼æ°ã®ãpermissionsãã®æå®ãæå³ä¸æéããããã...
ã½ã¼ã¹ã³ã¼ãã確èªããã¨ããã
â https://github.com/PyGithub/PyGithub/blob/main/github/GithubIntegration.py#L245
############################ Copyrights and license ############################ # # # Copyright 2023 Denis Blanchette <[email protected]> # # Copyright 2023 Enrico Minack <[email protected]> # # Copyright 2023 Hemslo Wang <[email protected]> # # Copyright 2023 Jirka Borovec <[email protected]> # # Copyright 2023 Mark Amery <[email protected]> # # Copyright 2023 Trim21 <[email protected]> # # Copyright 2023 chantra <[email protected]> # # Copyright 2024 Enrico Minack <[email protected]> # # Copyright 2024 Jirka Borovec <[email protected]> # # Copyright 2024 Min RK <[email protected]> # # # # This file is part of PyGithub. # # http://pygithub.readthedocs.io/ # # # # PyGithub is free software: you can redistribute it and/or modify it under # # the terms of the GNU Lesser General Public License as published by the Free # # Software Foundation, either version 3 of the License, or (at your option) # # any later version. # # # # PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # # details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with PyGithub. If not, see <http://www.gnu.org/licenses/>. # # # ################################################################################ from __future__ import annotations import urllib.parse import warnings from typing import Any import deprecated import urllib3 from urllib3 import Retry import github from github import Consts from github.Auth import AppAuth from github.GithubApp import GithubApp from github.GithubException import GithubException from github.Installation import Installation from github.InstallationAuthorization import InstallationAuthorization from github.PaginatedList import PaginatedList from github.Requester import Requester class GithubIntegration: """ Main class to obtain tokens for a GitHub integration. """ # keep non-deprecated arguments in-sync with Requester # v3: remove integration_id, private_key, jwt_expiry, jwt_issued_at and jwt_algorithm # v3: move auth to the front of arguments # v3: move * before first argument so all arguments must be named, # allows to reorder / add new arguments / remove deprecated arguments without breaking user code # added here to force named parameters because new parameters have been added auth: AppAuth base_url: str __requester: Requester def __init__( self, integration_id: int | str | None = None, private_key: str | None = None, base_url: str = Consts.DEFAULT_BASE_URL, *, timeout: int = Consts.DEFAULT_TIMEOUT, user_agent: str = Consts.DEFAULT_USER_AGENT, per_page: int = Consts.DEFAULT_PER_PAGE, verify: bool | str = True, retry: int | Retry | None = None, pool_size: int | None = None, seconds_between_requests: float | None = Consts.DEFAULT_SECONDS_BETWEEN_REQUESTS, seconds_between_writes: float | None = Consts.DEFAULT_SECONDS_BETWEEN_WRITES, jwt_expiry: int = Consts.DEFAULT_JWT_EXPIRY, jwt_issued_at: int = Consts.DEFAULT_JWT_ISSUED_AT, jwt_algorithm: str = Consts.DEFAULT_JWT_ALGORITHM, auth: AppAuth | None = None, # v3: set lazy = True as the default lazy: bool = False, ) -> None: """ :param integration_id: int deprecated, use auth=github.Auth.AppAuth(...) instead :param private_key: string deprecated, use auth=github.Auth.AppAuth(...) instead :param base_url: string :param timeout: integer :param user_agent: string :param per_page: int :param verify: boolean or string :param retry: int or urllib3.util.retry.Retry object :param pool_size: int :param seconds_between_requests: float :param seconds_between_writes: float :param jwt_expiry: int deprecated, use auth=github.Auth.AppAuth(...) instead :param jwt_issued_at: int deprecated, use auth=github.Auth.AppAuth(...) instead :param jwt_algorithm: string deprecated, use auth=github.Auth.AppAuth(...) instead :param auth: authentication method :param lazy: completable objects created from this instance are lazy, as well as completable objects created from those, and so on """ if integration_id is not None: assert isinstance(integration_id, (int, str)), integration_id if private_key is not None: assert isinstance(private_key, str), "supplied private key should be a string" assert isinstance(base_url, str), base_url assert isinstance(timeout, int), timeout assert user_agent is None or isinstance(user_agent, str), user_agent assert isinstance(per_page, int), per_page assert isinstance(verify, (bool, str)), verify assert retry is None or isinstance(retry, int) or isinstance(retry, urllib3.util.Retry), retry assert pool_size is None or isinstance(pool_size, int), pool_size assert seconds_between_requests is None or seconds_between_requests >= 0 assert seconds_between_writes is None or seconds_between_writes >= 0 assert isinstance(jwt_expiry, int), jwt_expiry assert Consts.MIN_JWT_EXPIRY <= jwt_expiry <= Consts.MAX_JWT_EXPIRY, jwt_expiry assert isinstance(jwt_issued_at, int) assert isinstance(lazy, bool), lazy self.base_url = base_url if ( integration_id is not None or private_key is not None or jwt_expiry != Consts.DEFAULT_JWT_EXPIRY or jwt_issued_at != Consts.DEFAULT_JWT_ISSUED_AT or jwt_algorithm != Consts.DEFAULT_JWT_ALGORITHM ): warnings.warn( "Arguments integration_id, private_key, jwt_expiry, jwt_issued_at and jwt_algorithm are deprecated, " "please use auth=github.Auth.AppAuth(...) instead", category=DeprecationWarning, ) auth = AppAuth( integration_id, # type: ignore private_key, # type: ignore jwt_expiry=jwt_expiry, jwt_issued_at=jwt_issued_at, jwt_algorithm=jwt_algorithm, ) assert isinstance( auth, AppAuth ), f"GithubIntegration requires github.Auth.AppAuth authentication, not {type(auth)}" self.auth = auth self.__requester = Requester( auth=auth, base_url=self.base_url, timeout=timeout, user_agent=user_agent, per_page=per_page, verify=verify, retry=retry, pool_size=pool_size, seconds_between_requests=seconds_between_requests, seconds_between_writes=seconds_between_writes, lazy=lazy, ) def withLazy(self, lazy: bool) -> GithubIntegration: """ Create a GithubIntegration instance with identical configuration but the given lazy setting. :param lazy: completable objects created from this instance are lazy, as well as completable objects created from those, and so on :return: new Github instance """ kwargs = self.__requester.kwargs kwargs.update(lazy=lazy) return GithubIntegration(**kwargs) def close(self) -> None: """Close connections to the server. Alternatively, use the GithubIntegration object as a context manager: .. code-block:: python with github.GithubIntegration(...) as gi: # do something """ self.__requester.close() def __enter__(self) -> GithubIntegration: return self def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: self.close() def get_github_for_installation( self, installation_id: int, token_permissions: dict[str, str] | None = None ) -> github.Github: # The installation has to authenticate as an installation, not an app auth = self.auth.get_installation_auth(installation_id, token_permissions, self.__requester) return github.Github(**self.__requester.withAuth(auth).kwargs) @property def requester(self) -> Requester: """ Return my Requester object. For example, to make requests to API endpoints not yet supported by PyGitHub. """ return self.__requester def _get_headers(self) -> dict[str, str]: """ Get headers for the requests. """ return { "Accept": Consts.mediaTypeIntegrationPreview, } def _get_installed_app(self, url: str) -> Installation: """ Get installation for the given URL. """ headers, response = self.__requester.requestJsonAndCheck("GET", url, headers=self._get_headers()) return Installation( requester=self.__requester, headers=headers, attributes=response, ) @deprecated.deprecated( "Use github.Github(auth=github.Auth.AppAuth), github.Auth.AppAuth.token or github.Auth.AppAuth.create_jwt(expiration) instead" ) def create_jwt(self, expiration: int | None = None) -> str: """ Create a signed JWT https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#authenticating-as-a-github-app """ return self.auth.create_jwt(expiration) def get_access_token( self, installation_id: int, permissions: dict[str, str] | None = None ) -> InstallationAuthorization: """ :calls: `POST /app/installations/{installation_id}/access_tokens <https://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-app>` """ if permissions is None: permissions = {} if not isinstance(permissions, dict): raise GithubException(status=400, data={"message": "Invalid permissions"}, headers=None) body = {"permissions": permissions} headers, response = self.__requester.requestJsonAndCheck( "POST", f"/app/installations/{installation_id}/access_tokens", headers=self._get_headers(), input=body, ) return InstallationAuthorization( requester=self.__requester, headers=headers, attributes=response, ) @deprecated.deprecated("Use get_repo_installation") def get_installation(self, owner: str, repo: str) -> Installation: """ Deprecated by get_repo_installation. :calls:`GET /repos/{owner}/{repo}/installation <https://docs.github.com/en/rest/reference/apps#get-a-repository- installation-for-the-authenticated-app>` :calls:`GET /repos/{owner}/{repo}/installation <https://docs.github.com/en/rest/reference/apps#get-a-repository- installation-for-the-authenticated-app>` """ owner = urllib.parse.quote(owner) repo = urllib.parse.quote(repo) return self._get_installed_app(url=f"/repos/{owner}/{repo}/installation") def get_installations(self) -> PaginatedList[Installation]: """ :calls: GET /app/installations <https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app> """ return PaginatedList( contentClass=Installation, requester=self.__requester, firstUrl="/app/installations", firstParams=None, headers=self._get_headers(), list_item="installations", ) def get_org_installation(self, org: str) -> Installation: """ :calls: `GET /orgs/{org}/installation <https://docs.github.com/en/rest/apps/apps#get-an-organization-installation-for-the-authenticated-app>` """ org = urllib.parse.quote(org) return self._get_installed_app(url=f"/orgs/{org}/installation") def get_repo_installation(self, owner: str, repo: str) -> Installation: """ :calls: `GET /repos/{owner}/{repo}/installation <https://docs.github.com/en/rest/reference/apps#get-a-repository-installation-for-the-authenticated-app>` """ owner = urllib.parse.quote(owner) repo = urllib.parse.quote(repo) return self._get_installed_app(url=f"/repos/{owner}/{repo}/installation") def get_user_installation(self, username: str) -> Installation: """ :calls: `GET /users/{username}/installation <https://docs.github.com/en/rest/apps/apps#get-a-user-installation-for-the-authenticated-app>` """ username = urllib.parse.quote(username) return self._get_installed_app(url=f"/users/{username}/installation") def get_app_installation(self, installation_id: int) -> Installation: """ :calls: `GET /app/installations/{installation_id} <https://docs.github.com/en/rest/apps/apps#get-an-installation-for-the-authenticated-app>` """ return self._get_installed_app(url=f"/app/installations/{installation_id}") def get_app(self) -> GithubApp: """ :calls: `GET /app <https://docs.github.com/en/rest/reference/apps#get-the-authenticated-app>`_ """ headers, data = self.__requester.requestJsonAndCheck("GET", "/app", headers=self._get_headers()) return GithubApp(requester=self.__requester, headers=headers, attributes=data, completed=True)
⧠ã¨ããããhttps://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-appãã確èªããã¨ã
⧠ãªãã»ã©ããGitHub Appãã®ãpermissionãã®è¨å®ã®ãã¨ã£ã½ãã§ããªã
å¿
è¦ã«å¿ãã¦ãpermissions
 æ¬æãã©ã¡ã¼ã¿ã¼ã使ã£ã¦ãã¤ã³ã¹ãã¼ã« ã¢ã¯ã»ã¹ ãã¼ã¯ã³ã«å¿
è¦ãªã¢ã¯ã»ã¹è¨±å¯ãæå®ãã¾ãã permissions
 ãæå®ããã¦ããªãå ´åãã¤ã³ã¹ãã¼ã« ã¢ã¯ã»ã¹ ãã¼ã¯ã³ã«ã¯ãã¢ããªã«ä»ä¸ããããã¹ã¦ã®ã¢ã¯ã»ã¹è¨±å¯ãä»ä¸ããã¾ãã ã¤ã³ã¹ãã¼ã« ã¢ã¯ã»ã¹ ãã¼ã¯ã³ã«ãã¢ããªãä»ä¸ããã¦ããªãã¢ã¯ã»ã¹è¨±å¯ãä»ä¸ãããã¨ã¯ã§ãã¾ããã
⧠ã¨ããã®ã ãã©ãå ·ä½çãªè¨å®ã§ããå¤ã«ã¤ãã¦ãã©ããåç §ããã°è¯ãã®ããµãããªåãããªã...
Pythonã®ã©ã¤ãã©ãªPyGitHubã§GitHub Appã®Installation Access Tokenãçºè¡ãã¦ã¿ã
ã¨ãããããä¾ã®å¦ãããWSL 2ï¼Windows Subsystem for Linux 2ï¼ãã«ã¤ã³ã¹ãã¼ã«ãã¦ãããRocky Linux 9ãã®ç°å¢ã§è©¦ãã¦ã¿ãã
⧠ååã®ç°å¢ã«ã©ã¤ãã©ãªã追å ãã¦ãããã¨ã«ãã¾ãã
äºåã«ããGitHub Appããä½æãã¦ã権éããè¨å®ãããGitãªãã¸ããªãããGitHub Appãã«æå±ããã¦ããå¿ è¦ã¯ããã
ãGitHub Appãã¨ãGitãªãã¸ããªãã®é¢ä¿ãªã©ã¯ã
⧠ä¸è¨ã®è¨äºããåç §ãã ããã
ã§ã¯ããPyGitHubããã¤ã³ã¹ãã¼ã«ã
以ä¸ã®ãããªãã¡ã¤ã«ãä½æã
ã½ã¼ã¹ã³ã¼ãã¯ä»¥ä¸ã®ãããªæããããªãé©å½ã§ãã
â /home/ts0818/work/app/python/app/src/main/py/api/service/rest/pygithub/pygithub_service.py
from github import Auth from github import GithubIntegration from github import InstallationAuthorization class PyGitHubService: @staticmethod def app_auth(app_id:str, private_pem_key_contents: str): auth = Auth.AppAuth(app_id, private_pem_key_contents) gi = GithubIntegration(auth=auth) return gi @staticmethod def get_installation_id(gi:GithubIntegration): for installation in gi.get_installations(): return installation.id @staticmethod def get_installation_access_token(gi:GithubIntegration, installation_id:int): result:InstallationAuthorization = gi.get_access_token(installation_id) return result.token
pytestç¨ã®ã³ã¼ãã
â /home/ts0818/work/app/python/app/src/test/py/api/service/rest/pygithub/test_pygithub_service.py
import pytest import logging from github import GithubIntegration from src.main.py.api.service.rest.pygithub.pygithub_service import PyGitHubService class TestPyGitHubService: logger = logging.getLogger(__name__) def test_get_token(self, caplog): caplog.set_level(logging.DEBUG) TestPyGitHubService.logger.info("[start]test_get_token") github_app_id = "GitHub Appã®App IDã®å¤" github_app_private_pem_file_path = "/home/ts0818/work/app/python/app/test-github-app.pem" with open(github_app_private_pem_file_path) as pem_file: private_key_contents = pem_file.read() gi:GithubIntegration = PyGitHubService.app_auth(github_app_id, private_key_contents) installation_id:int = PyGitHubService.get_installation_id(gi) token:str = PyGitHubService.get_installation_access_token(gi, installation_id) TestPyGitHubService.logger.info(f"\nâ â â token â â â \n {token}") assert token != None log = caplog.text TestPyGitHubService.logger.info("log: {log}") TestPyGitHubService.logger.info("[finish]test_get_token")
ã§ãå®è¡ã
ã¨ãããããå ¬å¼ã®ããã¥ã¡ã³ããåããè¾ã...
ãããã®æ å ±ãæ¼ã£ã¦ããã¨ããã
⧠ãã¤ãã¦ããæ¹ãããããã®ã§ãä¸è¬çã«åããè¾ãã¨æããã®ãèªç¶ã®ããã ã
ææã¨ãã¦ã¯ãã¡ã½ããã®å¼æ°ãæ»ãå¤ããæ½åºããé¨åã¨ãã®èª¬æã欲ããæ°ããã...
Pythonã«è©³ãã人ãªãã½ã¼ã¹ã³ã¼ãããèªè§£ããæãã«ãªããã ãããã©ãPythonç´ äººã®æ輩ã«ã¯ã½ã¼ã¹ã³ã¼ããèªã¿è§£ãã£ã¦ã®ã¯è¾ãã®ãã...
æ軽ã«ä½¿ããªãã£ãããã©ã¤ãã©ãªã®æå³ãç¡ãæ°ããã¾ãããª...
æ¯åº¦ã¢ã¤ã¢ã¤æãå端ãªãâ¦
ä»åã¯ãã®ã¸ãã§ã
Â
Â