Coverage for src/rhiza_task/tasks/paper.py: 100%
61 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-11-30 09:28 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-11-30 09:28 +0000
1"""The LaTeX tasks: paper.mk, as tasks.
3Closer in shape to ``book`` than to the CLI wrappers: a build with an output worth
4naming. The engine does the hard part -- it reruns the TeX pass and bibtex until the
5citations and cross-references converge -- so the task is a folder, a file choice and a
6fixed flag set.
8**The engine is tectonic**, which is the one substantive change from paper.mk. paper.mk
9drove a full TeX distribution, so a consumer provisioned the distribution *and* the list
10of packages their document happened to cite, and the two workflows here each carried their
11own copy of that list. tectonic is a single binary that resolves what a document cites out
12of its web bundle and caches it, so there is one tool to install and no list to keep in
13step. Three consequences the flag set below records rather than restates:
15* Convergence and bibtex are the engine's own loop, not a driver's, so neither is asked
16 for -- the argument vector is the document and nothing about *how* to build it.
17* There is no interaction mode to pin. tectonic never stops for a prompt, so it needs no
18 flag saying so; a broken document exits non-zero, which :func:`~rhiza_task.uv.tool`
19 turns into :class:`~rhiza_task.spec.Failed`.
20* A cold cache needs the network. A provisioned distribution did not, and that is the one
21 thing this trade costs; the cache is per-machine and survives between runs, so it is a
22 first-run cost rather than a per-build one.
24The file choice is the other thing that changed, and it changed earlier. paper.mk reads
26 if [ -f $(PAPER_DIR)/basanos.tex ]; then tex_file="basanos.tex"; else <first *.tex>; fi
28-- a named preference for one downstream repository's paper, in a template every consumer
29syncs. :func:`main_document` replaces it with two conventional names and then alphabetical
30order, so the behaviour is the same for a folder with one ``.tex`` (the overwhelmingly
31common case) and no longer privileges a stranger's filename.
33``-maxdepth 1`` survives as :meth:`~pathlib.Path.glob` rather than
34:meth:`~pathlib.Path.rglob`, and deliberately: a LaTeX project's subdirectories hold
35included chapters, and the engine must be pointed at the root document, not at a chapter.
37**``joss`` is a second task rather than a second branch of ``paper``** (#147). A Journal of
38Open Source Software manuscript is Markdown plus BibTeX, typeset by the journal's own
39pipeline, and teaching ``paper`` to recognise it would have made one task name answer for
40two engines whose outputs are not comparable. So ``paper`` is unchanged, and ``joss`` runs
41the journal's pipeline as the journal does: the `inara <https://github.com/openjournals/inara>`_
42image, which is what JOSS's draft action runs, over ``paper.md`` in the same
43``paper_folder``. :data:`JOSS_IMAGE` says why it is pinned.
44"""
46from __future__ import annotations
48import os
49from pathlib import Path
51from ..config import Config
52from ..spec import Guard, Skip, task
53from ..uv import tool
54from .docker import HAVE_DOCKER
56SECTION = "Paper"
58HAVE_TECTONIC = Guard(
59 tool="tectonic",
60 reason="tectonic not found; see https://tectonic-typesetting.github.io/en-US/install.html",
61)
63PREFERRED = ("main.tex", "paper.tex")
64"""Root-document names tried before falling back to alphabetical order."""
66AUX_SUFFIXES = (".aux", ".bbl", ".blg", ".log", ".out", ".synctex.gz", ".toc")
67"""What a TeX run leaves beside the document, mirroring .gitignore's list for this folder.
69The PDF is deliberately absent: this is the set that is *never* worth keeping, and both
70callers want it -- :func:`paper_clean` adds the PDF because removing the output is the
71point of a clean, and ``book``'s prune keeps the PDF because publishing it is the point of
72the build.
74These are the names TeX itself writes. A driver's own bookkeeping files -- the
75rebuild-cache and file-list a make-style LaTeX driver keeps -- are not listed, because no
76driver runs here: tectonic is the whole engine and writes the ``.log`` (asked for below)
77and, only when asked, the rest.
79Matched as name suffixes rather than through :attr:`~pathlib.PurePath.suffix`, because
80``.synctex.gz`` is two extensions and ``suffix`` would report only ``.gz``.
81"""
83JOSS_DOCUMENT = "paper.md"
84"""The manuscript ``joss`` compiles: the name JOSS's submission guidelines and its draft action
85both default to, and the only one inara reads without being told otherwise."""
87JOSS_IMAGE = "openjournals/inara:1.3.1"
88"""The journal's typesetting image, pinned to a release tag.
90JOSS's own draft action runs ``:latest``, so a pin can lag what the journal renders. The pin
91wins anyway, for the reason the whole package exists: an unpinned image changes the PDF
92under a green pull request with no commit touching the repository, and a typesetting
93pipeline's output moves between releases. Nothing automated moves a Python string, so this
94is one of the hand-reviewed pins ``.github/dependabot.yml`` lists at its foot -- bump it
95deliberately, and look at the PDF when you do.
96"""
99def has_joss_paper(cfg: Config) -> bool:
100 """Return whether the repository has a JOSS manuscript, for ``list``.
102 Narrower than :func:`has_paper` on purpose: a LaTeX-only paper folder should not list a
103 task that would only ever skip.
105 Args:
106 cfg: The resolved config.
108 Returns:
109 True when ``<paper_folder>/paper.md`` exists.
110 """
111 return (cfg.root / cfg.paper_folder / JOSS_DOCUMENT).is_file()
114def user_flags() -> list[str]:
115 """Return the ``--user`` flag that makes the container write files the caller owns.
117 inara runs as root by default, so on Linux the PDF it writes into the mounted folder
118 would be root-owned and undeletable by ``paper-clean`` or the next build -- which is why
119 inara's own instructions pass ``-u $(id -u):$(id -g)``. Windows has no uid to pass, and
120 Docker Desktop maps ownership on the way out regardless, so there the flag is omitted
121 rather than invented.
123 Returns:
124 ``["--user", "<uid>:<gid>"]`` where the platform has them, else an empty list.
125 """
126 if not hasattr(os, "getuid"):
127 return []
128 return ["--user", f"{os.getuid()}:{os.getgid()}"]
131def main_document(folder: Path) -> Path | None:
132 """Choose the root ``.tex`` file in a folder.
134 Args:
135 folder: The paper folder.
137 Returns:
138 The document to compile, or None when the folder holds no top-level ``.tex``.
139 """
140 candidates = sorted(p for p in folder.glob("*.tex") if p.is_file())
141 if not candidates:
142 return None
143 by_name = {p.name: p for p in candidates}
144 return next((by_name[name] for name in PREFERRED if name in by_name), candidates[0])
147def has_paper(cfg: Config) -> bool:
148 """Return whether the repository has a paper, for ``list``.
150 Args:
151 cfg: The resolved config.
153 Returns:
154 True when ``paper_folder`` exists -- the folder both tasks skip without.
155 """
156 return (cfg.root / cfg.paper_folder).is_dir()
159@task(
160 "paper",
161 "compile the LaTeX paper to PDF",
162 section=SECTION,
163 guards=(HAVE_TECTONIC, Guard("paper_folder")),
164 applies=has_paper,
165)
166def paper(cfg: Config) -> None:
167 """Run tectonic over the paper folder's root document.
169 Args:
170 cfg: The resolved config.
172 Raises:
173 Skip: When the folder holds no top-level ``.tex`` file.
174 """
175 folder = cfg.path("paper_folder")
176 document = main_document(folder)
177 if document is None:
178 raise Skip(f"no .tex files in '{cfg.paper_folder}'")
180 print(f"[INFO] compiling {document.name}")
181 # cwd is the paper folder, as `cd $(PAPER_DIR) && <engine>` was: tectonic resolves
182 # \input paths relative to the document and writes its output beside it, which is what
183 # lets `book` publish the PDF with no copy step.
184 #
185 # `--keep-logs` is the one flag, and it is not cosmetic: tectonic writes only the PDF by
186 # default, and on a runner the log is the artefact you upload when a compile fails. It
187 # is also the file `book`'s prune exists to keep out of the published site, since it
188 # records absolute paths from whichever machine built it.
189 tool("tectonic", "--keep-logs", document.name, cwd=folder)
190 print(f"[SUCCESS] {cfg.paper_folder}/{document.stem}.pdf")
193@task(
194 "joss",
195 "compile the JOSS Markdown paper to a draft PDF",
196 section=SECTION,
197 guards=(HAVE_DOCKER, Guard("paper_folder")),
198 applies=has_joss_paper,
199)
200def joss(cfg: Config) -> None:
201 """Run the journal's inara image over ``<paper_folder>/paper.md``.
203 The output is a **draft** -- watermarked and line-numbered, which is inara's default
204 and what JOSS's draft action produces. The production PDF is the journal's to build
205 at acceptance, so there is no flag here for it.
207 Args:
208 cfg: The resolved config.
210 Raises:
211 Skip: When the folder holds no ``paper.md``.
212 """
213 folder = cfg.path("paper_folder")
214 if not (folder / JOSS_DOCUMENT).is_file():
215 raise Skip(f"no {JOSS_DOCUMENT} in '{cfg.paper_folder}'")
217 print(f"[INFO] compiling {JOSS_DOCUMENT} with {JOSS_IMAGE}")
218 # The folder is mounted on /data, inara's working directory, so the manuscript is named
219 # relative to it and `paper.bib`, figures and the PDF all sit beside it -- the same
220 # "output lands next to the source" rule `paper` follows. `JOURNAL=joss` is the image's
221 # default too; it is passed anyway, as the draft action passes it, so the vector says
222 # which journal's template it renders rather than relying on an ENV line upstream.
223 # `-o pdf` because the default also writes JATS XML, which is the journal's artefact
224 # rather than the author's.
225 tool(
226 "docker",
227 "run",
228 "--rm",
229 "--volume",
230 f"{folder}:/data",
231 *user_flags(),
232 "--env",
233 "JOURNAL=joss",
234 JOSS_IMAGE,
235 "-o",
236 "pdf",
237 JOSS_DOCUMENT,
238 cwd=folder,
239 )
240 print(f"[SUCCESS] {cfg.paper_folder}/{Path(JOSS_DOCUMENT).stem}.pdf")
243@task("paper-clean", "remove the LaTeX build artifacts", section=SECTION, applies=has_paper)
244def paper_clean(cfg: Config) -> None:
245 """Remove the PDF and auxiliary files belonging to the folder's top-level documents.
247 Pure Python, and unguarded on any tool: tectonic has no clean subcommand to delegate
248 to, so there is nothing to be absent. That makes this the one task in the section that
249 works on a machine which cannot build the paper at all -- an improvement over
250 delegating, where cleaning required the very toolchain you were cleaning up after.
252 **Scoped by document stem, not by extension sweep.** ``paper.tex`` authorises deleting
253 ``paper.pdf`` and ``paper.log``; a ``figures/`` diagram exported to ``diagram.pdf`` and
254 committed beside the source has no ``diagram.tex`` and survives. An extension sweep
255 would be one line shorter and would delete a consumer's checked-in artwork, which is
256 not recoverable by rebuilding.
258 Args:
259 cfg: The resolved config.
261 Raises:
262 Skip: When there is no paper folder to clean.
263 """
264 folder = cfg.path("paper_folder")
265 if not folder.is_dir():
266 raise Skip(f"paper_folder '{cfg.paper_folder}' not found")
268 removed = 0
269 for stem in sorted({p.stem for p in folder.glob("*.tex") if p.is_file()}):
270 for suffix in (*AUX_SUFFIXES, ".pdf"):
271 artifact = folder / f"{stem}{suffix}"
272 if artifact.is_file():
273 artifact.unlink()
274 removed += 1
275 # Cleaning a folder that was never built leaves nothing to report and is not a failure,
276 # which is what paper.mk's `|| true` bought; here it falls out of there being no tool
277 # to fail.
278 print(f"[SUCCESS] cleaned {cfg.paper_folder} ({removed} file(s))")