doxygen.py

clew/doxygen.py

Doxygen invocation, output handling, and Doxyfile parsing.

_build_doxyfile_content

str clew.doxygen._build_doxyfile_content(Path doxyfile, list[str]|None extra_input, list[str]|None extra_exclude, bool replace_input=False, Path|None output_dir=None, str predefined="")

Build the augmented Doxyfile content piped to doxygen on stdin.

clew/doxygen.py:715

Source · 85 lines
def _build_doxyfile_content(
    doxyfile: Path,
    extra_input: list[str] | None,
    extra_exclude: list[str] | None,
    replace_input: bool = False,
    output_dir: Path | None = None,
    predefined: str = "",
) -> str:
    """Build the augmented Doxyfile content piped to doxygen on stdin.

    Forces SQLite/XML/EXTRACT_ALL flags. `extra_exclude` always applies:
    without `extra_input` it is APPENDED to the repo's own EXCLUDE (so
    `--extra-exclude` works standalone to trim scope); with `extra_input` the
    EXCLUDE list is first CLEARED then re-applied, so submodule source added via
    `extra_input` isn't silently dropped by the repo's own EXCLUDE.

    `replace_input` additionally CLEARS the Doxyfile's own INPUT list, so the
    supplied roots become the whole scope. That is what a declaration-derived
    scope (`--scope from-guard`) needs: the Doxyfile's INPUT is a different,
    independently-written statement of scope, and silently unioning the two
    would re-admit exactly the trees the repo's declaration leaves out.

    `predefined` is pre-rendered Doxyfile text from `preprocessor.doxyfile_lines`
    (gh#17) — the declared PREPROCESSOR CONFIGURATION this index represents. It is
    appended AFTER the repo's own Doxyfile text and as `PREDEFINED +=`, never `=`,
    so a target that already declares its own PREDEFINED keeps it and gains ours.
    A target declaring nothing passes `""`, and the content is byte-identical to
    what this function produced before gh#17.

    Rendering happens in `preprocessor.py` rather than here, and passing TEXT
    rather than a macro list is deliberate: this string is what
    `doxyfile_content_for` hashes for the index cache, so there is exactly one
    place that decides what doxygen sees and no way for the hashed form and the
    piped form to drift.
    """
    ## `predefined` COMES FROM THE TARGET REPO'S `.clew.yaml` and lands AFTER the forced
    ## block, so anything it smuggles wins over every line above. `_declared_macros` applies
    ## only `str(v).strip()`, so an interior newline survives and a trailing `#` defeats the
    ## quoting — the same line-based injection as a path, through a different door. Filtered
    ## here because this is the single choke point every source passes through.
    content = doxyfile.read_text() + _DOXYFILE_FORCED_FLAGS + _safe_predefined(predefined)
    if output_dir is not None:
        # Forced LAST so it wins over the repo's own OUTPUT_DIRECTORY (doxygen
        # takes the final assignment). Absolute, so it is independent of cwd —
        # which must stay the repo root for relative INPUT paths to resolve.
        content += f"OUTPUT_DIRECTORY = {Path(output_dir).resolve()}\n"
    # The SAME rule `treescan.doxygen_input_roots` mirrors when it enumerates the
    # tree for the index cache, asked of one shared predicate rather than
    # re-derived here (gh#3). The two were identical and free to drift, and the
    # only symptom of drift would have been a cache that hashes a different file
    # set than doxygen reads.
    from .treescan import extra_input_clears_exclude

    if not extra_input_clears_exclude(extra_input):
        # --extra-exclude still applies standalone: append to the repo's own
        # EXCLUDE (no clear — with no extra_input there is no submodule source
        # to un-hide). Previously this early-returned, silently dropping it.
        return content + _exclude_lines(_inlineable(list(extra_exclude or []), "EXCLUDE"))
    if replace_input:
        content += "INPUT =\n"
        ## AND `EXCLUDE_PATTERNS`, which is the GLOB spelling of the same decision
        ## (gh#333). Clearing `EXCLUDE` below and leaving this standing was arbitrary,
        ## and it silently defeated the whole scope change on the target it was built
        ## for: entropic declares `EXCLUDE_PATTERNS = */extern/* */build/* */tests/*`,
        ## so its llama.cpp submodule was admitted to INPUT and then dropped again —
        ## a build that indexed 16 vendored files, reported success, and looked like a
        ## working measurement.
        ##
        ## Only under `replace_input`, i.e. only when the operator asked for the
        ## repo's own scope statement to be replaced. A plain `--extra-exclude` build
        ## leaves both keys exactly as the repo wrote them.
        content += "EXCLUDE_PATTERNS =\n"
    for path in _inlineable(list(extra_input), "INPUT"):
        content += f"INPUT += {path}\n"
    content += "EXCLUDE =\n"
    if extra_exclude:
        content += _exclude_lines(_inlineable(list(extra_exclude), "EXCLUDE"))
    logger.info(
        "Appending %d extra INPUT entries (EXCLUDE cleared, %d re-excluded)",
        len(extra_input),
        len(extra_exclude) if extra_exclude else 0,
    )
    return content

Activity · 16 steps
lines 755–755content = doxyfile.read_text() + _DOXYFILE_FORCED_FLAGS + _safe_predefined(predefined)lines 756–756◇ if output_dir is not Nonelines 760–760content += f"OUTPUT_DIRECTORY = {Path(output_dir).resolve()}\n"lines 766–766from .treescan import extra_input_clears_excludelines 768–768◇ if not extra_input_clears_exclude(extra_input)lines 772–772return content + _exclude_lines(_inlineable(list(extra_exclude or []), "EXCLUDE"))lines 773–773◇ if replace_inputlines 774–774content += "INPUT =\n"lines 786–786content += "EXCLUDE_PATTERNS =\n"lines 787–787◇ for path in _inlineable(list(extra_input), "INPUT")lines 788–788content += f"INPUT += {path}\n"lines 789–789content += "EXCLUDE =\n"lines 790–790◇ if extra_excludelines 791–791content += _exclude_lines(_inlineable(list(extra_exclude), "EXCLUDE"))lines 792–796logger.info( "Appending %d extra INPUT entries (EXCLUDE cleared, %d re-excluded)", len(extra_input), len(extra_exclude) if extra_exclude else 0, )lines 797–797return content

Requirements

REQ-DDB-INDEX-001

_exclude_lines

str clew.doxygen._exclude_lines(list[str] paths)

Render exclusions, sending absolute directories to EXCLUDE_PATTERNS so doxygen prunes them.

clew/doxygen.py:810

Source · 32 lines
def _exclude_lines(paths: list[str]) -> str:
    """DOXYGEN READS AN EXCLUDED DIRECTORY IN FULL. Measured against 1.18.0: a directory named in
    `EXCLUDE` is expanded into the set of every file beneath it before anything is excluded, so
    excluding a vendored tree costs a read of the whole tree. On a 60k-file fixture that was
    1.73 s against 0.03 s for the equivalent pattern. The pattern is matched as doxygen recurses,
    so a matching directory is never entered. Across three real repositories a full build's
    doxygen pass dropped by 40-60% with file-for-file identical output
    (`tests/test_doxygen_exclude_walk.py`).

    MOVED, NOT DUPLICATED. With both spellings present the `EXCLUDE` entry still forces the read
    (1.30 s on the same fixture).

    ANCHORED AT THE ABSOLUTE PATH: `<dir>/*` rather than `*/<name>/*`, which would also drop an
    unrelated directory of the same name. Doxygen matches patterns against absolute file paths,
    so a relative exclusion cannot be rewritten and stays in `EXCLUDE`. So does a file, which
    costs nothing to exclude, and a path containing a wildcard character.

    @brief Render EXCLUDE / EXCLUDE_PATTERNS lines for a list of exclusions.
    @return The lines, newline-terminated.
    @version 1
    """
    lines = []
    for path in paths:
        pruned = (
            Path(path).is_absolute()
            and not _WILDCARD_CHARS.intersection(path)
            and Path(path).is_dir()
        )
        lines.append(f"EXCLUDE_PATTERNS += {path}/*\n" if pruned else f"EXCLUDE += {path}\n")
    return "".join(lines)

