| """Narrow GitHub publishing helpers; credentials stay in the Job environment.""" |
|
|
| from __future__ import annotations |
|
|
| import json |
| import os |
| import subprocess |
| from dataclasses import dataclass |
| from pathlib import Path |
| from typing import Any |
|
|
| from .validate import ValidationError, validate_scope |
|
|
|
|
| class GitHubPublishingError(RuntimeError): |
| """Raised when generated changes cannot be safely published.""" |
|
|
|
|
| def _run(command: list[str], cwd: Path) -> str: |
| completed = subprocess.run(command, cwd=cwd, check=True, text=True, capture_output=True) |
| return completed.stdout.strip() |
|
|
|
|
| @dataclass(frozen=True) |
| class PullRequestSpec: |
| base_repository: str |
| base_branch: str |
| head_repository: str |
| head_branch: str |
| title: str |
| body: str |
| draft: bool = True |
|
|
|
|
| def build_pr_body(manifest: dict[str, Any]) -> str: |
| """Build a non-secret, reproducible PR description from a run manifest.""" |
|
|
| checks = manifest.get("checks", {}) |
| counts = manifest.get("inventory", {}) |
| metrics = manifest.get("metrics", {}) |
| return "\n".join( |
| [ |
| "## Japanese documentation synchronization", |
| "", |
| "Machine-generated from the English documentation source of truth; no native Japanese review was performed.", |
| "", |
| f"- English base SHA: `{manifest.get('transformers_source_sha')}`", |
| f"- Model: `{manifest.get('model_id')}` at `{manifest.get('model_revision')}`", |
| f"- Runner revision: `{manifest.get('runner_revision')}`", |
| f"- Doc-builder revision: `{manifest.get('doc_builder_revision')}`", |
| f"- Pages added: `{counts.get('missing_count', 0)}`", |
| f"- Pages overwritten: `{counts.get('shared_count', 0)}`", |
| f"- Pages deleted: `{counts.get('target_only_count', 0)}`", |
| f"- Total pages: `{counts.get('english_count', 0)}`", |
| f"- Path parity: `{checks.get('path_parity', 'unknown')}`", |
| f"- Cache hits/misses: `{metrics.get('cache_hits', 0)}` / `{metrics.get('cache_misses', 0)}`", |
| f"- Input/output tokens per second: `{metrics.get('translation', {}).get('input_tokens_per_second', 0):.2f}` / `{metrics.get('translation', {}).get('output_tokens_per_second', 0):.2f}`", |
| f"- Peak GPU memory: `{metrics.get('peak_gpu_memory_bytes', 'not recorded')}`", |
| f"- Validation: `{checks.get('validation', 'unknown')}`", |
| f"- Doc build: `{checks.get('doc_build', 'not run')}`", |
| f"- Job run: `{manifest.get('job_url', 'not recorded')}`", |
| f"- Bucket run record: `{manifest.get('run_record', 'not recorded')}`", |
| ] |
| ) |
|
|
|
|
| class GitHubPublisher: |
| def __init__(self, checkout: Path, target_prefix: str = "docs/source/ja/"): |
| self.checkout = checkout |
| self.target_prefix = target_prefix |
|
|
| def require_clean_checkout(self) -> None: |
| status = _run(["git", "status", "--porcelain"], self.checkout) |
| if status: |
| raise GitHubPublishingError("refusing publication from a dirty checkout") |
|
|
| def require_scope(self, base_ref: str) -> list[str]: |
| changed = _run(["git", "diff", "--name-only", f"{base_ref}...HEAD"], self.checkout).splitlines() |
| try: |
| validate_scope(changed, self.target_prefix) |
| except ValidationError as exc: |
| raise GitHubPublishingError(str(exc)) from exc |
| return changed |
|
|
| def commit_generated_tree(self, source_sha: str) -> str: |
| _run(["git", "add", "--", self.target_prefix], self.checkout) |
| changed = _run(["git", "diff", "--cached", "--name-only"], self.checkout).splitlines() |
| try: |
| validate_scope(changed, self.target_prefix) |
| except ValidationError as exc: |
| raise GitHubPublishingError(str(exc)) from exc |
| if not changed: |
| raise GitHubPublishingError("generated tree is unchanged; refusing an empty commit") |
| _run(["git", "commit", "-m", f"[i18n-ja] Sync Japanese docs from {source_sha[:12]}"], self.checkout) |
| return _run(["git", "rev-parse", "HEAD"], self.checkout) |
|
|
| def push_with_lease(self, remote: str, local_branch: str, remote_branch: str) -> None: |
| if os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN"): |
| _run(["gh", "auth", "setup-git", "--hostname", "github.com", "--force"], self.checkout) |
| _run(["git", "push", "--force-with-lease", remote, f"{local_branch}:{remote_branch}"], self.checkout) |
|
|
| def find_open_pr(self, base_repository: str, base_branch: str, head: str) -> dict[str, Any] | None: |
| output = _run( |
| [ |
| "gh", |
| "pr", |
| "list", |
| "--repo", |
| base_repository, |
| "--state", |
| "open", |
| "--base", |
| base_branch, |
| "--head", |
| head, |
| "--json", |
| "number,url,state,headRefName,baseRefName", |
| ], |
| self.checkout, |
| ) |
| values = json.loads(output or "[]") |
| return values[0] if values else None |
|
|
| def read_pr(self, repository: str, number: int) -> dict[str, Any]: |
| output = _run( |
| [ |
| "gh", |
| "pr", |
| "view", |
| str(number), |
| "--repo", |
| repository, |
| "--json", |
| "number,state,mergedAt,baseRefName,headRefName", |
| ], |
| self.checkout, |
| ) |
| return json.loads(output) |
|
|
| def create_or_update_pr(self, spec: PullRequestSpec) -> dict[str, Any]: |
| head = f"{spec.head_repository}:{spec.head_branch}" |
| existing = self.find_open_pr(spec.base_repository, spec.base_branch, head) |
| if existing: |
| _run(["gh", "pr", "edit", str(existing["number"]), "--body", spec.body, "--title", spec.title], self.checkout) |
| return existing |
| command = [ |
| "gh", |
| "pr", |
| "create", |
| "--repo", |
| spec.base_repository, |
| "--base", |
| spec.base_branch, |
| "--head", |
| head, |
| "--title", |
| spec.title, |
| "--body", |
| spec.body, |
| ] |
| if spec.draft: |
| command.append("--draft") |
| url = _run(command, self.checkout) |
| return {"url": url, "state": "OPEN", "headRefName": spec.head_branch, "baseRefName": spec.base_branch} |
|
|