_common.py

clew/_common.py

Shared helpers for the clew package.

captured_output

Iterator[io.StringIO] clew._common.captured_output()

Send every pipeline writer into a buffer instead of the process stdout.

clew/_common.py:210

Source · 33 lines
def captured_output() -> Iterator[io.StringIO]:
    """The seam a caller uses when its `sys.stdout` is a protocol transport: the
    progress bars, the doxygen warning lines, the build summary and the pipeline's
    own log records all land in the yielded buffer, and stdout is untouched for
    anyone else.

    The LOG half is here because the log is where the pipeline explains itself —
    which Doxyfile it resolved, which scope tier it fell back to, what it refused.
    Capturing the rendered output alone would hand a caller a table of row counts
    and drop the sentence saying why the counts are what they are.

    The buffer stays readable after the block ends, so the partial output of a run
    that raised is still available to report.

    @brief Capture pipeline output and logging for the duration of a call.
    @return The buffer receiving everything the pipeline emits.
    @version 2
    """
    buffer = io.StringIO()
    handler = _OwnThreadHandler(buffer)
    handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
    level = logger.level
    token = _render_target.set(Console(file=buffer, no_color=True, width=100))
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)
    try:
        yield buffer
    finally:
        logger.setLevel(level)
        logger.removeHandler(handler)
        _render_target.reset(token)

Activity · 9 steps
lines 228–228buffer = io.StringIO()lines 229–229handler = _OwnThreadHandler(buffer)lines 230–230handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))lines 231–231level = logger.levellines 232–232token = _render_target.set(Console(file=buffer, no_color=True, width=100))lines 233–233logger.addHandler(handler)lines 234–234logger.setLevel(logging.INFO)lines 235–235trylines 236–236yield buffer

Flows

clean_subprocess_env

dict[str, str] clew._common.clean_subprocess_env()

os.environ + NO_COLOR/TERM=dumb so pipeline subprocesses emit no ANSI.

clew/_common.py:142

Show on the map →

Called by _discover_targets, _require_nightly_rustdoc, _run_rustdoc_json, doxygen_supports_sqlite3, run_doxygen

Calls none

Source · 15 lines
def clean_subprocess_env() -> dict[str, str]:
    """Return a copy of the environment with color/interactive TTY hints forced
    off (NO_COLOR=1, TERM=dumb, CLICOLOR=0). Passed to every pipeline subprocess
    (e.g. doxygen) so captured build output carries no SGR escape sequences.

    @brief Build a color-suppressing environment for pipeline subprocesses.
    @version 2
    """
    env = dict(os.environ)
    env["NO_COLOR"] = "1"
    env["TERM"] = "dumb"
    env["CLICOLOR"] = "0"
    return env

Activity · 5 steps
lines 150–150env = dict(os.environ)lines 151–151env["NO_COLOR"] = "1"lines 152–152env["TERM"] = "dumb"lines 153–153env["CLICOLOR"] = "0"lines 154–154return env

Requirements

REQ-DDB-PIPE-006

Flows

within_repo

Path | None clew._common.within_repo(Path candidate, Path root, *str setting, dict[str, str]|None memo=None)

Resolve a path and require it to stay inside the repository.

clew/_common.py:90

Show on the map →

Called by _collect_file_docs, _declared_doxyfile, _declared_kconfig, _locate, _named_config_header, _sourced_outside, ingest_file_licenses, ingest_kerneldoc, ingest_supplementary_docs

Calls _real, _real_file

Source · 48 lines
def within_repo(
    candidate: Path, root: Path, *, setting: str, memo: dict[str, str] | None = None
) -> Path | None:
    """RESOLVE FIRST, THEN CONTAIN. The other order does not hold: git tracks symlinks, so a
    repository can ship `README.md -> /proc/self/environ` whose every string looks
    repo-relative, and joining an ABSOLUTE declared entry discards `root` entirely
    (`Path("/repo") / "/etc"` is `/etc`). The 1.1.0 audit found four pipeline stages reading a
    path that had been joined to the root and then only stat'ed — prose ingest, file-level
    docs, `kconfig.root`, `preprocessor.config_header` — each one an arbitrary read whose
    content is then served to a model LABELLED WITH THE IN-REPO PATH, which is the part an
    agent has no way to doubt.

    NON-RAISING, because all four call sites already have a skip-and-warn branch for a path
    that does not exist, and an escaping path is the same kind of event: this declaration or
    this file contributes nothing, and the log says which and why. A raise would turn a
    hostile README into a failed build at those sites, and the guard's own
    `resolve_contained_path` already covers the places where refusing outright IS the answer.

    `clew.guard` deliberately shares no code with the pipeline, so it keeps its own copy of
    this rule; that duplication is a layering decision, recorded in both docstrings.

    @brief Resolve-then-contain a repo-relative path, warning when it escapes.
    @return The resolved path, or None.
    @version 1
    """
    ## STRINGS, AND `memo` FOR A LOOP (1.3.4). `Path.resolve()` of the root on every call, a full
    ## component-by-component realpath of every file, and `root in resolved.parents` (which builds
    ## every ancestor as a Path) were most of what the per-file stages spent on this check —
    ## measured on a 19.5k-path tree, more than the reads it guards. A caller looping over many
    ## files passes one `memo` dict for THAT LOOP: the root and each directory are resolved once,
    ## and a file that is not itself a symlink resolves to its resolved directory plus its name,
    ## which is exactly what realpath would return. The memo lives only as long as the caller's
    ## loop, so a long-lived server never trusts a directory resolution from an earlier build.
    resolved_root = _real(os.fspath(root), memo)
    resolved_s = _real_file(os.fspath(candidate), memo)
    if resolved_s == resolved_root or resolved_s.startswith(resolved_root.rstrip(os.sep) + os.sep):
        return Path(resolved_s)
    resolved = Path(resolved_s)
    logger.warning(
        "%s resolves to %s, OUTSIDE the repository %s — refusing to read it. Paths here are "
        "repository-relative, and a symlink pointing out of the tree is not followed.",
        setting,
        resolved,
        resolved_root,
    )
    return None

Activity · 7 steps
lines 123–123resolved_root = _real(os.fspath(root), memo)lines 124–124resolved_s = _real_file(os.fspath(candidate), memo)lines 125–125◇ if resolved_s == resolved_root or resolved_s.startswith(resolved_root.rstrip(os.sep) + os.sep)lines 126–126return Path(resolved_s)lines 127–127resolved = Path(resolved_s)lines 128–134logger.warning( "%s resolves to %s, OUTSIDE the repository %s — refusing to read it. Paths here are " "repository-relative, and a symlink pointing out of the tree is not followed.", setting, resolved, resolved_root, )lines 135–135return None

Requirements

REQ-DDB-PIPE-014