Activity · 5 steps
lines 831–831lines = []lines 832–832◇ for path in pathslines 833–837pruned = ( Path(path).is_absolute() and not _WILDCARD_CHARS.intersection(path) and Path(path).is_dir() )lines 838–838lines.append(f"EXCLUDE_PATTERNS += {path}/*\n" if pruned else f"EXCLUDE += {path}\n")lines 839–839return "".join(lines)

Requirements

REQ-DDB-INDEX-001

copy_database

None clew.doxygen.copy_database(Path src, Path dest)

Copy the generated database to the target location.

clew/doxygen.py:1537

Show on the map →

Called by _build_stages

Calls none

Source · 18 lines
def copy_database(src: Path, dest: Path) -> None:
    """Copy the generated database to the target location.

    @brief Copy database to output location.
    @version 1
    """
    # mode=0o700 — the docs DB is built per-user from per-user repo state;
    # restrict the parent dir (typically `.explorer/`) to the owner.
    dest.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    shutil.copy2(str(src), str(dest))
    logger.info("Copied database to: %s", dest)


# doxygen writes descriptions straight from source comments into its sqlite3
# output; a non-UTF-8 source comment (latin-1/GBK/etc.) lands as raw invalid
# bytes in these free-text columns. The docs server already decodes with
# errors="replace" on read, but sanitizing at build time keeps the shipped
# index clean and every downstream augmentation step honest.
Activity · 3 steps
lines 1545–1545dest.parent.mkdir(parents=True, exist_ok=True, mode=0o700)lines 1546–1546shutil.copy2(str(src), str(dest))lines 1547–1547logger.info("Copied database to: %s", dest)

Requirements

REQ-DDB-INDEX-001

declared_file_patterns

list[str] clew.doxygen.declared_file_patterns(Path doxyfile)

The FILE_PATTERNS a target's own Doxyfile declares, for reporting only.

clew/doxygen.py:365

Source · 16 lines
def declared_file_patterns(doxyfile: Path) -> list[str]:
    """KEPT BECAUSE THE DECLARATION IS STILL A FACT, just no longer a policy. A target that
    publishes an API reference with `FILE_PATTERNS = *.h` has said something true about its
    DOCUMENTATION target, and a consumer asking "why does the index hold more than the docs
    do" deserves that answer rather than silence.

    Empty, not the defaults, when nothing is declared — "not recorded" and "recorded as
    doxygen's default" are different claims and only the caller knows which it needs.

    @brief Read a target's declared FILE_PATTERNS.
    @return Declared patterns, or [].
    @version 1
    """
    return parse_doxyfile_values(doxyfile, "FILE_PATTERNS") or []

Activity · 1 steps
lines 378–378return parse_doxyfile_values(doxyfile, "FILE_PATTERNS") or []

Requirements

REQ-DDB-CONFIG-001

describe_doxyfile_resolution

DoxyfileResolution clew.doxygen.describe_doxyfile_resolution(Path|None explicit, Path|None repo_root, list[Path] candidates)

