treescan.py

clew/treescan.py

File-identity hashing and indexed-tree enumeration for incremental builds.

describe

str clew.treescan.ScanSummary.describe(self)

Human-readable one-line summary for logging.

clew/treescan.py:79

Show on the map →

Called by none

Calls none

Source · 10 lines
    def describe(self) -> str:
        ## SAYS ITS UNIT (#470). These four are SOURCE FILES, while the refresh cost line reports
        ## (file, stage) payloads — a different unit, normally ~10x larger. Unlabelled, the two
        ## lines read as two contradicting counts of one change set.
        return (
            f"{len(self.unchanged)} unchanged, {len(self.modified)} modified, "
            f"{len(self.added)} added, {len(self.removed)} removed source file(s)"
        )

Activity · 1 steps
lines 83–86return ( f"{len(self.unchanged)} unchanged, {len(self.modified)} modified, " f"{len(self.added)} added, {len(self.removed)} removed source file(s)" )

Requirements

REQ-DDB-PIPE-003

doxygen_input_roots

tuple[list[Path], list[Path]] clew.treescan.doxygen_input_roots(Path doxyfile, Path work_dir, list[str]|None extra_input, list[str]|None extra_exclude, bool replace_input=False)

Resolve the Doxyfile's INPUT/EXCLUDE lists into absolute roots.

clew/treescan.py:343

Source · 34 lines
def doxygen_input_roots(
    doxyfile: Path,
    work_dir: Path,
    extra_input: list[str] | None,
    extra_exclude: list[str] | None,
    replace_input: bool = False,
) -> tuple[list[Path], list[Path]]:
    """Mirror `doxygen._build_doxyfile_content`'s semantics exactly: extra
    INPUT paths are appended, and when any are given the Doxyfile's own
    EXCLUDE list is CLEARED and only `--extra-exclude` applies. With
    `replace_input` the Doxyfile's INPUT is cleared too, so the extra roots
    ARE the scope. Reading the DECLARED lists (never hardcoding a repo's
    layout) keeps the enumeration correct for any target repo.

    The extra-input-clears-EXCLUDE rule is asked of `extra_input_clears_exclude`
    rather than re-derived here, so the mirror of `_build_doxyfile_content` cannot
    drift silently (gh#3).

    @brief Enumerate the doxygen INPUT/EXCLUDE roots.
    @version 4
    """
    from .doxygen import parse_doxyfile_values

    declared = [] if (replace_input and extra_input) else parse_doxyfile_values(doxyfile, "INPUT")
    inputs = declared + list(extra_input or [])
    excludes = (
        list(extra_exclude or [])
        if extra_input_clears_exclude(extra_input)
        else parse_doxyfile_values(doxyfile, "EXCLUDE")
    )
    return (
        [(work_dir / entry).resolve() for entry in inputs],
        [(work_dir / entry).resolve() for entry in excludes],
    )

1 more lines, not shown

Activity · 5 steps
lines 364–364from .doxygen import parse_doxyfile_valueslines 366–366declared = [] if (replace_input and extra_input) else parse_doxyfile_values(doxyfile, "INPUT")lines 367–367inputs = declared + list(extra_input or [])lines 368–372excludes = ( list(extra_exclude or []) if extra_input_clears_exclude(extra_input) else parse_doxyfile_values(doxyfile, "EXCLUDE") )lines 373–376return ( [(work_dir / entry).resolve() for entry in inputs], [(work_dir / entry).resolve() for entry in excludes], )

Requirements

REQ-DDB-PIPE-003

enumerate_tree

dict[str, Path] clew.treescan.enumerate_tree(list[Path] roots, list[Path] excludes, Path repo_root)

Enumerate every file doxygen would read, honouring EXCLUDE roots.

clew/treescan.py:203

Source · 25 lines
def enumerate_tree(roots: list[Path], excludes: list[Path], repo_root: Path) -> dict[str, Path]:
    """Walk the INPUT roots recursively (the pipeline forces RECURSIVE=YES) and
    drop anything under an EXCLUDE root. Deliberately NOT extension-filtered:
    hashing every file under INPUT means any change at all forces a doxygen
    re-run, which is the conservative side of the "when in doubt, MISS" rule.

    THAT CONSERVATISM IS FREE ON THE HOT PATH, so it is kept whole. What a warm
    refresh actually costs is the WALK, not the hash: `size + mtime_ns` lets an
    unchanged file skip re-hashing, so a refresh that reprocesses nothing hashes
    nothing. Sizing the walk to the surviving set — `_files_under` prunes
    excluded subtrees instead of enumerating and discarding them — leaves every
    file's identity, and therefore every invalidation, exactly as it was. An
    extension filter would trade a documented safety property for a saving the
    prefilter already delivers.

    @brief Enumerate the indexed file tree.
    @version 3
    """
    found: dict[str, Path] = {}
    for root in roots:
        for path in _files_under(root, excludes):
            found[rel_key(path, repo_root)] = path
    return found

