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.

clew/toolchain.py:150

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
lines 157–157◇ if not isinstance(entry, dict) or entry.get("rule")lines 158–158return ()lines 159–159patterns = [entry.get("file"), entry.get("file_glob")]lines 160–160return tuple(p for p in patterns if isinstance(p, str) and p)

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.

clew/toolchain.py:108

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
lines 115–115from .tomlcompat import require_toml_modulelines 117–117trylines 118–118with path.open("rb") as handlelines 119–119data = require_toml_module().load(handle)lines 120–120except (OSError, ValueError) as exclines 121–121problems.append(f"{path.name}: could not be read ({exc}) — its exclusions are ignored")lines 122–122return {}lines 123–123return data if isinstance(data, dict) else {}

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.

clew/toolchain.py:134

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
lines 136–136value = table.get(key) if isinstance(table, dict) else Nonelines 137–137◇ if value is Nonelines 138–138return ()lines 139–139◇ if not isinstance(value, list) or not all(isinstance(v, str) for v in value)lines 140–140problems.append(f"{where}.{key} is not a list of strings — ignored")lines 141–141return ()lines 142–142return tuple(value)

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.

clew/toolchain.py:209

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
lines 216–216from lang_parsing_substrate import PathIgnorelines 218–218valid = []lines 219–219◇ for glob in globslines 220–220trylines 221–221PathIgnore([glob])lines 222–222except ValueError as exclines 223–223logger.warning("toolchain config: invalid glob %r ignored (%s)", glob, exc)lines 224–224continuelines 225–225valid.append(glob)lines 226–226return PathIgnore(valid) if valid else None

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.

clew/toolchain.py:256

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
lines 274–274matcher = compile_globs(globs)lines 275–275◇ if matcher is Nonelines 276–276return []lines 277–277root = Path(repo_root)lines 278–278pruned = {str(Path(p)) for p in prune}lines 279–279out: list[Path] = []lines 280–280◇ for dirpath, dirnames, filenames in os.walk(root)lines 281–281here = Path(dirpath)lines 282–282rel_here = "" if here == root else here.relative_to(root).as_posix() + "/"lines 283–283keep = []lines 284–284◇ for name in sorted(dirnames)lines 285–285full = here / namelines 286–286◇ if matches(matcher, rel_here + name, is_dir=True)lines 287–287out.append(full)lines 288–288continuelines 289–289◇ if name in _NEVER_WALK or str(full) in prunedlines 290–290continuelines 291–291keep.append(name)lines 292–292dirnames[:] = keeplines 293–293out += [here / f for f in sorted(filenames) if matcher.is_ignored(rel_here + f)]lines 294–294found = sorted(out)lines 301–301◇ if len(found) > _LARGE_EXPANSIONlines 302–308logger.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), )lines 309–309return found

Requirements

REQ-DDB-CONFIG-009

load_toolchain_config

ToolchainConfig clew.toolchain.load_toolchain_config(Path|str repo_root)

Locate and read a repository's toolchain.toml and suppress.toml.

clew/toolchain.py:168

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
lines 170–170root = Path(repo_root)lines 171–171toolchain = root / TOOLCHAIN_FILElines 172–172suppress = root / SUPPRESS_FILElines 173–173problems: list[str] = []lines 174–174index: list[str] = []lines 175–175gate: list[str] = []lines 177–177◇ if toolchain.is_file()lines 178–178data = _read_toml(toolchain, problems)lines 179–179index += _string_list(data.get("ignore"), "paths", "ignore", problems)lines 180–180own = data.get(TOOL_NAME) if isinstance(data.get(TOOL_NAME), dict) else {}lines 181–181gate += _string_list(own.get("ignore"), "paths", f"{TOOL_NAME}.ignore", problems)lines 183–183◇ if suppress.is_file()lines 184–184data = _read_toml(suppress, problems)lines 185–185entries = data.get("suppress", [])lines 186–186◇ for entry in entries if isinstance(entries, list) else []lines 187–187tool = entry.get("tool") if isinstance(entry, dict) else Nonelines 188–188◇ if tool == _ALL_TOOLSlines 189–189index += _entry_globs(entry)lines 190–190◇ elif tool == TOOL_NAMElines 191–191gate += _entry_globs(entry)lines 193–193◇ for problem in problemslines 194–194logger.warning("toolchain config: %s", problem)lines 195–201return 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), )

Requirements

REQ-DDB-CONFIG-009

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.

clew/toolchain.py:236

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 + "/")

Activity · 3 steps
lines 244–244◇ if matcher.is_ignored(rel)lines 245–245return Truelines 246–246return is_dir and matcher.is_ignored(rel + "/")

Flows