Files

712 lines
25 KiB
Python
Executable File

#!/usr/bin/env python3
"""pj3-splice release helper.
Subcommands:
prepare update Cargo.toml/Cargo.lock and validate CHANGELOG + release notes
verify validate the six release artifacts, SHA256SUMS and Win7 imports
tag create an annotated local tag (no push)
publish push branch/tag and create/update a Gitea release (or --dry-run)
The Gitea token is read from GITEA_TOKEN or $HOME/.config/gitea/token. It is
never printed, written to the repository, or placed in a URL/argv. curl receives
it through a stdin config (--config -).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.parse
from pathlib import Path
DEFAULT_BASE_URL = "https://buaagit.dawnmagnet.top"
DEFAULT_REPOSITORY = "509OUT/pj3-splice"
DEFAULT_BRANCH = "master"
EXPECTED_ARTIFACTS = (
"pj3-splice-{tag}-windows-x86_64-gui.exe",
"pj3-splice-{tag}-windows-x86_64-cli.exe",
"pj3-splice-{tag}-win7-x86_64-gui.exe",
"pj3-splice-{tag}-linux-x86_64-gui.tar.gz",
"pj3-splice-{tag}-linux-x86_64-musl-docker.tar.gz",
"pj3-splice-{tag}-deploy.tar.gz",
)
WIN7_ALLOWED_DLLS = {
"kernel32.dll",
"opengl32.dll",
"advapi32.dll",
"comdlg32.dll",
"dwmapi.dll",
"gdi32.dll",
"imm32.dll",
"msvcrt.dll",
"ntdll.dll",
"ole32.dll",
"shell32.dll",
"user32.dll",
"uxtheme.dll",
"ws2_32.dll",
}
class ReleaseError(RuntimeError):
pass
def root() -> Path:
return Path(__file__).resolve().parent.parent
def read_text(path: Path) -> str:
with path.open("r", encoding="utf-8", newline="") as handle:
return handle.read()
def write_text(path: Path, value: str) -> None:
with path.open("w", encoding="utf-8", newline="") as handle:
handle.write(value)
def cargo_version() -> str:
text = read_text(root() / "Cargo.toml")
match = re.search(r"(?ms)^\[package\]\s*\n(.*?)(?=^\[)", text)
if not match:
raise ReleaseError("Cargo.toml is missing a [package] section")
version = re.search(r'(?m)^version\s*=\s*"([^"]+)"\s*$', match.group(1))
if not version:
raise ReleaseError("Cargo.toml package version was not found")
return version.group(1)
def release_tag(version: str) -> str:
return "v" + version
def release_dir(version: str) -> Path:
return root() / "target" / "release-assets" / release_tag(version)
def notes_path(version: str) -> Path:
return root() / "doc" / "releases" / (release_tag(version) + ".md")
def changelog_path() -> Path:
return root() / "CHANGELOG.md"
def validate_version(value: str) -> None:
if not re.fullmatch(r"\d+\.\d+\.\d+", value):
raise ReleaseError("VERSION must look like x.y.z, got: " + value)
def validate_release_docs(version: str) -> None:
notes = notes_path(version)
if not notes.is_file() or notes.stat().st_size == 0:
raise ReleaseError("missing or empty release notes: " + str(notes))
changelog = read_text(changelog_path())
pattern = r"(?m)^## \[" + re.escape(version) + r"\]"
if not re.search(pattern, changelog):
raise ReleaseError("CHANGELOG.md has no '## [" + version + "]' section")
def replace_package_version(text: str, version: str) -> tuple[str, str]:
section = re.search(r"(?ms)^\[package\]\s*\n(.*?)(?=^\[)", text)
if not section:
raise ReleaseError("Cargo.toml is missing a [package] section")
body = section.group(1)
match = re.search(r'(?m)^version\s*=\s*"([^"]+)"\s*$', body)
if not match:
raise ReleaseError("Cargo.toml package version was not found")
old = match.group(1)
body = body[: match.start(1)] + version + body[match.end(1) :]
start, end = section.span(1)
return text[:start] + body + text[end:], old
def replace_lock_version(text: str, version: str) -> tuple[str, str]:
pattern = re.compile(
r'(?m)(^\[\[package\]\]\nname = "pj3-splice"\nversion = ")([^"]+)(")'
)
matches = list(pattern.finditer(text))
if len(matches) != 1:
raise ReleaseError("Cargo.lock must contain exactly one pj3-splice package entry")
old = matches[0].group(2)
if old == version:
return text, old
start, end = matches[0].span(2)
return text[:start] + version + text[end:], old
def cmd_prepare(args: argparse.Namespace) -> int:
version = args.version or cargo_version()
validate_version(version)
validate_release_docs(version)
cargo = root() / "Cargo.toml"
lock = root() / "Cargo.lock"
cargo_text = read_text(cargo)
lock_text = read_text(lock)
new_cargo, old_cargo = replace_package_version(cargo_text, version)
new_lock, old_lock = replace_lock_version(lock_text, version)
if args.dry_run:
print("would update Cargo.toml package version: " + old_cargo + " -> " + version)
print("would update Cargo.lock pj3-splice version: " + old_lock + " -> " + version)
print("CHANGELOG.md and " + str(notes_path(version)) + " are present")
return 0
if new_cargo != cargo_text:
write_text(cargo, new_cargo)
if new_lock != lock_text:
write_text(lock, new_lock)
print("prepared version " + version)
print(" Cargo.toml: " + old_cargo + " -> " + version)
print(" Cargo.lock pj3-splice: " + old_lock + " -> " + version)
print(" CHANGELOG.md: section [" + version + "] present")
print(" release notes: " + str(notes_path(version)))
return 0
def expected_names(version: str) -> set[str]:
return {name.format(tag=release_tag(version)) for name in EXPECTED_ARTIFACTS}
def parse_sums(path: Path) -> dict[str, str]:
if not path.is_file():
raise ReleaseError("missing SHA256SUMS: " + str(path))
result: dict[str, str] = {}
for line in read_text(path).splitlines():
line = line.strip()
if not line:
continue
parts = line.split(None, 1)
if len(parts) != 2:
raise ReleaseError("invalid SHA256SUMS line: " + line)
digest, name = parts[0], parts[1].lstrip("*")
if name in result:
raise ReleaseError("duplicate SHA256SUMS entry: " + name)
result[name] = digest
return result
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def find_objdump() -> str:
candidates = [
os.environ.get("OBJDUMP"),
"x86_64-w64-mingw32-objdump",
"llvm-objdump",
"objdump",
]
for candidate in candidates:
if candidate and shutil.which(candidate):
return candidate
raise ReleaseError("objdump not found; set OBJDUMP or install mingw-w64/binutils")
def win7_imports(path: Path) -> list[str]:
command = [find_objdump(), "-p", str(path)]
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
raise ReleaseError("objdump failed for " + str(path) + ": " + result.stderr.strip())
imports = sorted(
{
match.group(1)
for match in re.finditer(r"DLL Name:\s*(\S+)", result.stdout, re.IGNORECASE)
},
key=str.lower,
)
if not imports:
raise ReleaseError("no DLL imports found in " + str(path))
bad = [name for name in imports if name.lower() not in WIN7_ALLOWED_DLLS]
if bad:
raise ReleaseError(
"Win7 executable imports non-allowlisted DLL(s): " + ", ".join(bad)
)
for name in imports:
lowered = name.lower()
if lowered.startswith("api-ms-win-") or lowered in {
"combase.dll",
"bcryptprimitives.dll",
}:
raise ReleaseError("Win7 executable imports Win8+ DLL: " + name)
return imports
def verify_tree(version: str, directory: Path) -> dict[str, int]:
expected = expected_names(version)
if not directory.is_dir():
raise ReleaseError("release directory does not exist: " + str(directory))
actual = {path.name for path in directory.iterdir() if path.is_file()}
required = expected | {"SHA256SUMS"}
missing = sorted(required - actual)
extra = sorted(actual - required)
if missing:
raise ReleaseError("missing release artifact(s): " + ", ".join(missing))
if extra:
raise ReleaseError("unexpected file(s) in release directory: " + ", ".join(extra))
sums = parse_sums(directory / "SHA256SUMS")
if set(sums) != expected:
raise ReleaseError("SHA256SUMS names do not match the six expected artifacts")
sizes: dict[str, int] = {}
for name in sorted(expected):
path = directory / name
digest = sha256(path)
if digest != sums[name]:
raise ReleaseError("SHA256 mismatch for " + name)
sizes[name] = path.stat().st_size
win7 = directory / "pj3-splice-{tag}-win7-x86_64-gui.exe".format(tag=release_tag(version))
imports = win7_imports(win7)
linux_gui = directory / "pj3-splice-{tag}-linux-x86_64-gui.tar.gz".format(
tag=release_tag(version)
)
with tarfile.open(linux_gui, "r:gz") as archive:
names = set(archive.getnames())
if not {"pj3-splice", "README.txt"}.issubset(names):
raise ReleaseError("Linux GUI archive must contain pj3-splice and README.txt")
deploy = directory / "pj3-splice-{tag}-deploy.tar.gz".format(tag=release_tag(version))
with tarfile.open(deploy, "r:gz") as archive:
names = set(archive.getnames())
required_deploy = {
"pj3-splice-{tag}.tar.gz".format(tag=release_tag(version)),
"Taskfile.yml",
"Makefile",
}
if not required_deploy.issubset(names):
raise ReleaseError("deploy archive is missing required files")
print("release artifacts verified in " + str(directory))
for name in sorted(expected):
print(" {:>12} {}".format(sizes[name], name))
print("Win7 imports:")
for name in imports:
print(" " + name)
return sizes
def cmd_verify(args: argparse.Namespace) -> int:
version = args.version or cargo_version()
validate_version(version)
verify_tree(version, release_dir(version))
return 0
def git_output(args: list[str], check: bool = True) -> str:
result = subprocess.run(["git", *args], cwd=root(), capture_output=True, text=True)
if check and result.returncode != 0:
raise ReleaseError("git " + " ".join(args) + " failed: " + result.stderr.strip())
return result.stdout.strip()
def local_identity() -> tuple[str, str]:
name = git_output(["config", "--local", "user.name"], check=False)
email = git_output(["config", "--local", "user.email"], check=False)
if not name or not email:
raise ReleaseError(
"repository-local git user.name/user.email are required; "
"set them with git config (without --global)"
)
return name, email
def ensure_clean_tree() -> None:
status = git_output(["status", "--porcelain"], check=False)
if status:
raise ReleaseError("working tree must be clean before tagging/publishing")
def cmd_tag(args: argparse.Namespace) -> int:
version = args.version or cargo_version()
tag = release_tag(version)
name, email = local_identity()
ensure_clean_tree()
head = git_output(["rev-parse", "HEAD"])
existing = git_output(["rev-parse", "-q", "--verify", "refs/tags/" + tag + "^{}"], check=False)
if existing:
if existing == head:
print("local tag already exists at HEAD: " + tag)
return 0
raise ReleaseError("local tag " + tag + " points at another commit: " + existing)
if args.dry_run:
print("would create annotated tag " + tag + " at " + head)
print(" identity: " + name + " <" + email + ">")
print(" remote tag check skipped; not pushing")
return 0
remote = git_output(["ls-remote", "--tags", "origin", "refs/tags/" + tag], check=False)
if remote:
raise ReleaseError("remote tag already exists; refusing to overwrite: " + remote)
subprocess.run(
["git", "tag", "-a", tag, "-m", "Release " + tag, head],
cwd=root(),
check=True,
)
print("created annotated local tag " + tag + " at " + head)
print("not pushing; use release:publish when ready")
return 0
def token() -> str:
value = os.environ.get("GITEA_TOKEN", "").strip()
if value:
return value
path = Path.home() / ".config" / "gitea" / "token"
if path.is_file():
value = path.read_text(encoding="utf-8").strip()
if value:
return value
raise ReleaseError(
"Gitea token unavailable; set GITEA_TOKEN or create $HOME/.config/gitea/token"
)
def token_source() -> str:
if os.environ.get("GITEA_TOKEN", "").strip():
return "GITEA_TOKEN"
path = Path.home() / ".config" / "gitea" / "token"
return str(path) if path.is_file() else "missing"
def config_for_token(value: str) -> str:
# curl --config - reads this from stdin; the token never appears in argv.
return 'header = "Authorization: token ' + value.replace('"', "") + '"\n'
def curl_request(
args: list[str],
token_value: str,
accept_404: bool = False,
retries: int = 5,
timeout: int = 600,
) -> tuple[int, str]:
last_error = ""
for attempt in range(1, retries + 1):
command = [
"curl",
"--silent",
"--show-error",
"--config",
"-",
"--connect-timeout",
"15",
"--max-time",
str(timeout),
"--speed-limit",
"1024",
"--speed-time",
"30",
"--write-out",
"\\n%{http_code}",
*args,
]
result = subprocess.run(
command,
input=config_for_token(token_value).encode("utf-8"),
capture_output=True,
)
stdout = result.stdout.decode("utf-8", errors="replace")
stderr = result.stderr.decode("utf-8", errors="replace")
body, _, code_text = stdout.rpartition("\n")
try:
code = int(code_text.strip()) if code_text.strip() else 0
except ValueError:
code = 0
if result.returncode == 0 and 200 <= code < 300:
return code, body
if code == 404 and accept_404:
return code, body
last_error = stderr.strip() or (
"curl exit {} with HTTP {}".format(result.returncode, code)
)
if 400 <= code < 500 and code not in (408, 429):
raise ReleaseError("Gitea API rejected request (HTTP {}): {}".format(code, body[:500]))
if attempt < retries:
time.sleep(min(2 ** (attempt - 1), 8))
raise ReleaseError("request failed after retries: " + last_error)
def api_json(
method: str,
url: str,
token_value: str,
payload: dict | None = None,
accept_404: bool = False,
) -> tuple[int, dict | list | None]:
args = ["--request", method, "--header", "Content-Type: application/json"]
temp_path = None
try:
if payload is not None:
handle = tempfile.NamedTemporaryFile(
"w", encoding="utf-8", delete=False, suffix=".json"
)
json.dump(payload, handle, ensure_ascii=False)
handle.close()
temp_path = handle.name
args.extend(["--data-binary", "@" + temp_path])
code, body = curl_request(args + [url], token_value, accept_404=accept_404)
if not body.strip():
return code, None
return code, json.loads(body)
finally:
if temp_path:
try:
os.unlink(temp_path)
except OSError:
pass
def download_table(version: str, directory: Path, base_url: str, repo: str) -> str:
tag = release_tag(version)
sums = parse_sums(directory / "SHA256SUMS")
base = base_url.rstrip("/")
lines = [
"## 下载",
"",
"| 文件 | 大小(字节) | SHA-256 |",
"| --- | ---: | --- |",
]
for name in sorted(sums):
size = (directory / name).stat().st_size
url = base + "/" + repo + "/releases/download/" + urllib.parse.quote(tag) + "/" + urllib.parse.quote(name)
lines.append("| [{}]({}) | {} | `{}` |".format(name, url, size, sums[name]))
return "\n".join(lines) + "\n"
def release_body(version: str, directory: Path, base_url: str, repo: str) -> str:
notes = read_text(notes_path(version)).rstrip()
marker = "\n\n<!-- auto-generated download table -->\n\n"
table = download_table(version, directory, base_url, repo)
if marker in notes:
notes = notes.split(marker, 1)[0].rstrip()
return notes + marker + table
def upload_asset(url: str, path: Path, token_value: str, retries: int = 5) -> dict:
last_error = ""
for attempt in range(1, retries + 1):
command = [
"curl",
"--silent",
"--show-error",
"--config",
"-",
"--connect-timeout",
"15",
"--max-time",
"900",
"--speed-limit",
"1024",
"--speed-time",
"30",
"--write-out",
"\\n%{http_code}",
"--form",
"attachment=@" + str(path),
url,
]
result = subprocess.run(
command,
input=config_for_token(token_value).encode("utf-8"),
capture_output=True,
)
stdout = result.stdout.decode("utf-8", errors="replace")
stderr = result.stderr.decode("utf-8", errors="replace")
body, _, code_text = stdout.rpartition("\n")
try:
code = int(code_text.strip()) if code_text.strip() else 0
except ValueError:
code = 0
if result.returncode == 0 and 200 <= code < 300:
return json.loads(body) if body.strip() else {}
last_error = stderr.strip() or (
"curl exit {} with HTTP {}".format(result.returncode, code)
)
if 400 <= code < 500 and code not in (408, 429):
raise ReleaseError("asset upload rejected (HTTP {}): {}".format(code, body[:500]))
if attempt < retries:
time.sleep(min(2 ** (attempt - 1), 8))
raise ReleaseError("asset upload failed after retries: " + last_error)
def cmd_publish(args: argparse.Namespace) -> int:
version = args.version or cargo_version()
validate_version(version)
tag = release_tag(version)
directory = release_dir(version)
verify_tree(version, directory)
sizes = {path.name: path.stat().st_size for path in directory.iterdir() if path.is_file()}
notes = notes_path(version)
base_url = os.environ.get("GITEA_URL", DEFAULT_BASE_URL).rstrip("/")
repo = os.environ.get("GITEA_REPOSITORY", DEFAULT_REPOSITORY).strip("/")
branch = os.environ.get("GIT_BRANCH", DEFAULT_BRANCH)
# GITEA_URL 只决定 API/上传走哪条路(例如绕过 Cloudflare 的内网隧道);
# 发布说明里的下载链接始终使用公网域名 GITEA_PUBLIC_URL。
public_url = os.environ.get("GITEA_PUBLIC_URL", DEFAULT_BASE_URL).rstrip("/")
body = release_body(version, directory, public_url, repo)
if args.dry_run:
print("dry-run: no push, no API write, no upload")
print(" tag: " + tag)
print(" branch: " + branch)
print(" repository: " + repo)
print(" api: " + base_url + "/api/v1/repos/" + repo)
print(" release notes: " + str(notes))
print(" token source: " + token_source() + " (value not read/printed)")
print(" would run: git push origin HEAD:" + branch)
print(" would run: git push origin " + tag)
print(" would GET release by tag, then POST/PATCH release with " + str(len(body)) + " body bytes")
print(" would upload " + str(len(sizes)) + " asset(s):")
for name in sorted(sizes):
print(" {:>12} {}".format(sizes[name], name))
print(" download table preview:")
print(download_table(version, directory, public_url, repo).strip())
return 0
ensure_clean_tree()
local_identity()
tag_commit = git_output(["rev-parse", "refs/tags/" + tag + "^{}"], check=False)
head = git_output(["rev-parse", "HEAD"])
if not tag_commit:
raise ReleaseError("tag " + tag + " does not exist; run release:tag first")
if tag_commit != head:
raise ReleaseError("tag " + tag + " does not point at HEAD")
token_value = token()
print("pushing branch " + branch + " (no force)")
subprocess.run(["git", "push", "origin", "HEAD:" + branch], cwd=root(), check=True)
print("pushing tag " + tag + " (no force)")
subprocess.run(["git", "push", "origin", tag], cwd=root(), check=True)
api_root = base_url + "/api/v1/repos/" + repo
code, existing = api_json(
"GET", api_root + "/releases/tags/" + urllib.parse.quote(tag), token_value, accept_404=True
)
if code == 404:
payload = {
"tag_name": tag,
"target_commitish": head,
"name": "pj3-splice " + tag,
"body": body,
"draft": False,
"prerelease": False,
}
code, created = api_json("POST", api_root + "/releases", token_value, payload)
if not isinstance(created, dict):
raise ReleaseError("Gitea create release returned no JSON object")
release_id = int(created["id"])
print("created Gitea release " + tag)
else:
if not isinstance(existing, dict):
raise ReleaseError("Gitea release lookup returned no JSON object")
release_id = int(existing["id"])
payload = {"tag_name": tag, "name": "pj3-splice " + tag, "body": body}
api_json("PATCH", api_root + "/releases/" + str(release_id), token_value, payload)
print("updated Gitea release " + tag)
code, assets = api_json(
"GET", api_root + "/releases/" + str(release_id) + "/assets", token_value
)
existing_assets = {}
if isinstance(assets, list):
for asset in assets:
if isinstance(asset, dict) and "name" in asset and "size" in asset:
existing_assets[str(asset["name"])] = int(asset["size"])
for name in sorted(sizes):
local_size = sizes[name]
if name in existing_assets:
if existing_assets[name] == local_size:
print("skip existing asset (same size): " + name)
continue
raise ReleaseError(
"existing asset has a different size, refusing to overwrite: {} ({} != {})".format(
name, existing_assets[name], local_size
)
)
url = (
api_root
+ "/releases/"
+ str(release_id)
+ "/assets?name="
+ urllib.parse.quote(name)
)
uploaded = upload_asset(url, directory / name, token_value)
remote_size = uploaded.get("size")
if remote_size is not None and int(remote_size) != local_size:
raise ReleaseError("uploaded asset size mismatch for " + name)
print("uploaded " + name + " (" + str(local_size) + " bytes)")
code, final_assets = api_json(
"GET", api_root + "/releases/" + str(release_id) + "/assets", token_value
)
final = {}
if isinstance(final_assets, list):
for asset in final_assets:
if isinstance(asset, dict) and "name" in asset and "size" in asset:
final[str(asset["name"])] = int(asset["size"])
if set(final) != set(sizes):
raise ReleaseError("remote asset names do not match local release artifacts")
for name, local_size in sizes.items():
if final[name] != local_size:
raise ReleaseError("remote asset size mismatch for " + name)
print("release assets verified: " + str(len(final)) + " file(s)")
print("released: " + public_url + "/" + repo + "/releases/tag/" + tag)
return 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
prepare = sub.add_parser("prepare", help="prepare Cargo.toml/Cargo.lock for a version")
prepare.add_argument("--version", default="")
prepare.add_argument("--dry-run", action="store_true")
prepare.set_defaults(func=cmd_prepare)
verify = sub.add_parser("verify", help="verify release artifacts and checksums")
verify.add_argument("--version", default="")
verify.set_defaults(func=cmd_verify)
tag = sub.add_parser("tag", help="create an annotated local tag")
tag.add_argument("--version", default="")
tag.add_argument("--dry-run", action="store_true")
tag.set_defaults(func=cmd_tag)
publish = sub.add_parser("publish", help="push branch/tag and publish to Gitea")
publish.add_argument("--version", default="")
publish.add_argument("--dry-run", action="store_true")
publish.set_defaults(func=cmd_publish)
return parser
def main() -> int:
parser = build_parser()
args = parser.parse_args()
try:
return args.func(args)
except Exception as error:
# Include the real exception class/message for diagnosis. No secret is
# part of these messages; the token is never placed in argv or files.
print("release error ({}): {}".format(type(error).__name__, error), file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())