Activity · 5 steps
lines 221–221found: dict[str, Path] = {}lines 222–222◇ for root in rootslines 223–223◇ for path in _files_under(root, excludes)lines 224–224found[rel_key(path, repo_root)] = pathlines 225–225return found

Requirements

REQ-DDB-INDEX-002

extra_input_clears_exclude

bool clew.treescan.extra_input_clears_exclude(list[str]|None extra_input)

Whether adding extra INPUT clears the Doxyfile's own EXCLUDE list.

clew/treescan.py:233

Source · 27 lines
def extra_input_clears_exclude(extra_input: list[str] | None) -> bool:
    """ONE rule, previously spelled out twice in two files.

    `doxygen._build_doxyfile_content` emits `EXCLUDE =` (clearing it) whenever any
    extra INPUT is present, so submodule source added via `--extra-input` is not
    silently dropped by the target's own EXCLUDE. `doxygen_input_roots` has to
    MIRROR that exactly, or the incremental cache would hash a different file set
    than doxygen reads — a cache that can answer "unchanged" about a tree it
    enumerated wrongly.

    Both call sites now ask this function instead of each re-deriving `bool(...)`
    from `extra_input`. The two implementations were correct and identical today;
    they were also free to drift, with the only symptom a cache-hit rate that is
    subtly wrong. Naming the rule once makes a change to it land in one place and
    makes the coupling greppable.

    Deliberately NOT an attempt to share the text emission itself: one call site
    produces Doxyfile DIRECTIVES incrementally and the other produces RESOLVED
    PATH LISTS, and the emitted bytes are hashed for the index cache, so unifying
    the media would change cache keys for no correctness gain.

    @brief The extra-input-clears-EXCLUDE rule, stated once.
    @version 1
    """
    return bool(extra_input)

Activity · 1 steps
lines 257–257return bool(extra_input)

Requirements

REQ-DDB-PIPE-003

hash_file

str clew.treescan.hash_file(Path path)

sha256 of a file's bytes, streamed in chunks.

clew/treescan.py:93

Source · 17 lines
def hash_file(path: Path) -> str:
    """Stream a file through sha256. Unreadable files hash to "" so they are
    treated as perpetually-changed (fail toward a MISS, never a false hit).

    @brief Content sha256 of one file.
    @version 2
    """
    digest = hashlib.sha256()
    try:
        with path.open("rb") as handle:
            while chunk := handle.read(_HASH_CHUNK):
                digest.update(chunk)
    except OSError:
        return ""
    return digest.hexdigest()

Activity · 8 steps
lines 100–100digest = hashlib.sha256()lines 101–101trylines 102–102with path.open("rb") as handlelines 103–103◇ while chunk := handle.read(_HASH_CHUNK)lines 104–104digest.update(chunk)lines 105–105except OSErrorlines 106–106return ""lines 107–107return digest.hexdigest()

Requirements

REQ-DDB-INDEX-002

manifest_key

str clew.treescan.manifest_key(Path|dict|None source)

sha256 of a manifest's content, for folding into a stage cache key.

clew/treescan.py:115

Source · 22 lines
def manifest_key(source: Path | dict | None) -> str:
    """Hash an optional manifest (--thread-patterns / --shared-key-patterns /
    --mqtt-dispatch / --data-model / --guard-config). Its CONTENT changes what
    the per-file extractors emit, so it belongs in the affected stage's key.

    A manifest can now arrive as a section of the repo's `.clew.yaml` rather
    than as a file, so a MAPPING is hashed by its canonical serialization. That
    keeps the invalidation property intact — editing a declaration must re-run
    the stages it feeds, exactly as editing a standalone manifest does.

    @brief Cache-key contribution of an optional manifest.
    @version 3
    """
    if source is None:
        return ""
    if isinstance(source, dict):
        canonical = json.dumps(source, sort_keys=True, default=str).encode("utf-8")
        return hashlib.sha256(canonical).hexdigest()
    sha = hash_file(source)
    return sha or "missing"

