"""Measurements taken from the workspace: package graph, file sizes, source pattern counts.""" import json import pathlib import re import subprocess from .rustsource import cell_alternation, cell_holders, production_lines, requires_test, type_definitions TEST_DIRS = ("tests",) def load_metadata(root): """Workspace packages with their normal internal and external dependencies.""" cmd = ["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"] meta = json.loads(subprocess.run(cmd, cwd=root, check=True, capture_output=True, text=True).stdout) internal = {p["name"] for p in meta["packages"]} return sorted((_package(p, internal) for p in meta["packages"]), key=lambda p: p["name"]) def _package(raw, internal): normal = [d["name"] for d in raw["dependencies"] if d["kind"] is None] return { "name": raw["name"], "dir": pathlib.Path(raw["manifest_path"]).parent, "normal": sorted({n for n in normal if n in internal}), "external": sorted({n for n in normal if n not in internal}), } def rust_files(directory): """Every .rs file under a directory except build output.""" for path in sorted(directory.rglob("*.rs")): if "target" not in path.relative_to(directory).parts: yield path def _text(path): return path.read_text(encoding="utf-8", errors="replace") def file_lines(root, packages): """{relative posix path: line count} for every .rs file in a workspace package.""" sizes = {} for pkg in packages: for path in rust_files(pkg["dir"]): sizes[path.relative_to(root).as_posix()] = len(_text(path).splitlines()) return sizes def mechanical_names(root, packages, config): """Sorted relative paths of the .rs files whose NAME is a leftover of a mechanical split (`impl_*.rs`, `*_fn.rs`, `*_.rs`): a name must say what the module is and what it is for. `allow` lists legitimate stems.""" bad = [re.compile(p) for p in config.get("patterns", [])] ok = [re.compile(p) for p in config.get("allow", [])] found = set() for pkg in packages: for path in rust_files(pkg["dir"]): if any(p.search(path.name) for p in bad) and not any(p.search(path.name) for p in ok): found.add(path.relative_to(root).as_posix()) return sorted(found) def is_test_file(path, src): """A test module in its own file counts like the inline `#[cfg(test)]` module it replaces.""" parts = path.relative_to(src).parts return path.name == "tests.rs" or path.name.endswith("_tests.rs") or any(d in parts[:-1] for d in TEST_DIRS) def count_patterns(packages, patterns, exceptions=(), excused=None): """{":": n} for the non-zero counts, over production code in src/ only (test files and modules declared under a test cfg are skipped). A file named by an entry of `exceptions` ({"crate", "file", "ratchet", "reason"}; `file` is relative to the crate directory) is not counted for that ratchet; the hits it excused are added to `excused` ({(crate, file, ratchet): n}) when it is given.""" compiled = _compile_patterns(patterns, packages) counts = {} for pkg in packages: skip = {(e["file"], e["ratchet"]) for e in exceptions if e["crate"] == pkg["name"]} for pid, n in _package_counts(pkg["dir"] / "src", compiled[pkg["name"]], skip, pkg["name"], excused).items(): counts[f"{pid}:{pkg['name']}"] = n return counts CELL_TYPES = "{cell_types}" def _compile_patterns(patterns, packages): """{crate: [(id, compiled regex, ignore_imports)]}. `{cell_types}` in a regex stands for the interior-mutable types a crate can name: the standard cells and every type that holds one, so `static X: Holder` is found like `static X: Mutex<_>` while an instance field of the same type is not.""" needs_cells = any(CELL_TYPES in pattern["regex"] for pattern in patterns) own = {pkg["name"]: _package_type_definitions(pkg) for pkg in packages} if needs_cells else {} by_name = {pkg["name"]: pkg for pkg in packages} compiled = {} for pkg in packages: alternation = cell_alternation(cell_holders(_visible_definitions(pkg, by_name, own))) if needs_cells else "" compiled[pkg["name"]] = [ (p["id"], re.compile(p["regex"].replace(CELL_TYPES, alternation)), bool(p.get("ignore_imports"))) for p in patterns] return compiled def _package_type_definitions(pkg): """{type name: definition text} of the production code of one package.""" src = pkg["dir"] / "src" definitions = {} if src.is_dir(): test_files = test_only_modules(src) for path in rust_files(src): if not is_test_file(path, src) and not _under_test_module(path, test_files): for name, body in type_definitions(_text(path)).items(): definitions[name] = definitions.get(name, "") + body return definitions def _visible_definitions(pkg, by_name, own): """The type definitions a crate can name: its own, which shadow those of the workspace crates it depends on, directly or not.""" reached, pending = set(), list(pkg["normal"]) while pending: name = pending.pop() if name in by_name and name not in reached: reached.add(name) pending.extend(by_name[name]["normal"]) visible = {} for name in sorted(reached): visible.update(own[name]) visible.update(own[pkg["name"]]) return visible _MOD_LINE = re.compile(r"(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*;") _PATH_ATTR = re.compile(r'#\[path\s*=\s*"([^"]+)"\]') def test_only_modules(src): """Files compiled only for tests: a `mod x;` declared under a `#[cfg(...test...)]` attribute (with or without a `#[path]`), and every module those files declare in turn. `_under_test_module` extends this to the files below such a module.""" declared = {path.resolve(): _declarations(_text(path)) for path in rust_files(src)} queue = [ target for path, decls in declared.items() for name, explicit, tested in decls if tested and (target := _module_file(path, name, explicit)) is not None ] found = set() while queue: owner = queue.pop() if owner not in found: found.add(owner) queue.extend(_declared_targets(owner, declared.get(owner, []))) return found def _declared_targets(owner, decls): """The module files `owner` declares through `mod x;` lines.""" targets = (_module_file(owner, name, explicit) for name, explicit, _ in decls) return [target for target in targets if target is not None] def _declarations(text): """[(module name, #[path] value or None, declared under a test cfg)] of the `mod x;` lines of a file.""" out = [] attrs = [] for line in text.splitlines(): stripped = line.strip() if stripped.startswith("#[") or (attrs and _unbalanced(" ".join(attrs))): attrs.append(stripped) continue decl = _MOD_LINE.match(stripped) if decl: block = " ".join(attrs) explicit = _PATH_ATTR.search(block) out.append((decl.group(1), explicit.group(1) if explicit else None, requires_test(block))) attrs = [] return out def _unbalanced(text): return text.count("[") > text.count("]") or text.count("(") > text.count(")") def _module_file(declaring, name, explicit): here = declaring.parent if explicit: target = (here / explicit).resolve() return target if target.is_file() else None base = here if declaring.name in ("lib.rs", "main.rs", "mod.rs") else here / declaring.stem for candidate in (base / f"{name}.rs", base / name / "mod.rs"): if candidate.is_file(): return candidate.resolve() return None def _under_test_module(path, test_files): """The file itself or a file in the directory a test-only module owns (`x.rs` owns `x/`, `mod.rs` its folder).""" resolved = path.resolve() for owner in test_files: folder = owner.parent if owner.name == "mod.rs" else owner.with_suffix("") if resolved == owner or resolved.is_relative_to(folder): return True return False # a `use` statement of any length: a name in an import list is not a use of it (patterns with "ignore_imports") _USE_STATEMENT = re.compile(r"(?m)^[ \t]*(?:pub(?:\([^)]*\))?[ \t]+)?use\b[^;]*;[ \t]*\n?") def _file_hits(path, compiled): """{pattern id: hits} of the production code of one file.""" text = _text(path) rows = production_lines(text) rows_without_imports = _USE_STATEMENT.sub("", "\n".join(rows)).splitlines() hits = {pid: sum(len(rx.findall(row)) for row in (rows_without_imports if ignore_imports else rows)) for pid, rx, ignore_imports in compiled} return {pid: n for pid, n in hits.items() if n} def _package_counts(src, compiled, skip=frozenset(), crate="", excused=None): totals = {} if not src.is_dir(): return totals test_files = test_only_modules(src) for path in rust_files(src): if is_test_file(path, src) or _under_test_module(path, test_files): continue relative = path.relative_to(src.parent).as_posix() for pid, n in _file_hits(path, compiled).items(): if (relative, pid) in skip: if excused is not None: excused[(crate, relative, pid)] = n else: totals[pid] = totals.get(pid, 0) + n return totals