Files
claude-config/bin/forge/commands.py
T

43 lines
1.7 KiB
Python

"""Which forge a checkout's origin is on, and running that forge's CLI in the checkout."""
import json
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 runner(cwd: str) -> Run:
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)
except OSError as failure:
return Failure(f"{command[0]} could not start: {failure}")
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