toolchain.py¶
clew/toolchain.py
The shared toolchain config: `toolchain.toml` ignores and `suppress.toml` entries.
_entry_globs
tuple[str, ...] clew.toolchain._entry_globs(Any entry)
The globs of one [[suppress]] entry that suppresses whole files.
Source · 13 lines
def _entry_globs(entry: Any) -> tuple[str, ...]:
"""An entry with a `rule` suppresses that rule only (AND semantics in the spec), so it
is not a file exclusion.
@brief File patterns of a file-level suppress entry.
@return The patterns.
"""
if not isinstance(entry, dict) or entry.get("rule"):
return ()
patterns = [entry.get("file"), entry.get("file_glob")]
return tuple(p for p in patterns if isinstance(p, str) and p)
Activity · 4 steps
Flows
_read_toml
dict[str, Any] clew.toolchain._read_toml(Path path, list[str] problems)
Read a TOML file into a mapping, recording rather than raising on failure.
Source · 18 lines
def _read_toml(path: Path, problems: list[str]) -> dict[str, Any]:
"""A broken shared config must not fail a build: every tool reads this file, and
clew refusing it would be the wrong severity. It is reported instead.
@brief Parse one TOML file tolerantly.
@return The mapping, or {}.
"""
from .tomlcompat import require_toml_module
try:
with path.open("rb") as handle:
data = require_toml_module().load(handle)
except (OSError, ValueError) as exc:
problems.append(f"{path.name}: could not be read ({exc}) — its exclusions are ignored")
return {}
return data if isinstance(data, dict) else {}
Activity · 8 steps
Flows
_string_list
tuple[str, ...] clew.toolchain._string_list(Any table, str key, str where, list[str] problems)
The string list at table[key] , or () when absent or malformed.
Source · 11 lines
def _string_list(table: Any, key: str, where: str, problems: list[str]) -> tuple[str, ...]:
"""@brief Read a list-of-strings value."""
value = table.get(key) if isinstance(table, dict) else None
if value is None:
return ()
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
problems.append(f"{where}.{key} is not a list of strings — ignored")
return ()
return tuple(value)
Activity · 7 steps
Flows
compile_globs
Any | None clew.toolchain.compile_globs(tuple[str,...] globs)
Compile globs into the substrate's matcher, dropping any that do not compile.
Source · 20 lines
def compile_globs(globs: tuple[str, ...]) -> Any | None:
"""One bad glob must not take the rest down with it, so each is checked on its own
and a refused one is reported by name.
@brief Build a PathIgnore from the valid globs.
@return The matcher, or None.
"""
from lang_parsing_substrate import PathIgnore
valid = []
for glob in globs:
try:
PathIgnore([glob])
except ValueError as exc:
logger.warning("toolchain config: invalid glob %r ignored (%s)", glob, exc)
continue
valid.append(glob)
return PathIgnore(valid) if valid else None
Activity · 10 steps
Flows
expand_globs
list[Path] clew.toolchain.expand_globs(Path repo_root, tuple[str,...] globs, Sequence[str] prune=())
Expand toolchain globs into the concrete paths they exclude under a root.
Called by _apply_toolchain_exclusions
Tested by 6 tests
test_a_declared_never_walk_directory_is_reported_as_an_exclusion, test_an_invalid_glob_does_not_disable_the_rest, test_an_undeclared_never_walk_directory_is_still_pruned_silently, test_matched_directories_are_returned_whole, test_pruned_directories_are_not_walked, test_the_gate_and_the_index_agree_on_one_declaration
Calls _relative, compile_globs, matches
Source · 56 lines
def expand_globs(repo_root: Path, globs: tuple[str, ...], prune: Sequence[str] = ()) -> list[Path]:
"""Doxygen's EXCLUDE and the tree scan take paths, not globs, so the globs are
resolved against the tree once per build. A matched directory is returned whole and
not descended into, which keeps `vendor/**` one exclusion rather than thousands.
MATCH BEFORE PRUNE (B3, 1.1.0 merge review). This tested `_NEVER_WALK` and the caller's
prune set FIRST, so a repository stating `node_modules/**` — or `.venv/**`, or
`**/__pycache__` — got `[]` back and the index's EXCLUDE never named the tree the owner
had just excluded. The gate matches the same globs directly and never walks, so it
honoured the statement; one `toolchain.toml` line meant two different things depending
on which half of clew read it. A declared never-walk name is now RETURNED as an
exclusion and still not descended into; an UNDECLARED one is still pruned silently,
because turning every incidental `node_modules` into an exclusion would put it in the
Doxyfile and in the cache key for no statement the owner made.
@brief Resolve globs to concrete excluded paths.
@return The excluded paths.
"""
matcher = compile_globs(globs)
if matcher is None:
return []
root = Path(repo_root)
pruned = {str(Path(p)) for p in prune}
out: list[Path] = []
for dirpath, dirnames, filenames in os.walk(root):
here = Path(dirpath)
rel_here = "" if here == root else here.relative_to(root).as_posix() + "/"
keep = []
for name in sorted(dirnames):
full = here / name
if matches(matcher, rel_here + name, is_dir=True):
out.append(full)
continue # returned whole; descending would add thousands of children
if name in _NEVER_WALK or str(full) in pruned:
continue # not declared, so not an exclusion — just not walked
keep.append(name)
dirnames[:] = keep
out += [here / f for f in sorted(filenames) if matcher.is_ignored(rel_here + f)]
found = sorted(out)
## AN EXPANSION THIS SIZE IS A GLOB, NOT A TREE. A correct declaration names directories
## and comes back with a handful of paths; thousands means a file-level pattern such as
## `**/*.c` matched individually, and every one of them lands in the Doxyfile's EXCLUDE
## and in the cache key. Reported rather than capped — the declaration is the owner's to
## make — and reported HERE rather than through `ToolchainConfig.problems`, which is built
## in `load_toolchain_config` and frozen long before any tree is walked.
if len(found) > _LARGE_EXPANSION:
logger.warning(
"toolchain config: %s resolved to %d excluded path(s) from %s — a directory glob "
"would be one exclusion instead of thousands",
_relative(root, root) or str(root),
len(found),
", ".join(globs),
)
return found
Activity · 24 steps
Requirements
load_toolchain_config
ToolchainConfig clew.toolchain.load_toolchain_config(Path|str repo_root)
Locate and read a repository's toolchain.toml and suppress.toml.
Called by _apply_toolchain_exclusions, _gate_matcher
Tested by
Calls _entry_globs, _read_toml, _string_list
Source · 36 lines
def load_toolchain_config(repo_root: Path | str) -> ToolchainConfig:
"""@brief Read the shared toolchain exclusions for one repo."""
root = Path(repo_root)
toolchain = root / TOOLCHAIN_FILE
suppress = root / SUPPRESS_FILE
problems: list[str] = []
index: list[str] = []
gate: list[str] = []
if toolchain.is_file():
data = _read_toml(toolchain, problems)
index += _string_list(data.get("ignore"), "paths", "ignore", problems)
own = data.get(TOOL_NAME) if isinstance(data.get(TOOL_NAME), dict) else {}
gate += _string_list(own.get("ignore"), "paths", f"{TOOL_NAME}.ignore", problems)
if suppress.is_file():
data = _read_toml(suppress, problems)
entries = data.get("suppress", [])
for entry in entries if isinstance(entries, list) else []:
tool = entry.get("tool") if isinstance(entry, dict) else None
if tool == _ALL_TOOLS:
index += _entry_globs(entry)
elif tool == TOOL_NAME:
gate += _entry_globs(entry)
for problem in problems:
logger.warning("toolchain config: %s", problem)
return ToolchainConfig(
toolchain_path=toolchain if toolchain.is_file() else None,
suppress_path=suppress if suppress.is_file() else None,
index_globs=tuple(dict.fromkeys(index)),
gate_globs=tuple(dict.fromkeys(index + gate)),
problems=tuple(problems),
)
Activity · 23 steps
Requirements
Flows
matches
bool clew.toolchain.matches(Any matcher, str rel, *bool is_dir=False)
Whether a repo-relative path matches, as a file or as a directory.
Source · 13 lines
def matches(matcher: Any, rel: str, *, is_dir: bool = False) -> bool:
"""globset reads `vendor/**` as matching `vendor/` and everything under it, but not
`vendor`; a bare `build` matches `build` and nothing under it. A directory is tested
both ways, so both spellings exclude the directory.
@brief Match one path against the toolchain globs.
@return True when excluded.
"""
if matcher.is_ignored(rel):
return True
return is_dir and matcher.is_ignored(rel + "/")