|
| 1 | +# Copyright (c) 2024 Airbyte, Inc., all rights reserved. |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import time |
| 8 | +from collections.abc import Iterable, Iterator |
| 9 | +from contextlib import contextmanager |
| 10 | +from typing import TYPE_CHECKING |
| 11 | + |
| 12 | +from github import Auth, Github |
| 13 | + |
| 14 | +from .consts import AIRBYTE_REPO, AUTO_MERGE_LABEL, BASE_BRANCH, CONNECTOR_PATH_PREFIXES |
| 15 | +from .env import GITHUB_TOKEN, PRODUCTION |
| 16 | +from .helpers import generate_job_summary_as_markdown |
| 17 | +from .pr_validators import ENABLED_VALIDATORS |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from github.Commit import Commit as GithubCommit |
| 21 | + from github.PullRequest import PullRequest |
| 22 | + from github.Repository import Repository as GithubRepo |
| 23 | + |
| 24 | +logging.basicConfig() |
| 25 | +logger = logging.getLogger("auto_merge") |
| 26 | +logger.setLevel(logging.INFO) |
| 27 | + |
| 28 | + |
| 29 | +@contextmanager |
| 30 | +def github_client() -> Iterator[Github]: |
| 31 | + client = None |
| 32 | + try: |
| 33 | + client = Github(auth=Auth.Token(GITHUB_TOKEN), seconds_between_requests=0) |
| 34 | + yield client |
| 35 | + finally: |
| 36 | + if client: |
| 37 | + client.close() |
| 38 | + |
| 39 | + |
| 40 | +def check_if_pr_is_auto_mergeable(head_commit: GithubCommit, pr: PullRequest, required_checks: set[str]) -> bool: |
| 41 | + """Run all enabled validators and return if they all pass. |
| 42 | +
|
| 43 | + Args: |
| 44 | + head_commit (GithubCommit): The head commit of the PR |
| 45 | + pr (PullRequest): The PR to check |
| 46 | + required_checks (set[str]): The set of required passing checks |
| 47 | +
|
| 48 | + Returns: |
| 49 | + bool: True if the PR is auto-mergeable, False otherwise |
| 50 | + """ |
| 51 | + for validator in ENABLED_VALIDATORS: |
| 52 | + is_valid, error = validator(head_commit, pr, required_checks) |
| 53 | + if not is_valid: |
| 54 | + if error: |
| 55 | + logger.info(f"PR #{pr.number} - {error}") |
| 56 | + return False |
| 57 | + return True |
| 58 | + |
| 59 | + |
| 60 | +def process_pr(repo: GithubRepo, pr: PullRequest, required_passing_contexts: set[str], dry_run: bool) -> None | PullRequest: |
| 61 | + """Process a PR to see if it is auto-mergeable and merge it if it is. |
| 62 | +
|
| 63 | + Args: |
| 64 | + repo (GithubRepo): The repository the PR is in |
| 65 | + pr (PullRequest): The PR to process |
| 66 | + required_passing_contexts (set[str]): The set of required passing checks |
| 67 | + dry_run (bool): Whether to actually merge the PR or not |
| 68 | +
|
| 69 | + Returns: |
| 70 | + None | PullRequest: The PR if it was merged, None otherwise |
| 71 | + """ |
| 72 | + logger.info(f"Processing PR #{pr.number}") |
| 73 | + head_commit = repo.get_commit(sha=pr.head.sha) |
| 74 | + if check_if_pr_is_auto_mergeable(head_commit, pr, required_passing_contexts): |
| 75 | + if not dry_run: |
| 76 | + pr.merge() |
| 77 | + logger.info(f"PR #{pr.number} was auto-merged") |
| 78 | + return pr |
| 79 | + else: |
| 80 | + logger.info(f"PR #{pr.number} is auto-mergeable but dry-run is enabled") |
| 81 | + return None |
| 82 | + |
| 83 | + |
| 84 | +def back_off_if_rate_limited(github_client: Github) -> None: |
| 85 | + """Sleep if the rate limit is reached |
| 86 | +
|
| 87 | + Args: |
| 88 | + github_client (Github): The Github client to check the rate limit of |
| 89 | + """ |
| 90 | + remaining_requests, _ = github_client.rate_limiting |
| 91 | + if remaining_requests < 100: |
| 92 | + logging.warning(f"Rate limit almost reached. Remaining requests: {remaining_requests}") |
| 93 | + if remaining_requests == 0: |
| 94 | + logging.warning(f"Rate limited. Sleeping for {github_client.rate_limiting_resettime - time.time()} seconds") |
| 95 | + time.sleep(github_client.rate_limiting_resettime - time.time()) |
| 96 | + return None |
| 97 | + |
| 98 | + |
| 99 | +def auto_merge() -> None: |
| 100 | + """Main function to auto-merge PRs that are candidates for auto-merge. |
| 101 | + If the AUTO_MERGE_PRODUCTION environment variable is not set to "true", this will be a dry run. |
| 102 | + """ |
| 103 | + dry_run = PRODUCTION is False |
| 104 | + with github_client() as gh_client: |
| 105 | + repo = gh_client.get_repo(AIRBYTE_REPO) |
| 106 | + main_branch = repo.get_branch(BASE_BRANCH) |
| 107 | + logger.info(f"Fetching required passing contexts for {BASE_BRANCH}") |
| 108 | + required_passing_contexts = set(main_branch.get_required_status_checks().contexts) |
| 109 | + candidate_issues = gh_client.search_issues(f"repo:{AIRBYTE_REPO} is:pr label:{AUTO_MERGE_LABEL} base:{BASE_BRANCH} state:open") |
| 110 | + prs = [issue.as_pull_request() for issue in candidate_issues] |
| 111 | + logger.info(f"Found {len(prs)} open PRs targeting {BASE_BRANCH} with the {AUTO_MERGE_LABEL} label") |
| 112 | + merged_prs = [] |
| 113 | + for pr in prs: |
| 114 | + back_off_if_rate_limited(gh_client) |
| 115 | + if merged_pr := process_pr(repo, pr, required_passing_contexts, dry_run): |
| 116 | + merged_prs.append(merged_pr) |
| 117 | + if PRODUCTION: |
| 118 | + os.environ["GITHUB_STEP_SUMMARY"] = generate_job_summary_as_markdown(merged_prs) |
0 commit comments