Files

54 lines
2.4 KiB
Python

"""Which forge a checkout's origin is on, a repo's URL beside that origin's, and running the forge's CLI in the checkout."""
import json
import re
import subprocess
import typing
from failure import Failure
# The CLI of the forge that origin is on, as forge_of picks it.
Forge = typing.Literal["gh", "tea"]
# Runs a command in the checkout: what it printed, or a Failure with its reason.
Run = typing.Callable[[list[str]], str | Failure]
def forge_of(origin_url: str) -> Forge:
return "gh" if "github.com" in origin_url else "tea"
def url_beside(origin_url: str, name: str) -> str | None:
"""The origin URL of the repo called name under the same host and owner as origin_url's repo; None where origin_url has no place, such as a bare name. The URL has no `.git`, which git clones without."""
place = re.fullmatch(r"(.+[/:])[^/:]+", origin_url.rstrip("/"))
# An origin of only a scheme and a host, such as `https://host`, has no owner folder to put a name in.
return place.group(1) + name if place and not place.group(1).endswith("//") else None
def runner(cwd: str, timeout: float | None = None) -> Run:
"""Runs a command in cwd, stopped after timeout seconds where one is given."""
def run(command: list[str]) -> str | Failure:
try:
done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=timeout)
except OSError as failure:
return Failure(f"{command[0]} could not start: {failure}")
except subprocess.TimeoutExpired:
return Failure(f"{' '.join(command[:3])}: stopped after {timeout} s")
if done.returncode:
return Failure(f"{' '.join(command[:3])}: {(done.stderr or done.stdout).strip()}")
return done.stdout
return run
def gitea(run: Run, endpoint: str, *fields: str) -> typing.Any | Failure:
"""What Gitea's API answered at endpoint, parsed; with fields, `key=value` strings, a POST of them. tea api exits 0 on an HTTP error too, so an answer with Gitea's `message` key is a Failure."""
answered = run(["tea", "api", *(["--method", "POST"] if fields else []), *[word for field in fields for word in ("--field", field)], endpoint])
if isinstance(answered, Failure) or not answered.strip():
return answered
try:
parsed = json.loads(answered)
except ValueError:
return Failure(f"tea api {endpoint} printed no JSON: {answered.strip()[:200]}")
if isinstance(parsed, dict) and "message" in parsed:
return Failure(f"tea api {endpoint}: {parsed['message']}")
return parsed