1 parent
639362fbf5
commit
bdd69f0aad
101 files changed
+22691
-531
No files matched your search
Executable
+632
@@ -0,0 +1,632 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish verified, idempotent Gitea releases and prune old nightlies."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import stat
|
||||
import sys
|
||||
from typing import Any, NoReturn
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import quote, urlencode, urljoin, urlsplit
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
|
||||
MAX_JSON_BYTES = 8 * 1024 * 1024
|
||||
UPLOAD_CHUNK_BYTES = 1024 * 1024
|
||||
SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,255}$")
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, *_args: Any, **_kwargs: Any) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def fail(message: str) -> NoReturn:
|
||||
raise SystemExit(f"gitea-release: {message}")
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(UPLOAD_CHUNK_BYTES), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def validate_regular_file(path: Path) -> Path:
|
||||
try:
|
||||
metadata = path.lstat()
|
||||
except OSError as error:
|
||||
fail(f"cannot inspect artifact {path}: {error}")
|
||||
if not stat.S_ISREG(metadata.st_mode) or path.is_symlink():
|
||||
fail(f"artifact is not a regular file: {path}")
|
||||
if not SAFE_NAME.fullmatch(path.name):
|
||||
fail(f"artifact has an unsafe filename: {path}")
|
||||
return path.resolve(strict=True)
|
||||
|
||||
|
||||
class GiteaApi:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
token: str,
|
||||
*,
|
||||
allow_http: bool = False,
|
||||
timeout_seconds: int = 120,
|
||||
) -> None:
|
||||
self.base_url = base_url.rstrip("/") + "/"
|
||||
parsed = urlsplit(self.base_url)
|
||||
loopback = parsed.hostname in {"127.0.0.1", "::1", "localhost"}
|
||||
if parsed.scheme != "https" and not (
|
||||
allow_http and parsed.scheme == "http" and loopback
|
||||
):
|
||||
fail("the Gitea API URL must use HTTPS")
|
||||
if (
|
||||
not parsed.hostname
|
||||
or parsed.username
|
||||
or parsed.password
|
||||
or parsed.query
|
||||
or parsed.fragment
|
||||
):
|
||||
fail("the Gitea API URL is malformed or contains credentials")
|
||||
if not token or any(character in token for character in "\r\n\0"):
|
||||
fail("the release token is empty or contains a control character")
|
||||
self._parsed = parsed
|
||||
self._token = token
|
||||
self._timeout_seconds = timeout_seconds
|
||||
self._opener = build_opener(NoRedirect)
|
||||
|
||||
def url(self, path: str) -> str:
|
||||
return urljoin(self.base_url, path.lstrip("/"))
|
||||
|
||||
@property
|
||||
def headers(self) -> dict[str, str]:
|
||||
return {
|
||||
"Accept": "application/json",
|
||||
"Authorization": f"token {self._token}",
|
||||
"User-Agent": "echoion-gitea-release/1",
|
||||
}
|
||||
|
||||
def request_json(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
document: dict[str, Any] | None = None,
|
||||
*,
|
||||
allowed_statuses: tuple[int, ...] = (200,),
|
||||
) -> tuple[int, Any | None]:
|
||||
body = None
|
||||
headers = self.headers
|
||||
if document is not None:
|
||||
body = json.dumps(document, separators=(",", ":")).encode("utf-8")
|
||||
headers = {**headers, "Content-Type": "application/json"}
|
||||
request = Request(self.url(path), data=body, headers=headers, method=method)
|
||||
try:
|
||||
with self._opener.open(request, timeout=self._timeout_seconds) as response:
|
||||
status = response.status
|
||||
content = response.read(MAX_JSON_BYTES + 1)
|
||||
except HTTPError as error:
|
||||
status = error.code
|
||||
content = error.read(64 * 1024)
|
||||
except (OSError, URLError) as error:
|
||||
fail(f"{method} {path} failed: {error}")
|
||||
if status not in allowed_statuses:
|
||||
detail = content.decode("utf-8", errors="replace").strip()
|
||||
fail(f"{method} {path} returned HTTP {status}: {detail[:1000]}")
|
||||
if len(content) > MAX_JSON_BYTES:
|
||||
fail(f"{method} {path} returned an oversized JSON response")
|
||||
if not content:
|
||||
return status, None
|
||||
try:
|
||||
return status, json.loads(content)
|
||||
except json.JSONDecodeError as error:
|
||||
fail(f"{method} {path} returned invalid JSON: {error}")
|
||||
|
||||
def upload_asset(self, release_id: int, artifact: Path) -> dict[str, Any]:
|
||||
boundary = f"echoion-{secrets.token_hex(24)}"
|
||||
mime_type = mimetypes.guess_type(artifact.name)[0] or "application/octet-stream"
|
||||
prefix = (
|
||||
f"--{boundary}\r\n"
|
||||
f'Content-Disposition: form-data; name="attachment"; '
|
||||
f'filename="{artifact.name}"\r\n'
|
||||
f"Content-Type: {mime_type}\r\n\r\n"
|
||||
).encode("utf-8")
|
||||
suffix = f"\r\n--{boundary}--\r\n".encode("ascii")
|
||||
content_length = len(prefix) + artifact.stat().st_size + len(suffix)
|
||||
query = urlencode({"name": artifact.name})
|
||||
relative = (
|
||||
f"repos/{quote_owner(self.owner)}/{quote_owner(self.repo)}/releases/"
|
||||
f"{release_id}/assets?{query}"
|
||||
)
|
||||
target = urlsplit(self.url(relative))
|
||||
connection_type = (
|
||||
http.client.HTTPSConnection
|
||||
if target.scheme == "https"
|
||||
else http.client.HTTPConnection
|
||||
)
|
||||
connection = connection_type(
|
||||
target.hostname,
|
||||
target.port,
|
||||
timeout=self._timeout_seconds,
|
||||
)
|
||||
try:
|
||||
request_target = target.path + (f"?{target.query}" if target.query else "")
|
||||
connection.putrequest("POST", request_target)
|
||||
for name, value in self.headers.items():
|
||||
connection.putheader(name, value)
|
||||
connection.putheader("Content-Type", f"multipart/form-data; boundary={boundary}")
|
||||
connection.putheader("Content-Length", str(content_length))
|
||||
connection.endheaders()
|
||||
connection.send(prefix)
|
||||
with artifact.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(UPLOAD_CHUNK_BYTES), b""):
|
||||
connection.send(chunk)
|
||||
connection.send(suffix)
|
||||
response = connection.getresponse()
|
||||
content = response.read(MAX_JSON_BYTES + 1)
|
||||
status = response.status
|
||||
except OSError as error:
|
||||
fail(f"uploading {artifact.name} failed: {error}")
|
||||
finally:
|
||||
connection.close()
|
||||
if status != 201:
|
||||
detail = content.decode("utf-8", errors="replace").strip()
|
||||
fail(f"uploading {artifact.name} returned HTTP {status}: {detail[:1000]}")
|
||||
if len(content) > MAX_JSON_BYTES:
|
||||
fail(f"uploading {artifact.name} returned oversized JSON")
|
||||
try:
|
||||
result = json.loads(content)
|
||||
except json.JSONDecodeError as error:
|
||||
fail(f"uploading {artifact.name} returned invalid JSON: {error}")
|
||||
if not isinstance(result, dict):
|
||||
fail(f"uploading {artifact.name} returned an invalid asset")
|
||||
return result
|
||||
|
||||
def bind_repository(self, owner: str, repo: str) -> None:
|
||||
self.owner = owner
|
||||
self.repo = repo
|
||||
|
||||
def remote_sha256(self, download_url: str) -> tuple[int, str]:
|
||||
target = urljoin(self.base_url, download_url)
|
||||
parsed = urlsplit(target)
|
||||
base = self._parsed
|
||||
parsed_port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
||||
base_port = base.port or (443 if base.scheme == "https" else 80)
|
||||
if (
|
||||
parsed.scheme != base.scheme
|
||||
or parsed.hostname != base.hostname
|
||||
or parsed_port != base_port
|
||||
or parsed.username
|
||||
or parsed.password
|
||||
or parsed.fragment
|
||||
):
|
||||
fail(f"Gitea returned an untrusted asset URL: {download_url!r}")
|
||||
request = Request(target, headers=self.headers, method="GET")
|
||||
result = hashlib.sha256()
|
||||
size = 0
|
||||
try:
|
||||
with self._opener.open(request, timeout=self._timeout_seconds) as response:
|
||||
if response.status != 200:
|
||||
fail(f"downloading an asset returned HTTP {response.status}")
|
||||
while chunk := response.read(UPLOAD_CHUNK_BYTES):
|
||||
size += len(chunk)
|
||||
result.update(chunk)
|
||||
except (HTTPError, OSError, URLError) as error:
|
||||
fail(f"downloading an asset for verification failed: {error}")
|
||||
return size, result.hexdigest()
|
||||
|
||||
|
||||
def quote_owner(value: str) -> str:
|
||||
if not SAFE_NAME.fullmatch(value):
|
||||
fail(f"invalid repository name: {value!r}")
|
||||
return quote(value, safe="")
|
||||
|
||||
|
||||
def repository_path(owner: str, repo: str) -> str:
|
||||
return f"repos/{quote_owner(owner)}/{quote_owner(repo)}"
|
||||
|
||||
|
||||
def load_artifacts(directory: Path) -> dict[str, Path]:
|
||||
try:
|
||||
entries = list(directory.iterdir())
|
||||
except OSError as error:
|
||||
fail(f"cannot enumerate artifact directory {directory}: {error}")
|
||||
artifacts: dict[str, Path] = {}
|
||||
for entry in sorted(entries, key=lambda value: value.name):
|
||||
path = validate_regular_file(entry)
|
||||
if path.name in artifacts:
|
||||
fail(f"duplicate artifact filename: {path.name}")
|
||||
artifacts[path.name] = path
|
||||
if not artifacts:
|
||||
fail("the artifact directory is empty")
|
||||
return artifacts
|
||||
|
||||
|
||||
def release_body(arguments: argparse.Namespace) -> str:
|
||||
if arguments.body_file is None:
|
||||
body = arguments.body
|
||||
if "\0" in body or len(body.encode("utf-8")) > 1024 * 1024:
|
||||
fail("the release body is invalid or too large")
|
||||
return body
|
||||
path = validate_regular_file(arguments.body_file)
|
||||
if path.stat().st_size > 1024 * 1024:
|
||||
fail("the release body file is too large")
|
||||
try:
|
||||
body = path.read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError) as error:
|
||||
fail(f"cannot read release body file {path}: {error}")
|
||||
if "\0" in body:
|
||||
fail("the release body contains a NUL byte")
|
||||
return body
|
||||
|
||||
|
||||
def release_assets(release: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
assets = release.get("assets", [])
|
||||
if not isinstance(assets, list) or not all(isinstance(asset, dict) for asset in assets):
|
||||
fail("Gitea returned an invalid release asset list")
|
||||
return assets
|
||||
|
||||
|
||||
def verify_assets(
|
||||
api: GiteaApi,
|
||||
release: dict[str, Any],
|
||||
artifacts: dict[str, Path],
|
||||
) -> None:
|
||||
remote: dict[str, dict[str, Any]] = {}
|
||||
for asset in release_assets(release):
|
||||
name = asset.get("name")
|
||||
if not isinstance(name, str) or not name or name in remote:
|
||||
fail("Gitea returned missing or duplicate release asset names")
|
||||
remote[name] = asset
|
||||
if set(remote) != set(artifacts):
|
||||
missing = sorted(set(artifacts) - set(remote))
|
||||
extra = sorted(set(remote) - set(artifacts))
|
||||
fail(f"release asset set mismatch (missing={missing}, extra={extra})")
|
||||
for name, path in artifacts.items():
|
||||
asset = remote[name]
|
||||
download_url = asset.get("browser_download_url")
|
||||
if not isinstance(download_url, str) or not download_url:
|
||||
fail(f"Gitea returned no download URL for {name}")
|
||||
expected_size = path.stat().st_size
|
||||
if asset.get("size") != expected_size:
|
||||
fail(f"Gitea metadata size mismatch for {name}")
|
||||
actual_size, actual_hash = api.remote_sha256(download_url)
|
||||
if actual_size != expected_size or actual_hash != sha256(path):
|
||||
fail(f"download verification failed for {name}")
|
||||
|
||||
|
||||
def verify_release_metadata(
|
||||
release: dict[str, Any],
|
||||
*,
|
||||
tag: str,
|
||||
name: str,
|
||||
body: str,
|
||||
prerelease: bool,
|
||||
) -> None:
|
||||
expected = {
|
||||
"tag_name": tag,
|
||||
"name": name,
|
||||
"body": body,
|
||||
"prerelease": prerelease,
|
||||
}
|
||||
mismatched = [field for field, value in expected.items() if release.get(field) != value]
|
||||
if mismatched:
|
||||
fail(f"release metadata mismatch: {', '.join(mismatched)}")
|
||||
|
||||
|
||||
def verify_tag_target(
|
||||
api: GiteaApi, base: str, tag: str, expected_commit: str
|
||||
) -> None:
|
||||
_, document = api.request_json(
|
||||
"GET", f"{base}/tags/{quote(tag, safe='')}", allowed_statuses=(200,)
|
||||
)
|
||||
if (
|
||||
not isinstance(document, dict)
|
||||
or not isinstance(document.get("commit"), dict)
|
||||
or document["commit"].get("sha") != expected_commit
|
||||
):
|
||||
fail("the release tag does not target the requested commit")
|
||||
|
||||
|
||||
def publish(arguments: argparse.Namespace, api: GiteaApi) -> None:
|
||||
owner = arguments.owner
|
||||
repo = arguments.repo
|
||||
api.bind_repository(owner, repo)
|
||||
base = repository_path(owner, repo)
|
||||
artifacts = load_artifacts(arguments.artifacts)
|
||||
body = release_body(arguments)
|
||||
tag = arguments.tag
|
||||
if not SAFE_NAME.fullmatch(tag):
|
||||
fail("the release tag is invalid")
|
||||
if not re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", arguments.target):
|
||||
fail("the release target must be a full commit object id")
|
||||
if (
|
||||
not arguments.name
|
||||
or len(arguments.name) > 255
|
||||
or any(character in arguments.name for character in "\r\n\0")
|
||||
):
|
||||
fail("the release name is invalid")
|
||||
tag_path = quote(tag, safe="")
|
||||
status, release = api.request_json(
|
||||
"GET",
|
||||
f"{base}/releases/tags/{tag_path}",
|
||||
allowed_statuses=(200, 404),
|
||||
)
|
||||
if status == 404:
|
||||
_, release = api.request_json(
|
||||
"POST",
|
||||
f"{base}/releases",
|
||||
{
|
||||
"tag_name": tag,
|
||||
"target_commitish": arguments.target,
|
||||
"name": arguments.name,
|
||||
"body": body,
|
||||
"draft": True,
|
||||
"prerelease": arguments.prerelease,
|
||||
},
|
||||
allowed_statuses=(201,),
|
||||
)
|
||||
if not isinstance(release, dict) or not isinstance(release.get("id"), int):
|
||||
fail("Gitea returned an invalid release")
|
||||
if release.get("tag_name") != tag:
|
||||
fail("Gitea returned a release for the wrong tag")
|
||||
verify_tag_target(api, base, tag, arguments.target)
|
||||
release_id = release["id"]
|
||||
if not release.get("draft", False):
|
||||
verify_release_metadata(
|
||||
release,
|
||||
tag=tag,
|
||||
name=arguments.name,
|
||||
body=body,
|
||||
prerelease=arguments.prerelease,
|
||||
)
|
||||
verify_assets(api, release, artifacts)
|
||||
print(f"release {tag} is already published and verified")
|
||||
return
|
||||
|
||||
api.request_json(
|
||||
"PATCH",
|
||||
f"{base}/releases/{release_id}",
|
||||
{
|
||||
"name": arguments.name,
|
||||
"body": body,
|
||||
"draft": True,
|
||||
"prerelease": arguments.prerelease,
|
||||
"target_commitish": arguments.target,
|
||||
},
|
||||
allowed_statuses=(200,),
|
||||
)
|
||||
for asset in release_assets(release):
|
||||
asset_id = asset.get("id")
|
||||
if not isinstance(asset_id, int):
|
||||
fail("Gitea returned an invalid release asset id")
|
||||
api.request_json(
|
||||
"DELETE",
|
||||
f"{base}/releases/{release_id}/assets/{asset_id}",
|
||||
allowed_statuses=(204, 404),
|
||||
)
|
||||
for artifact in artifacts.values():
|
||||
api.upload_asset(release_id, artifact)
|
||||
_, release = api.request_json(
|
||||
"GET", f"{base}/releases/{release_id}", allowed_statuses=(200,)
|
||||
)
|
||||
if not isinstance(release, dict):
|
||||
fail("Gitea returned an invalid release after upload")
|
||||
verify_release_metadata(
|
||||
release,
|
||||
tag=tag,
|
||||
name=arguments.name,
|
||||
body=body,
|
||||
prerelease=arguments.prerelease,
|
||||
)
|
||||
verify_assets(api, release, artifacts)
|
||||
_, release = api.request_json(
|
||||
"PATCH",
|
||||
f"{base}/releases/{release_id}",
|
||||
{
|
||||
"name": arguments.name,
|
||||
"body": body,
|
||||
"draft": False,
|
||||
"prerelease": arguments.prerelease,
|
||||
"target_commitish": arguments.target,
|
||||
},
|
||||
allowed_statuses=(200,),
|
||||
)
|
||||
if not isinstance(release, dict) or release.get("draft", True):
|
||||
fail("Gitea did not publish the verified draft")
|
||||
verify_release_metadata(
|
||||
release,
|
||||
tag=tag,
|
||||
name=arguments.name,
|
||||
body=body,
|
||||
prerelease=arguments.prerelease,
|
||||
)
|
||||
verify_tag_target(api, base, tag, arguments.target)
|
||||
print(f"published and verified release {tag} with {len(artifacts)} assets")
|
||||
|
||||
|
||||
def prune_nightlies(arguments: argparse.Namespace, api: GiteaApi) -> None:
|
||||
base = repository_path(arguments.owner, arguments.repo)
|
||||
releases: list[dict[str, Any]] = []
|
||||
page = 1
|
||||
while True:
|
||||
query = urlencode({"limit": 50, "page": page})
|
||||
_, batch = api.request_json(
|
||||
"GET", f"{base}/releases?{query}", allowed_statuses=(200,)
|
||||
)
|
||||
if not isinstance(batch, list) or not all(
|
||||
isinstance(release, dict) for release in batch
|
||||
):
|
||||
fail("Gitea returned an invalid release page")
|
||||
releases.extend(batch)
|
||||
if len(batch) < 50:
|
||||
break
|
||||
page += 1
|
||||
if page > 1000:
|
||||
fail("Gitea release pagination exceeded the safety limit")
|
||||
nightlies = [
|
||||
release
|
||||
for release in releases
|
||||
if release.get("prerelease") is True
|
||||
and isinstance(release.get("tag_name"), str)
|
||||
and release["tag_name"].startswith(arguments.tag_prefix)
|
||||
]
|
||||
nightlies.sort(
|
||||
key=lambda release: (
|
||||
str(release.get("published_at") or release.get("created_at") or ""),
|
||||
int(release.get("id", -1)),
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
release_ids: set[int] = set()
|
||||
for release in nightlies:
|
||||
release_id = release.get("id")
|
||||
if not isinstance(release_id, int) or release_id in release_ids:
|
||||
fail("Gitea returned a missing or duplicate nightly release id")
|
||||
release_ids.add(release_id)
|
||||
protected = [
|
||||
release
|
||||
for release in nightlies
|
||||
if release["tag_name"] == arguments.protect_tag
|
||||
]
|
||||
if len(protected) > 1:
|
||||
fail("Gitea returned duplicate releases for the protected nightly tag")
|
||||
ordered_to_keep = [
|
||||
*protected,
|
||||
*[
|
||||
release
|
||||
for release in nightlies
|
||||
if not protected or release["id"] != protected[0]["id"]
|
||||
],
|
||||
]
|
||||
retained_ids = {
|
||||
release["id"] for release in ordered_to_keep[: arguments.keep]
|
||||
}
|
||||
deleted = 0
|
||||
for release in nightlies:
|
||||
tag = release["tag_name"]
|
||||
release_id = release["id"]
|
||||
if release_id in retained_ids:
|
||||
continue
|
||||
api.request_json(
|
||||
"DELETE",
|
||||
f"{base}/tags/{quote(tag, safe='')}",
|
||||
allowed_statuses=(204, 404),
|
||||
)
|
||||
api.request_json(
|
||||
"DELETE",
|
||||
f"{base}/releases/{release_id}",
|
||||
allowed_statuses=(204, 404),
|
||||
)
|
||||
deleted += 1
|
||||
print(f"kept {len(retained_ids)} nightly releases and deleted {deleted}")
|
||||
|
||||
|
||||
def verify_tag_protection(arguments: argparse.Namespace, api: GiteaApi) -> None:
|
||||
base = repository_path(arguments.owner, arguments.repo)
|
||||
_, protections = api.request_json(
|
||||
"GET", f"{base}/tag_protections", allowed_statuses=(200,)
|
||||
)
|
||||
if not isinstance(protections, list) or not all(
|
||||
isinstance(protection, dict) for protection in protections
|
||||
):
|
||||
fail("Gitea returned an invalid tag-protection list")
|
||||
matches = [
|
||||
protection
|
||||
for protection in protections
|
||||
if protection.get("name_pattern") == arguments.required_pattern
|
||||
]
|
||||
if not matches:
|
||||
fail(f"required protected tag pattern is missing: {arguments.required_pattern}")
|
||||
if len(matches) != 1:
|
||||
fail(
|
||||
"required protected tag pattern is ambiguous: "
|
||||
f"{arguments.required_pattern}"
|
||||
)
|
||||
protection = matches[0]
|
||||
users = protection.get("whitelist_usernames")
|
||||
teams = protection.get("whitelist_teams")
|
||||
if (
|
||||
not isinstance(users, list)
|
||||
or not all(isinstance(value, str) and value for value in users)
|
||||
or not isinstance(teams, list)
|
||||
or not all(isinstance(value, str) and value for value in teams)
|
||||
):
|
||||
fail("Gitea returned an invalid protected-tag allowlist")
|
||||
if not users and not teams:
|
||||
fail("the required protected tag pattern has an empty allowlist")
|
||||
print(
|
||||
f"verified protected tag pattern {arguments.required_pattern} "
|
||||
f"(users={len(users)}, teams={len(teams)})"
|
||||
)
|
||||
|
||||
|
||||
def parser() -> argparse.ArgumentParser:
|
||||
result = argparse.ArgumentParser(description=__doc__)
|
||||
result.add_argument("--api-url", required=True)
|
||||
result.add_argument("--token-env", default="GITEA_RELEASE_TOKEN")
|
||||
result.add_argument("--allow-http", action="store_true", help=argparse.SUPPRESS)
|
||||
subparsers = result.add_subparsers(dest="command", required=True)
|
||||
|
||||
publish_parser = subparsers.add_parser("publish")
|
||||
publish_parser.add_argument("--owner", required=True)
|
||||
publish_parser.add_argument("--repo", required=True)
|
||||
publish_parser.add_argument("--tag", required=True)
|
||||
publish_parser.add_argument("--target", required=True)
|
||||
publish_parser.add_argument("--name", required=True)
|
||||
body_group = publish_parser.add_mutually_exclusive_group()
|
||||
body_group.add_argument("--body", default="")
|
||||
body_group.add_argument("--body-file", type=Path)
|
||||
publish_parser.add_argument("--artifacts", type=Path, required=True)
|
||||
publish_parser.add_argument("--prerelease", action="store_true")
|
||||
|
||||
prune_parser = subparsers.add_parser("prune-nightlies")
|
||||
prune_parser.add_argument("--owner", required=True)
|
||||
prune_parser.add_argument("--repo", required=True)
|
||||
prune_parser.add_argument("--tag-prefix", default="nightly-")
|
||||
prune_parser.add_argument("--keep", type=int, default=14)
|
||||
prune_parser.add_argument("--protect-tag", default="")
|
||||
|
||||
protection_parser = subparsers.add_parser("verify-tag-protection")
|
||||
protection_parser.add_argument("--owner", required=True)
|
||||
protection_parser.add_argument("--repo", required=True)
|
||||
protection_parser.add_argument("--required-pattern", default="v*")
|
||||
return result
|
||||
|
||||
|
||||
def main() -> None:
|
||||
arguments = parser().parse_args()
|
||||
if arguments.command == "prune-nightlies" and arguments.keep < 1:
|
||||
fail("--keep must be positive")
|
||||
if arguments.command == "prune-nightlies":
|
||||
if not SAFE_NAME.fullmatch(arguments.tag_prefix):
|
||||
fail("--tag-prefix must be a non-empty safe tag prefix")
|
||||
if (
|
||||
arguments.protect_tag
|
||||
and not arguments.protect_tag.startswith(arguments.tag_prefix)
|
||||
):
|
||||
fail("--protect-tag must start with --tag-prefix")
|
||||
token = os.environ.get(arguments.token_env, "")
|
||||
api = GiteaApi(arguments.api_url, token, allow_http=arguments.allow_http)
|
||||
if arguments.command == "publish":
|
||||
publish(arguments, api)
|
||||
elif arguments.command == "prune-nightlies":
|
||||
prune_nightlies(arguments, api)
|
||||
else:
|
||||
verify_tag_protection(arguments, api)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(130)
|
||||
Reference in new issue
Block a user