Files

215 lines
11 KiB
Python

"""Publish a verified stable release to the user's simgreek Gitea organization.
Credentials are read from Git Credential Manager into memory only. No secret is
accepted on the command line, written to a report, or embedded in remote URLs.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import tomllib
import urllib.error
import urllib.parse
import urllib.request
import uuid
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
SERVER = "https://git.simgreek.com"
HOST = "git.simgreek.com"
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
# Never forward authentication to an attachment redirect or another host.
return None
def validate_name(value: str) -> str:
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", value):
raise ValueError("Invalid organization or repository name")
return value
def multipart_attachment(file: Path, boundary: str) -> tuple[bytes, str]:
name = file.name
if not re.fullmatch(r"[A-Za-z0-9_.-]+", name):
raise ValueError("Unsafe release attachment filename")
header = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\n'
'Content-Type: application/octet-stream\r\n\r\n').encode("ascii")
return header + file.read_bytes() + f"\r\n--{boundary}--\r\n".encode("ascii"), f"multipart/form-data; boundary={boundary}"
def git(*args: str) -> str:
env = dict(os.environ, GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="Never")
result = subprocess.run(["git", *args], cwd=ROOT, env=env, capture_output=True, text=True, check=True, timeout=240)
return result.stdout.strip()
def credentials() -> str:
env = dict(os.environ, GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="Never")
result = subprocess.run(["git", "credential", "fill"], cwd=ROOT, env=env,
input=f"protocol=https\nhost={HOST}\n\n", capture_output=True, text=True, timeout=30)
fields = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)
if result.returncode or not fields.get("username") or not fields.get("password"):
raise RuntimeError("No stored Git credential for git.simgreek.com; sign in using your normal Git client first")
return "Basic " + base64.b64encode((fields["username"] + ":" + fields["password"]).encode("utf8")).decode("ascii")
class Client:
def __init__(self, authorization: str):
self.authorization = authorization
# The existing Git configuration explicitly disables a proxy for this host.
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
def request(self, path: str, method="GET", data=None, attachment=None, missing_ok=False):
headers = {"Authorization": self.authorization, "Accept": "application/json", "User-Agent": "MentorPDFExporter-release"}
body = None
if attachment:
body, headers["Content-Type"] = multipart_attachment(attachment, "mentor-release-" + uuid.uuid4().hex)
elif data is not None:
body = json.dumps(data).encode("utf8")
headers["Content-Type"] = "application/json"
url = SERVER + "/api/v1" + path
for attempt in range(3):
try:
request = urllib.request.Request(url, data=body, headers=headers, method=method)
with self.opener.open(request, timeout=180 if attachment else 30) as response:
content = response.read()
return json.loads(content) if content else None
except urllib.error.HTTPError as error:
if error.code == 404 and missing_ok:
return None
if method == "GET" and error.code in (502, 503, 504) and attempt < 2:
time.sleep(2 * (attempt + 1))
continue
raise RuntimeError(f"git.simgreek.com returned HTTP {error.code} for {path}; nothing is claimed uploaded") from None
raise RuntimeError("Server unavailable")
def attachment_hash(self, url: str) -> str:
parsed = urllib.parse.urlsplit(url)
if parsed.scheme != "https" or parsed.hostname != HOST or parsed.username or parsed.password or parsed.port not in (None, 443):
raise ValueError("Attachment download URL does not belong to the trusted Git host")
request = urllib.request.Request(url, headers={"Authorization": self.authorization, "User-Agent": "MentorPDFExporter-release"})
digest = hashlib.sha256()
with self.opener.open(request, timeout=180) as response:
while data := response.read(1024 * 1024):
digest.update(data)
return digest.hexdigest()
def file_hash(file: Path) -> str:
with file.open("rb") as source:
return hashlib.file_digest(source, "sha256").hexdigest()
def verified_artifacts(version: str) -> tuple[Path, Path]:
report = ROOT / "artifacts" / f"release-{version}" / "verification.json"
data = json.loads(report.read_text(encoding="utf8"))
archive = ROOT / "release" / f"MentorPDFExporter-{version}-win64.zip"
checksum = archive.with_suffix(".zip.sha256")
if not data.get("passed") or data.get("version") != version or data.get("zip_sha256") != file_hash(archive):
raise ValueError("Release archive does not match its passed verification report")
if checksum.read_text(encoding="ascii").split()[0] != file_hash(archive):
raise ValueError("Release ZIP checksum differs")
tree = ET.parse(ROOT / "artifacts" / "pytest-v100-final.xml")
suites = tree.getroot().iter("testsuite")
counts = [(int(s.get("tests", "0")), int(s.get("failures", "0")), int(s.get("errors", "0"))) for s in suites]
if not counts or sum(x[0] for x in counts) < 236 or any(x[1] or x[2] for x in counts):
raise ValueError("A passing complete release regression run is required")
# Re-check current application code rather than trusting stale build metadata.
sys.path.insert(0, str(ROOT / "packaging"))
from verify_release import verify_source
verify_source(ROOT / "release" / f"MentorPDFExporter-{version}" / "MentorPDFExporter.exe")
return archive, checksum
def publish(client: Client, org: str, repo: str, version: str) -> dict:
archive, checksum = verified_artifacts(version)
if git("status", "--porcelain"):
raise ValueError("Commit release source before publishing; the working tree must be clean")
commit = git("rev-parse", "HEAD")
tag = "v" + version
if git("rev-parse", tag + "^{commit}") != commit:
raise ValueError("Release tag must identify the current source commit")
remote_url = f"{SERVER}/{org}/{repo}.git"
remotes = git("remote").splitlines()
original_remote = git("remote", "get-url", "origin") if "origin" in remotes else None
if original_remote is not None and original_remote != remote_url:
raise ValueError("Existing origin differs from requested organization repository")
existing = client.request(f"/repos/{org}/{repo}", missing_ok=True)
if existing is not None and not existing.get("empty", False) and original_remote is None:
raise ValueError("Repository already contains unrelated history; refusing to overwrite it")
if existing is None:
existing = client.request(f"/orgs/{org}/repos", method="POST", data={
"name": repo, "description": "Mentor / DxDesigner PDF batch exporter for Windows",
"private": True, "auto_init": False, "default_branch": "main",
})
if original_remote is None:
git("remote", "add", "origin", remote_url)
# No force push; branch and tag are published together or not at all.
git("push", "--atomic", "-u", "origin", "HEAD:refs/heads/main", "refs/tags/" + tag)
refs = git("ls-remote", "origin", "refs/heads/main", "refs/tags/" + tag + "^{}")
refmap = dict(line.split()[::-1] for line in refs.splitlines())
if refmap.get("refs/heads/main") != commit or refmap.get("refs/tags/" + tag + "^{}") != commit:
raise ValueError("Remote branch/tag does not match the release source commit")
release = client.request(f"/repos/{org}/{repo}/releases/tags/{tag}", missing_ok=True)
if release is None:
release = client.request(f"/repos/{org}/{repo}/releases", method="POST", data={
"tag_name": tag, "target_commitish": commit, "name": f"Mentor PDF 批量导出 {tag}",
"body": (ROOT / "docs/releases" / f"{version}.md").read_text(encoding="utf8"),
"draft": False, "prerelease": False,
})
if release.get("draft") or release.get("prerelease"):
raise ValueError("Existing release is not a formal stable release; refusing implicit changes")
release_id = release["id"]
assets = {asset["name"]: asset for asset in release.get("assets", [])}
uploaded = []
for file in (archive, checksum):
asset = assets.get(file.name)
if asset is None:
asset = client.request(f"/repos/{org}/{repo}/releases/{release_id}/assets?name={urllib.parse.quote(file.name)}", method="POST", attachment=file)
if client.attachment_hash(asset["browser_download_url"]) != file_hash(file):
raise ValueError("Remote attachment hash mismatch; existing attachments are never silently replaced")
uploaded.append({"name": file.name, "sha256": file_hash(file), "url": asset["browser_download_url"]})
return {"published": True, "repository": existing["html_url"], "release": release["html_url"],
"version": version, "commit": commit, "tag": tag, "assets": uploaded}
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="Publish a verified stable release to simgreek Gitea")
parser.add_argument("--org", default="simgreek")
parser.add_argument("--repo", default="mentor-pdf-exporter")
parser.add_argument("--publish", action="store_true", help="Create the private repository if needed, push source/tag and upload the verified release")
args = parser.parse_args(argv)
org, repo = validate_name(args.org), validate_name(args.repo)
version = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf8"))["project"]["version"]
try:
client = Client(credentials())
server = client.request("/version")
user = client.request("/user")
organization = client.request(f"/orgs/{org}")
print(json.dumps({"server": server, "authenticated_user": user.get("login"), "organization": organization.get("username", org)}, ensure_ascii=True))
if args.publish:
result = publish(client, org, repo, version)
evidence = ROOT / "artifacts" / f"release-{version}"
evidence.mkdir(parents=True, exist_ok=True)
(evidence / "published.json").write_text(json.dumps(result, indent=2), encoding="utf8")
print(json.dumps(result, ensure_ascii=True, indent=2))
return 0
except (RuntimeError, ValueError, OSError, subprocess.CalledProcessError, urllib.error.URLError) as error:
print(f"Release not completed: {type(error).__name__}: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())