#!/usr/bin/env python3 """Make one Gitea issue depend on another issue.""" from __future__ import annotations import argparse import json import urllib.error import urllib.parse import urllib.request from pathlib import Path from typing import Any from gitea_common import DEFAULT_ENV_FILE, config def api_url(base_url: str, owner: str, repo: str, suffix: str) -> str: encoded_owner = urllib.parse.quote(owner, safe="") encoded_repo = urllib.parse.quote(repo, safe="") return f"{base_url.rstrip('/')}/api/v1/repos/{encoded_owner}/{encoded_repo}/{suffix.lstrip('/')}" def request_json(method: str, url: str, token: str, payload: dict[str, Any]) -> Any: request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), method=method) request.add_header("Authorization", f"token {token}") request.add_header("Accept", "application/json") request.add_header("Content-Type", "application/json") try: with urllib.request.urlopen(request, timeout=30) as response: body = response.read().decode("utf-8") except urllib.error.HTTPError as exc: error_body = exc.read().decode("utf-8", errors="replace") raise SystemExit(f"Gitea API request failed: HTTP {exc.code}\n{error_body}") from exc except urllib.error.URLError as exc: raise SystemExit(f"Gitea API request failed: {exc.reason}") from exc return json.loads(body) if body else None def main() -> int: parser = argparse.ArgumentParser(description="Make a Gitea issue depend on another issue.") parser.add_argument("--parent", type=int, required=True, help="Issue number that is blocked.") parser.add_argument("--child", type=int, required=True, help="Issue number the parent depends on.") parser.add_argument("--child-owner", help="Owner of the child issue repo. Defaults to GITEA_OWNER.") parser.add_argument("--child-repo", help="Repo of the child issue. Defaults to GITEA_REPO.") parser.add_argument("--env-file", type=Path, default=DEFAULT_ENV_FILE) args = parser.parse_args() cfg = config(args.env_file.expanduser()) child_owner = args.child_owner or cfg["GITEA_OWNER"] child_repo = args.child_repo or cfg["GITEA_REPO"] issue = request_json( "POST", api_url( cfg["GITEA_BASE_URL"], cfg["GITEA_OWNER"], cfg["GITEA_REPO"], f"issues/{args.parent}/dependencies", ), cfg["GITEA_TOKEN"], {"owner": child_owner, "repo": child_repo, "index": args.child}, ) print(issue.get("html_url") or issue.get("url") or json.dumps(issue, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())