scope.py¶
clew/scope.py
Resolve the index scope: a declaration, else the whole repository.
_declaration_advice
str clew.scope._declaration_advice()
How to declare an index scope, in this build's own spelling.
Source · 20 lines
def _declaration_advice() -> str:
"""A fallback scope reports that the boundary was not chosen; without this it does
not report the fix, and a diagnosis an owner cannot act on is half a diagnosis
(gh#32's lesson about the skew report, one tier up).
Spellings are imported rather than written out, so the advice cannot drift from the
names the loader actually accepts — the failure `test_declaration.py` pins for
`index_scope` itself. Imported lazily because `declaration` reads a declaration and
`scope` interprets one; the module-level cycle is what `_declared_index_scope`
already avoids the same way.
@brief Name the declarations that would narrow a fallback scope.
@return The advice sentence.
@version 4
"""
from .declaration import DECLARATION_NAME
return f"Declare an `{INDEX_SCOPE_SECTION}:` in {DECLARATION_NAME} to let the two differ."
Activity · 2 steps
Requirements
Flows
_declaration_note
str clew.scope._declaration_note(Path root)
Where a declaration was looked for, phrased for a fallback reason.
Source · 18 lines
def _declaration_note(root: Path) -> str:
"""SAY WHERE WE LOOKED, BEFORE FALLING BACK (gh#16): "this repo declares no scope"
and "we looked in the wrong place" must not produce the same message. There is one
place now, `<root>/.clew.yaml`, so the clause names it and says whether it exists;
a file that exists and declares no `index_scope:` (one that configures only the
gate, say) is no contradiction.
@brief Describe the declaration search for a fallback reason.
@return A human-readable clause.
"""
from .declaration import DECLARATION_NAME
path = root / DECLARATION_NAME
if not path.is_file():
return f"no {DECLARATION_NAME} was found at {path}"
return f"{path} exists but carries no {INDEX_SCOPE_SECTION}"
Activity · 5 steps
Requirements
Flows
_declared_index_scope
DerivedScope | None clew.scope._declared_index_scope(Path root, dict|None stated=None)
Index scope declared directly in the repo's .clew.yaml .
Called by declared_scope_rejection, derive_scope
Source · 85 lines
def _declared_index_scope(root: Path, stated: dict | None = None) -> DerivedScope | None:
"""Read an explicit `index_scope:` declaration::
index_scope:
roots: [clew, scripts, tests]
excludes: [tests/fixtures]
Roots are repo-relative so the declaration stays portable. A root that does
not exist is dropped with a warning rather than passed to doxygen, which
would otherwise emit a confusing "input not found" for a stale entry.
Returns None when nothing usable is declared, which drops the resolution to the
Doxyfile's own INPUT and then to the whole repository — the zero-config default
for every repo that says nothing.
A declared root is TAKEN AT ITS WORD AND NEVER WALKED, which is the whole point —
and which means a clone of another repository beneath it is indexed with no walk
to notice. Since gh#333 that is no longer a hazard to close but the behaviour to
have: `external.py` walks for those trees after the build and TAGS their rows, so
two codebases in one index can still be told apart in an answer.
@brief Load a declared index scope.
@return DerivedScope or None.
@version 9
"""
from .declaration import (
DECLARATION_NAME,
load_declaration_located,
)
if stated:
## gh#382 tier 1. Built through the SAME construction as a declared one, so a stated
## scope cannot differ from a written one in which paths it drops or how it reports
## itself. Only `reason` differs, and it has to: an owner reading "declared in
## <file>" for a scope that came from a tool call would go and edit a file that says
## nothing, which is the checkable-and-wrong attribution this function already fixed
## once for a declaration file.
declaration, source_path = {INDEX_SCOPE_SECTION: stated}, None
else:
declaration, source_path = load_declaration_located(root)
section = declaration.get(INDEX_SCOPE_SECTION)
if section is None:
return None
where = str(source_path) if source_path else "the stated declaration"
if not isinstance(section, dict):
return _Rejected(
f"{where} carries an {INDEX_SCOPE_SECTION} that is "
f"{type(section).__name__}, not a mapping"
)
## FAIL CLOSED AT THE ENTRY LEVEL, WHICH IS THE QUIETER ONE. The section name is validated
## against KNOWN_SECTIONS; the keys INSIDE it were not, so `exclude:` for `excludes:` parsed
## to a perfectly valid mapping that no consumer read. gh#5's reporter wrote exactly that,
## got "no index_scope is declared", and could not tell a schema slip from a bug. An
## accepted-but-unread key is this project's most repeated defect; this closes one more.
unknown = sorted(str(k) for k in section if str(k) not in _INDEX_SCOPE_KEYS)
if unknown:
return _Rejected(
f"{where} declares {INDEX_SCOPE_SECTION} with unknown key(s) "
f"{', '.join(unknown)} — the accepted keys are "
f"{', '.join(sorted(_INDEX_SCOPE_KEYS))}"
)
roots = _existing_paths(root, section.get("roots") or [], "root")
if not roots:
return _Rejected(
f"{where} declares {INDEX_SCOPE_SECTION} but no usable `roots:` — `roots` REPLACES "
f"the index scope and is REQUIRED; `excludes` alone does nothing, and a root that "
f"does not exist on disk is dropped"
)
excludes = _existing_paths(root, section.get("excludes") or [], "exclude")
return DerivedScope(
source=SOURCE_DECLARED,
## NAMES THE FILE IT WAS ACTUALLY READ FROM, or the caller when the scope was
## stated — never a file that need not exist, which sends an owner to edit nothing.
reason=(
f"{INDEX_SCOPE_SECTION} stated by the caller (tier 1)"
if stated
else f"{INDEX_SCOPE_SECTION} declared in {source_path or root / DECLARATION_NAME}"
),
roots=tuple(roots),
excludes=tuple(excludes),
)
Activity · 19 steps
Flows
_descendable
list[str] clew.scope._descendable(Path here, list[str] dirnames, set[Path] already, list[Path] found)
Split one directory's children into those worth walking and those to exclude.
Source · 25 lines
def _descendable(
here: Path, dirnames: list[str], already: set[Path], found: list[Path]
) -> list[str]:
"""A NESTED REPOSITORY IS DESCENDED INTO (gh#333). It used to be skipped here,
which was consistent while the scope excluded it wholesale; now that it is indexed
and tagged, skipping it would leave its `.git` object store and its caches as the
one part of the tree nothing prunes. `_skip_dir` catches `.git` itself, because it
is a dot-directory like any other.
@brief Choose which child directories to descend into.
@return Descendable child names.
@version 2
"""
keep: list[str] = []
for name in dirnames:
child = here / name
if any(_is_within(child, path) for path in already):
continue
if _skip_dir(name):
found.append(child)
continue
keep.append(name)
return keep
Activity · 10 steps
Flows
_direct_parent
Path clew.scope._direct_parent(Path tree, Path root, list[Path] all_nested)
The closest containing root for one nested tree, among a repo's own split.
Source · 16 lines
def _direct_parent(tree: Path, root: Path, all_nested: list[Path]) -> Path:
"""A TREE'S OWN SUB-INDEX MUST EXCLUDE ITS DIRECT CHILDREN ONLY, mirroring exactly what
first-party already does relative to depth 1: `roots=[tree]` bounds a build's INPUT to
everything under `tree`, so a GRANDCHILD nested tree is still inside that boundary and
still needs an explicit exclude to stay out of it — this is what supplies that exclude
to the right level, rather than every nested tree's exclude list naming every deeper
descendant regardless of which parent actually contains it directly.
@brief Find which root (the repo, or another nested tree) directly contains `tree`.
@return The nearest containing ancestor.
@version 1
"""
ancestors = [c for c in (root, *all_nested) if c != tree and c in tree.parents]
return max(ancestors, key=lambda p: len(p.parts))
Activity · 2 steps
Flows
_existing_paths
list[Path] clew.scope._existing_paths(Path root, list entries, str label)
Resolve declared repo-relative entries that exist INSIDE the repository.
Source · 38 lines
def _existing_paths(root: Path, entries: list, label: str) -> list[Path]:
"""RESOLVE, THEN CONTAIN, THEN STAT — in that order, because the other orders are the
bug (1.1.0 security audit, H5). `roots:` is repo-relative BY CONTRACT and nothing here
enforced it: `(root / "/etc").resolve()` is `/etc`, since joining an absolute path
discards the left operand, and `../` simply walks out. An index built from such a
declaration is served as THIS repository's content under paths its owner never offered,
and the declaration can be STATED by an MCP caller for a repository it merely names.
Dropped with a warning rather than raised: this function already drops an entry that does
not exist, and dropping every root leaves `roots` empty, which the caller above turns into
the rejection an operator sees. One failure mode, one existing message path.
@brief Resolve declared paths, dropping ones that escape the repo or do not exist.
@return Contained, existing absolute paths.
@version 2
"""
found = []
resolved_root = root.resolve()
for entry in entries:
path = (resolved_root / str(entry)).resolve()
if not _is_within(path, resolved_root):
logger.warning(
"index_scope %s %r resolves to %s, OUTSIDE %s — refusing it. Declared paths "
"are repository-relative; an absolute or `../` entry is not honoured.",
label,
entry,
path,
resolved_root,
)
elif path.exists():
found.append(path)
else:
logger.warning(
"index_scope %s %r does not exist under %s — ignoring", label, entry, root
)
return found
Activity · 11 steps
Flows
_first_party
SubIndex clew.scope._first_party(Path root, list[Path] direct, set[Path] git_ignored)
The first-party SubIndex from a repository's direct nested trees and its ignores.
Source · 15 lines
def _first_party(root: Path, direct: list[Path], git_ignored: set[Path]) -> SubIndex:
"""ONE RULE FOR BOTH ROUTES, so the full split and the shortcut cannot drift into naming two
different first-party scopes.
@brief Assemble the first-party SubIndex.
@return The SubIndex.
@version 1
"""
return SubIndex(
name=FIRST_PARTY_INDEX,
roots=(root,),
excludes=tuple(direct + _own_ignores(root, direct, git_ignored)),
)
Activity · 1 steps
Flows
_gitignored_paths
IgnoreSweep clew.scope._gitignored_paths(Path root)
Paths the repo's own git configuration ignores.
Source · 59 lines
def _gitignored_paths(root: Path) -> IgnoreSweep:
"""`.gitignore` is the one scope declaration essentially every repo already
writes, and it names exactly the trees the whole-repo tier must not swallow: the
virtualenv, the build output, the tool caches, the vendored checkout.
`--directory` collapses a wholly-ignored directory into a single entry, so the
result is a handful of paths rather than one per ignored file.
Git being absent, or the tree not being a repository, yields no exclusions and
says so: the scope still works, it is just wider than the repo asked for, and a
silently wider index is the outcome this project keeps paying for.
@brief List the paths git ignores under a repo root.
@return The sweep.
@version 4
"""
## `git_argv` RATHER THAN A BARE "git": the tree being inspected can set
## `core.fsmonitor` in its OWN `.git/config`, which git then RUNS on this very query —
## so pointing clew at a cloned repository was arbitrary code execution. `-c` on the
## command line outranks the config file; see `gitenv.GIT_COMMAND_VALUED_KEYS`.
command = git_argv(
"-C",
str(root),
"ls-files",
"-z",
"--others",
"--ignored",
"--exclude-standard",
"--directory",
)
try:
## `env=git_env()` and NOT the inherited environment: `git -C <root>` is OUTRANKED
## by an absolute `GIT_DIR`, which git exports to every hook it runs — so without
## this the ignore list belongs to whatever repository invoked us. See `gitenv`.
proc = subprocess.run(
command,
capture_output=True,
text=True,
check=False,
env=git_env(),
timeout=GIT_TIMEOUT_SECONDS,
)
except OSError as exc:
logger.warning("index_scope: git is unavailable (%s) — nothing ignored was excluded", exc)
return IgnoreSweep((), False, f"git is unavailable ({exc})")
if proc.returncode != 0:
logger.warning(
"index_scope: %s is not a git repository (git exit %d) — nothing ignored was "
"excluded from the whole-repo scope",
root,
proc.returncode,
)
return IgnoreSweep(
(), False, f"{root} is not a git repository (git exit {proc.returncode})"
)
found = tuple((root / entry).resolve() for entry in proc.stdout.split("\0") if entry)
return IgnoreSweep(found, True)
Activity · 11 steps
Flows
_holds_git_tree
bool clew.scope._holds_git_tree(Path directory)
Whether a directory owns a git tree, as a SUBMODULE or as a clone.
Called by _nested_repos_under, test_the_git_tree_probe_answers_no_for_an_unreadable_directory
Calls none
Source · 39 lines
def _holds_git_tree(directory: Path) -> bool:
"""A SUBMODULE'S `.git` IS A FILE, NOT A DIRECTORY, and missing that made the
whole nested-tree feature blind to the case it was built for. A `git submodule`
checkout writes a 44-byte `gitdir: ../../.git/modules/<name>` POINTER file where
a standalone clone has a directory — so `".git" in dirnames`, which is what this
used to be, found nested CLONES and silently skipped every submodule.
Measured on [tvanfossen/entropic](https://github.com/tvanfossen/entropic), which
wraps llama.cpp as a submodule: the directory test reported 28 nested trees and
`extern/llama.cpp` was not among them, while reporting 28 hits made the detector
look like it was working. Every unit fixture used a `.git` DIRECTORY, so nothing
in the suite could have caught it — the fixture matched the detector rather than
the world.
`exists()` covers both, and covers a worktree's `.git` file too.
THIS PREDICATE ANSWERS EXACTLY ONE QUESTION — "is there a separate git tree here?" — and
gh#352 half 2 first tried to make it answer two. Folding the gitlink test in (below) broke
the OTHER consumer: `_whole_repo_scope` walks these trees to honour each one's own
`.gitignore`, because `git ls-files` stops at any tree boundary, submodule or clone alike.
A developer's nested clone still hides its build output from its parent, so descent has to
see it whether or not the parent declared it. Ownership is a different question with a
different predicate — see `_is_dependency_of_parent`.
UNREADABLE IS "NO", SAID ONCE (#72 bug 1, 2.1): a directory without the search bit (a device log
pulled in at mode 0644) raised PermissionError here and failed the whole index. It cannot hold a
tree clew could read, so the answer is no, with a warning naming it.
@brief Test whether a directory holds its own git tree.
@return True for a nested clone, submodule or worktree.
@version 3
"""
try:
return (directory / ".git").exists()
except OSError as exc:
logger.warning("skipping %s: it cannot be searched (%s)", directory, exc.strerror or exc)
return False
Activity · 5 steps
Flows
_ignore_clause
str clew.scope._ignore_clause(IgnoreSweep sweep)
The scope reason's clause about ignored paths, true to what git actually answered.
Source · 18 lines
def _ignore_clause(sweep: IgnoreSweep) -> str:
"""THE CLAUSE MUST NOT OUTRUN THE MEASUREMENT. It used to read "less the paths git ignores"
unconditionally, so a tree git could not answer for got a reason claiming an exclusion that
never happened — beside a WARNING saying the opposite.
@brief Describe the ignore exclusion honestly.
@return Clause text.
@version 1
"""
if sweep.asked:
return "less the paths git ignores and the dot/cache directories."
return (
f"less ONLY the dot/cache directories: the ignore list could NOT be obtained "
f"({sweep.detail}), so NOTHING git would ignore was excluded and this scope is wider "
f"than the repository asked for."
)
Activity · 3 steps
Flows
_is_within
bool clew.scope._is_within(Path path, Path ancestor)
Whether a path is the same as, or inside, another.
Source · 5 lines
def _is_within(path: Path, ancestor: Path) -> bool:
"""@brief Containment test used to suppress already-declared exclusions."""
return path == ancestor or ancestor in path.parents
Activity · 1 steps
Flows
_nested_repos_under
list[Path] clew.scope._nested_repos_under(Path input_root)
Directories holding a .git strictly beneath one declared root.
Source · 36 lines
def _nested_repos_under(input_root: Path) -> list[Path]:
"""A BOUNDED walk, not `rglob`. `rglob` would descend into the object stores of the
repositories it finds and swallow an unreadable directory silently — and a swallowed
error here reads exactly like "no nested repository", which is the answer that lets
a foreign codebase into the index. `onerror` therefore WARNS: a directory we could
not read is a gap in the check, not a clean result.
Descent stops at a nested repository (its own nested repositories are already
excluded with it) and at `_MAX_DEPTH`. The root itself never counts, so declaring a
directory that IS a repository does not exclude the whole scope.
@brief Find nested repositories under one declared root.
@return Paths of nested repository directories.
@version 2
"""
found: list[Path] = []
for dirpath, dirnames, _ in os.walk(input_root, onerror=_warn_unwalkable):
here = Path(dirpath)
if here != input_root and _holds_git_tree(here):
found.append(here)
dirnames[:] = []
continue
if len(here.relative_to(input_root).parts) >= _MAX_DEPTH:
logger.warning(
"index_scope: depth limit reached under %s — not checking %s for nested "
"repositories",
input_root,
here,
)
_DEPTH_LIMITED.append(here)
dirnames[:] = []
continue
dirnames[:] = [d for d in dirnames if not _skip_dir(d)]
return found
Activity · 14 steps
Flows
_nested_trees_recursive
list[Path] clew.scope._nested_trees_recursive(Path under, set[Path] ignored)
Every nested git tree under one root, at ANY depth.
Called by derive_sub_indexes
Calls _gitignored_paths, _under_any, list, nested_repo_roots
Source · 36 lines
def _nested_trees_recursive(under: Path, ignored: set[Path]) -> list[Path]:
"""`nested_repo_roots` ITSELF ALREADY STOPS DESCENT at the first `.git` it finds — by
design, so a submodule's OWN internals are not walked for the boundary that owns them.
That is exactly right for ONE level and exactly wrong for splitting: it is also why a
vendored tree's OWN vendored trees (b12-slam's boost/opencv/pcl, libBissellIoT's own
curl/mbedtls/paho) were swallowed whole into their parent's sub-index instead of getting
their own. Recursing HERE — calling `nested_repo_roots` again from INSIDE each tree it
finds — is what gives each of those its own identity, without changing what any single
call does.
`ignored` IS EXTENDED PER LEVEL, not reused unchanged. A tree's own `.gitignore` is
invisible to a walk rooted above it (`git ls-files` stops at every boundary, the same
reason `whole_repo_scope` asks each nested tree for its own ignores rather than the
parent's), so a CMake `_deps`-style throwaway clone nested two levels down needs the
SAME filtering a one-level-down one already gets — extending the set per level is what
makes that consistent at any depth rather than only the first.
BOUNDED BY THE FILESYSTEM, NOT BY A COUNTER. Each call's own walk is capped by
`_MAX_DEPTH` as always; recursion terminates because real nesting bottoms out at a
finite number of actual git-tree boundaries, which a vendored dependency graph never
has many of even when it has more than one.
@brief Recursively find nested git trees at every depth under one root.
@return Every nested tree found, unsorted, at any depth.
@version 2
"""
direct = sorted(
p for p in {q.resolve() for q in nested_repo_roots(under)} if not _under_any(p, ignored)
)
found = list(direct)
for tree in direct:
deeper_ignored = ignored | {p.resolve() for p in _gitignored_paths(tree).paths}
found.extend(_nested_trees_recursive(tree, deeper_ignored))
return found
Activity · 6 steps
Flows
_own_ignores
list[Path] clew.scope._own_ignores(Path tree, list[Path] children, set[Path] git_ignored)
One tree's own gitignored paths, minus anything a child tree already excludes.
Source · 8 lines
def _own_ignores(tree: Path, children: list[Path], git_ignored: set[Path]) -> list[Path]:
"""@brief A tree's own ignores. @return Sorted paths. @version 1"""
kids = set(children)
return sorted(
p for p in git_ignored if p != tree and _under_any(p, {tree}) and not _under_any(p, kids)
)
Activity · 2 steps
Flows
_pruned_dirs
list[Path] clew.scope._pruned_dirs(Path root, set[Path] already, set[Path] nested, list[Path]|None vendored=None)
Dot and cache directories anywhere under a whole-repo root.
Source · 56 lines
def _pruned_dirs(
root: Path,
already: set[Path],
nested: set[Path],
vendored: list[Path] | None = None,
) -> list[Path]:
"""`_skip_dir` is this module's rule for a directory no repo declares and none
wants indexed. Under a declared root it is applied by pruning the walk that
builds the roots; the whole-repo root is never walked for its files, so the same
rule has to reach doxygen as EXCLUDE entries instead.
@brief Collect the dot/cache directories a whole-repo scope must exclude.
@return Absolute directory paths.
@version 4
"""
found: list[Path] = []
for dirpath, dirnames, _ in os.walk(root, onerror=_warn_unwalkable):
here = Path(dirpath)
## gh#36. STOP AT A NESTED GIT TREE, taking its own top-level dot directories with us.
## Descending them cost ~24.6 s of every build on a repository vendoring boost, opencv
## and pcl — the whole 641 MB of boost read to collect `libs/*/.github` entries doxygen
## would skip by file pattern anyway, which were also 390-odd of the exclude entries
## that overflowed a client's reply limit (gh#37).
##
## gh#333's REASON IS KEPT, NOT DISCARDED. That change made this walk enter nested trees
## deliberately, because the whole-repo tier INDEXES them and their `.git` object store
## was the one part of the tree nothing pruned. So the tree's own top level is still
## collected — a nested CLONE's `.git` is a directory and is exactly that case — and
## only the descent below it stops. What is lost is a dot-directory eleven levels inside
## a vendored library, which is the thing that was never worth 641 MB to find.
##
## MEMBERSHIP, NOT A FILESYSTEM PROBE. The first version of this called `_holds_git_tree`
## per directory and cost two stats each — measured +68 ms on 6,000 first-party
## directories in a repository with nothing vendored, so the fix charged every repository
## for a boundary few have. The caller already holds the answer from gh#24's cached walk.
if here in nested:
found.extend(here / name for name in dirnames if _skip_dir(name))
dirnames[:] = []
continue
if len(here.relative_to(root).parts) >= _MAX_DEPTH:
logger.warning(
"index_scope: depth limit reached under %s — not pruning below %s", root, here
)
_DEPTH_LIMITED.append(here)
dirnames[:] = []
continue
dirnames[:] = _descendable(here, dirnames, already, found)
## ON THE WALK THAT ALREADY HAPPENS, never a second one: gh#36 measured this walk at
## 24.6 s on a repository vendoring boost, and a separate probe cost +68 ms per 6,000
## directories. Only children the walk is about to DESCEND are considered, so an
## excluded or ignored tree is never reported as indexed.
if vendored is not None:
vendored.extend(here / n for n in dirnames if n.lower() in _VENDORED_DIR_NAMES)
return found
Activity · 16 steps
Flows
_skip_dir
bool clew.scope._skip_dir(str name)
Whether a directory entry should be skipped outright by the walk.
Source · 5 lines
def _skip_dir(name: str) -> bool:
"""@brief Prune dot-directories and cache directories from the walk."""
return name.startswith(".") or name in _SKIP_DIR_NAMES
Activity · 1 steps
Flows
_sub_index_name
str clew.scope._sub_index_name(Path nested, Path repo_root)
Name a nested tree by its repo-relative path, safe as a directory component.
Source · 16 lines
def _sub_index_name(nested: Path, repo_root: Path) -> str:
"""DERIVED FROM THE RELATIVE PATH, NOT THE BASENAME, because two vendored trees can share a
basename — `a/dep` and `b/dep` — and colliding names would land both on one database, which
is the wrong-index failure this project has recorded as its most expensive.
Stability matters as much as uniqueness: nothing persists a mapping from name to database, so
this derivation IS the mapping, exactly as the path digest is for a whole-repo slug.
@brief Name one nested tree.
@return The sub-index name.
@version 1
"""
relative = nested.relative_to(repo_root).as_posix()
return "-".join(part for part in relative.split("/") if part)
Activity · 2 steps
Flows
_under_any
bool clew.scope._under_any(Path path, set[Path] roots)
Whether a path is one of, or inside, any of the given roots.
Source · 12 lines
def _under_any(path: Path, roots: set[Path]) -> bool:
"""EQUALITY AS WELL AS CONTAINMENT. An exclusion names the directory itself, so testing only
`parents` would keep a nested tree that IS the excluded path — and `build/_deps/catch2-src`
excluded exactly is the shape that occurs.
@brief Test containment against a set of roots.
@return Whether the path falls under any root.
@version 1
"""
return path in roots or any(parent in roots for parent in path.parents)
Activity · 1 steps
Flows
_vendored_clause
str clew.scope._vendored_clause(Path root, list[Path] vendored)
Name the indexed trees that look vendored, and how to exclude them.
Source · 31 lines
def _vendored_clause(root: Path, vendored: list[Path]) -> str:
"""ONLY THE OUTERMOST. `pkg/vendor/foo/vendor` is one vendored tree, not two, so a match
nested inside another match is dropped before counting — otherwise the count overstates how
much third-party code there is, and the count is the part a reader acts on.
BOUNDED, BUT THE TRUE COUNT SURVIVES. gh#37 is why the names are capped; a summary that
dropped the count would make 400 vendored trees read like 5.
@brief Disclose vendored-looking indexed trees.
@return Clause text.
@version 1
"""
outer = sorted(v for v in set(vendored) if not any(o != v and o in v.parents for o in vendored))
if not outer:
return ""
rels = [v.relative_to(root).as_posix() for v in outer]
shown = ", ".join(rels[:_VENDORED_NAMED])
if len(rels) > _VENDORED_NAMED:
shown += f" and {len(rels) - _VENDORED_NAMED} more"
one = len(rels) == 1
subject = (
"1 tree that looks vendored IS" if one else f"{len(rels)} trees that look vendored ARE"
)
pronoun = "it is" if one else "they are"
return (
f" {subject} indexed: {shown}. A committed dependency is excluded by no ignore rule; if "
f"{pronoun} third-party code, declare `{INDEX_SCOPE_SECTION}` in .clew.yaml to narrow "
f"the scope (propose_declaration drafts one)."
)
Activity · 11 steps
Flows
_warn_unwalkable
None clew.scope._warn_unwalkable(OSError error)
Report a directory the nested-repository check could not read.
Source · 9 lines
def _warn_unwalkable(error: OSError) -> None:
"""@brief Warn that a directory was unreadable, so a gap never reads as a pass."""
logger.warning(
"index_scope: could not read %s (%s) — it was NOT checked for a nested repository",
getattr(error, "filename", "?"),
error,
)
Activity · 1 steps
Flows
declared_scope_rejection
str | None clew.scope.declared_scope_rejection(Path repo_root, dict|None stated=None)
Whether the repo's own index_scope would be REJECTED, without the fallback.
Source · 22 lines
def declared_scope_rejection(repo_root: Path, stated: dict | None = None) -> str | None:
"""`derive_scope` ABSORBS a rejected declaration into the whole-repo tier — a
deliberate choice for every INTERNAL pipeline caller, which must always get back a
usable scope rather than an exception. That absorption is exactly what let an
excludes-only `.clew.yaml` cost B12_single_rgb a 900s doxygen timeout under a
vendored tree its own declaration was trying to keep out: the WARNING logged the
contradiction, and the build proceeded into the widest possible scope anyway.
This is the SEPARATE, BUILD-TIME check a caller who can still refuse (the MCP refresh
path, the CLI) runs before committing to a scope — the same relationship
`stale_code_refusal` has to the build it guards: a guard function, not a change to
what the guarded thing itself does. `derive_scope`'s own contract is untouched, so
every existing caller of THAT function keeps its current behaviour exactly.
@brief Report whether the declared or stated index_scope would be rejected.
@return The rejection reason, or None.
@version 1
"""
declared = _declared_index_scope(Path(repo_root).expanduser().resolve(), stated)
return str(declared) if isinstance(declared, _Rejected) else None
Activity · 2 steps
Requirements
Flows
declared_sub_index_excludes
tuple[str, ...] clew.scope.declared_sub_index_excludes(Path repo_root, str name, tuple[str,...]|Callable[[], tuple[str,...]] buildable, dict|None stated=None)
Excludes the parent repository declares for one of its named sub-indexes.
Source · 73 lines
def declared_sub_index_excludes(
repo_root: Path,
name: str,
buildable: tuple[str, ...] | Callable[[], tuple[str, ...]],
stated: dict | None = None,
) -> tuple[str, ...]:
"""gh#39. A REPOSITORY VENDORING A TREE THAT VENDORS NINE MORE could say nothing about it.
`_sub_index_scope` builds a vendored sub-index from its `roots` alone; a `.clew.yaml` inside
the nested tree is never read, because discovery is rooted at the parent and the tree is
upstream's anyway. So a 641 MB boost, a 217 MB opencv and a 142 MB pcl were indexed as part
of their parent and the build could not finish inside the 900 s doxygen cap.
THE PARENT'S DECLARATION RATHER THAN CALL METADATA, which was the alternative: excludes
stashed in the sub-index's own database on its first build and replayed afterwards. That
puts the value somewhere only the operator who made the call can see, so two operators of
one commit hold different indexes — the shape gh#352 rejected, and the reason the
`options.*` tier rows exist at all. A declaration is durable, reviewable in the same diff as
the code, and readable by everyone who clones the repository.
EVERY DECLARED NAME IS VALIDATED, not just the one being built. A block naming a tree this
repository does not vendor would otherwise sit in the file doing nothing while its author
believed it was trimming a build — this project's most repeated defect, and the reason the
keys inside an `index_scope` are checked as well as the section itself.
A STATED BLOCK REPLACES THE DECLARED ONE, tier 1 over tier 2, exactly as every other option
resolves — and replacing rather than adding is what lets an operator WITHDRAW a declared
exclude they disagree with. `declared_scope_rejection` takes `stated` for the same reason
one section over: a declaration section that could only be written into the target's tree is
unreachable for an operator who does not own it.
`buildable` MAY BE A CALLABLE, resolved only when there is a block to validate. The names
come from the full split, which walks every vendored tree, and most repositories declare no
`sub_indexes:` block, so a first-party refresh should not pay for a check with nothing to check.
@brief Read the declared or stated excludes for one sub-index, refusing what cannot apply.
@return The excludes, or ().
@version 3
"""
from .declaration import SECTION_SUB_INDEXES, load_declaration
declared = (
stated if stated is not None else load_declaration(repo_root).get(SECTION_SUB_INDEXES)
)
if not declared:
return ()
if not isinstance(declared, dict):
raise ValueError(
f"{SECTION_SUB_INDEXES} is {type(declared).__name__}, not a mapping of sub-index "
f"name to its scope."
)
if callable(buildable):
buildable = buildable()
unknown = sorted(str(k) for k in declared if str(k) not in buildable)
if unknown:
raise ValueError(
f"{SECTION_SUB_INDEXES} names {', '.join(repr(u) for u in unknown)}, which this "
f"repository does not derive. Buildable: {', '.join(repr(b) for b in buildable)}. "
f"Refusing rather than ignoring it, so a block that trims nothing cannot read as "
f"one that does."
)
entry = declared.get(name) or {}
if not isinstance(entry, dict):
raise ValueError(f"{SECTION_SUB_INDEXES}.{name} is {type(entry).__name__}, not a mapping.")
bad_keys = sorted(str(k) for k in entry if str(k) not in _SUB_INDEX_KEYS)
if bad_keys:
raise ValueError(
f"{SECTION_SUB_INDEXES}.{name} carries {', '.join(repr(k) for k in bad_keys)}; only "
f"{', '.join(sorted(_SUB_INDEX_KEYS))} is accepted. A sub-index's roots are its "
f"tree, derived from the repository, and are not restatable here."
)
return tuple(str(p) for p in (entry.get("excludes") or []))
Activity · 18 steps
Requirements
Flows
dependency_roots
list[Path] clew.scope.dependency_roots(Path repo_root)
Nested trees the repo itself DECLARES as dependencies (submodule gitlinks).
Source · 18 lines
def dependency_roots(repo_root: Path) -> list[Path]:
"""THE SUBSET OF `nested_repo_roots` THE PARENT OWNS UP TO. Two questions were being
answered by one predicate until gh#352 half 2: descent (does this tree hide its own build
output from its parent?) and ownership (is this somebody else's code?). Both walks are the
same walk; only the filter differs, so they share `_nested_repos_under` and diverge here.
Descent must see every separate git tree, including a developer's stray clone, because
`git ls-files` stops at any tree boundary. Ownership must see only what the repository
committed as a gitlink — see `_is_dependency_of_parent` for the measurement that forced
the split.
@brief List the nested trees the repo declares as dependencies.
@return Absolute paths of dependency trees.
@version 1
"""
return [n for n in nested_repo_roots(repo_root) if _is_dependency_of_parent(n)]
Activity · 1 steps
Requirements
derive_scope
DerivedScope clew.scope.derive_scope(Path repo_root, dict|None stated=None)
Resolve the index scope: a declared index_scope, else the whole repository.
Called by _check_indexable, _resolve_doxyfile_and_root, _scope_provenance, build_context, derive_scope_logged
Tested by 20 tests
test_a_declared_exclude_outside_the_repository_is_dropped, test_a_declared_index_scope_is_the_decision, test_a_declared_root_indexes_a_nested_repository, test_a_declared_root_outside_the_repository_is_refused, test_a_deep_tree_records_where_the_walk_stopped, test_a_gate_pattern_alone_derives_no_index_scope, test_a_repo_declaring_nothing_still_reports_absence, test_a_shallow_tree_records_nothing, test_an_already_excluded_nested_repository_is_not_re_reported, test_an_index_scope_declaration_is_what_yields_roots, test_an_index_scope_with_no_roots_says_so_rather_than_claiming_none_is_declared, test_an_unknown_key_inside_index_scope_refuses_by_name 8 more
test_declared_index_scope_drops_paths_that_do_not_exist, test_empty_or_absent_index_scope_falls_back_to_the_whole_repo, test_no_declaration_yields_the_whole_repo, test_no_tier_hands_back_a_rootless_scope, test_the_declared_reason_names_the_file_it_was_read_from, test_the_record_is_reset_per_derivation, test_the_scope_fallback_names_where_it_looked, test_unparseable_config_falls_back_to_the_whole_repo
Source · 39 lines
def derive_scope(repo_root: Path, stated: dict | None = None) -> DerivedScope:
"""Read the declaration and hand back its roots. Every failure mode — no config,
no `index_scope:` section, no declared root that exists — falls through to
`whole_repo_scope`, which carries the REASON, so the caller can log which scope
was used and why. Nothing is ever silently guessed.
THE DOXYFILE FALLBACK IS GONE (gh#333). It used to sit here and name no roots at
all, which handed the indexed tree to the Doxyfile's own INPUT — a documentation
target standing in for a reasoning boundary. `_doxyfile_fallback`'s one surviving
job, saying WHERE a declaration was looked for, is now a clause inside the
whole-repo reason.
NO CONTAINMENT PASS. Every scope this module handed out used to run through
`_with_nested_repos_contained`, which cut nested git trees out of it. They are
now indexed and tagged instead (`external.py`), so the choke point was removed
rather than bypassed — a containment call left in place with its callers removed
is a safety property that reads as enforced and is not.
@brief Resolve INPUT roots from the repo's own index-scope declaration.
@return The declared scope, or the whole-repo tier.
@version 9
"""
## CLEARED HERE BECAUSE THIS IS THE SINGLE ENTRY POINT, so `depth_limited_paths()` after a
## derivation describes THAT derivation and not an accumulation across several. The build
## derives more than once — `_scope_provenance` re-derives on the whole-repo tier — and a
## record that grew across them would report the same directory two or three times and read
## as a wider problem than exists.
_DEPTH_LIMITED.clear()
root = Path(repo_root).expanduser().resolve()
declared = _declared_index_scope(root, stated)
if isinstance(declared, _Rejected):
## SAID OUT LOUD, not only returned. The contradiction gh#5 reports is between two LOG
## lines, so the correction has to reach the log too — a reason carried only in the
## payload leaves the WARNING still claiming absence.
logger.warning("index_scope: %s", declared)
return whole_repo_scope(root, rejected=str(declared))
return declared or whole_repo_scope(root)
Activity · 7 steps
Requirements
Flows
derive_scope_logged
DerivedScope clew.scope.derive_scope_logged(Path repo_root, dict|None stated=None)
Derive a scope and log which scope was used and why.
Source · 25 lines
def derive_scope_logged(repo_root: Path, stated: dict | None = None) -> DerivedScope:
"""Fail SAFE and LOUD: a declared derivation logs its roots at INFO, the
whole-repo default logs its reason at WARNING so a boundary nobody chose is never
mistaken for one somebody did.
The undeclared branch no longer says "falling back to the Doxyfile INPUT", which
since gh#333 would be a checkable and wrong statement about what got indexed —
the same defect class as stamping `source: doxyfile` on a whole-repo build.
@brief Derive the index scope with an explicit log line.
@return The derived (or whole-repo) scope.
@version 6
"""
scope = derive_scope(repo_root, stated)
if scope.is_derived():
logger.info(
"scope: declared — %s — %d INPUT root(s), %d EXCLUDE(s): %s",
scope.reason,
len(scope.roots),
len(scope.excludes),
", ".join(str(p) for p in scope.roots),
)
else:
logger.warning("scope: indexing the WHOLE repository — %s", scope.reason)
return scope1 more lines, not shown
Activity · 6 steps
Requirements
derive_sub_indexes
list[SubIndex] clew.scope.derive_sub_indexes(Path repo_root)
Split a repository into first-party and per-nested-tree indexes, at any depth.
Called by _buildable_sub_indexes, _offered_sub_indexes, _sub_index_scope, build_sub_indexes
Tested by 11 tests
test_a_child_trees_ignores_are_not_repeated_on_the_parent, test_a_first_party_refresh_never_walks_inside_a_vendored_tree, test_a_nested_trees_own_nested_trees_get_their_own_sub_index, test_a_repo_without_nested_trees_is_not_split, test_a_vendored_sub_index_excludes_its_own_gitignored_build, test_every_derived_sub_index_name_is_discoverable, test_ignored_nested_trees_are_not_sub_indexes, test_names_are_unique_stable_and_path_safe, test_submodules_and_clones_both_become_sub_indexes, test_the_cheap_first_party_split_equals_the_derived_one, test_the_tree_itself_is_never_in_its_own_excludes
Calls _direct_parent, _first_party, _gitignored_paths, _nested_trees_recursive, _own_ignores, _sub_index_name, whole_repo_scope
Source · 82 lines
def derive_sub_indexes(repo_root: Path) -> list[SubIndex]:
"""EMPTY MEANS "DO NOT SPLIT", and that is the compatibility contract. A repository with
nothing vendored must keep building to one index under the slug it already has — splitting it
would allocate a new slug and strand the index on disk, whose symptom is "no database has been
built" against a perfectly good one.
REUSES `nested_repo_roots`, which the pipeline already runs on every build and which handles
BOTH on-disk shapes of a nested repository: a clone's `.git` directory and a submodule's
`gitdir:` pointer FILE. That distinction is not academic — a detector seeing only directories
finds nested clones and silently skips every submodule, which is the case this split exists
for.
N LEVELS DEEP, NOT ONE. Field-reported: a vendored dependency that itself vendors several
more (a 1.2GB tree carrying boost, opencv, pcl and six others as its own submodules) was
getting ONE sub-index for the whole thing, dominated entirely by code none of it wrote.
Every nested tree found anywhere in the repository — at any depth — gets its own name and
its own sub-index; each one's `excludes` names exactly its own direct children, the same
relationship first-party already has to depth 1, so building it does not silently swallow
what belongs one level further down.
@brief Derive the sub-index split from nested git trees, at any depth.
@return The split, or [] to build the repository whole.
@version 6
"""
root = Path(repo_root).expanduser().resolve()
## THE SPLIT USES THE BUILD'S OWN RULE, and skipping this cost a real target twenty minutes.
## `nested_repo_roots` walks the WHOLE tree, so it finds every git clone on disk — including
## CMake FetchContent output under `build/`, which is a genuine clone and pure throwaway.
## Driving a real repository produced sub-indexes named `build-coverage-_deps-catch2-src`,
## `build-dev-_deps-httplib-src` and six more, each being indexed in turn, while every
## fixture test passed.
##
## `whole_repo_scope` already computes what the build excludes — git-ignored paths, plus each
## nested tree's own ignores, which `git ls-files` cannot see through. Reusing it is what
## keeps the split and the build agreeing about what the repository contains; deriving a
## second rule here would leave the split free to index trees the build would never touch,
## and the split is the one nobody looks at.
ignored = {p.resolve() for p in whole_repo_scope(root).excludes}
nested = sorted(set(_nested_trees_recursive(root, ignored)))
if not nested:
return []
## EACH TREE EXCLUDES ONLY ITS OWN DIRECT CHILDREN, not every deeper descendant — a
## grandchild is already excluded from ITS OWN parent's build, which is the tree one level
## up from it, not from every ancestor above that.
children_of: dict[Path, list[Path]] = {}
for tree in nested:
parent = _direct_parent(tree, root, nested)
children_of.setdefault(parent, []).append(tree)
## gh#23. A DERIVED SCOPE IS NOT A CURATED ONE, and that is why it must carry the ignores.
## A sub-index builds through a DECLARED `index_scope`, which the resolver takes at its word
## and never walks — correct for a human-written `.clew.yaml`, where walking would overrule
## the author. But THIS declaration is machine-derived, so nobody ever told it to skip the
## vendored tree's own `build/`, and a vendored dependency shipping generated headers there
## had `search` resolving symbols into throwaway output.
##
## ASKS GIT, NOT THE MERGED EXCLUDE SET. `ignored` above is gitignored paths PLUS the dot
## and cache directories `_pruned_dirs` adds, and folding those in would put `.git` into
## every sub-index's excludes — harmless but untrue to what this is for, and it broke the
## split test's own statement that a tree with no ignores of its own excludes nothing.
## What belongs here is exactly what the tree's own git says to ignore.
##
## Per tree rather than per repository, so this stays proportional to the number of
## vendored trees rather than repeating the whole-tree walk gh#24 just removed.
git_ignored = {p.resolve() for p in _gitignored_paths(root).paths}
for tree in nested:
git_ignored |= {p.resolve() for p in _gitignored_paths(tree).paths}
first = _first_party(root, children_of.get(root, []), git_ignored)
others = []
for tree in nested:
kids = children_of.get(tree, [])
others.append(
SubIndex(
name=_sub_index_name(tree, root),
roots=(tree,),
excludes=tuple(kids + _own_ignores(tree, kids, git_ignored)),
)
)
return [first] + others
Activity · 18 steps
Requirements
Flows
first_party_sub_index
SubIndex | None clew.scope.first_party_sub_index(Path repo_root)
The first-party sub-index of a split repository, without walking any vendored tree.
Called by _first_build_worker, _sub_index_rejection, _sub_index_scope
Tested by
Calls _first_party, _gitignored_paths, _under_any, nested_repo_roots, whole_repo_scope
Source · 27 lines
def first_party_sub_index(repo_root: Path) -> SubIndex | None:
"""gh#48's "<10 s nominally", on the repository that set the bar. `derive_sub_indexes`
recurses INTO every vendored tree to find the trees nested inside it: 24.6 s per pass on a
repository vendoring boost, opencv and pcl. A first-party refresh paid for four passes. None
of that recursion can change first-party's scope. First-party excludes its DIRECT nested
trees whole, so what lies inside them is irrelevant, and the ignore paths a vendored tree
contributes all sit under a direct child and are filtered out.
So this reads only what the full derivation's first entry reads: the root's non-ignored
direct nested trees, from a walk that stops at every nested boundary, and the root's own git
ignores. `tests/test_first_party_walk.py` pins equality with the full derivation on a
depth-2 fixture with ignored clones on both sides of a boundary.
@brief Derive only the first-party sub-index, cheaply.
@return The SubIndex, or None when the repository has no nested trees.
@version 2
"""
root = Path(repo_root).expanduser().resolve()
ignored = {p.resolve() for p in whole_repo_scope(root).excludes}
direct = sorted(
p for p in {q.resolve() for q in nested_repo_roots(root)} if not _under_any(p, ignored)
)
if not direct:
return None
return _first_party(root, direct, {p.resolve() for p in _gitignored_paths(root).paths})
Activity · 6 steps
Requirements
Flows
is_derived
bool clew.scope.DerivedScope.is_derived(self)
Whether this scope should override the Doxyfile's INPUT.
Source · 5 lines
def is_derived(self) -> bool:
"""@brief Whether a declaration produced usable roots."""
return self.source == SOURCE_DECLARED and bool(self.roots)
Activity · 1 steps
Requirements
Flows
nested_repo_roots
list[Path] clew.scope.nested_repo_roots(Path repo_root)
Directories holding their own git tree anywhere under a repo root.
Called by _nested_trees_recursive, dependency_roots, first_party_sub_index, whole_repo_scope
Tested by
Calls _nested_repos_under
Source · 32 lines
def nested_repo_roots(repo_root: Path) -> list[Path]:
"""THE SAME WALK THAT USED TO EXCLUDE THESE TREES, made public so gh#335 can tag
them instead. The pipeline already computed this answer on every build and threw
it away into a WARNING — the identical shape as the scope provenance that gh#319
persisted, and as the macro hop doxygen was already emitting.
A directory holding `.git` is a DIFFERENT repository. That is the ONLY test, and
the rule is deliberately not name-based: `vendor/` and `third_party/` are
conventions, not facts, and a copied-in third-party header with no git tree of its
own IS first party — the repo committed it and owns it, so its metrics should say
so.
The root ITSELF is never nested, so a root that IS a repository does not report
itself.
SHARED ACROSS ONE BUILD (gh#24) when `nested_tree_cache` is active, because three
callers ask this same question about the same root and a walk of a large tree is the
dominant cost of an otherwise-incremental refresh. Keyed on the RESOLVED root so two
callers spelling the same tree differently still share the answer.
@brief Find the nested git trees under a repo root.
@return Absolute paths of nested repository directories.
@version 2
"""
root = Path(repo_root).expanduser().resolve()
if _NESTED_CACHE is None:
return _nested_repos_under(root)
if root not in _NESTED_CACHE:
_NESTED_CACHE[root] = _nested_repos_under(root)
return _NESTED_CACHE[root]
Activity · 6 steps
Requirements
Flows
nested_tree_cache
Iterator[None] clew.scope.nested_tree_cache()
Share one nested-tree walk across everything a single build asks.
Source · 20 lines
def nested_tree_cache() -> Iterator[None]:
"""REENTRANT, AND THE OUTERMOST WINS. `build_index` opens one; a caller that has already
opened its own must not have the inner exit clear the cache out from under the rest of
the build, so an inner activation is inert rather than a second scope.
@brief Cache nested-tree walks for the duration of one build.
@return Generator yielding once.
@version 1
"""
global _NESTED_CACHE
if _NESTED_CACHE is not None:
yield
return
_NESTED_CACHE = {}
try:
yield
finally:
_NESTED_CACHE = None
Activity · 7 steps
Requirements
Flows
normalize_scope
str | None clew.scope.normalize_scope(str|None scope)
Resolve a caller's scope spelling to the value this codebase records.
Called by build_index
Tested by
Calls none
Source · 13 lines
def normalize_scope(scope: str | None) -> str | None:
"""NORMALIZING IS NOT VALIDATING, and the distinction is load-bearing. The refusal for an
unknown scope lives where the Doxyfile is resolved and already names the two values it
accepts with a reason; mapping an unknown value onto a default here would build a boundary
the caller never asked for and then report success — the silent-success failure this
release spent its blockers on.
@brief Map the `from-declaration` alias onto the recorded `from-guard`.
@return The recorded spelling, or the input unchanged.
"""
return SCOPE_FROM_GUARD if scope == SCOPE_FROM_DECLARATION else scope
Activity · 1 steps
Requirements
whole_repo_scope
DerivedScope clew.scope.whole_repo_scope(Path repo_root, str rejected="")
The whole repository as one INPUT root, less only what git ignores.
Called by derive_scope, derive_sub_indexes, first_party_sub_index
Tested by 12 tests
test_a_nested_repository_s_own_gitignore_is_honoured, test_a_nested_trees_own_top_level_dot_dirs_are_still_pruned, test_a_scope_that_could_not_ask_git_does_not_claim_it_excluded_ignores, test_a_targets_own_git_config_cannot_run_commands, test_an_indexed_tree_that_looks_vendored_is_named_with_the_remedy, test_dot_directories_are_excluded_from_the_whole_repo_scope, test_first_party_code_beside_the_vendored_tree_is_still_walked, test_first_party_platform_directories_are_not_reported_as_vendored, test_the_ignore_scope_answers_about_its_own_repo_inside_a_hook, test_the_nested_tree_itself_is_still_in_scope, test_the_vendored_disclosure_is_bounded, test_the_walk_does_not_descend_a_nested_tree
Calls _declaration_advice, _declaration_note, _gitignored_paths, _ignore_clause, _pruned_dirs, _vendored_clause, list, nested_repo_roots
Source · 64 lines
def whole_repo_scope(repo_root: Path, rejected: str = "") -> DerivedScope:
"""THE DEFAULT TIER since gh#333, not the last resort: reached whenever a repo
declares no `index_scope:`, whether or not it ships a Doxyfile.
Its single root is the whole repository, so a foreign clone parked anywhere
inside is inside it BY CONSTRUCTION — and since gh#333 that is the intent rather
than the hazard it used to be. entropic wraps llama.cpp; a `chain_trace` that
stopped at the submodule boundary said "this call leaves the repo" when it could
have said what the call does. `external.py` tags those rows so the two codebases
are still told apart in an answer.
The subtractions are what the repo has already said about itself — the paths git
ignores, on BOTH sides of every submodule boundary — plus the dot and cache
directories no repo restates. The doxygen-guard gate is NOT read here: the gate
answers what must be DOCUMENTED, and this tier exists because that is a different
question from what should be indexed.
@brief Build the whole-repo index scope.
@return The whole-repo scope.
@version 5
"""
root = Path(repo_root).expanduser().resolve()
sweep = _gitignored_paths(root)
ignored = list(sweep.paths)
## A SUBMODULE'S OWN `.gitignore` IS INVISIBLE TO THE PARENT. `git ls-files` stops
## at a submodule boundary, so the sweep above reports nothing inside a nested
## tree — and a nested tree is now INDEXED rather than excluded, which is exactly
## when its build output starts to matter. Asked per nested repo instead.
##
## gh#36. THE SAME LIST BOUNDS THE PRUNE WALK BELOW, which is what makes stopping at a
## nested tree free. `nested_repo_roots` is the walk gh#24 cached per build and this call
## site already paid for it; probing each directory for a `.git` instead cost two stats per
## directory everywhere — measured +68 ms on 6,000 first-party directories in a repository
## that vendors nothing, which is most of them.
nested_trees = nested_repo_roots(root)
for nested in nested_trees:
ignored.extend(_gitignored_paths(nested).paths)
vendored: list[Path] = []
excludes = [
*ignored,
*_pruned_dirs(root, set(ignored), {p.resolve() for p in nested_trees}, vendored),
]
return DerivedScope(
source=SOURCE_WHOLE_REPO,
## PRESENT-BUT-UNUSABLE IS NOT ABSENT (gh#5). A declaration carrying an `index_scope:`
## that yields no roots used to land here and report "no index_scope is declared" — while
## the loader had already logged "<file> declares index_scope" seconds earlier. A reporter
## got both lines from one build and could not tell whether to fix their YAML or file a
## bug; only `propose_declaration` settled it, and nobody reaches for that after a build
## reports success. `rejected` REPLACES the absence clause, never appends to it.
reason=(
(rejected if rejected else f"no {INDEX_SCOPE_SECTION} is declared for this repo")
+ f" — {_declaration_note(root)} — so the whole repository is the "
f"index scope, INCLUDING any nested git trees, {_ignore_clause(sweep)}"
f"{_vendored_clause(root, vendored)} "
f"A Doxyfile, if the repo ships one, still "
f"supplies ALIASES and PREDEFINED but no longer supplies the INPUT: that is "
f"a documentation target, not a reasoning boundary. {_declaration_advice()}"
),
roots=(root,),
excludes=tuple(excludes),
)