Activity · 7 steps
lines 128–128◇ if source is Nonelines 129–129return ""lines 130–130◇ if isinstance(source, dict)lines 131–131canonical = json.dumps(source, sort_keys=True, default=str).encode("utf-8")lines 132–132return hashlib.sha256(canonical).hexdigest()lines 133–133sha = hash_file(source)lines 134–134return sha or "missing"

Requirements

REQ-DDB-PIPE-003

rel_key

str clew.treescan.rel_key(Path path, Path repo_root)

Repo-root-relative string for a path, or its absolute form if outside.

clew/treescan.py:141

Show on the map →

Called by _declared_manifest, _parsed_manifests, _reference_enumerate, enumerate_tree, parse_ingot_manifest, parse_udm_manifest

Calls none

Source · 8 lines
def rel_key(path: Path, repo_root: Path) -> str:
    """@brief Key a scanned path the same way doxygen's `path` table does."""
    try:
        return str(path.relative_to(repo_root))
    except ValueError:
        return str(path)

Activity · 4 steps
lines 143–143trylines 144–144return str(path.relative_to(repo_root))lines 145–145except ValueErrorlines 146–146return str(path)

Requirements

REQ-DDB-PIPE-003

roots_matching_no_file_pattern

list[Path] clew.treescan.roots_matching_no_file_pattern(Path doxyfile, Path work_dir, list[str]|None extra_input, list[str]|None extra_exclude, Path repo_root)

extra-input roots that hold files but none doxygen will read (gh#3).

clew/treescan.py:289

Source · 50 lines
def roots_matching_no_file_pattern(
    doxyfile: Path,
    work_dir: Path,
    extra_input: list[str] | None,
    extra_exclude: list[str] | None,
    repo_root: Path,
) -> list[Path]:
    """Find the gh#3 silent drop: a root the user ASKED to have indexed whose files
    doxygen reads and discards, because nothing in this pipeline sets FILE_PATTERNS
    and the target's own declaration therefore applies to every appended
    `INPUT +=` line.

    THE DISCRIMINATOR IS "holds files, and none of them match" — never "contributed
    nothing". An empty directory and an absent path also contribute nothing, and
    FILE_PATTERNS is not why; blaming the patterns for those would be a guard that
    fires on the benign case, which this project has shipped once already and which
    trains the reader to ignore the message in the case that matters. Requiring at
    least one present-and-excluded file makes the check structurally unable to fire
    on an empty root, rather than merely unlikely to.

    The invisibility this recovers is worth naming: `enumerate_tree` is deliberately
    NOT extension-filtered, so the incremental cache happily hashes files doxygen
    will never read. The drop is therefore absent from the cache AND from the logs,
    and the only pre-existing signal — `warn_if_no_function_bodies` — fires solely
    when ZERO implementation bodies exist anywhere, which a header-only target
    legitimately satisfies.

    @brief Roots whose files are all excluded by FILE_PATTERNS.
    @return The offending resolved roots, empty when every root contributes.
    @version 5
    """
    from .doxygen import effective_file_patterns
    from .synth import claims

    if not extra_input:
        return []
    patterns = effective_file_patterns(doxyfile)
    excludes = [(work_dir / entry).resolve() for entry in extra_exclude or []]
    offenders: list[Path] = []
    for entry in extra_input:
        root = (work_dir / entry).resolve()
        present = _files_under(root, excludes)
        if not present:
            continue  # empty or absent: the patterns are not the reason
        ## A JS/TS file contributes through the parse-built front end, not doxygen.
        if not any(_matches_file_patterns(p.name, patterns) or claims(p.name) for p in present):
            offenders.append(root)
    return offenders

Activity · 15 steps
lines 320–320from .doxygen import effective_file_patternslines 321–321from .synth import claimslines 323–323◇ if not extra_inputlines 324–324return []lines 325–325patterns = effective_file_patterns(doxyfile)lines 326–326excludes = [(work_dir / entry).resolve() for entry in extra_exclude or []]lines 327–327offenders: list[Path] = []lines 328–328◇ for entry in extra_inputlines 329–329root = (work_dir / entry).resolve()lines 330–330present = _files_under(root, excludes)lines 331–331◇ if not presentlines 332–332continuelines 334–334◇ if not any(_matches_file_patterns(p.name, patterns) or claims(p.name) for p in present)lines 335–335offenders.append(root)lines 336–336return offenders

Requirements

REQ-DDB-INDEX-001