async def update_milestones(org: str = "thoth-station"): """Update Milestones for one org.""" access_token = GitHubOAuthToken(os.environ["GITHUB_ACCESS_TOKEN"]) async with aiohttp.ClientSession() as client: github_api = RawGitHubAPI(access_token, session=client, user_agent="sesheta-actions") async for repo in github_api.getiter(f"/orgs/{org}/repos"): slug = repo["full_name"] _LOGGER.debug("working on %s", slug) if repo["archived"]: _LOGGER.debug("skipping %s, this repository was archived!", slug) continue for milestone in DEFAULT_MILESTONES_THOTH: _LOGGER.debug("checking for %s", milestone) await create_or_update_milestone( slug, milestone["title"], milestone["description"], due_on=milestone["due_on"], )
async def create_or_update_label(slug: str, name: str, color: str = "") -> str: """Create or update the label in the given repository.""" access_token = GitHubOAuthToken(os.environ["GITHUB_ACCESS_TOKEN"]) async with aiohttp.ClientSession() as client: github_api = RawGitHubAPI(access_token, session=client, user_agent="sesheta-actions") try: _LOGGER.debug("get item...") label = await github_api.getitem(f"/repos/{slug}/labels/{name}", preview_api_version="symmetra") if label["color"] != color: _LOGGER.debug("patching item color...") await github_api.patch( f"/repos/{slug}/labels/{name}", preview_api_version="symmetra", data={"new_name": name, "color": color}, ) except gidgethub.BadRequest as bad: _LOGGER.error(f"Label '{name}', Repo: '{slug}': {bad}") try: resp = await github_api.post( f"/repos/{slug}/labels", preview_api_version="symmetra", data={"name": name, "color": color}, ) except gidgethub.BadRequest as created: _LOGGER.info( f"Label '{name}', Repo: '{slug}': created", ) # TODO maybe this should be a little more robust? return
async def trigger_update_branch(owner: str, repo: str, pull_request: int) -> bool: """Trigger /update-branch API on Pull Request.""" access_token = GitHubOAuthToken(os.environ["GITHUB_ACCESS_TOKEN"]) async with aiohttp.ClientSession() as client: github_api = RawGitHubAPI(access_token, session=client, user_agent="sesheta") try: if github_api.is_initialized: triggered = await github_api.put( f"/repos/{owner}/{repo}/pulls/{pull_request}/update-branch", preview_api_version="lydian", data=b"", ) _LOGGER.debug( f"rebasing Pull Request {pull_request} in {owner}/{repo} triggered: {triggered}" ) return True except gidgethub.BadRequest as bad_request: _LOGGER.error( f"{bad_request}: on /repos/{owner}/{repo}/pulls/{pull_request}/update-branch" ) return False except gidgethub.HTTPException as http_exception: if http_exception.status_code == 202: return True else: _LOGGER.error(http_exception) return False
async def create_or_update_milestone(slug: str, title: str, description: str, state: str = "open", due_on: str = None): """Create or update the Milestone in the given repository.""" access_token = GitHubOAuthToken(os.environ["GITHUB_ACCESS_TOKEN"]) async with aiohttp.ClientSession() as client: github_api = RawGitHubAPI(access_token, session=client, user_agent="sesheta-actions") # prepare a milestone milestone_data = { "title": title, "description": description, "state": state } if due_on is not None: milestone_data["due_on"] = due_on due_on_datetime = datetime.strptime(due_on, "%Y-%m-%dT%H:%M:%SZ") if due_on_datetime < datetime.utcnow(): _LOGGER.info( f"Milestone '{title}' has a due date in the past... skipping!" ) return try: # and see if it exists _LOGGER.debug("checking %s for %s", slug, title) async for milestone in github_api.getiter( f"/repos/{slug}/milestones"): _LOGGER.debug("found %s: %s", slug, milestone) if (milestone["title"] == title) and ( (milestone["due_on"] != due_on) or (milestone["description"] != description)): _LOGGER.debug("updating %s: %s", slug, milestone_data) del milestone_data["title"] await github_api.patch( f"/repos/{slug}/milestones/{milestone['number']}", data=milestone_data) return _LOGGER.debug("creating %s: %s", slug, milestone_data) await github_api.post(f"/repos/{slug}/milestones", data=milestone_data) except gidgethub.BadRequest as bad: _LOGGER.error(f"Milestone '{title}', Repo: '{slug}': {bad}") return
async def main(): access_token = GitHubOAuthToken(os.environ["GITHUB_TOKEN"]) gh = RawGitHubAPI(access_token, user_agent='webknjaz') res = await gh.post( '/repos/mariatta/strange-relationship/issues/207/reactions', preview_api_version='squirrel-girl', data={'content': 'heart'}, ) print(res)
async def main(): access_token = GitHubOAuthToken(os.environ["GITHUB_TOKEN"]) async with ClientSession() as http_session: gh = RawGitHubAPI(access_token, session=http_session, user_agent="drapegnik",) reaction = sample(REACTIONS, 1)[0] print(f"✨ react with {reaction}!") # https://github.com/Mariatta/strange-relationship/issues/243 await gh.post( "/repos/mariatta/strange-relationship/issues/243/reactions", data={"content": reaction}, preview_api_version="squirrel-girl", )
async def get_master_head_sha(owner: str, repo: str) -> str: """Get the SHA of the HEAD of the master.""" # TODO refactor this to a class? global variable? access_token = GitHubOAuthToken(os.environ["GITHUB_ACCESS_TOKEN"]) async with aiohttp.ClientSession() as client: github_api = RawGitHubAPI(access_token, session=client, user_agent="sesheta-actions") commits = await github_api.getitem(f"/repos/{owner}/{repo}/commits") _LOGGER.debug(f"HEAD commit of {owner}/{repo}: {commits[0]['sha']}") return commits[0]["sha"] # FIXME could raise IndexError
async def conclude_reviewer_list(owner: str = None, repo: str = None) -> typing.List[str]: """Conclude on a set of Reviewers (their GitHub user id) that could be assigned to a Pull Request.""" reviewers = [] github_api = None if owner is None or repo is None: return None try: github_api = RUNTIME_CONTEXT.app_installation_client except Exception: access_token = GitHubOAuthToken(os.environ["GITHUB_ACCESS_TOKEN"]) github_api = RawGitHubAPI(access_token, user_agent="sesheta-actions") try: codeowners = await github_api.getitem( f"/repos/{owner}/{repo}/contents/.github/CODEOWNERS") codeowners_content = base64.b64decode( codeowners["content"]).decode("utf-8") code_owner = CodeOwners(codeowners_content) for owner in code_owner.of("."): reviewers.append(owner[1][1:]) # remove the @ except gidgethub.HTTPException as http_exception: # if there is no CODEOWNERS, lets have some sane defaults if http_exception.status_code == 404: if owner.lower() == "thoth-station": reviewers.append("fridex") reviewers.append("pacospace") if "prometheus" in repo.lower(): reviewers.append("4n4nd") reviewers.append("MichaelClifford") if "log-" in repo.lower(): reviewers.append("zmhassan") reviewers.append("4n4nd") else: _LOGGER.error(http_exception) return None except Exception as err: # on any other Error, we can not generate a reviewers list _LOGGER.error(str(err)) return None _LOGGER.debug(f"final reviewers: '{reviewers}'") return reviewers
async def get_pull_request(owner: str, repo: str, pull_request: int) -> dict: """Get PR from owner/repo.""" access_token = GitHubOAuthToken(os.environ["GITHUB_ACCESS_TOKEN"]) async with aiohttp.ClientSession() as client: github_api = RawGitHubAPI(access_token, session=client, user_agent="sesheta-actions") _LOGGER.debug(f"getting {owner}/{repo}: PR {pull_request}") pr = await github_api.getitem( f"/repos/{owner}/{repo}/pulls/{pull_request}" ) # TODO exception handling _LOGGER.debug(f"got {owner}/{repo}: PR {pull_request}: {pr}") return pr
async def main(): access_token = GitHubOAuthToken(os.environ['GITHUB_TOKEN']) async with ClientSession() as http_session: gh = RawGitHubAPI( access_token, session=http_session, user_agent='temichus', ) # await gh.post( # '/repos/temichus/test_repo/issues', # data={ # 'title': 'We got a problem', # 'body': 'Use more emoji!', # }, # ) await gh.patch( '/repos/temichus/test_repo/issues{/number}', data={'state': 'closed'}, url_vars={'number': '1'}, )
async def update_labels(org: str): """Update Labels to comply to our standard.""" access_token = GitHubOAuthToken(os.environ["GITHUB_ACCESS_TOKEN"]) async with aiohttp.ClientSession() as client: github_api = RawGitHubAPI(access_token, session=client, user_agent="sesheta-actions") repos = await github_api.getitem(f"/orgs/{org}/repos") for repo in repos: if repo["archived"]: continue slug = repo["full_name"] for label in DEFAULT_LABELS: _LOGGER.debug(f"looking for {label['name']} in {slug}") await create_or_update_label(slug, label["name"], label["color"])
async def main(): access_token = GitHubOAuthToken(GITHUB_TOKEN) async with ClientSession() as http_session: gh = RawGitHubAPI( access_token, session=http_session, user_agent='gloriasky', ) await gh.post( '/repos/mariatta/strange-relationship/issues', data={ 'title': 'We got a problem', 'body': 'Use more emoji!', }, ) await gh.patch( '/repos/mariatta/strange-relationship/issues{/number}', data={'state': 'closed'}, url_vars={'number': '242'}, )
async def main(): access_token = GitHubOAuthToken(os.environ['GITHUB_TOKEN']) async with ClientSession() as http_session: gh = RawGitHubAPI( access_token, session=http_session, user_agent='j0shu4b0y', ) # await gh.post( # '/repos/mariatta/strange-relationship/issues', # data={ # 'title': 'We got a problem', # 'body': 'Use more emoji!', # }, # ) await gh.post( '/repos/mariatta/strange-relationship/issues/256', data={ 'state': 'closed', }, )
async def update_milestones(org: str = "thoth-station"): """Update Milestones for one org.""" access_token = GitHubOAuthToken(os.environ["GITHUB_ACCESS_TOKEN"]) async with aiohttp.ClientSession() as client: github_api = RawGitHubAPI(access_token, session=client, user_agent="sesheta-actions") repos = await github_api.getitem(f"/orgs/{org}/repos") for repo in repos: if repo["archived"]: continue slug = repo["full_name"] for milestone in DEFAULT_MILESTONES_THOTH: await create_or_update_milestone( slug, milestone["title"], milestone["description"], due_on=milestone["due_on"], )
import asyncio import textwrap import os from octomachinery.github.api.tokens import GitHubOAuthToken from octomachinery.github.api.raw_client import RawGitHubAPI access_token = GitHubOAuthToken(os.environ["GITHUB_TOKEN"].strip()) gh = RawGitHubAPI(access_token, user_agent='encukou-octomachinery-tutorial') async def main(): print('hello world') await close_issue() async def new_comment(): await gh.post( '/repos/mariatta/strange-relationship/issues/163/comments', data={'body': "Oh! I thought she's OOOS! (I'm also a bot)"}, ) async def close_issue(): await gh.patch( '/repos/mariatta/strange-relationship/issues/163', data={'state': 'closed'}, ) async def new_issue():