|
| 1 | +import logging |
| 2 | +import re |
| 3 | + |
| 4 | +from github import Github |
| 5 | +from pydantic import SecretStr |
| 6 | +from pydantic_settings import BaseSettings |
| 7 | + |
| 8 | + |
| 9 | +class Settings(BaseSettings): |
| 10 | + github_repository: str |
| 11 | + github_token: SecretStr |
| 12 | + deploy_url: str | None = None |
| 13 | + commit_sha: str |
| 14 | + run_id: int |
| 15 | + |
| 16 | + |
| 17 | +def main(): |
| 18 | + logging.basicConfig(level=logging.INFO) |
| 19 | + settings = Settings() |
| 20 | + |
| 21 | + logging.info(f"Using config: {settings.model_dump_json()}") |
| 22 | + g = Github(settings.github_token.get_secret_value()) |
| 23 | + repo = g.get_repo(settings.github_repository) |
| 24 | + use_pr = next( |
| 25 | + (pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None |
| 26 | + ) |
| 27 | + if not use_pr: |
| 28 | + logging.error(f"No PR found for hash: {settings.commit_sha}") |
| 29 | + return |
| 30 | + commits = list(use_pr.get_commits()) |
| 31 | + current_commit = [c for c in commits if c.sha == settings.commit_sha][0] |
| 32 | + run_url = f"https://github.com/{settings.github_repository}/actions/runs/{settings.run_id}" |
| 33 | + if not settings.deploy_url: |
| 34 | + current_commit.create_status( |
| 35 | + state="pending", |
| 36 | + description="Deploy Docs", |
| 37 | + context="deploy-docs", |
| 38 | + target_url=run_url, |
| 39 | + ) |
| 40 | + logging.info("No deploy URL available yet") |
| 41 | + return |
| 42 | + current_commit.create_status( |
| 43 | + state="success", |
| 44 | + description="Deploy Docs", |
| 45 | + context="deploy-docs", |
| 46 | + target_url=run_url, |
| 47 | + ) |
| 48 | + |
| 49 | + files = list(use_pr.get_files()) |
| 50 | + docs_files = [f for f in files if f.filename.startswith("docs/")] |
| 51 | + |
| 52 | + deploy_url = settings.deploy_url.rstrip("/") |
| 53 | + links: list[str] = [] |
| 54 | + for f in docs_files: |
| 55 | + match = re.match(r"docs/(.*)", f.filename) |
| 56 | + assert match |
| 57 | + path = match.group(1) |
| 58 | + if path.endswith("index.md"): |
| 59 | + path = path.replace("index.md", "") |
| 60 | + else: |
| 61 | + path = path.replace(".md", "/") |
| 62 | + link = f"{deploy_url}/{path}" |
| 63 | + links.append(link) |
| 64 | + links.sort() |
| 65 | + |
| 66 | + message = f"📝 Docs preview for commit {settings.commit_sha} at: {deploy_url}" |
| 67 | + |
| 68 | + if links: |
| 69 | + message += "\n\n### Modified Pages\n\n" |
| 70 | + message += "\n".join([f"* {link}" for link in links]) |
| 71 | + |
| 72 | + print(message) |
| 73 | + use_pr.as_issue().create_comment(message) |
| 74 | + |
| 75 | + logging.info("Finished") |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + main() |
0 commit comments