Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(refactoring): keep a precompiled header from naming a split-file group (#2932)
Yang Bai14626bd37bec
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.pyindex 959e0379c..3d7aab1c7 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py@@ -49,7 +49,7 @@ need a back-compat re-export shim, surfaced as ``shim_required``.from __future__ import annotationsfrom collections import Counter, defaultdict-from collections.abc import Iterator+from collections.abc import Iterable, Iteratorfrom dataclasses import dataclass, fieldfrom itertools import combinationsfrom typing import Any@@ -244,11 +244,21 @@ def _label_identifier(label: str) -> str:return "".join(ch if (ch.isalnum() or ch == "_") else "_" for ch in seg).strip("_")+# Every C++ function in a project with a precompiled header calls into it, so+# it wins the vote and names nothing; ``pch.cpp`` is also the file that builds it.+_PRECOMPILED_HEADER_STEMS = frozenset({"pch", "stdafx", "precomp", "precompiled"})++def _module_label(foreign_of: dict[str, set[str]], members: list[str], self_segments: set[str]) -> str:"""The group's most-called foreign module label as a file name, or ``""``."""- labels = Counter(lab for m in members for lab in foreign_of.get(m, set()))+ labels = Counter(+ lab+ for m in members+ for lab in foreign_of.get(m, set())+ if _label_identifier(lab).lower() not in _PRECOMPILED_HEADER_STEMS+ )if not labels:return ""best = min(labels, key=lambda lab: (-labels[lab], lab))@@ -617,7 +627,7 @@ class SplitFileDetector(RefactoringDetector):) -> RefactoringSuggestion:groups = self._shape_groups(ctx, fg, partition.groups)residual = (- {"symbols": sorted(self._sym_name(fg.defined, m) for m in partition.residual)}+ {"symbols": self._sym_names(fg.defined, partition.residual)}if partition.residualelse None)@@ -761,7 +771,7 @@ class SplitFileDetector(RefactoringDetector):groups.append({"name": label or None,- "symbols": sorted(self._sym_name(fg.defined, m) for m in members),+ "symbols": self._sym_names(fg.defined, members),"suggested_file": suggested,})@@ -793,6 +803,11 @@ class SplitFileDetector(RefactoringDetector):def _sym_name(defined: dict[str, dict], sid: str) -> str:return defined.get(sid, {}).get("name") or sid.rsplit("::", 1)[-1]+ @classmethod+ def _sym_names(cls, defined: dict[str, dict], sids: Iterable[str]) -> list[str]:+ """Sorted bare names, each once: overloads are separate ids with one name."""+ return sorted({cls._sym_name(defined, sid) for sid in sids})+def _blast_radius(self, ctx: RefactoringContext, defined: dict[str, dict], *, shim_required: bool) -> dict[str, Any]:diff --git a/tests/unit/health/test_refactoring_split_file.py b/tests/unit/health/test_refactoring_split_file.pyindex ee4a14757..a2e700fe9 100644--- a/tests/unit/health/test_refactoring_split_file.py+++ b/tests/unit/health/test_refactoring_split_file.py@@ -13,6 +13,7 @@ from __future__ import annotationsfrom types import SimpleNamespaceimport networkx as nx+import pytestfrom repowise.core.analysis.health.function_blame_rollup import (blame_commit_entries,@@ -482,3 +483,96 @@ def test_empty_blame_index_is_silent():# An empty index (the documented "no signal" outcome) must not raise and# must not invent co-change edges.assert _detect(_disconnected_blocks(), "big.py", blame_index=BlameIndex()) == []+++# --- group labels and symbol lists (#2885) -----------------------------------++_CPP = "src/Workspaces/AppUtils.cpp"+++def _two_cpp_clusters(header: str, names: list[str] | None = None) -> nx.DiGraph:+ """Two call cliques of four functions with no shared name token, every+ function calling into the precompiled *header*."""+ g = nx.DiGraph()+ names = names or [f"fn_{i}" for i in range(8)]+ sids = [_add_func(g, _CPP, name, start=10 * i + 1, end=10 * i + 10) for i, name in enumerate(names)]+ for cluster in (sids[:4], sids[4:]):+ for src in cluster:+ for dst in cluster:+ if src != dst:+ _call(g, src, dst)+ for sid in sids:+ _add_foreign_call(g, sid, f"src/Workspaces/{header}", "precompiled")+ return g++[email protected]("header", ["pch.h", "pch.hpp", "stdafx.h", "StdAfx.h", "precomp.h"])+def test_a_precompiled_header_never_names_a_group(header):+ out = _detect(_two_cpp_clusters(header), _CPP, language="cpp")+ assert len(out) == 1+ groups = out[0].plan["groups"]+ assert len(groups) == 2+ # Nothing else is called, so there is no honest name: the surface asks.+ assert [g["name"] for g in groups] == [None, None]+ assert [g["suggested_file"] for g in groups] == [None, None]++[email protected]("header", ["pch.h", "pch.hpp", "stdafx.h", "StdAfx.h"])+def test_a_group_takes_the_next_most_called_module_over_the_precompiled_header(header):+ g = _two_cpp_clusters(header)+ # Three of four, so the header (four of four) still wins the vote.+ for i in range(3):+ _add_foreign_call(g, f"{_CPP}::fn_{i}", "src/Workspaces/registry.h", "open_key")+ for i in range(4, 7):+ _add_foreign_call(g, f"{_CPP}::fn_{i}", "src/Workspaces/layout.h", "arrange")+ out = _detect(g, _CPP, language="cpp")+ assert len(out) == 1+ by_first = {grp["symbols"][0]: grp for grp in out[0].plan["groups"]}+ assert by_first["fn_0"]["name"] == "registry"+ assert by_first["fn_0"]["suggested_file"] == "src/Workspaces/registry.cpp"+ assert by_first["fn_4"]["name"] == "layout"+ assert by_first["fn_4"]["suggested_file"] == "src/Workspaces/layout.cpp"+++def test_overloads_are_listed_once_in_a_group():+ g = _two_cpp_clusters("pch.h", ["GetApp", *(f"fn_{i}" for i in range(1, 8))])+ # A second overload: its own node id, the same bare name.+ overload = f"{_CPP}::GetApp#2"+ g.add_node(+ overload,+ node_type="symbol",+ kind="function",+ name="GetApp",+ file_path=_CPP,+ start_line=81,+ end_line=90,+ parent_name=None,+ )+ g.add_edge(_CPP, overload, edge_type="defines")+ for i in range(1, 4):+ _call(g, overload, f"{_CPP}::fn_{i}")+ _call(g, f"{_CPP}::fn_{i}", overload)+ out = _detect(g, _CPP, language="cpp")+ assert len(out) == 1+ symbols = next(grp["symbols"] for grp in out[0].plan["groups"] if "GetApp" in grp["symbols"])+ assert symbols == ["GetApp", "fn_1", "fn_2", "fn_3"]+++def test_overloads_are_listed_once_in_the_residual():+ g = _two_cpp_clusters("pch.h")+ # Two overloads nothing in the file is tied to: neither joins a group.+ for sid, start in ((f"{_CPP}::Trim", 81), (f"{_CPP}::Trim#2", 91)):+ g.add_node(+ sid,+ node_type="symbol",+ kind="function",+ name="Trim",+ file_path=_CPP,+ start_line=start,+ end_line=start + 9,+ parent_name=None,+ )+ g.add_edge(_CPP, sid, edge_type="defines")+ out = _detect(g, _CPP, language="cpp")+ assert len(out) == 1+ assert out[0].plan["residual"] == {"symbols": ["Trim"]}