[upstream] pin CORE_SHA to c44b0f943875 #6
No files matched your search
@@ -14,3 +14,4 @@
|
||||
# Python tooling cache
|
||||
__pycache__/
|
||||
*.pyc
|
||||
dist/
|
||||
@@ -0,0 +1,40 @@
|
||||
when:
|
||||
- event: [tag, manual]
|
||||
|
||||
steps:
|
||||
publish:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5
|
||||
environment:
|
||||
GITEA_PUBLISH_TOKEN:
|
||||
from_secret: gitea_publish_token
|
||||
WOODPECKER_NOTIFY_TOKEN:
|
||||
from_secret: woodpecker_notify_token
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
test -n "${GITEA_PUBLISH_TOKEN:?}"
|
||||
test -n "${CI_COMMIT_TAG:?}"
|
||||
export SOURCE_SHA="${CI_COMMIT_SHA}"
|
||||
export VERSION="${CI_COMMIT_TAG#v}"
|
||||
scripts/ci.sh
|
||||
scripts/package-release.sh
|
||||
# Attach release-evidence then publish immutably.
|
||||
ARCHIVE=$(ls dist/marqdo-knowledge-*.tar.gz | head -1)
|
||||
python3 scripts/release/write_evidence.py \
|
||||
--component-id knowledge \
|
||||
--repository cflmy/marqdo-knowledge \
|
||||
--tag "${CI_COMMIT_TAG}" \
|
||||
--source-sha "${SOURCE_SHA}" \
|
||||
--asset "$ARCHIVE" \
|
||||
--asset "${ARCHIVE}.sha256" \
|
||||
--out dist/release-evidence.json
|
||||
python3 scripts/release/publish_gitea.py \
|
||||
--repo cflmy/marqdo-knowledge \
|
||||
--tag "${CI_COMMIT_TAG}" \
|
||||
--target "${SOURCE_SHA}" \
|
||||
--prerelease \
|
||||
--body-file "docs/releases/${VERSION}.md" \
|
||||
--asset "$ARCHIVE" \
|
||||
--asset "${ARCHIVE}.sha256" \
|
||||
--asset dist/release-evidence.json \
|
||||
--evidence-out dist/gitea-publish-result.json
|
||||
@@ -1,7 +1,3 @@
|
||||
# Fast-path notification: a completed Gitea release asks the root reconcile
|
||||
# workflow to check it. The payload is only a hint; the root reconcile verifies
|
||||
# the release/assets from the authoritative Gitea API. A lost call is recovered
|
||||
# by the root `release-reconcile` cron.
|
||||
when:
|
||||
event: [release]
|
||||
|
||||
@@ -9,10 +5,12 @@ steps:
|
||||
notify:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
|
||||
environment:
|
||||
WOODPECKER_TOKEN:
|
||||
from_secret: woodpecker_token
|
||||
WOODPECKER_NOTIFY_TOKEN:
|
||||
from_secret: woodpecker_notify_token
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
test -n "${WOODPECKER_TOKEN:?woodpecker_token secret missing}"
|
||||
curl -fsS -X POST -H "Authorization: Bearer $WOODPECKER_TOKEN" -H "Content-Type: application/json" -d '{"branch":"main","workflow":"reconcile"}' https://ci.cflmy.cn/api/repos/6/pipelines
|
||||
test -n "${WOODPECKER_NOTIFY_TOKEN:?woodpecker_notify_token secret missing}"
|
||||
python3 scripts/release/notify_root.py \
|
||||
--hint-component "knowledge" \
|
||||
--hint-tag "${CI_COMMIT_TAG:-}"
|
||||
@@ -0,0 +1,18 @@
|
||||
# Consumer upstream validation (issue #10 §8.2 / CI-08).
|
||||
when:
|
||||
- event: [manual]
|
||||
branch: [main, master]
|
||||
|
||||
steps:
|
||||
upstream:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5
|
||||
environment:
|
||||
MARQDO_BIN: /opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/marqdo
|
||||
MARQDO_STDLIB_DIR: /opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/stdlib
|
||||
MARQDO_TEST_BIN: /opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/marqdo
|
||||
MARQDO_TOOL_HOME: /tmp/marqdo-tool-home
|
||||
MARQDO_GIT_TOKEN:
|
||||
from_secret: GITEA_TOKEN
|
||||
MARQDO_UPSTREAM_APPLY: "1"
|
||||
commands:
|
||||
- sh scripts/upstream.sh
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
CARGO="$ROOT/scripts/cargo.sh"
|
||||
CORE_SHA=${CORE_SHA:-4bbefc92449ee480c8a2c89b0308feb4cda8d0e7}
|
||||
CORE_SHA=${CORE_SHA:-c44b0f943875d563bb7c170f8ccd3fd56a82360f}
|
||||
CORE_REPO=${CORE_REPO:-https://github.com/cflmy/marqdo-cli}
|
||||
LANE=${1:-all}
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Vendored from marqdo scripts/component-release
|
||||
#
|
||||
# Do not edit in place across repositories. Change the root copy, re-test,
|
||||
# then re-run install-vendor.sh and record the hashes below.
|
||||
#
|
||||
# package_source.py sha256=cb18c2f7fbe807f55d49e2cf77720f0d3e57d355177d2b127ac09e119f90c6ae
|
||||
# write_evidence.py sha256=bb194bfd251e39308bc1dd53f46fd9efac181082ea43f668484b067d9e54acfc
|
||||
# publish_gitea.py sha256=a21a84146d9ea826eb8d0632a18a991b0c39f17005d83bd988c92fc608f67523
|
||||
# notify_root.py sha256=8eee83eb2bb31b99d93981f2a97fc2f0f9a486cc3c5c072f7dc12cfb63baf025
|
||||
Executable
+103
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ask the root Marqdo reconcile workflow to scan after a release.
|
||||
|
||||
The payload is only a hint. Correctness comes from the root
|
||||
`scripts/reconcile-releases.py` reading authoritative Gitea releases.
|
||||
Lost notifications are recovered by the root `release-reconcile` cron.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
DEFAULT_URL = "https://ci.cflmy.cn/api/repos/6/pipelines"
|
||||
DEFAULT_BODY = {"branch": "main", "workflow": "reconcile"}
|
||||
|
||||
|
||||
class NotifyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def token() -> str:
|
||||
value = (
|
||||
os.environ.get("WOODPECKER_NOTIFY_TOKEN")
|
||||
or os.environ.get("WOODPECKER_TOKEN")
|
||||
or os.environ.get("woodpecker_token")
|
||||
)
|
||||
if not value:
|
||||
raise NotifyError("WOODPECKER_NOTIFY_TOKEN (or WOODPECKER_TOKEN) is not set")
|
||||
return value
|
||||
|
||||
|
||||
def trigger(url: str, token_value: str, body: dict, attempts: int = 3) -> dict:
|
||||
payload = json.dumps(body).encode()
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
data=payload,
|
||||
method="POST",
|
||||
headers={
|
||||
"Authorization": f"Bearer {token_value}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
raw = response.read()
|
||||
decoded = json.loads(raw) if raw else {}
|
||||
return {
|
||||
"status": "triggered",
|
||||
"http_status": response.status,
|
||||
"pipeline_id": decoded.get("id"),
|
||||
"pipeline_number": decoded.get("number"),
|
||||
"attempt": attempt,
|
||||
}
|
||||
except urllib.error.HTTPError as error:
|
||||
# Auth/permission failures must not retry forever.
|
||||
if error.code in (401, 403, 404):
|
||||
raise NotifyError(f"trigger rejected with HTTP {error.code}") from error
|
||||
last_error = error
|
||||
except urllib.error.URLError as error:
|
||||
last_error = error
|
||||
if attempt < attempts:
|
||||
delay = (2 ** (attempt - 1)) + random.uniform(0, 0.5)
|
||||
time.sleep(delay)
|
||||
raise NotifyError(f"trigger failed after {attempts} attempts: {last_error}")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--url", default=os.environ.get("MARQDO_RECONCILE_TRIGGER_URL", DEFAULT_URL))
|
||||
parser.add_argument("--branch", default="main")
|
||||
parser.add_argument("--workflow", default="reconcile")
|
||||
parser.add_argument("--hint-component", default="")
|
||||
parser.add_argument("--hint-tag", default="")
|
||||
parser.add_argument("--attempts", type=int, default=3)
|
||||
args = parser.parse_args(argv)
|
||||
body = {"branch": args.branch, "workflow": args.workflow}
|
||||
# Hints are informational only; the root reconcile never trusts them as commands.
|
||||
if args.hint_component or args.hint_tag:
|
||||
body["variables"] = {
|
||||
"MARQDO_RELEASE_HINT_COMPONENT": args.hint_component,
|
||||
"MARQDO_RELEASE_HINT_TAG": args.hint_tag,
|
||||
}
|
||||
try:
|
||||
result = trigger(args.url, token(), body, attempts=max(1, args.attempts))
|
||||
except NotifyError as error:
|
||||
print(f"notify_root: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+145
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a deterministic source archive for a Marqdo component release.
|
||||
|
||||
Only allowlisted relative paths are included. The archive uses fixed mtime,
|
||||
uid/gid, and sorted member names so the same tree always yields the same
|
||||
sha256. Output is written under an isolated directory (default: dist/).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_ALLOWLIST = (
|
||||
"modules",
|
||||
"index.mq.md",
|
||||
"marqdo.yaml",
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
)
|
||||
FIXED_MTIME = 0
|
||||
EVIDENCE_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class PackageError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
raise PackageError(message)
|
||||
|
||||
|
||||
def is_safe_relative(path: str) -> bool:
|
||||
if not path or path.startswith("/") or path.startswith("\\"):
|
||||
return False
|
||||
parts = Path(path).parts
|
||||
return not any(part in (".", "..") for part in parts)
|
||||
|
||||
|
||||
def collect_files(root: Path, allowlist: list[str]) -> list[tuple[str, Path]]:
|
||||
selected: dict[str, Path] = {}
|
||||
for entry in allowlist:
|
||||
if not is_safe_relative(entry):
|
||||
fail(f"unsafe allowlist entry: {entry!r}")
|
||||
target = root / entry
|
||||
if not target.exists():
|
||||
continue
|
||||
if target.is_file():
|
||||
selected[entry.replace("\\", "/")] = target
|
||||
continue
|
||||
if not target.is_dir():
|
||||
fail(f"allowlist entry is not a regular file or directory: {entry}")
|
||||
for path in sorted(target.rglob("*")):
|
||||
if not path.is_file():
|
||||
continue
|
||||
if path.is_symlink():
|
||||
fail(f"symlinks are not publishable: {path.relative_to(root)}")
|
||||
relative = path.relative_to(root).as_posix()
|
||||
if not is_safe_relative(relative):
|
||||
fail(f"unsafe relative path: {relative}")
|
||||
selected[relative] = path
|
||||
if not selected:
|
||||
fail("allowlist matched no files")
|
||||
return sorted(selected.items(), key=lambda item: item[0])
|
||||
|
||||
|
||||
def archive_bytes(files: list[tuple[str, Path]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode="w:gz", format=tarfile.PAX_FORMAT, compresslevel=9) as archive:
|
||||
for relative, path in files:
|
||||
data = path.read_bytes()
|
||||
info = tarfile.TarInfo(name=relative)
|
||||
info.size = len(data)
|
||||
info.mtime = FIXED_MTIME
|
||||
info.uid = 0
|
||||
info.gid = 0
|
||||
info.uname = ""
|
||||
info.gname = ""
|
||||
info.mode = 0o644
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def write_outputs(
|
||||
root: Path,
|
||||
out_dir: Path,
|
||||
component_id: str,
|
||||
version: str,
|
||||
allowlist: list[str],
|
||||
) -> dict:
|
||||
files = collect_files(root, allowlist)
|
||||
payload = archive_bytes(files)
|
||||
digest = hashlib.sha256(payload).hexdigest()
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
archive_name = f"marqdo-{component_id}-{version}-source.tar.gz"
|
||||
archive_path = out_dir / archive_name
|
||||
sha_path = out_dir / f"{archive_name}.sha256"
|
||||
archive_path.write_bytes(payload)
|
||||
sha_path.write_text(f"{digest} {archive_name}\n", encoding="utf-8")
|
||||
return {
|
||||
"archive": str(archive_path),
|
||||
"sha256_file": str(sha_path),
|
||||
"name": archive_name,
|
||||
"size": len(payload),
|
||||
"sha256": digest,
|
||||
"files": [relative for relative, _ in files],
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", default=".", help="component repository root")
|
||||
parser.add_argument("--component-id", required=True)
|
||||
parser.add_argument("--version", required=True, help="version without leading v")
|
||||
parser.add_argument("--out-dir", default="dist")
|
||||
parser.add_argument(
|
||||
"--allow",
|
||||
action="append",
|
||||
default=[],
|
||||
help="relative allowlist entry (repeatable); defaults applied when omitted",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
allowlist = args.allow or list(DEFAULT_ALLOWLIST)
|
||||
root = Path(args.root).resolve()
|
||||
out_dir = Path(args.out_dir)
|
||||
if not out_dir.is_absolute():
|
||||
out_dir = root / out_dir
|
||||
try:
|
||||
result = write_outputs(root, out_dir, args.component_id, args.version, allowlist)
|
||||
except PackageError as error:
|
||||
print(f"package_source: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(result["archive"])
|
||||
print(result["sha256_file"])
|
||||
print(f"sha256={result['sha256']} size={result['size']} files={len(result['files'])}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+352
@@ -0,0 +1,352 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish a Gitea release with a draft transaction and immutable public assets.
|
||||
|
||||
Order (issue #10 §4.2):
|
||||
create/reuse draft → upload non-index assets → upload release-evidence.json last
|
||||
→ re-read and verify → mark non-draft → re-confirm.
|
||||
|
||||
Never deletes or replaces assets on an already-published (non-draft) release.
|
||||
Identical published identity is treated as idempotent success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
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"
|
||||
INDEX_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class PublishError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def token() -> str:
|
||||
value = (
|
||||
os.environ.get("GITEA_PUBLISH_TOKEN")
|
||||
or os.environ.get("GITEA_TOKEN")
|
||||
or os.environ.get("gitea_token")
|
||||
)
|
||||
if not value:
|
||||
raise PublishError("GITEA_PUBLISH_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=120) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read()
|
||||
|
||||
|
||||
def decode(body: bytes) -> object:
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def get_release_by_tag(api: str, repo: str, tag: str, token_value: str) -> dict | None:
|
||||
status, body = request(
|
||||
api,
|
||||
"GET",
|
||||
f"/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe='')}",
|
||||
token_value,
|
||||
)
|
||||
if status == 404:
|
||||
return None
|
||||
if status != 200:
|
||||
raise PublishError(f"lookup release {tag} failed with HTTP {status}")
|
||||
release = decode(body)
|
||||
if not isinstance(release, dict) or "id" not in release:
|
||||
raise PublishError("release lookup response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def create_draft(
|
||||
api: str,
|
||||
repo: str,
|
||||
tag: str,
|
||||
body: str,
|
||||
token_value: str,
|
||||
*,
|
||||
prerelease: bool,
|
||||
target: str,
|
||||
) -> dict:
|
||||
payload = {
|
||||
"tag_name": tag,
|
||||
"name": tag,
|
||||
"body": body,
|
||||
"draft": True,
|
||||
"prerelease": prerelease,
|
||||
"target_commitish": target,
|
||||
}
|
||||
status, response = request(api, "POST", f"/repos/{repo}/releases", token_value, payload)
|
||||
if status not in (200, 201):
|
||||
raise PublishError(f"creating draft release failed with HTTP {status}: {response[:200]!r}")
|
||||
release = decode(response)
|
||||
if not isinstance(release, dict) or "id" not in release:
|
||||
raise PublishError("draft create response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def patch_release(api: str, repo: str, release_id: int, token_value: str, payload: dict) -> dict:
|
||||
status, response = request(
|
||||
api, "PATCH", f"/repos/{repo}/releases/{release_id}", token_value, payload
|
||||
)
|
||||
if status != 200:
|
||||
raise PublishError(f"updating release {release_id} failed with HTTP {status}")
|
||||
release = decode(response)
|
||||
if not isinstance(release, dict):
|
||||
raise PublishError("release patch response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def list_assets(api: str, repo: str, release_id: int, token_value: str) -> list[dict]:
|
||||
status, response = request(
|
||||
api, "GET", f"/repos/{repo}/releases/{release_id}/assets", token_value
|
||||
)
|
||||
if status != 200:
|
||||
raise PublishError(f"listing assets failed with HTTP {status}")
|
||||
assets = decode(response)
|
||||
if not isinstance(assets, list):
|
||||
raise PublishError("asset list malformed")
|
||||
return assets
|
||||
|
||||
|
||||
def upload_asset(
|
||||
api: str, repo: str, release_id: int, path: Path, token_value: str
|
||||
) -> dict:
|
||||
name = path.name
|
||||
if not name or "/" in name or name in (".", ".."):
|
||||
raise PublishError(f"unsafe asset name: {name!r}")
|
||||
existing = list_assets(api, repo, release_id, token_value)
|
||||
for asset in existing:
|
||||
if asset.get("name") == name:
|
||||
raise PublishError(
|
||||
f"asset {name} already exists on draft/release {release_id}; "
|
||||
"refusing to overwrite"
|
||||
)
|
||||
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 (200, 201):
|
||||
raise PublishError(f"uploading {name} failed with HTTP {status}: {response[:200]!r}")
|
||||
result = decode(response)
|
||||
if not isinstance(result, dict):
|
||||
raise PublishError(f"upload response for {name} malformed")
|
||||
return result
|
||||
|
||||
|
||||
def asset_identity(path: Path) -> dict:
|
||||
return {
|
||||
"name": path.name,
|
||||
"size": path.stat().st_size,
|
||||
"sha256": sha256_file(path),
|
||||
}
|
||||
|
||||
|
||||
def published_matches(release: dict, expected: list[dict]) -> bool:
|
||||
remote = {
|
||||
asset.get("name"): int(asset.get("size") or -1)
|
||||
for asset in (release.get("assets") or [])
|
||||
}
|
||||
if set(remote) != {item["name"] for item in expected}:
|
||||
return False
|
||||
for item in expected:
|
||||
if remote.get(item["name"]) != item["size"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def publish(
|
||||
*,
|
||||
api: str,
|
||||
repo: str,
|
||||
tag: str,
|
||||
body: str,
|
||||
target: str,
|
||||
assets: list[Path],
|
||||
prerelease: bool,
|
||||
token_value: str,
|
||||
) -> dict:
|
||||
if not assets:
|
||||
raise PublishError("no assets to publish")
|
||||
index_assets = [path for path in assets if path.name == INDEX_NAME]
|
||||
other_assets = [path for path in assets if path.name != INDEX_NAME]
|
||||
if len(index_assets) != 1:
|
||||
raise PublishError("exactly one release-evidence.json is required")
|
||||
ordered = other_assets + index_assets
|
||||
expected = [asset_identity(path) for path in ordered]
|
||||
|
||||
existing = get_release_by_tag(api, repo, tag, token_value)
|
||||
if existing and not existing.get("draft"):
|
||||
if published_matches(existing, expected):
|
||||
return {
|
||||
"status": "idempotent",
|
||||
"release_id": existing["id"],
|
||||
"html_url": existing.get("html_url"),
|
||||
"tag": tag,
|
||||
"assets": expected,
|
||||
}
|
||||
raise PublishError(
|
||||
f"published release {tag} already exists with different assets; "
|
||||
"refusing to overwrite"
|
||||
)
|
||||
|
||||
if existing and existing.get("draft"):
|
||||
release = existing
|
||||
# Keep draft body/target aligned when continuing an interrupted publish.
|
||||
release = patch_release(
|
||||
api,
|
||||
repo,
|
||||
int(release["id"]),
|
||||
token_value,
|
||||
{
|
||||
"name": tag,
|
||||
"body": body,
|
||||
"draft": True,
|
||||
"prerelease": prerelease,
|
||||
"target_commitish": target,
|
||||
},
|
||||
)
|
||||
else:
|
||||
release = create_draft(
|
||||
api, repo, tag, body, token_value, prerelease=prerelease, target=target
|
||||
)
|
||||
|
||||
release_id = int(release["id"])
|
||||
remote_names = {asset.get("name") for asset in list_assets(api, repo, release_id, token_value)}
|
||||
for path in ordered:
|
||||
if path.name in remote_names:
|
||||
# Same-name asset already on this draft: require identical size, else fail.
|
||||
match = next(
|
||||
asset
|
||||
for asset in list_assets(api, repo, release_id, token_value)
|
||||
if asset.get("name") == path.name
|
||||
)
|
||||
if int(match.get("size") or -1) != path.stat().st_size:
|
||||
raise PublishError(
|
||||
f"draft asset {path.name} size mismatch; refusing to overwrite"
|
||||
)
|
||||
continue
|
||||
upload_asset(api, repo, release_id, path, token_value)
|
||||
|
||||
refreshed = get_release_by_tag(api, repo, tag, token_value)
|
||||
if not refreshed or not published_matches(refreshed, expected):
|
||||
raise PublishError("post-upload release asset list does not match local files")
|
||||
|
||||
published = patch_release(
|
||||
api,
|
||||
repo,
|
||||
release_id,
|
||||
token_value,
|
||||
{"draft": False, "prerelease": prerelease, "name": tag, "body": body},
|
||||
)
|
||||
if published.get("draft"):
|
||||
raise PublishError("release remained draft after publish")
|
||||
final = get_release_by_tag(api, repo, tag, token_value)
|
||||
if not final or final.get("draft") or not published_matches(final, expected):
|
||||
raise PublishError("final release confirmation failed")
|
||||
return {
|
||||
"status": "published",
|
||||
"release_id": final["id"],
|
||||
"html_url": final.get("html_url"),
|
||||
"tag": tag,
|
||||
"assets": expected,
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", DEFAULT_API))
|
||||
parser.add_argument("--repo", required=True, help="owner/name")
|
||||
parser.add_argument("--tag", required=True)
|
||||
parser.add_argument("--target", required=True, help="full commit SHA for the tag")
|
||||
parser.add_argument("--body-file", default=None)
|
||||
parser.add_argument("--body", default="")
|
||||
parser.add_argument("--asset", action="append", default=[], required=True)
|
||||
parser.add_argument("--prerelease", action="store_true", default=False)
|
||||
parser.add_argument("--evidence-out", default="dist/gitea-publish-result.json")
|
||||
args = parser.parse_args(argv)
|
||||
body = args.body
|
||||
if args.body_file:
|
||||
body = Path(args.body_file).read_text(encoding="utf-8")
|
||||
assets = [Path(item) for item in args.asset]
|
||||
for path in assets:
|
||||
if not path.is_file():
|
||||
print(f"publish_gitea: FAIL: missing asset {path}", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
result = publish(
|
||||
api=args.api_url.rstrip("/"),
|
||||
repo=args.repo,
|
||||
tag=args.tag,
|
||||
body=body,
|
||||
target=args.target,
|
||||
assets=assets,
|
||||
prerelease=args.prerelease,
|
||||
token_value=token(),
|
||||
)
|
||||
except PublishError as error:
|
||||
print(f"publish_gitea: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
out = Path(args.evidence_out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+165
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Write the external release-evidence.json index for a component release.
|
||||
|
||||
The index references already-built assets. It never includes itself in
|
||||
`assets[]` (no self-referential digest). Downstream discoverers hash the index
|
||||
bytes separately when they download it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SHA_RE = re.compile(r"^[0-9a-f]{40}$")
|
||||
DIGEST_RE = re.compile(r"^[0-9a-f]{64}$")
|
||||
MAX_ASSETS = 128
|
||||
MAX_DEPENDENCIES = 256
|
||||
INDEX_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class EvidenceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
while True:
|
||||
chunk = handle.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def parse_dependency(raw: str) -> dict:
|
||||
# id=cli,source_sha=<40hex>[,asset_sha256=<64hex>]
|
||||
fields = {}
|
||||
for part in raw.split(","):
|
||||
if "=" not in part:
|
||||
raise EvidenceError(f"invalid dependency field: {raw!r}")
|
||||
key, value = part.split("=", 1)
|
||||
fields[key.strip()] = value.strip()
|
||||
component_id = fields.get("id")
|
||||
source_sha = fields.get("source_sha")
|
||||
if not component_id or not source_sha or not SHA_RE.match(source_sha):
|
||||
raise EvidenceError(f"dependency requires id and 40-hex source_sha: {raw!r}")
|
||||
entry = {"id": component_id, "source_sha": source_sha}
|
||||
asset = fields.get("asset_sha256")
|
||||
if asset:
|
||||
if not DIGEST_RE.match(asset):
|
||||
raise EvidenceError(f"invalid asset_sha256 in dependency: {raw!r}")
|
||||
entry["asset_sha256"] = asset
|
||||
return entry
|
||||
|
||||
|
||||
def build_evidence(
|
||||
*,
|
||||
component_id: str,
|
||||
repository: str,
|
||||
tag: str,
|
||||
source_sha: str,
|
||||
assets: list[Path],
|
||||
dependencies: list[dict],
|
||||
pipeline_number: int | None,
|
||||
pipeline_url: str | None,
|
||||
) -> dict:
|
||||
if not component_id:
|
||||
raise EvidenceError("component_id is required")
|
||||
if "/" not in repository:
|
||||
raise EvidenceError("repository must be owner/name")
|
||||
if not tag:
|
||||
raise EvidenceError("tag is required")
|
||||
if not SHA_RE.match(source_sha):
|
||||
raise EvidenceError("source_sha must be a 40-hex commit")
|
||||
if not assets:
|
||||
raise EvidenceError("at least one non-index asset is required")
|
||||
if len(assets) > MAX_ASSETS:
|
||||
raise EvidenceError(f"more than {MAX_ASSETS} assets")
|
||||
if len(dependencies) > MAX_DEPENDENCIES:
|
||||
raise EvidenceError(f"more than {MAX_DEPENDENCIES} dependencies")
|
||||
|
||||
asset_entries = []
|
||||
seen_names: set[str] = set()
|
||||
for path in assets:
|
||||
if not path.is_file():
|
||||
raise EvidenceError(f"asset missing: {path}")
|
||||
name = path.name
|
||||
if name == INDEX_NAME:
|
||||
raise EvidenceError("assets must not include release-evidence.json itself")
|
||||
if name in seen_names or "/" in name or name in (".", ".."):
|
||||
raise EvidenceError(f"unsafe or duplicate asset name: {name!r}")
|
||||
seen_names.add(name)
|
||||
target = "source"
|
||||
if name.endswith(".tar.gz") and "linux" in name:
|
||||
target = "x86_64-unknown-linux-gnu"
|
||||
asset_entries.append(
|
||||
{
|
||||
"name": name,
|
||||
"target": target,
|
||||
"size": path.stat().st_size,
|
||||
"sha256": sha256_file(path),
|
||||
}
|
||||
)
|
||||
|
||||
evidence = {
|
||||
"component_id": component_id,
|
||||
"repository": repository,
|
||||
"tag": tag,
|
||||
"source_sha": source_sha,
|
||||
"ci": {
|
||||
"pipeline_number": pipeline_number,
|
||||
"url": pipeline_url,
|
||||
"source_sha": source_sha,
|
||||
},
|
||||
"assets": asset_entries,
|
||||
"dependencies": dependencies,
|
||||
}
|
||||
return evidence
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--component-id", required=True)
|
||||
parser.add_argument("--repository", required=True)
|
||||
parser.add_argument("--tag", required=True)
|
||||
parser.add_argument("--source-sha", required=True)
|
||||
parser.add_argument("--asset", action="append", default=[], required=True)
|
||||
parser.add_argument("--dependency", action="append", default=[])
|
||||
parser.add_argument("--pipeline-number", type=int, default=None)
|
||||
parser.add_argument("--pipeline-url", default=None)
|
||||
parser.add_argument("--out", default=f"dist/{INDEX_NAME}")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
dependencies = [parse_dependency(item) for item in args.dependency]
|
||||
evidence = build_evidence(
|
||||
component_id=args.component_id,
|
||||
repository=args.repository,
|
||||
tag=args.tag,
|
||||
source_sha=args.source_sha,
|
||||
assets=[Path(item) for item in args.asset],
|
||||
dependencies=dependencies,
|
||||
pipeline_number=args.pipeline_number,
|
||||
pipeline_url=args.pipeline_url,
|
||||
)
|
||||
except EvidenceError as error:
|
||||
print(f"write_evidence: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
out = Path(args.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
|
||||
if len(payload.encode()) > 1024 * 1024:
|
||||
print("write_evidence: FAIL: index exceeds 1 MiB", file=sys.stderr)
|
||||
return 1
|
||||
out.write_text(payload, encoding="utf-8")
|
||||
print(out)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+117
@@ -0,0 +1,117 @@
|
||||
#!/bin/sh
|
||||
# Validate an Upstream task Issue and, when safe, open a dependency pin PR.
|
||||
#
|
||||
# Inputs:
|
||||
# MARQDO_UPSTREAM_ISSUE hint issue number from root reconcile
|
||||
# MARQDO_GIT_TOKEN read Issues; optional write for pin PR
|
||||
# MARQDO_UPSTREAM_APPLY set to 1 to push pin branch + open PR
|
||||
# CI entry: scripts/ci.sh or scripts/test.sh
|
||||
#
|
||||
# Trusted inputs are only the Issue fields re-read from Gitea (source_sha/tag).
|
||||
# Release notes are never executed.
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
|
||||
API_BASE=${MARQDO_GITEA_API:-https://git.cflmy.cn/api/v1}
|
||||
OWNER=${CI_REPO_OWNER:-}
|
||||
NAME=${CI_REPO_NAME:-}
|
||||
if [ -z "$OWNER" ] || [ -z "$NAME" ]; then
|
||||
case "${CI_REPO:-}" in
|
||||
*/*) OWNER=$(echo "$CI_REPO" | cut -d/ -f1); NAME=$(echo "$CI_REPO" | cut -d/ -f2) ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
SOURCE_SHA=""
|
||||
ISSUE_JSON=""
|
||||
if [ -n "${MARQDO_UPSTREAM_ISSUE:-}" ] && [ -n "${MARQDO_GIT_TOKEN:-}" ] && [ -n "$OWNER" ] && [ -n "$NAME" ]; then
|
||||
echo "upstream hint issue=${MARQDO_UPSTREAM_ISSUE}"
|
||||
ISSUE_JSON=$(curl -fsS -H "Authorization: token ${MARQDO_GIT_TOKEN}" \
|
||||
"${API_BASE}/repos/${OWNER}/${NAME}/issues/${MARQDO_UPSTREAM_ISSUE}")
|
||||
echo "$ISSUE_JSON" | python3 - <<'PY'
|
||||
import json,sys,re
|
||||
issue=json.load(sys.stdin)
|
||||
body=issue.get("body") or ""
|
||||
if "marqdo:upstream-task key=" not in body:
|
||||
raise SystemExit("upstream issue missing task marker; refusing to run")
|
||||
m=re.search(r"upstream source_sha: `([0-9a-f]{40})`", body)
|
||||
if not m:
|
||||
raise SystemExit("upstream issue missing source_sha")
|
||||
open("/tmp/upstream-source-sha","w").write(m.group(1))
|
||||
print("validated upstream task issue", issue.get("number"), "sha", m.group(1))
|
||||
PY
|
||||
SOURCE_SHA=$(cat /tmp/upstream-source-sha)
|
||||
fi
|
||||
|
||||
# Optional CORE_SHA pin (Knowledge / tools that clone a pinned CLI commit).
|
||||
PIN_CHANGED=0
|
||||
if [ -n "$SOURCE_SHA" ] && [ -f scripts/ci.sh ] && grep -q 'CORE_SHA=' scripts/ci.sh; then
|
||||
CURRENT=$(grep -E '^CORE_SHA=\$\{CORE_SHA:-' scripts/ci.sh | head -1 | sed -E 's/.*:-([0-9a-f]{40})\}.*/\1/')
|
||||
if [ -n "$CURRENT" ] && [ "$CURRENT" != "$SOURCE_SHA" ]; then
|
||||
echo "pin CORE_SHA ${CURRENT} -> ${SOURCE_SHA}"
|
||||
python3 - <<PY
|
||||
from pathlib import Path
|
||||
import re
|
||||
path=Path("scripts/ci.sh")
|
||||
text=path.read_text()
|
||||
new=re.sub(
|
||||
r"(CORE_SHA=\$\{CORE_SHA:-)[0-9a-f]{40}(\})",
|
||||
r"\g<1>${SOURCE_SHA}\2",
|
||||
text,
|
||||
count=1,
|
||||
)
|
||||
if new==text:
|
||||
raise SystemExit("failed to rewrite CORE_SHA pin")
|
||||
path.write_text(new)
|
||||
PY
|
||||
PIN_CHANGED=1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -x scripts/ci.sh ] || [ -f scripts/ci.sh ]; then
|
||||
# Prefer the cheap test lane when present; image already supplies MARQDO_BIN.
|
||||
if grep -q 'lane_test\|scripts/ci.sh test' scripts/ci.sh 2>/dev/null; then
|
||||
sh scripts/ci.sh test
|
||||
else
|
||||
sh scripts/ci.sh
|
||||
fi
|
||||
elif [ -x scripts/test.sh ] || [ -f scripts/test.sh ]; then
|
||||
sh scripts/test.sh
|
||||
else
|
||||
echo "upstream.sh: no scripts/ci.sh or scripts/test.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$PIN_CHANGED" = "1" ] && [ "${MARQDO_UPSTREAM_APPLY:-0}" = "1" ]; then
|
||||
if [ -z "${MARQDO_GIT_TOKEN:-}" ] || [ -z "$OWNER" ] || [ -z "$NAME" ]; then
|
||||
echo "pin changed but cannot open PR without token/repo" >&2
|
||||
exit 1
|
||||
fi
|
||||
BRANCH="upstream/cli-${SOURCE_SHA%????????????????????????????}"
|
||||
BRANCH="upstream/cli-$(echo "$SOURCE_SHA" | cut -c1-12)"
|
||||
git config user.email "marqdo-reconcile@users.noreply.cflmy.cn"
|
||||
git config user.name "marqdo-reconcile"
|
||||
git checkout -B "$BRANCH"
|
||||
git add scripts/ci.sh
|
||||
git commit -m "upstream: pin CORE_SHA to ${SOURCE_SHA}"
|
||||
git push -u "https://oauth2:${MARQDO_GIT_TOKEN}@git.cflmy.cn/${OWNER}/${NAME}.git" "HEAD:${BRANCH}"
|
||||
python3 - <<PY
|
||||
import json,os,urllib.request
|
||||
api=os.environ.get("MARQDO_GITEA_API","https://git.cflmy.cn/api/v1")
|
||||
owner,name,branch,sha,issue="${OWNER}","${NAME}","${BRANCH}","${SOURCE_SHA}","${MARQDO_UPSTREAM_ISSUE}"
|
||||
body={
|
||||
"title": f"[upstream] pin CORE_SHA to {sha[:12]}",
|
||||
"body": f"Dependency pin from Upstream #{issue}.\n\n- CORE_SHA: \`{sha}\`\n- opened by scripts/upstream.sh after local CI lane\n- does not merge automatically",
|
||||
"head": branch,
|
||||
"base": os.environ.get("CI_COMMIT_BRANCH") or os.environ.get("CI_REPO_DEFAULT_BRANCH") or "master",
|
||||
}
|
||||
req=urllib.request.Request(
|
||||
f"{api}/repos/{owner}/{name}/pulls",
|
||||
data=json.dumps(body).encode(),
|
||||
method="POST",
|
||||
headers={"Authorization":f"token {os.environ['MARQDO_GIT_TOKEN']}","Content-Type":"application/json"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
print(resp.read().decode())
|
||||
PY
|
||||
fi
|
||||
+61
-187
@@ -1,211 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create/update the prerelease on the project's Gitea forge and attach assets.
|
||||
"""Compatibility wrapper: delegate to the vendored immutable publisher.
|
||||
|
||||
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
|
||||
Historical knowledge releases used an overwrite-friendly uploader. New publishes
|
||||
must follow issue #10 §4.2 (no overwrite of public assets; draft transaction).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import subprocess
|
||||
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 {}
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
VENDOR = ROOT / "scripts" / "release" / "publish_gitea.py"
|
||||
|
||||
|
||||
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("--api-url", default=os.environ.get("GITEA_API_URL", "https://git.cflmy.cn/api/v1"))
|
||||
parser.add_argument("--repo", default="cflmy/marqdo-knowledge")
|
||||
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")
|
||||
parser.add_argument("--target", default=os.environ.get("SOURCE_SHA") or os.environ.get("CI_COMMIT_SHA"))
|
||||
parser.add_argument("--prerelease", action="store_true", default=True)
|
||||
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 not args.target:
|
||||
print("publish-gitea: FAIL: --target / SOURCE_SHA / CI_COMMIT_SHA required", file=sys.stderr)
|
||||
return 1
|
||||
assets = [args.archive, *args.files]
|
||||
cmd = [
|
||||
sys.executable,
|
||||
str(VENDOR),
|
||||
"--api-url",
|
||||
args.api_url,
|
||||
"--repo",
|
||||
args.repo,
|
||||
"--tag",
|
||||
args.tag,
|
||||
"--target",
|
||||
args.target,
|
||||
"--body-file",
|
||||
args.body_file,
|
||||
"--evidence-out",
|
||||
args.evidence_out,
|
||||
]
|
||||
if args.prerelease:
|
||||
cmd.append("--prerelease")
|
||||
for asset in assets:
|
||||
cmd.extend(["--asset", asset])
|
||||
# Ensure release-evidence.json exists or generate a minimal one from assets.
|
||||
evidence = Path("dist/release-evidence.json")
|
||||
if not evidence.is_file():
|
||||
write = ROOT / "scripts" / "release" / "write_evidence.py"
|
||||
source_sha = args.target
|
||||
version = args.tag.removeprefix("v")
|
||||
gen = [
|
||||
sys.executable,
|
||||
str(write),
|
||||
"--component-id",
|
||||
"knowledge",
|
||||
"--repository",
|
||||
args.repo,
|
||||
"--tag",
|
||||
args.tag,
|
||||
"--source-sha",
|
||||
source_sha,
|
||||
"--out",
|
||||
str(evidence),
|
||||
]
|
||||
for asset in assets:
|
||||
gen.extend(["--asset", asset])
|
||||
subprocess.check_call(gen)
|
||||
if str(evidence) not in assets and evidence.is_file():
|
||||
cmd.extend(["--asset", str(evidence)])
|
||||
return subprocess.call(cmd)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user