diplodocus 0.15.0

Build coherent documentation websites for polyglot software projects.
Documentation
#!/usr/bin/env python3
"""Check the native helper against caller-prepared roxygen2 library profiles.

Run with ``compute run -- python scripts/test-roxygen-compat.py`` for the
current environment, or repeat ``--profile VERSION=LIBRARY`` for isolated R
libraries. This script does not install packages or change producer checkouts.
"""

from __future__ import annotations

import argparse
import json
import os
from pathlib import Path
import subprocess
import tempfile


def run_profile(expected: str | None, library: str | None) -> None:
    environment = os.environ.copy()
    if library is not None:
        environment["R_LIBS_USER"] = str(Path(library).resolve())
    version = subprocess.run(
        ["R", "--vanilla", "--slave", "-e", 'cat(as.character(packageVersion("roxygen2")))'],
        check=True,
        capture_output=True,
        text=True,
        env=environment,
    ).stdout.strip()
    if expected is not None and version != expected:
        raise AssertionError(f"Expected roxygen2 {expected}, found {version}")
    repository = Path(__file__).resolve().parents[1]
    source = "\n".join(
        (repository / "src/assembly" / name).read_text()
        for name in ("r_runtime.R", "r_environment.R", "r_native.R")
    )
    for loader in ("pkgload", "source"):
        with tempfile.TemporaryDirectory(prefix="diplodocus-roxygen-compat-") as directory:
            staging = Path(directory)
            package = staging / "package"
            (package / "R").mkdir(parents=True)
            (package / "man").mkdir()
            (package / "DESCRIPTION").write_text(
                "Package: nativefixture\nVersion: 1.0-1\nTitle: Native fixture\n"
                "Description: Native compatibility fixture.\nLicense: MIT\nEncoding: UTF-8\n"
                f"Roxygen: list(markdown = TRUE, load = '{loader}')\nRoxygenNote: {version}\n"
            )
            (package / "NAMESPACE").write_text(
                "# Generated by roxygen2: do not edit by hand\nexport(add)\n"
            )
            api = package / "R/api.R"
            api.write_text(
                "#' Add values\n#' @param x A number.\n#' @param y Another number.\n"
                "#' @export\n#' @examples\n#' writeLines('ran', 'example-ran')\n"
                "add <- function(x, y = NULL) x + y\n"
                "alias <- add\n"
                "UseMethod <- function(...) NULL\n"
                "ordinary <- function(x) UseMethod('ordinary')\n"
                "nested <- function(x) { f <- function(x) base::UseMethod('nested'); x }\n"
                "qualified <- function(x) base::UseMethod('qualified')\n"
            )
            helper = staging / "native.R"
            helper.write_text(source)
            output = staging / "native.json"
            command = [
                "R", "--vanilla", "--slave", "-f", str(helper), "--args",
                str(package), str(output), "nativefixture", "1.0-1", "roxygen2",
            ]
            completed = subprocess.run(
                command, cwd=package, env=environment, text=True, capture_output=True
            )
            if completed.returncode != 0:
                raise AssertionError(f"{version}/{loader}: {completed.stderr}")
            record = json.loads(output.read_text())
            assert record["complete"] == "r-native-v1"
            assert record["generation"]["loader"] == loader
            assert record["generation"]["roxygen2_version"] == version
            assert "add" in record["observation"]["exports"]
            bindings = {binding["name"]: binding for binding in record["observation"]["bindings"]}
            assert bindings["add"]["formals"] == [
                {"name": "x", "required": True, "default": None},
                {"name": "y", "required": False, "default": "NULL"},
            ]
            assert bindings["ordinary"]["generic"] is None
            assert bindings["nested"]["generic"] is None
            assert bindings["qualified"]["generic"] == "qualified"
            assert "alias" in bindings["add"]["same_as"]
            assert "add" in bindings["alias"]["same_as"]
            assert not (package / "example-ran").exists()
            assert "Add values" in (package / "man/add.Rd").read_text()
            assert record["observation"]["package_version"] == "1.0-1"
            api.write_text(
                "#' Multiply values\n#' @param x A number.\n#' @export\n"
                "multiply <- function(x) 2 * x\n"
            )
            renamed = subprocess.run(
                command, cwd=package, env=environment, text=True, capture_output=True
            )
            if renamed.returncode != 0:
                raise AssertionError(f"{version}/{loader} removed export: {renamed.stderr}")
            assert json.loads(output.read_text())["observation"]["exports"] == ["multiply"]
            assert not (package / "man/add.Rd").exists()
            output.unlink()
            api.write_text("#' Add values\n#' @param\n#' @export\nadd <- function(x) x\n")
            rejected = subprocess.run(
                command, cwd=package, env=environment, text=True, capture_output=True
            )
            assert rejected.returncode != 0, f"{version}/{loader}: malformed tag succeeded"
            assert not output.exists(), "A failed generation retained completion evidence"
            assert "@param" in rejected.stderr
            api.write_text("add <- function(x) x\n.onLoad <- function(...) warning('checkout hook warning')\n")
            command[-1] = "rd"
            maintained = subprocess.run(
                command, cwd=package, env=environment, text=True, capture_output=True
            )
            if maintained.returncode != 0:
                raise AssertionError(f"{version}/{loader} maintained Rd: {maintained.stderr}")
            warnings = json.loads(output.read_text())["warnings"]
            assert any("checkout hook warning" in warning for warning in warnings)
            output.unlink()
            api.write_text("add <- function(x) x\n.onUnload <- function(...) warning('checkout cleanup warning')\n")
            cleanup = subprocess.run(
                command, cwd=package, env=environment, text=True, capture_output=True
            )
            assert cleanup.returncode != 0 and not output.exists()
            assert "checkout cleanup warning" in cleanup.stderr
            print(f"roxygen2 {version}, {loader}: generation, reflection, export removal, inert examples, diagnostic rejection, native warnings, and cleanup rejection passed")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--profile", action="append", default=[], metavar="VERSION=LIBRARY",
        help="Use a caller-prepared isolated R library and require the given version.",
    )
    arguments = parser.parse_args()
    if not arguments.profile:
        run_profile(None, None)
    for profile in arguments.profile:
        version, separator, library = profile.partition("=")
        if not separator or not version or not library:
            parser.error("Profiles must use VERSION=LIBRARY")
        run_profile(version, library)


if __name__ == "__main__":
    main()