Files
lucioandClaude Fable 5 72fa9f5742 Stop tracking tile pyramids; add tools/release.py for Gitea static releases
The tiles were 10.7k LFS objects for 82 MB: almost all of the per-object
transfer cost of a push/pull for 1% of the bytes. build.py regenerates them
from the committed build/<id>/base.png in a couple of minutes (and skips the
PSD render via base.stamp.json), so web/tiles* go back to .gitignore.

tools/release.py makes a stable static-site release: the read-only export ZIP
(server/serve.py export_static_site), an annotated git tag, and a Gitea
release for that tag with the ZIP attached through the REST API
(GITEA_TOKEN from env or .env). README documents the flow and deployment.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-22 09:59:16 -07:00

263 lines
12 KiB
Python

"""Cut a stable static-site release: ZIP of web/, git tag, Gitea release + asset.
python tools/release.py v2026.08.22 # zip + tag + Gitea release
python tools/release.py v2026.08.22 --build # run tools/build.py first
python tools/release.py v2026.08.22 --zip-only # just exports/tarkov-maps-<tag>.zip
python tools/release.py v2026.08.22 --notes NOTES.md --prerelease
python tools/release.py v2026.08.22 --replace # re-upload over an existing asset
The ZIP is the same read-only bundle the editable server's "Export site ZIP"
button makes (server/serve.py: export_static_site): the finished web/ document
root plus export-manifest.json, nothing else. Unzip it into any static host's
document root (see server/Caddyfile) and the site is live.
Gitea: the release is created through the REST API of the `origin` remote
(https://<host>/api/v1). Authentication is a personal access token with
repository write scope, read from $GITEA_TOKEN or a GITEA_TOKEN= line in the
project's .env (gitignored). Release attachments are capped by the server's
[attachment] MAX_SIZE (Gitea default 2048 MB) and ALLOWED_TYPES (.zip is in
the default list).
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid
from datetime import date
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
EXPORT_DIR = ROOT / "exports"
def run(*args: str, check: bool = True, capture: bool = True) -> str:
result = subprocess.run(args, cwd=ROOT, check=False, text=True,
capture_output=capture)
if check and result.returncode != 0:
raise SystemExit(f"{' '.join(args)} failed:\n{result.stderr or result.stdout}")
return (result.stdout or "").strip()
# --- git ----------------------------------------------------------------------
def ensure_clean(allow_dirty: bool) -> None:
dirty = run("git", "status", "--porcelain", "--untracked-files=no")
if dirty and not allow_dirty:
raise SystemExit("working tree has uncommitted changes; commit them or pass "
"--allow-dirty\n" + dirty)
def ensure_tag(tag: str, push: bool) -> str:
"""Create an annotated tag at HEAD if missing, push it, return the commit sha."""
existing = run("git", "rev-parse", "-q", "--verify", f"refs/tags/{tag}^{{commit}}",
check=False)
head = run("git", "rev-parse", "HEAD")
if existing:
if existing != head:
print(f"tag {tag} already exists at {existing[:10]} (HEAD is {head[:10]}); "
"releasing that commit")
sha = existing
else:
run("git", "tag", "-a", tag, "-m", f"Static site release {tag}")
print(f"tagged {tag} at {head[:10]}")
sha = head
if push:
run("git", "push", "origin", f"refs/tags/{tag}")
print(f"pushed tag {tag}")
return sha
def origin_repo() -> tuple[str, str, str]:
"""(api_base, owner, repo) from the origin remote URL."""
url = run("git", "remote", "get-url", "origin")
if url.startswith("git@"): # git@host:owner/repo.git
host, path = url[4:].split(":", 1)
scheme = "https"
else: # https://host/owner/repo.git
parts = urllib.parse.urlsplit(url)
host, path, scheme = parts.netloc, parts.path.lstrip("/"), parts.scheme or "https"
host = host.rsplit("@", 1)[-1] # drop user:pass@
owner, repo = path.removesuffix(".git").split("/", 1)
return f"{scheme}://{host}/api/v1", owner, repo
# --- zip ----------------------------------------------------------------------
def build_zip(tag: str, run_build: bool) -> Path:
if run_build:
print("running tools/build.py ...")
subprocess.run([sys.executable, str(ROOT / "tools" / "build.py")], cwd=ROOT, check=True)
sys.path.insert(0, str(ROOT / "server"))
import serve # noqa: E402 (server/serve.py; importing it starts nothing)
try:
result = serve.export_static_site()
except serve.PlacementError as exc:
raise SystemExit(f"export failed: {exc}") from exc
target = EXPORT_DIR / f"tarkov-maps-{tag}.zip"
shutil.copyfile(serve.EXPORT_ZIP, target)
print(f"wrote {target.relative_to(ROOT)}: {result['fileCount']} files, "
f"{result['zipBytes'] / 1e6:.1f} MB")
return target
# --- gitea --------------------------------------------------------------------
def load_token(explicit: str | None) -> str:
token = explicit or os.environ.get("GITEA_TOKEN")
if not token:
env_file = ROOT / ".env"
if env_file.exists():
for line in env_file.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line.startswith("GITEA_TOKEN=") and not line.startswith("#"):
token = line.split("=", 1)[1].strip().strip("\"'")
if not token:
raise SystemExit("no Gitea token: set GITEA_TOKEN (env or .env) or pass --token")
return token
class Gitea:
def __init__(self, api: str, owner: str, repo: str, token: str) -> None:
self.base = f"{api}/repos/{owner}/{repo}"
self.token = token
def request(self, method: str, path: str, *, body: bytes | None = None,
content_type: str | None = None, ok=(200, 201, 204)) -> tuple[int, dict | list | None]:
request = urllib.request.Request(self.base + path, data=body, method=method)
request.add_header("Authorization", f"token {self.token}")
request.add_header("Accept", "application/json")
if content_type:
request.add_header("Content-Type", content_type)
try:
with urllib.request.urlopen(request, timeout=600) as response:
raw = response.read()
status = response.status
except urllib.error.HTTPError as error:
raw = error.read()
status = error.code
payload = None
if raw:
try:
payload = json.loads(raw)
except ValueError:
payload = {"raw": raw[:500].decode("utf-8", "replace")}
if status not in ok:
message = payload.get("message") if isinstance(payload, dict) else payload
raise SystemExit(f"Gitea {method} {path} -> {status}: {message}")
return status, payload
def json(self, method: str, path: str, data: dict, ok=(200, 201)) -> dict:
return self.request(method, path, body=json.dumps(data).encode("utf-8"),
content_type="application/json", ok=ok)[1]
def release_for_tag(self, tag: str) -> dict | None:
status, payload = self.request("GET", f"/releases/tags/{urllib.parse.quote(tag)}",
ok=(200, 404))
return payload if status == 200 else None
def create_or_get_release(self, tag: str, sha: str, name: str, body: str,
draft: bool, prerelease: bool) -> dict:
release = self.release_for_tag(tag)
if release:
print(f"release for {tag} already exists (id {release['id']}); adding asset")
return release
release = self.json("POST", "/releases", {
"tag_name": tag, "target_commitish": sha, "name": name, "body": body,
"draft": draft, "prerelease": prerelease,
})
print(f"created release {tag} (id {release['id']})")
return release
def upload_asset(self, release_id: int, path: Path, replace: bool) -> dict:
name = path.name
_, assets = self.request("GET", f"/releases/{release_id}/assets")
for asset in assets or []:
if asset.get("name") == name:
if not replace:
raise SystemExit(f"asset {name} already exists on this release; "
"pass --replace to overwrite it")
self.request("DELETE", f"/releases/{release_id}/assets/{asset['id']}")
print(f"deleted existing asset {name}")
boundary = f"----tarkovmaps{uuid.uuid4().hex}"
head = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"attachment\"; "
f"filename=\"{name}\"\r\nContent-Type: application/zip\r\n\r\n").encode()
body = head + path.read_bytes() + f"\r\n--{boundary}--\r\n".encode()
_, asset = self.request(
"POST", f"/releases/{release_id}/assets?name={urllib.parse.quote(name)}",
body=body, content_type=f"multipart/form-data; boundary={boundary}",
ok=(201,))
return asset
def default_notes(tag: str, sha: str) -> str:
subject = run("git", "log", "-1", "--format=%s", sha)
world = ROOT / "web" / "data" / "world.json"
maps = ""
if world.exists():
names = [m.get("name", m.get("id", "?")) for m in
json.loads(world.read_text(encoding="utf-8")).get("maps", [])
if not m.get("base")]
maps = f"\n\nMaps: {', '.join(names)}"
return (f"Static site release {tag} ({date.today().isoformat()}) from {sha[:10]}: "
f"{subject}.\n\nUnzip the attached archive into a static host's document "
f"root (see server/Caddyfile). Read-only viewer; marker edits made by "
f"visitors stay in their browser.{maps}\n")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("tag", help="release tag, e.g. v2026.08.22")
parser.add_argument("--build", action="store_true", help="run tools/build.py first")
parser.add_argument("--zip-only", action="store_true",
help="only create exports/tarkov-maps-<tag>.zip (no tag, no upload)")
parser.add_argument("--notes", type=Path, help="Markdown file used as the release body")
parser.add_argument("--name", help="release title (default: the tag)")
parser.add_argument("--draft", action="store_true")
parser.add_argument("--prerelease", action="store_true")
parser.add_argument("--replace", action="store_true",
help="replace an asset of the same name on an existing release")
parser.add_argument("--allow-dirty", action="store_true",
help="release even with uncommitted tracked changes")
parser.add_argument("--no-push", action="store_true", help="do not push the tag")
parser.add_argument("--token", help="Gitea token (prefer $GITEA_TOKEN or .env)")
parser.add_argument("--api", help="API base, e.g. https://git.example.com/api/v1 "
"(default: derived from the origin remote)")
args = parser.parse_args()
tag = args.tag
if any(c in tag for c in " /\\") or not tag:
raise SystemExit("tag must be a single token like v2026.08.22")
if args.zip_only:
build_zip(tag, args.build)
return
token = load_token(args.token) # fail early, before tagging
ensure_clean(args.allow_dirty)
api, owner, repo = origin_repo()
if args.api:
api = args.api.rstrip("/")
archive = build_zip(tag, args.build)
sha = ensure_tag(tag, push=not args.no_push)
notes = args.notes.read_text(encoding="utf-8") if args.notes else default_notes(tag, sha)
gitea = Gitea(api, owner, repo, token)
release = gitea.create_or_get_release(tag, sha, args.name or tag, notes,
args.draft, args.prerelease)
asset = gitea.upload_asset(release["id"], archive, args.replace)
print(f"uploaded {asset.get('name')} ({int(asset.get('size', 0)) / 1e6:.1f} MB)")
print(f"release: {release.get('html_url', '(no url returned)')}")
print(f"asset: {asset.get('browser_download_url', '(no url returned)')}")
if __name__ == "__main__":
main()