- fetch the pinned core CLI from git.cflmy.cn in Woodpecker instead of relying on GitHub access from the internal runner - add tools/release/publish-gitea.py: idempotent create/update of the prerelease for the tag and upload of archive, checksum, FILES.sha256, RELEASE_INFO.json and smoke evidence; token only from the environment - the tag-only Woodpecker lane now publishes through that script and fails closed when the GITEA_TOKEN repo secret is missing
212 lines
7.3 KiB
Python
Executable File
212 lines
7.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Create/update the prerelease on the project's Gitea forge and attach assets.
|
|
|
|
Reads the token from the environment (`GITEA_TOKEN` or `gitea_token`), never
|
|
prints or stores it. Idempotent: an existing release for the tag is updated and
|
|
existing assets are replaced so a re-run of the tag pipeline produces the same
|
|
release instead of failing.
|
|
|
|
Usage:
|
|
GITEA_TOKEN=... python3 tools/release/publish-gitea.py \
|
|
--tag v0.1.0-beta.2 \
|
|
--archive dist/marqdo-knowledge-...tar.gz \
|
|
--files dist/marqdo-knowledge-....sha256 dist/RELEASE_INFO.json \
|
|
dist/FILES.sha256 dist/smoke-evidence.json \
|
|
--body-file docs/releases/0.1.0-beta.2.md
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import mimetypes
|
|
import os
|
|
import sys
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
DEFAULT_API = "https://git.cflmy.cn/api/v1"
|
|
DEFAULT_REPO = "cflmy/marqdo-knowledge"
|
|
|
|
|
|
def fail(message: str) -> "NoReturn":
|
|
print(f"publish-gitea: FAIL: {message}", file=sys.stderr)
|
|
raise SystemExit(1)
|
|
|
|
|
|
def token() -> str:
|
|
value = os.environ.get("GITEA_TOKEN") or os.environ.get("gitea_token")
|
|
if not value:
|
|
fail("GITEA_TOKEN (or gitea_token) is not set")
|
|
return value
|
|
|
|
|
|
def request(
|
|
api: str,
|
|
method: str,
|
|
path: str,
|
|
token_value: str,
|
|
payload: dict | None = None,
|
|
raw: bytes | None = None,
|
|
content_type: str = "application/json",
|
|
) -> tuple[int, bytes]:
|
|
url = f"{api}{path}"
|
|
headers = {"Authorization": f"token {token_value}", "Accept": "application/json"}
|
|
data = None
|
|
if payload is not None:
|
|
data = json.dumps(payload).encode()
|
|
headers["Content-Type"] = content_type
|
|
elif raw is not None:
|
|
data = raw
|
|
headers["Content-Type"] = content_type
|
|
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=60) as response:
|
|
return response.status, response.read()
|
|
except urllib.error.HTTPError as error:
|
|
return error.code, error.read()
|
|
|
|
|
|
def decode(body: bytes) -> object:
|
|
try:
|
|
return json.loads(body)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def create_or_update_release(
|
|
api: str, repo: str, tag: str, body: str, token_value: str
|
|
) -> dict:
|
|
path = f"/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe='')}"
|
|
status, response = request(api, "GET", path, token_value)
|
|
payload = {
|
|
"tag_name": tag,
|
|
"name": f"marqdo-knowledge {tag.removeprefix('v')}",
|
|
"prerelease": True,
|
|
"draft": False,
|
|
"body": body,
|
|
}
|
|
if status == 200:
|
|
release = decode(response)
|
|
if not isinstance(release, dict) or "id" not in release:
|
|
fail("existing release response is malformed")
|
|
status, response = request(
|
|
api, "PATCH", f"/repos/{repo}/releases/{release['id']}", token_value, payload
|
|
)
|
|
if status != 200:
|
|
fail(f"updating the existing release failed with HTTP {status}")
|
|
release = decode(response)
|
|
print(f"updated release id={release.get('id')} tag={tag}")
|
|
return release
|
|
if status != 404:
|
|
fail(f"looking up the release failed with HTTP {status}")
|
|
status, response = request(api, "POST", f"/repos/{repo}/releases", token_value, payload)
|
|
if status not in (201, 200):
|
|
fail(f"creating the release failed with HTTP {status}")
|
|
release = decode(response)
|
|
if not isinstance(release, dict) or "id" not in release:
|
|
fail("release create response is malformed")
|
|
print(f"created release id={release.get('id')} tag={tag}")
|
|
return release
|
|
|
|
|
|
def upload_asset(
|
|
api: str, repo: str, release_id: int, path: Path, token_value: str
|
|
) -> dict:
|
|
name = path.name
|
|
status, response = request(
|
|
api, "GET", f"/repos/{repo}/releases/{release_id}/assets", token_value
|
|
)
|
|
if status == 200:
|
|
existing = decode(response)
|
|
if isinstance(existing, list):
|
|
for asset in existing:
|
|
if asset.get("name") == name:
|
|
request(
|
|
api,
|
|
"DELETE",
|
|
f"/repos/{repo}/releases/{release_id}/assets/{asset['id']}",
|
|
token_value,
|
|
)
|
|
boundary = f"----marqdo{uuid.uuid4().hex}"
|
|
content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
|
|
body = bytearray()
|
|
body.extend(f"--{boundary}\r\n".encode())
|
|
body.extend(
|
|
f'Content-Disposition: form-data; name="attachment"; filename="{name}"\r\n'.encode()
|
|
)
|
|
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode())
|
|
body.extend(path.read_bytes())
|
|
body.extend(f"\r\n--{boundary}--\r\n".encode())
|
|
status, response = request(
|
|
api,
|
|
"POST",
|
|
f"/repos/{repo}/releases/{release_id}/assets?name={urllib.parse.quote(name)}",
|
|
token_value,
|
|
raw=bytes(body),
|
|
content_type=f"multipart/form-data; boundary={boundary}",
|
|
)
|
|
if status not in (201, 200):
|
|
fail(f"uploading asset {name} failed with HTTP {status}")
|
|
result = decode(response)
|
|
print(f"uploaded asset {name} ({path.stat().st_size} bytes)")
|
|
return result if isinstance(result, dict) else {}
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", DEFAULT_API))
|
|
parser.add_argument("--repo", default=DEFAULT_REPO)
|
|
parser.add_argument("--tag", required=True)
|
|
parser.add_argument("--archive", required=True)
|
|
parser.add_argument("--files", nargs="*", default=[])
|
|
parser.add_argument("--body-file", required=True)
|
|
parser.add_argument("--evidence-out", default="dist/gitea-release-evidence.json")
|
|
args = parser.parse_args()
|
|
|
|
token_value = token()
|
|
archive = Path(args.archive)
|
|
if not archive.is_file():
|
|
fail(f"archive {archive} does not exist")
|
|
body = Path(args.body_file).read_text(encoding="utf-8")
|
|
release = create_or_update_release(args.api_url, args.repo, args.tag, body, token_value)
|
|
release_id = release["id"]
|
|
assets = [archive]
|
|
assets.extend(Path(item) for item in args.files if Path(item).is_file())
|
|
uploaded = []
|
|
for path in assets:
|
|
result = upload_asset(args.api_url, args.repo, release_id, path, token_value)
|
|
uploaded.append(
|
|
{
|
|
"name": path.name,
|
|
"size": path.stat().st_size,
|
|
"sha256": __import__("hashlib").sha256(path.read_bytes()).hexdigest(),
|
|
"browser_url": result.get("browser_download_url"),
|
|
}
|
|
)
|
|
evidence = {
|
|
"schema": "marqdo.knowledge.gitea-release",
|
|
"schema_version": 1,
|
|
"tag": args.tag,
|
|
"release_id": release_id,
|
|
"html_url": release.get("html_url"),
|
|
"prerelease": True,
|
|
"assets": uploaded,
|
|
}
|
|
evidence_path = Path(args.evidence_out)
|
|
evidence_path.parent.mkdir(parents=True, exist_ok=True)
|
|
evidence_path.write_text(
|
|
json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
|
|
encoding="utf-8",
|
|
)
|
|
print(f"release_url: {release.get('html_url')}")
|
|
print(f"evidence: {evidence_path}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|