Files
claude-config/bin/adf_codec/convert.py
T
2026-11-14 16:27:40 +01:00

115 lines
4.3 KiB
Python

"""Converts markdown to ADF (Atlassian Document Format, the rich text of Jira Cloud and Confluence) and back.
It runs @larvit/adf-codec's portable calls in a throwaway container, since adf-codec is a Node package:
`portableMarkdownToAdf` to write ADF and `adfToPortableMarkdown` to read it. The container holds node_shim/shim.mjs,
whose exit status says what happened: 0 answered, 2 adf-codec refused the input (its error code is in the Failure), 1 the shim itself failed.
"""
import dataclasses
import hashlib
import json
import pathlib
import subprocess
import typing
from failure import Failure
SHIM = pathlib.Path(__file__).resolve().parent / "node_shim"
SHIM_FILES = ("Dockerfile", "package.json", "package-lock.json", "shim.mjs")
# Both limits are equal, so the container can't swap: a document too big for it ends in a Failure, not in a slow machine.
MEMORY = "256m"
RUN_SECONDS = 60
BUILD_SECONDS = 300
REFUSED = 2
@dataclasses.dataclass(frozen=True)
class Ran:
status: int
out: str
err: str
# Runs the shim in the given mode (`to-adf` or `to-markdown`) on a text, or fails to start it.
Run = typing.Callable[[str, str], Ran | Failure]
def image_tag(shim: pathlib.Path) -> str:
"""A tag that changes with every file the image is built from, so an edited shim or a bumped adf-codec rebuilds it."""
digest = hashlib.sha256()
for name in SHIM_FILES:
digest.update((shim / name).read_bytes())
return f"claude-config-adf-codec:{digest.hexdigest()[:12]}"
def docker_args(image: str, mode: str) -> list[str]:
return ["docker", "run", "--rm", "-i", "--memory", MEMORY, "--memory-swap", MEMORY, "--network", "none", "--read-only", image, mode]
def docker(args: list[str], text: str, seconds: int) -> Ran | Failure:
try:
done = subprocess.run(args, input=text, capture_output=True, text=True, encoding="utf-8", timeout=seconds)
except FileNotFoundError:
return Failure("docker is not installed, and the adf-codec shim runs in a container")
except subprocess.TimeoutExpired:
return Failure(f"`{' '.join(args[:2])}` took more than {seconds} seconds")
return Ran(done.returncode, done.stdout, done.stderr)
def ensure_image(shim: pathlib.Path) -> str | Failure:
"""The tag of the shim's image, built from node_shim/ first where this machine has no image under that tag."""
tag = image_tag(shim)
found = docker(["docker", "image", "inspect", tag], "", RUN_SECONDS)
if isinstance(found, Failure) or found.status == 0:
return found if isinstance(found, Failure) else tag
built = docker(["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(shim)], "", BUILD_SECONDS)
if isinstance(built, Failure):
return built
if built.status != 0:
return Failure(f"building the adf-codec shim's image failed with exit {built.status}: {built.err.strip()}")
return tag
def container_run(mode: str, text: str) -> Ran | Failure:
image = ensure_image(SHIM)
if isinstance(image, Failure):
return image
return docker(docker_args(image, mode), text, RUN_SECONDS)
def answer(mode: str, text: str, run: Run) -> str | Failure:
"""What the shim printed for text, or a Failure saying why it printed none."""
ran = run(mode, text)
if isinstance(ran, Failure):
return ran
if ran.status == 0:
return ran.out
if ran.status == REFUSED:
return refusal(ran.out)
return Failure(f"the adf-codec shim failed with exit {ran.status}: {ran.err.strip()}")
def refusal(out: str) -> Failure:
try:
error = json.loads(out)["error"]
where = f"line {error['position']['line']}" if "position" in error else ".".join(str(step) for step in error["path"]) or "the document"
return Failure(f"adf-codec refused the input with {error['code']}: {error['message']} (at {where})")
except (ValueError, KeyError, TypeError):
return Failure(f"the adf-codec shim refused with output that is not an error: {out.strip()}")
def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
"""The ADF document markdown reads as."""
out = answer("to-adf", markdown, run)
if isinstance(out, Failure):
return out
try:
document = json.loads(out)
except ValueError:
return Failure(f"the adf-codec shim printed output that is not JSON: {out.strip()}")
return document
def adf_to_markdown(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
"""The markdown an ADF document reads as."""
return answer("to-markdown", json.dumps(document), run)