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.
Called by doxyfile_content_for, run_doxygen
Tested by 16 tests
test_a_newline_in_a_path_cannot_inject_a_directive, test_a_repos_own_doxyfile_cannot_declare_a_filter_command, test_an_absolute_directory_exclude_becomes_an_anchored_pattern, test_build_doxyfile_appends_extra_input_clears_exclude, test_build_doxyfile_appends_forced_flags, test_build_doxyfile_extra_exclude_applies_standalone, test_declared_predefined_cannot_inject_a_directive, test_forced_output_dir_keeps_doxygen_out_of_the_target_repo, test_no_command_valued_option_survives_a_hostile_doxyfile, test_no_file_reading_command_survives_a_hostile_source_comment, test_output_dir_defaults_to_the_doxyfile_when_not_forced, test_replacing_input_also_clears_the_repo_s_exclude_patterns
Calls _exclude_lines, _inlineable, _safe_predefined, extra_input_clears_exclude
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
Requirements
_exclude_lines
str clew.doxygen._exclude_lines(list[str] paths)
Render exclusions, sending absolute directories to EXCLUDE_PATTERNS so doxygen prunes them.
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
Requirements
copy_database
None clew.doxygen.copy_database(Path src, Path dest)
Copy the generated database to the target location.
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
Requirements
declared_file_patterns
list[str] clew.doxygen.declared_file_patterns(Path doxyfile)
The FILE_PATTERNS a target's own Doxyfile declares, for reporting only.
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
Requirements
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).
Called by _resolve_doxyfile_and_root
Tested by 6 tests
test_a_missing_explicit_doxyfile_does_not_propose_passing_one, test_a_rejected_candidate_says_where_and_why, test_no_doxyfile_anywhere_is_described_as_supported, test_only_the_unresolvable_situations_are_errors, test_the_four_situations_produce_four_distinct_sentences, test_with_no_target_at_all_the_message_names_synthesis
Calls _doxyfile_situation
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
Requirements
discover_doxyfile
Path | None clew.doxygen.discover_doxyfile(Path repo)
Discover a repo's own Doxyfile (declaration-driven, never hardcoded).
Called by _check_indexable, _doxyfile_scope, _resolve_doxyfile_and_root, _run_build_walked, uses_rustdoc
Tested by
Calls none
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
Requirements
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.
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
Requirements
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.
Called by run_doxygen
Tested by
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
Requirements
doxygen_supports_sqlite3
bool | None clew.doxygen.doxygen_supports_sqlite3(str binary="doxygen")
Whether the doxygen on PATH was BUILT with sqlite3 output support.
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
Requirements
Flows
effective_file_patterns
list[str] clew.doxygen.effective_file_patterns(Path doxyfile)
The FILE_PATTERNS actually in effect for a build.
Called by _doxygen_has_source, _verify_extra_input_is_read, in_doxygen_scope, roots_matching_no_file_pattern
Tested by
Calls list
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
Requirements
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.
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
Requirements
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.
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
Requirements
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.
Called by _incremental_plan
Tested by
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
Requirements
parse_doxyfile_value
str clew.doxygen.parse_doxyfile_value(Path doxyfile, str key)
Extract a value from a Doxyfile by key.
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
Requirements
parse_doxyfile_values
list[str] clew.doxygen.parse_doxyfile_values(Path doxyfile, str key)
Collect every value assigned to a Doxyfile key, across = / += / continuations.
Called by _doxyfile_scope, declared_file_patterns, doxygen_input_roots, in_doxygen_scope
Calls none
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
Requirements
rejected_doxyfile_candidates
list[Path] clew.doxygen.rejected_doxyfile_candidates(Path repo)
Doxyfile candidates discovery found but declined to adopt.
Called by _resolve_doxyfile_and_root
Tested by
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
Requirements
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.
Called by _build_stages
Tested by
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
Requirements
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.
Called by _crash_log, _run, _run, _run_doxygen_from_args, _run_subset, _time_subset, cmd_outbound, cmd_refids
Tested by
Calls _build_doxyfile_content, _consume_doxygen_output, _prune_abandoned_output, _reap_process_group, _surface_doxygen_warnings, clean_subprocess_env, doxygen_db_path, doxygen_supports_sqlite3, effective_output_dir
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
Requirements
sanitize_doxygen_text
int clew.doxygen.sanitize_doxygen_text(Path db_path)
Sanitize non-UTF-8 bytes doxygen wrote into description columns.
Called by _build_stages
Tested by
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
Requirements
synthesize_doxyfile
Path clew.doxygen.synthesize_doxyfile(Path repo_root, Path output_dir)
Synthesize a minimal Doxyfile for a repo that has none.
Called by _resolve_doxyfile_and_root
Tested by
Calls none
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
Requirements
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.
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