Classify a Doxyfile-resolution outcome and phrase it (gh#4).

clew/doxygen.py:615

Source · 36 lines
def describe_doxyfile_resolution(
    explicit: Path | None,
    repo_root: Path | None,
    candidates: list[Path],
) -> DoxyfileResolution:
    """Say what was looked for, where, what was found, and the ONE action that
    changes the outcome — and never propose an action already taken.

    The situations, in the order they are distinguished:

    - `explicit_missing` — a `--doxyfile` was passed and is not on disk. FATAL, and
      the one case the old text got actively wrong: it answered "Pass --doxyfile".
      The action that changes the outcome is `--repo-root`, because a repo with no
      usable Doxyfile is still indexable by synthesis.
    - `no_target` — neither flag. FATAL, and "Doxyfile not found" was not even true:
      no directory was ever searched. The old text rendered the absent path as the
      literal string "None".
    - `rejected` — a repo was searched and Doxyfiles were found outside the trusted
      locations. NOT fatal; synthesis proceeds. The message carries the reasoning,
      because discovery refuses to guess among strays for a measured reason — it was
      once caught selecting a test fixture's Doxyfile to index a whole project — and
      a bare "not used" invites the reader to conclude the tool failed to find what
      it plainly did find.
    - `absent` — a repo was searched and genuinely ships none. NOT fatal, and this
      is the bullet gh#4 leads with: a SUPPORTED configuration that the tool handles
      well and used to greet with an error.

    @brief Classify and phrase a Doxyfile-resolution outcome.
    @return The situation, its sentence, and its severity.
    @version 1
    """
    kind = _doxyfile_situation(explicit, repo_root, candidates)
    message = _DOXYFILE_MESSAGES[kind](explicit, repo_root, candidates)
    return DoxyfileResolution(kind, message, kind in _DOXYFILE_FATAL_SITUATIONS)

Activity · 3 steps
lines 646–646kind = _doxyfile_situation(explicit, repo_root, candidates)lines 647–647message = _DOXYFILE_MESSAGES[kind](explicit, repo_root, candidates)lines 648–648return DoxyfileResolution(kind, message, kind in _DOXYFILE_FATAL_SITUATIONS)

Requirements

REQ-DDB-INDEX-001

discover_doxyfile

Path | None clew.doxygen.discover_doxyfile(Path repo)

Discover a repo's own Doxyfile (declaration-driven, never hardcoded).

clew/doxygen.py:392

Source · 56 lines
def discover_doxyfile(repo: Path) -> Path | None:
    """Look for `Doxyfile` at the repo root, then in doxygen's conventional
    `docs/`/`doc/` locations. Callers may always pass an explicit path instead;
    this is a convenience, not an assumption about layout.

    Lives here (not in the MCP layer) because BOTH entry points need it. It
    previously existed only in `mcp_server/state.py`, so the MCP server found a
    repo's Doxyfile while the CLI jumped straight to synthesis — the same repo
    built two ways produced materially different databases, silently dropping
    the repo's declared ALIASES / PREDEFINED / filters.

    REFUSES TO GUESS beyond those locations. It used to fall back to
    `sorted(repo.glob("*/Doxyfile"))[0]` — any subdirectory, resolved
    alphabetically. Dogfooding clew on itself caught what that does: it
    selected `sample/Doxyfile`, the demobot TEST FIXTURE, to index the whole
    project, and ran doxygen with cwd=sample/. The damage was masked because
    `--scope from-guard` replaces INPUT; under `--scope doxyfile` clew would
    have indexed the fixture instead of itself, silently, producing a
    well-formed database describing the wrong code.

    Measured across every codebase checked, that glob never once helped: the large
    C and C++ codebases have root Doxyfiles, one has none and correctly synthesizes,
    and the only repo where it fired was the one it got wrong. A wrong Doxyfile
    is worse than none, because none triggers synthesis from the declared scope.

    NOW A PURE QUERY — it no longer warns about the strays it declines (gh#4). It
    used to, and the advice it gave ("pass --doxyfile explicitly, or let the
    scope-derived Doxyfile be synthesized") became the SECOND of two messages once
    the CLI began reporting the same finding, so a user met one fact twice in one
    build. The strays are exposed by `rejected_doxyfile_candidates` and phrased by
    `describe_doxyfile_resolution`, which is the only place that knows what happens
    NEXT — and "what happens next" is the half that makes the finding actionable.

    Nothing lost by the removal, checked rather than assumed: `init._check_indexable`
    builds its own message from the return value, and the MCP build path captures the
    pipeline's log records into its result, so the CLI's sentence reaches a caller
    there too.

    @brief Find a repo's Doxyfile, refusing to guess among strays.
    @return The Doxyfile path, or None when none is found.
    @version 9
    """
    for candidate in (repo / "Doxyfile", *(repo / d / "Doxyfile" for d in _DOXYFILE_DIRS)):
        if candidate.is_file():
            return candidate
    return None


# The four situations Doxyfile resolution can land in (gh#4). They used to share
# ONE sentence, which described none of them: it named a path that was often the
# literal string "None", and it proposed `--doxyfile` to a user whose only way of
# reaching it was to have passed `--doxyfile` already.
#
# Two are supported routes that proceed via synthesis, two are genuine refusals.
# Keeping that split explicit is the point — a supported configuration reported as
# an error costs the reader their next twenty minutes on the wrong hypothesis.
Activity · 4 steps
lines 434–434◇ for candidate in (repo / "Doxyfile", *(repo / d / "Doxyfile" for d in _DOXYFILE_DIRS))lines 435–435◇ if candidate.is_file()lines 436–436return candidatelines 437–437return None

Requirements

REQ-DDB-INDEX-001

Flows

doxyfile_content_for

str clew.doxygen.doxyfile_content_for(Path doxyfile, list[str]|None extra_input=None, list[str]|None extra_exclude=None, bool replace_input=False, str predefined="")

The exact Doxyfile text the pipeline pipes to doxygen.

clew/doxygen.py:1192

Source · 28 lines
def doxyfile_content_for(
    doxyfile: Path,
    extra_input: list[str] | None = None,
    extra_exclude: list[str] | None = None,
    replace_input: bool = False,
    predefined: str = "",
) -> str:
    """Public wrapper over `_build_doxyfile_content` so the incremental index
    cache can hash EXACTLY what doxygen will be fed (Doxyfile bytes + forced
    flags + PREDEFINED + extra INPUT/EXCLUDE lines) when computing its tree hash.

    `predefined` MUST be threaded through here and not only into `run_doxygen`
    (gh#17). The cache's whole claim is "this tree and this Doxyfile text are
    unchanged, so the previous doxygen output is still valid" — and a changed
    `preprocessor:` declaration changes neither a source file nor the target's
    Doxyfile. Omitted from the hash, editing the declared macro list would serve
    the PREVIOUS configuration's parse from cache and report success: a
    well-formed index of a variant the owner just stopped declaring. That is the
    silent-wrong-answer class this repo keeps finding, so it is pinned by a test.

    @brief Expose the augmented Doxyfile content for hashing.
    @version 4
    """
    return _build_doxyfile_content(
        doxyfile, extra_input, extra_exclude, replace_input, None, predefined
    )

Activity · 1 steps
lines 1215–1217return _build_doxyfile_content( doxyfile, extra_input, extra_exclude, replace_input, None, predefined )

Requirements

REQ-DDB-INDEX-001

doxygen_db_path

Path clew.doxygen.doxygen_db_path(Path doxyfile, Path work_dir, Path|None output_dir=None)

Resolve where doxygen writes its SQLite output for this build.

clew/doxygen.py:1256

Source · 13 lines
def doxygen_db_path(doxyfile: Path, work_dir: Path, output_dir: Path | None = None) -> Path:
    """Doxygen puts sqlite3 output in <OUTPUT_DIRECTORY>/sqlite3/ by default,
    or <OUTPUT_DIRECTORY>/<SQLITE3_OUTPUT>/ when that key is set.

    @brief Locate the doxygen SQLite output path.
    @version 2
    """
    sqlite_subdir = parse_doxyfile_value(doxyfile, "SQLITE3_OUTPUT") or "sqlite3"
    return (
        effective_output_dir(doxyfile, work_dir, output_dir) / sqlite_subdir / "doxygen_sqlite3.db"
    )

Activity · 2 steps
lines 1263–1263sqlite_subdir = parse_doxyfile_value(doxyfile, "SQLITE3_OUTPUT") or "sqlite3"lines 1264–1266return ( effective_output_dir(doxyfile, work_dir, output_dir) / sqlite_subdir / "doxygen_sqlite3.db" )

Requirements

REQ-DDB-INDEX-001

doxygen_supports_sqlite3

bool | None clew.doxygen.doxygen_supports_sqlite3(str binary="doxygen")

Whether the doxygen on PATH was BUILT with sqlite3 output support.

clew/doxygen.py:1275

Source · 43 lines
def doxygen_supports_sqlite3(binary: str = "doxygen") -> bool | None:
    """A BUILD-TIME OPTION, NOT A VERSION. doxygen's sqlite3 generator is gated behind
    `-Dbuild_sqlite3=ON`, and Ubuntu ships it OFF — so `apt install doxygen` on 22.04 yields
    1.9.1 with no sqlite3 support, and upgrading the version does not necessarily fix it.
    Every stock 22.04 user hits this (gh#3).

    THE SYMPTOM IS SEVERAL LAYERS FROM THE CAUSE, which is why this exists. An unsupported
    tag is IGNORED rather than refused: doxygen warns "ignoring unsupported tag
    'GENERATE_SQLITE3'", buries it among thousands of suppressed warnings, exits ZERO, and
    writes no database. The pipeline then reports "Expected database not found: <path>",
    naming neither doxygen nor sqlite3 nor anything actionable.

    PROBED FROM THE BINARY'S OWN CONFIG TEMPLATE. `doxygen -g -` writes a default Doxyfile to
    stdout listing every tag the binary implements, so the tag's ABSENCE there is the binary
    telling us it cannot do this. Measured: 4 occurrences on a 1.9.8 build with support, 0 on
    Ubuntu's 1.9.1 without it. Parsing `--version` would be wrong — the same version number
    exists both ways.

    RETURNS None WHEN THE PROBE ITSELF COULD NOT RUN, never False. A missing binary or a
    timeout is not evidence of missing support, and reporting it as such would send someone
    rebuilding doxygen to fix a PATH problem.

    @brief Probe whether doxygen implements GENERATE_SQLITE3.
    @return True/False, or None when the probe could not be run.
    @version 1
    """
    if shutil.which(binary) is None:
        return None
    try:
        proc = subprocess.run(
            [binary, "-g", "-"],
            capture_output=True,
            text=True,
            timeout=30,
            env=clean_subprocess_env(),
        )
    except (OSError, subprocess.SubprocessError):
        return None
    if proc.returncode != 0:
        return None
    return "GENERATE_SQLITE3" in proc.stdout

Activity · 9 steps
lines 1301–1301◇ if shutil.which(binary) is Nonelines 1302–1302return Nonelines 1303–1303trylines 1304–1310proc = subprocess.run( [binary, "-g", "-"], capture_output=True, text=True, timeout=30, env=clean_subprocess_env(), )lines 1311–1311except (OSError, subprocess.SubprocessError)lines 1312–1312return Nonelines 1313–1313◇ if proc.returncode != 0lines 1314–1314return Nonelines 1315–1315return "GENERATE_SQLITE3" in proc.stdout

Requirements

REQ-DDB-CLI-002

Flows

effective_file_patterns

list[str] clew.doxygen.effective_file_patterns(Path doxyfile)

The FILE_PATTERNS actually in effect for a build.

clew/doxygen.py:285

Source · 21 lines
def effective_file_patterns(doxyfile: Path) -> list[str]:
    """IT RETURNS WHAT THE BUILD USES, which since gh#340 is the FORCED set and no longer the
    target's declaration. The previous version read the declaration, and leaving it that way
    would have been the sharper half of the bug rather than a leftover: its consumer is the
    gh#3 guard, which exits 1 when a root's every file is excluded by these patterns. Judging
    an added root against a pattern list that no longer governs the build would fail benign
    roots — a guard firing on the ordinary case, from a fix meant to stop a silent veto.

    So the guard now asks the right question and will essentially never fire, because the
    forced set is doxygen's own broad default. That is the correct outcome: the veto it was
    built to detect cannot happen any more. `declared_file_patterns` is what to call when the
    question is what the TARGET asked for — reporting the difference is still worth doing, and
    it is a different question from what the build did.

    @brief Resolve the FILE_PATTERNS doxygen will actually match against.
    @return The forced pattern set.
    @version 2
    """
    return list(DOXYGEN_DEFAULT_FILE_PATTERNS)

Activity · 1 steps
lines 303–303return list(DOXYGEN_DEFAULT_FILE_PATTERNS)

Requirements

REQ-DDB-CONFIG-001 REQ-DDB-INDEX-001

effective_output_dir

Path clew.doxygen.effective_output_dir(Path doxyfile, Path work_dir, Path|None output_dir=None)

The doxygen output directory actually in effect for a build.

clew/doxygen.py:1227

Source · 22 lines
def effective_output_dir(doxyfile: Path, work_dir: Path, output_dir: Path | None = None) -> Path:
    """clew is a READ-ONLY consumer of target repos, so it forces its own
    OUTPUT_DIRECTORY rather than honoring the Doxyfile's. Honoring it wrote
    doxygen's sqlite3/xml output straight into the target working tree (a repo
    declares `docs/generated/doxygen`), which mutates a repo the operator may
    be mid-edit in, collides between concurrent builds of the same repo, and
    silently shares a directory with that repo's OWN doxygen output.

    Honoring a repo's declared INPUT/ALIASES/PREDEFINED while overriding where
    output lands is the right split: the declaration says WHAT to index, not
    where clew should put its artifacts.

    @brief Resolve the effective doxygen output directory.
    @return The forced directory when given, else the Doxyfile's.
    @version 3
    """
    if output_dir is not None:
        return Path(output_dir).resolve()
    base_dir = parse_doxyfile_value(doxyfile, "OUTPUT_DIRECTORY") or "."
    return (work_dir / base_dir).resolve()

Activity · 4 steps
lines 1243–1243◇ if output_dir is not Nonelines 1244–1244return Path(output_dir).resolve()lines 1245–1245base_dir = parse_doxyfile_value(doxyfile, "OUTPUT_DIRECTORY") or "."lines 1246–1246return (work_dir / base_dir).resolve()

Requirements

REQ-DDB-INDEX-001

fix_doxygen_paths

None clew.doxygen.fix_doxygen_paths(Path db_path, Path doxyfile, Path repo_root)

Rewrite path table entries to be repo-root-relative.

clew/doxygen.py:1843

Show on the map →

Called by _build_stages, _fixed_closure, _incremental_doxygen

Calls _relative_name, parse_doxyfile_value

Source · 70 lines
def fix_doxygen_paths(db_path: Path, doxyfile: Path, repo_root: Path) -> None:
    """Enforce the contract that `path.name` is REPO-ROOT-RELATIVE.

    Doxygen's STRIP_FROM_PATH removes directory prefixes from stored paths, which
    makes them unusable for reading a file back, so this reconstructs the full
    repo-root-relative path from the known INPUT directories.

    IT NOW RUNS EVEN WITHOUT STRIP_FROM_PATH, and that is the fix. Previously it
    returned early when the Doxyfile declared none — reasonable-sounding, since
    with no stripping there is nothing to reconstruct, but it left ABSOLUTE names
    stored verbatim. `path.name` is published by `list_files` and `search` over
    MCP, so a shared database disclosed the build machine's directory layout.

    #97 fixed this for the SYNTHESIZED Doxyfile by forcing STRIP_FROM_PATH there,
    and this function's own docstring then claimed "only the repo-supplied-Doxyfile
    path produced relative names". **That was measurably false.** A repo shipping
    its own Doxyfile whose STRIP_FROM_PATH covers only part of its tree keeps
    absolute names for everything else — measured on a real C++ target: 145 of 474
    rows absolute, each carrying the builder's home directory, all of them under
    paths its STRIP_FROM_PATH did not mention.

    A repo still OWNS its STRIP_FROM_PATH — that declaration is not overridden.
    What is enforced is the post-condition, which is clew's own contract.

    @brief Fix doxygen paths so they resolve from the repo root.
    @return None.
    @version 3
    """
    strip_raw = parse_doxyfile_value(doxyfile, "STRIP_FROM_PATH")
    doxyfile_dir = doxyfile.parent
    strip_dirs = [(doxyfile_dir / d).resolve() for d in (strip_raw or "").split()]

    conn = sqlite3.connect(str(db_path))
    try:
        ## EVERY row, not just `type = 1`. The filter used to read files only, and
        ## directory rows (`type = 2`) kept absolute names for exactly the same
        ## reason — 32 of them on a real C++ target, each naming the builder's home
        ## directory. A privacy contract that holds for one row type and not another
        ## is not a contract.
        rows = conn.execute("SELECT rowid, name FROM path").fetchall()
        fixed, external = 0, 0
        for rowid, name in rows:
            resolved = _relative_name(name.rstrip("/"), strip_dirs, repo_root)
            if resolved is None:
                ## Outside the repo root entirely (a vendored include, a system
                ## header). Storing the absolute name is the disclosure, so keep
                ## only the final component and count it — loudly, since a large
                ## number here means the index scope reaches outside the repo.
                external += 1
                conn.execute(
                    "UPDATE path SET name = ? WHERE rowid = ?",
                    (Path(name.rstrip("/")).name, rowid),
                )
                continue
            if resolved != name:
                conn.execute("UPDATE path SET name = ? WHERE rowid = ?", (resolved, rowid))
                fixed += 1
        conn.commit()
    finally:
        conn.close()

    if fixed:
        logger.info("path: rewrote %d/%d entries to repo-root-relative", fixed, len(rows))
    if external:
        logger.warning(
            "path: %d entries resolved OUTSIDE %s and were reduced to their basename "
            "— an absolute path here would disclose this machine's layout",
            external,
            repo_root,
        )

1 more lines, not shown

Activity · 21 steps
lines 1871–1871strip_raw = parse_doxyfile_value(doxyfile, "STRIP_FROM_PATH")lines 1872–1872doxyfile_dir = doxyfile.parentlines 1873–1873strip_dirs = [(doxyfile_dir / d).resolve() for d in (strip_raw or "").split()]lines 1875–1875conn = sqlite3.connect(str(db_path))lines 1876–1876trylines 1882–1882rows = conn.execute("SELECT rowid, name FROM path").fetchall()lines 1883–1883fixed, external = 0, 0lines 1884–1884◇ for rowid, name in rowslines 1885–1885resolved = _relative_name(name.rstrip("/"), strip_dirs, repo_root)lines 1886–1886◇ if resolved is Nonelines 1891–1891external += 1lines 1892–1895conn.execute( "UPDATE path SET name = ? WHERE rowid = ?", (Path(name.rstrip("/")).name, rowid), )lines 1896–1896continuelines 1897–1897◇ if resolved != namelines 1898–1898conn.execute("UPDATE path SET name = ? WHERE rowid = ?", (resolved, rowid))lines 1899–1899fixed += 1lines 1900–1900conn.commit()lines 1904–1904◇ if fixedlines 1905–1905logger.info("path: rewrote %d/%d entries to repo-root-relative", fixed, len(rows))lines 1906–1906◇ if externallines 1907–1912logger.warning( "path: %d entries resolved OUTSIDE %s and were reduced to their basename " "— an absolute path here would disclose this machine's layout", external, repo_root, )

Requirements

REQ-DDB-INDEX-001

in_doxygen_scope

list[str] clew.doxygen.in_doxygen_scope(list[str] paths, Path doxyfile, bool honor_exclude_patterns)

Restrict a file list to what a doxygen run over the roots would actually index.

clew/doxygen.py:314

Source · 46 lines
def in_doxygen_scope(paths: list[str], doxyfile: Path, honor_exclude_patterns: bool) -> list[str]:
    """A SCOPE STATEMENT HAS THREE KEYS AND THE TREE SCAN READS ONE. `enumerate_tree` honours
    INPUT and EXCLUDE roots and is DELIBERATELY not extension-filtered — correct for its own
    job, which is deciding WHETHER anything changed ("when in doubt, MISS"). Reusing that
    unfiltered set as the doxygen INPUT is what this fixes: `FILE_PATTERNS` and
    `EXCLUDE_PATTERNS` are the other two keys, and a subset run bypasses both because doxygen
    applies FILE_PATTERNS only to DIRECTORY entries and the run clears EXCLUDE_PATTERNS in
    order to list files individually.

    The consequence measured on the C fixture: a `vendor/` file the Doxyfile excludes by glob
    entered the changed set, was listed explicitly, and was spliced INTO the master — so the
    incremental index held a file no full rebuild would ever produce, with a healthy report and
    nothing in `skipped`. Silently WIDENING scope is worse than narrowing it, because every
    coverage and orphan figure is then computed over a set the operator never asked for.

    EXCLUDE_PATTERNS IS CONDITIONAL, and that asymmetry is deliberate rather than sloppy. A
    repo with a declared scope builds with `replace_input`, which clears EXCLUDE_PATTERNS for
    the WHOLE-TREE run too — so honouring them in the subset would make the subset NARROWER
    than the full build and leave real files stale. The flag says which regime the caller is
    in, so the subset matches whichever one the master was built under.

    @brief Filter a candidate list down to the doxygen run's real scope.
    @return The in-scope subset.
    @version 1
    """
    patterns = effective_file_patterns(doxyfile)
    excluded = parse_doxyfile_values(doxyfile, "EXCLUDE_PATTERNS") if honor_exclude_patterns else []
    kept: list[str] = []
    for rel in paths:
        name = PurePosixPath(rel).name
        if patterns and not any(fnmatch.fnmatch(name, pat) for pat in patterns):
            continue
        if any(fnmatch.fnmatch(rel, pat) or fnmatch.fnmatch("/" + rel, pat) for pat in excluded):
            continue
        kept.append(rel)
    dropped = len(paths) - len(kept)
    if dropped:
        logger.info(
            "scope: %d of %d candidate file(s) are outside the doxygen run's scope "
            "(FILE_PATTERNS or EXCLUDE_PATTERNS) and are not indexed incrementally either",
            dropped,
            len(paths),
        )
    return kept

Activity · 14 steps
lines 339–339patterns = effective_file_patterns(doxyfile)lines 340–340excluded = parse_doxyfile_values(doxyfile, "EXCLUDE_PATTERNS") if honor_exclude_patterns else []lines 341–341kept: list[str] = []lines 342–342◇ for rel in pathslines 343–343name = PurePosixPath(rel).namelines 344–344◇ if patterns and not any(fnmatch.fnmatch(name, pat) for pat in patterns)lines 345–345continuelines 346–346◇ if any(fnmatch.fnmatch(rel, pat) or fnmatch.fnmatch("/" + rel, pat) for pat in excluded)lines 347–347continuelines 348–348kept.append(rel)lines 349–349dropped = len(paths) - len(kept)lines 350–350◇ if droppedlines 351–356logger.info( "scope: %d of %d candidate file(s) are outside the doxygen run's scope " "(FILE_PATTERNS or EXCLUDE_PATTERNS) and are not indexed incrementally either", dropped, len(paths), )lines 357–357return kept

Requirements

REQ-DDB-INDEX-002

parse_doxyfile_value

str clew.doxygen.parse_doxyfile_value(Path doxyfile, str key)

Extract a value from a Doxyfile by key.

clew/doxygen.py:1142

Source · 13 lines
def parse_doxyfile_value(doxyfile: Path, key: str) -> str:
    """Extract a value from a Doxyfile by key.

    @brief Parse a single key=value from a Doxyfile.
    @version 3
    """
    for line in doxyfile.read_text().splitlines():
        stripped = line.strip()
        if stripped.startswith(key) and "=" in stripped:
            return stripped.split("=", 1)[1].strip()
    return ""

Activity · 5 steps
lines 1148–1148◇ for line in doxyfile.read_text().splitlines()lines 1149–1149stripped = line.strip()lines 1150–1150◇ if stripped.startswith(key) and "=" in strippedlines 1151–1151return stripped.split("=", 1)[1].strip()lines 1152–1152return ""

Requirements

REQ-DDB-INDEX-001

parse_doxyfile_values

list[str] clew.doxygen.parse_doxyfile_values(Path doxyfile, str key)

Collect every value assigned to a Doxyfile key, across = / += / continuations.

clew/doxygen.py:1159

Source · 29 lines
def parse_doxyfile_values(doxyfile: Path, key: str) -> list[str]:
    """Doxyfile lists (INPUT, EXCLUDE) may be split over `=` plus any number
    of `+=` lines and backslash continuations. `parse_doxyfile_value` returns
    only the first line's text, which is fine for scalars but loses list
    entries — this collects them all, for the incremental cache's file
    enumeration.

    @brief Parse a whole Doxyfile list value.
    @version 1
    """
    values: list[str] = []
    collecting = False
    for raw in doxyfile.read_text().splitlines():
        line = raw.strip()
        continues = line.endswith("\\")
        body = line[:-1].strip() if continues else line
        if not collecting:
            if not (body.startswith(key) and "=" in body):
                continue
            lhs, rhs = body.split("=", 1)
            if lhs.strip().rstrip("+") != key:
                continue
            values.extend(rhs.split())
        else:
            values.extend(body.split())
        collecting = continues
    return values

Activity · 17 steps
lines 1169–1169values: list[str] = []lines 1170–1170collecting = Falselines 1171–1171◇ for raw in doxyfile.read_text().splitlines()lines 1172–1172line = raw.strip()lines 1173–1173continues = line.endswith("\\")lines 1174–1174body = line[:-1].strip() if continues else linelines 1175–1175◇ if not collectinglines 1176–1176◇ if not (body.startswith(key) and "=" in body)lines 1177–1177continuelines 1178–1178lhs, rhs = body.split("=", 1)lines 1179–1179◇ if lhs.strip().rstrip("+") != keylines 1180–1180continuelines 1181–1181values.extend(rhs.split())lines 1182–1182elselines 1183–1183values.extend(body.split())lines 1184–1184collecting = continueslines 1185–1185return values

Requirements

REQ-DDB-INDEX-001

rejected_doxyfile_candidates

list[Path] clew.doxygen.rejected_doxyfile_candidates(Path repo)

Doxyfile candidates discovery found but declined to adopt.

clew/doxygen.py:483

Show on the map →

Called by _resolve_doxyfile_and_root

Tested by

1 teststest_candidates_are_reported_without_being_adopted

Calls none

Source · 20 lines
def rejected_doxyfile_candidates(repo: Path) -> list[Path]:
    """The strays `discover_doxyfile` refuses to guess among, exposed separately so
    a message can say WHERE a Doxyfile was found without discovery having to adopt
    it. Splitting "what did you find" from "what will you use" is what lets the
    refusal keep its reasoning: previously the only record that anything had been
    found at all was a warning inside discovery, so the CLI's own error could not
    mention it.

    Deliberately NOT a behaviour change. `discover_doxyfile` still returns None for
    every path this lists — adopting one is the defect that put a test fixture's
    Doxyfile in charge of indexing a whole project.

    @brief List the Doxyfiles discovery declined to adopt.
    @return Sorted stray candidate paths.
    @version 1
    """
    trusted = {repo / "Doxyfile", *(repo / d / "Doxyfile" for d in _DOXYFILE_DIRS)}
    return [p for p in sorted(repo.glob("*/Doxyfile")) if p not in trusted]

Activity · 2 steps
lines 499–499trusted = {repo / "Doxyfile", *(repo / d / "Doxyfile" for d in _DOXYFILE_DIRS)}lines 500–500return [p for p in sorted(repo.glob("*/Doxyfile")) if p not in trusted]

Requirements

REQ-DDB-INDEX-001

repair_attribute_named_functions

int clew.doxygen.repair_attribute_named_functions(Path db_path, Path repo_root)

Repair memberdefs doxygen mis-named ' attribute ' to the real name.

clew/doxygen.py:1686

Show on the map →

Called by _build_stages

Tested by

3 teststest_repair_merges_body_into_declaration, test_repair_noop_without_attribute_rows, test_repair_renames_when_no_declaration

Calls _real_function_name_at, _repair_one_attribute_row

Source · 24 lines
def repair_attribute_named_functions(db_path: Path, repo_root: Path) -> int:
    conn = sqlite3.connect(str(db_path))
    try:
        rows = conn.execute(
            "SELECT m.rowid, m.bodystart, m.bodyend, m.file_id, p.name "
            "FROM memberdef m JOIN path p ON m.bodyfile_id = p.rowid "
            "WHERE m.name = '__attribute__' AND m.kind = 'function' "
            "AND m.bodystart > 0",
        ).fetchall()
        cache: dict = {}
        fixed = 0
        for rowid, bstart, bend, file_id, rel in rows:
            real = _real_function_name_at(repo_root, rel, bstart, cache)
            if real and real != "__attribute__":
                _repair_one_attribute_row(conn, rowid, bstart, bend, file_id, real)
                fixed += 1
        conn.commit()
    finally:
        conn.close()
    if fixed:
        logger.info("Repaired %d __attribute__-mislabeled function name(s)", fixed)
    return fixed

Activity · 14 steps
lines 1687–1687conn = sqlite3.connect(str(db_path))lines 1688–1688trylines 1689–1694rows = conn.execute( "SELECT m.rowid, m.bodystart, m.bodyend, m.file_id, p.name " "FROM memberdef m JOIN path p ON m.bodyfile_id = p.rowid " "WHERE m.name = '__attribute__' AND m.kind = 'function' " "AND m.bodystart > 0", ).fetchall()lines 1695–1695cache: dict = {}lines 1696–1696fixed = 0lines 1697–1697◇ for rowid, bstart, bend, file_id, rel in rowslines 1698–1698real = _real_function_name_at(repo_root, rel, bstart, cache)lines 1699–1699◇ if real and real != "__attribute__"lines 1700–1700_repair_one_attribute_row(conn, rowid, bstart, bend, file_id, real)lines 1701–1701fixed += 1lines 1702–1702conn.commit()lines 1705–1705◇ if fixedlines 1706–1706logger.info("Repaired %d __attribute__-mislabeled function name(s)", fixed)lines 1707–1707return fixed

Requirements

REQ-DDB-INDEX-001

run_doxygen

Path clew.doxygen.run_doxygen(Path doxyfile, Path work_dir, list[str]|None extra_input=None, list[str]|None extra_exclude=None, bool replace_input=False, Path|None output_dir=None, str predefined="")

Run doxygen with GENERATE_SQLITE3 and return the database path.

clew/doxygen.py:1327

Source · 120 lines
def run_doxygen(
    doxyfile: Path,
    work_dir: Path,
    extra_input: list[str] | None = None,
    extra_exclude: list[str] | None = None,
    replace_input: bool = False,
    output_dir: Path | None = None,
    predefined: str = "",
) -> Path:
    """Run doxygen with GENERATE_SQLITE3 and return the database path.

    output_dir: force where doxygen writes, overriding the Doxyfile's own
    OUTPUT_DIRECTORY. The pipeline always passes one so a build never writes
    into the target repo (see effective_output_dir).

    extra_input: additional INPUT paths appended to the Doxyfile. Useful
    for pulling in submodule source that isn't in the repo's baseline
    INPUT list. With EXTRACT_ALL=YES doxygen creates memberdef rows
    for these files even when they lack doxygen-formatted docstrings.

    replace_input: make extra_input the WHOLE INPUT list (the Doxyfile's own
    INPUT is cleared) — used by the declaration-derived scope.

    predefined: pre-rendered `PREDEFINED +=` Doxyfile text for the declared
    preprocessor configuration (gh#17). Empty for a target that declares none, in
    which case doxygen is fed exactly what it was fed before that change.

    REFUSES BEFORE SPAWNING when the binary is absent, because `subprocess.Popen`
    on a missing executable raises a FileNotFoundError naming `'doxygen'` from
    twelve frames deep — which reads as a clew crash rather than a missing
    prerequisite. Checked HERE rather than in the CLI because this function is the
    single choke point both entry points pass through, so the CLI and the MCP
    server get the same refusal without either restating it.

    @brief Run doxygen and return path to generated sqlite3 database.
    @raises DoxygenUnavailableError When the doxygen binary is not on PATH.
    @version 15
    """
    if shutil.which("doxygen") is None:
        raise DoxygenUnavailableError(
            "the 'doxygen' binary is not on PATH, and it is the one prerequisite "
            "that cannot be installed from PyPI (it is a system package).\n"
            "  Debian/Ubuntu:  sudo apt install doxygen\n"
            "  macOS:          brew install doxygen\n"
            "  Fedora:         sudo dnf install doxygen\n"
            "Then re-run this build. 'clew init' also checks for it."
        )
    logger.info("Running doxygen: %s (cwd: %s)", doxyfile, work_dir)
    doxyfile_content = _build_doxyfile_content(
        doxyfile,
        extra_input,
        extra_exclude,
        replace_input,
        output_dir,
        predefined,
    )
    proc = subprocess.Popen(
        ["doxygen", "-"],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        cwd=str(work_dir),
        text=True,
        bufsize=1,
        env=clean_subprocess_env(),
        ## ITS OWN PROCESS GROUP, SO ABANDONING THIS CALL CAN REAP EVERYTHING IT STARTED.
        ##
        ## FIELD-OBSERVED TWICE: aborting a slow refresh reported success while doxygen kept
        ## running, still parented to the MCP server at ~4 GB resident, and had to be killed by
        ## hand. The next attempt then competed with its own orphans for the machine, which is
        ## how one of them was misread as a concurrency problem.
        ##
        ## `proc.kill()` alone is not enough: it reaches the pid we hold and nothing that pid
        ## spawned. A leader plus `killpg` reaches the whole tree whatever the failure path was —
        ## demonstrated by the reap test's stub, which leaves a shell AND a sleeping child, and
        ## whose first version was itself fooled into finding only one of the two.
        start_new_session=True,
    )
    assert proc.stdin is not None and proc.stdout is not None
    ## STDIN IS WRITTEN ON A THREAD, AND THAT IS A DEADLOCK FIX RATHER THAN A TIDY-UP.
    ##
    ## This used to be `write(...)` then `close()` then read stdout — nobody read stdout until the
    ## WHOLE config had been written. Both pipes have a ~64 KiB OS buffer, and the config is not
    ## small: clew writes explicit file lists into INPUT, so it scales with the repo.
    ## MEASURED: 356,077 bytes for a 4,878-file INPUT — 5.4x the buffer. doxygen emits
    ## config-parse warnings while it is still reading, so its stdout fills, it blocks on write,
    ## we block on write, and neither side can ever proceed. Reproduced with this exact spawn
    ## shape: hung until killed.
    ##
    ## Observed in the field as a single MCP call hanging with no concurrency at all, which is
    ## what ruled out the concurrent-build theory this was first attributed to.
    ##
    ## `communicate()` is the textbook fix and is NOT used here, deliberately: it buffers stdout
    ## and would delete the live progress bar `_consume_doxygen_output` drives off the stream, on
    ## a stage that routinely runs for seconds. A writer thread fixes the deadlock and keeps the
    ## bar — both pipes are serviced at once, which is the actual requirement.
    writer = threading.Thread(
        target=_write_doxyfile_stdin, args=(proc, doxyfile_content), daemon=True
    )
    writer.start()
    ## THE TIMEOUT MUST FIRE FROM A TIMER, NOT FROM `proc.wait`, AND THAT IS THE WHOLE FIX.
    ##
    ## This was `_consume_doxygen_output(proc)` followed by `proc.wait(timeout=...)`, which reads
    ## as bounded and is not: the read loop is `for raw in proc.stdout`, which blocks until the
    ## child closes the pipe. A doxygen that is alive — working OR wedged — never does, so the
    ## line carrying the timeout is not reached and the bound can never be evaluated.
    ##
    ## PROVED, not reasoned. With a stub holding the pipe open, the call was still running at
    ## 20 s against a 3 s timeout; with the stub closing its fds, the same timeout fired at
    ## 3.0 s. In the field this was six consecutive builds of one target, each ending only when
    ## a human or the client killed it — nothing in clew would ever have ended any of them.
    ##
    ## BOTH FDS, because `stderr=subprocess.STDOUT` above puts two descriptors on one pipe.
    ## Closing stdout alone yields no EOF; the first version of the control test missed this and
    ## reported a hang where the mechanism was sound.
    ##
    ## Killing is what UNBLOCKS the reader: the fds close, the loop takes EOF, and the existing
    ## reporting path runs with the flag telling it what happened.
    timed_out = threading.Event()

87 more lines, not shown

Activity · 37 steps
lines 1365–1365◇ if shutil.which("doxygen") is Nonelines 1366–1373raise DoxygenUnavailableError( "the 'doxygen' binary is not on PATH, and it is the one prerequisite " "that cannot be installed from PyPI (it is a system package).\n" " Debian/Ubuntu: sudo apt install doxygen\n" " macOS: brew install doxygen\n" " Fedora: sudo dnf install doxygen\n" "Then re-run this build. 'clew init' also checks for it." )lines 1374–1374logger.info("Running doxygen: %s (cwd: %s)", doxyfile, work_dir)lines 1375–1382doxyfile_content = _build_doxyfile_content( doxyfile, extra_input, extra_exclude, replace_input, output_dir, predefined, )lines 1383–1404proc = subprocess.Popen( ["doxygen", "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=str(work_dir), text=True, bufsize=1, env=clean_subprocess_env(), ## ITS OWN PROCESS GROUP, SO ABANDONING THIS CALL CAN REAP EVERYTHING IT STARTED. ## ## FIELD-OBSERVED TWICE: aborting a slow refresh reported success while doxygen kept ## running, still parented to the MCP server at ~4 GB resident, and had to be killed by ## hand. The next attempt then competed with its own orphans for the machine, which is ## how one of them was misread as a concurrency problem. ## ## `proc.kill()` alone is not enough: it reaches the pid we hold and nothing that pid ## spawned. A leader plus `killpg` reaches the whole tree whatever the failure path was — ## demonstrated by the reap test's stub, which leaves a shell AND a sleeping child, and ## whose first version was itself fooled into finding only one of the two. start_new_session=True, )lines 1405–1405assert proc.stdin is not None and proc.stdout is not Nonelines 1423–1425writer = threading.Thread( target=_write_doxyfile_stdin, args=(proc, doxyfile_content), daemon=True )lines 1426–1426writer.start()lines 1445–1445timed_out = threading.Event()lines 1447–1449def _kill_on_deadline() -> None: timed_out.set() _reap_process_group(proc)lines 1451–1451watchdog = threading.Timer(_DOXYGEN_TIMEOUT, _kill_on_deadline)lines 1452–1452watchdog.daemon = Truelines 1453–1453watchdog.start()lines 1454–1454trylines 1455–1455out = _consume_doxygen_output(proc)lines 1456–1456rc = proc.wait()lines 1457–1457except BaseExceptionlines 1462–1462_reap_process_group(proc)lines 1463–1463raiselines 1466–1466writer.join(timeout=5)lines 1470–1470◇ if timed_out.is_set()lines 1471–1476logger.error( "doxygen did not finish within %d s and was killed. The index was NOT updated; the " "previous one is untouched, because the build stages into a temp file and only " "swaps on success.", _DOXYGEN_TIMEOUT, )lines 1477–1479raise DoxygenFailedError( f"doxygen did not finish within {_DOXYGEN_TIMEOUT} s and was killed" )lines 1480–1480_surface_doxygen_warnings(out.warn_count, list(out.first_warnings))lines 1481–1481◇ if rc != 0lines 1486–1495logger.error( "doxygen exited with status %d after parsing %d file(s). Its last output:\n%s\n" "The index was NOT updated; the previous one is untouched, because the build stages " "into a temp file and only swaps on success. A crash this far into a run is most " "often an over-wide scope — check the index scope reason, or declare index_scope " "in .clew.yaml to narrow it.", rc, out.parsed_files, "\n".join(f" {line}" for line in out.tail) or " (doxygen printed nothing)", )lines 1498–1498last = out.tail[-1].strip() if out.tail else "doxygen printed nothing"lines 1499–1501raise DoxygenFailedError( f"doxygen exited with status {rc} after parsing {out.parsed_files} file(s): {last}" )lines 1507–1507_prune_abandoned_output(effective_output_dir(doxyfile, work_dir, output_dir))lines 1509–1509db_path = doxygen_db_path(doxyfile, work_dir, output_dir)lines 1510–1510◇ if not db_path.exists()lines 1519–1519◇ if doxygen_supports_sqlite3() is Falselines 1520–1525logger.error( "doxygen was built WITHOUT sqlite3 support, so it ignored GENERATE_SQLITE3 and " "wrote no database. This is a build option (-Dbuild_sqlite3=ON), not a version — " "Ubuntu 22.04's doxygen 1.9.1 lacks it. Install a build that has it, then " "confirm with: doxygen -g - | grep GENERATE_SQLITE3" )lines 1526–1528raise DoxygenFailedError( "doxygen was built without sqlite3 support and wrote no database" )lines 1529–1529logger.error("Expected database not found: %s", db_path)lines 1530–1530raise DoxygenFailedError(f"doxygen exited 0 but wrote no database at {db_path}")lines 1531–1531return db_path

Requirements

REQ-DDB-INDEX-001

sanitize_doxygen_text

int clew.doxygen.sanitize_doxygen_text(Path db_path)

Sanitize non-UTF-8 bytes doxygen wrote into description columns.

clew/doxygen.py:1588

Show on the map →

Called by _build_stages

Tested by

1 teststest_sanitize_doxygen_text_repairs_invalid_utf8

Calls _repair_utf8_column

Source · 25 lines
def sanitize_doxygen_text(db_path: Path) -> int:
    """Repair invalid-UTF-8 description text in the doxygen sqlite output.

    Runs right after doxygen generates the db (before augmentation) so every
    downstream step and the shipped index see clean UTF-8. Returns rows fixed.

    @brief Repair non-UTF-8 description columns in the doxygen sqlite db.
    @version 1
    """
    conn = sqlite3.connect(str(db_path))
    conn.text_factory = bytes  # raw bytes so invalid UTF-8 is detectable
    try:
        fixed = sum(
            _repair_utf8_column(conn, table, col)
            for table, cols in _SANITIZE_TARGETS
            for col in cols
        )
        conn.commit()
    finally:
        conn.close()
    if fixed:
        logger.info("Sanitized %d non-UTF-8 description row(s)", fixed)
    return fixed

Activity · 8 steps
lines 1597–1597conn = sqlite3.connect(str(db_path))lines 1598–1598conn.text_factory = byteslines 1599–1599trylines 1600–1604fixed = sum( _repair_utf8_column(conn, table, col) for table, cols in _SANITIZE_TARGETS for col in cols )lines 1605–1605conn.commit()lines 1608–1608◇ if fixedlines 1609–1609logger.info("Sanitized %d non-UTF-8 description row(s)", fixed)lines 1610–1610return fixed

Requirements

REQ-DDB-INDEX-001

synthesize_doxyfile

Path clew.doxygen.synthesize_doxyfile(Path repo_root, Path output_dir)

Synthesize a minimal Doxyfile for a repo that has none.

clew/doxygen.py:657

Source · 55 lines
def synthesize_doxyfile(repo_root: Path, output_dir: Path) -> Path:
    """Write the smallest Doxyfile that lets the pipeline run: PROJECT_NAME, an
    ABSOLUTE OUTPUT_DIRECTORY, STRIP_FROM_PATH, and an empty INPUT. Everything
    else the pipeline needs — GENERATE_SQLITE3, EXTRACT_ALL, RECURSIVE, ...
    — is appended by `_build_doxyfile_content`'s forced flags, and the actual
    INPUT comes from the resolved scope via `replace_input`. This lets clew
    index a repo that ships no Doxyfile — over its declared `index_scope:` roots, or
    over the whole repository when it declares nothing — deriving the whole build
    from declarations, per the no-hardcoding mandate.

    STRIP_FROM_PATH IS NOT COSMETIC, and its absence was a privacy defect. The
    pipeline's contract is that `path.name` holds a REPO-ROOT-RELATIVE path —
    that is the whole reason `fix_doxygen_paths` exists. On this path the
    contract was broken three ways at once: nothing set STRIP_FROM_PATH,
    `replace_input` feeds doxygen ABSOLUTE resolved INPUT paths so it stored
    absolute names, and `fix_doxygen_paths` then returned early precisely because
    STRIP_FROM_PATH was unset. Measured on this repo's own self-index: 112 of 112
    rows absolute, every one carrying the builder's home directory. `list_files`
    publishes that column over MCP, so a synthesized index disclosed the build
    machine's directory layout to any consumer of a shared db.

    It survived because it FAILS SILENTLY UPWARD: `Path(repo_root) / "/abs/p"`
    returns the absolute operand, so every downstream reader resolved correctly
    and no test could notice.

    **This docstring used to continue "Only the repo-supplied-Doxyfile path
    produced relative names." That was FALSE, and saying it is why nobody looked
    there for two more weeks.** A repo whose own STRIP_FROM_PATH covers part of its
    tree keeps absolute names for the rest — measured on a real C++ target: 145 of
    474 rows, plus 32 directory rows the fix did not even scan. `fix_doxygen_paths`
    now enforces the repo-root-relative contract as a POST-CONDITION on every row,
    which is where the guarantee belongs.

    Set only in the SYNTHESIZED Doxyfile, never in the forced flags: a repo that
    ships its own Doxyfile owns its STRIP_FROM_PATH, and overriding it would both
    discard a declaration and defeat `fix_doxygen_paths`' reconstruction. We
    dictate policy only where we are the author — and enforce our own contract
    afterwards regardless of whose declaration produced the input.

    @brief Write a minimal Doxyfile driven by the derived scope.
    @version 5
    """
    output_dir.mkdir(parents=True, exist_ok=True)
    doxyfile = output_dir / "Doxyfile.synth"
    doxyfile.write_text(
        f"PROJECT_NAME = {repo_root.name}\n"
        f"OUTPUT_DIRECTORY = {output_dir}\n"
        f"STRIP_FROM_PATH = {repo_root.resolve()}\n"
        "INPUT =\n",
        encoding="utf-8",
    )
    logger.info("synthesized a Doxyfile (repo declares scope but ships none): %s", doxyfile)
    return doxyfile

Activity · 5 steps
lines 699–699output_dir.mkdir(parents=True, exist_ok=True)lines 700–700doxyfile = output_dir / "Doxyfile.synth"lines 701–707doxyfile.write_text( f"PROJECT_NAME = {repo_root.name}\n" f"OUTPUT_DIRECTORY = {output_dir}\n" f"STRIP_FROM_PATH = {repo_root.resolve()}\n" "INPUT =\n", encoding="utf-8", )lines 708–708logger.info("synthesized a Doxyfile (repo declares scope but ships none): %s", doxyfile)lines 709–709return doxyfile

Requirements

REQ-DDB-INDEX-001

warn_if_no_function_bodies

int clew.doxygen.warn_if_no_function_bodies(Path db_path)

Warn when source files were indexed but yielded no function bodies.

clew/doxygen.py:1715

Source · 56 lines
def warn_if_no_function_bodies(db_path: Path) -> int:
    """A build that indexes source and extracts NOTHING from it is almost always
    a preprocessor problem, and it reports success either way.

    MEASURED on a real C library whose implementation sits behind
    `#if defined(<FEATURE>_C)` guards: 30 `.c` files present in `path`, **zero**
    functions with a body in any of them, and a normal summary printed. A
    consumer received a well-formed database describing a library with no
    implementation. Supplying `PREDEFINED` for the feature macros took the same
    build to 322 bodies.

    Deliberately a WARNING, not a failure, and deliberately not a fix: clew
    must never guess a target's feature macros — that is the target's
    declaration to make. But the ratio is never legitimately zero for a real
    C/C++ codebase, so silence here is the wrong default. This is the same class
    as every other "the layer is empty, and empty means four different things"
    problem: say which one it is.

    Headers alone are not enough to conclude anything — a header-only library or
    a docs-oriented Doxyfile (`FILE_PATTERNS = *.h`) legitimately has no bodies —
    so the check requires INDEXED IMPLEMENTATION FILES before it fires.

    @brief Warn when implementation files yielded no function bodies.
    @return Count of implementation files indexed with zero bodies.
    @version 3
    """
    impl = ("%.c", "%.cpp", "%.cc", "%.cxx")
    conn = sqlite3.connect(str(db_path))
    try:
        clause = " OR ".join("p.name LIKE ?" for _ in impl)
        files = conn.execute(
            f"SELECT COUNT(*) FROM path p WHERE {clause}",
            impl,
        ).fetchone()[0]
        if not files:
            return 0
        bodies = conn.execute(
            "SELECT COUNT(*) FROM memberdef m JOIN path p ON p.rowid = m.bodyfile_id "
            f"WHERE m.kind='function' AND ({clause})",
            impl,
        ).fetchone()[0]
    finally:
        conn.close()

    if bodies:
        return 0
    logger.warning(
        "%d implementation file(s) were indexed but NOT ONE yielded a function body. "
        "The usual cause is a preprocessor guard the build did not satisfy — if this "
        "repo wraps its code in feature macros, its Doxyfile needs PREDEFINED for "
        "them. Every AST and call-graph layer will read empty against this index",
        files,
    )
    return files

Activity · 12 steps
lines 1741–1741impl = ("%.c", "%.cpp", "%.cc", "%.cxx")lines 1742–1742conn = sqlite3.connect(str(db_path))lines 1743–1743trylines 1744–1744clause = " OR ".join("p.name LIKE ?" for _ in impl)lines 1745–1748files = conn.execute( f"SELECT COUNT(*) FROM path p WHERE {clause}", impl, ).fetchone()[0]lines 1749–1749◇ if not fileslines 1750–1750return 0lines 1751–1755bodies = conn.execute( "SELECT COUNT(*) FROM memberdef m JOIN path p ON p.rowid = m.bodyfile_id " f"WHERE m.kind='function' AND ({clause})", impl, ).fetchone()[0]lines 1759–1759◇ if bodieslines 1760–1760return 0lines 1761–1767logger.warning( "%d implementation file(s) were indexed but NOT ONE yielded a function body. " "The usual cause is a preprocessor guard the build did not satisfy — if this " "repo wraps its code in feature macros, its Doxyfile needs PREDEFINED for " "them. Every AST and call-graph layer will read empty against this index", files, )lines 1768–1768return files

Requirements

REQ-DDB-INDEX-001