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): drop a module label that more than one split-file group would take (#2976)
Yang Bai668ea6c5ff81
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 17bca9893..356acc93d 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@@ -243,20 +243,55 @@ def _label_identifier(label: str) -> str:_PRECOMPILED_HEADER_STEMS = frozenset({"pch", "stdafx", "precomp", "precompiled"})-def _module_label(- foreign_of: dict[str, set[str]], members: list[str], self_segments: set[str]+def _top_module(+ foreign_of: dict[str, set[str]], members: list[str], excluded: frozenset[str] = frozenset()) -> str:- """The group's most-called foreign module label as a file name, or ``""``."""+ """The group's most-called foreign module label, or ``""`` when none is left."""labels = Counter(labfor m in membersfor lab in foreign_of.get(m, set())# "tpl, resources" is a two-area community label, not a module name.- if "," not in lab and _label_identifier(lab).lower() not in _PRECOMPILED_HEADER_STEMS+ if "," not in lab+ and lab not in excluded+ and _label_identifier(lab).lower() not in _PRECOMPILED_HEADER_STEMS)if not labels:return ""- best = min(labels, key=lambda lab: (-labels[lab], lab))+ return min(labels, key=lambda lab: (-labels[lab], lab))+++def _shared_top_modules(+ foreign_of: dict[str, set[str]], groups: list[list[str]]+) -> frozenset[str]:+ """Module labels that would be the top pick of more than one group.++ A module most of the file calls into (``utils.h``, ``common.h``) wins the+ vote in every group, and a name two groups share tells them apart only by+ the ``_2`` the filename de-duplication adds. Such a label is dropped for+ all of them, and the next pick is checked the same way.+ """+ excluded: frozenset[str] = frozenset()+ while True:+ tops = Counter(+ top for members in groups if (top := _top_module(foreign_of, members, excluded))+ )+ shared = {lab for lab, count in tops.items() if count > 1}+ if not shared:+ return excluded+ excluded |= shared+++def _module_label(+ foreign_of: dict[str, set[str]],+ members: list[str],+ self_segments: set[str],+ excluded: frozenset[str] = frozenset(),+) -> str:+ """The group's most-called foreign module label as a file name, or ``""``."""+ best = _top_module(foreign_of, members, excluded)+ if not best:+ return ""cleaned = _label_identifier(best)# Reject uninformative labels: too short, carrying a community-dedup# digit suffix, or naming the file's own namespace (tells you@@ -756,8 +791,13 @@ class SplitFileDetector(RefactoringDetector):groups: list[dict] = []self_segments = {seg.lower() for seg in ctx.file_path.replace("\\", "/").split("/")}self_segments.add(stem.lower())+ # Only the groups that fall back to a module label take part in the vote.+ shared = _shared_top_modules(+ fg.signals.foreign_of,+ [m for m in substantive if not self._name_token(fg, m, self_segments)],+ )for members in substantive:- label = self._group_label(fg, members, self_segments)+ label = self._group_label(fg, members, self_segments, shared)# No shared name token means no honest filename; the surfaces prompt for one.suggested = Noneif label:@@ -772,17 +812,31 @@ class SplitFileDetector(RefactoringDetector):)return groups- def _group_label(self, fg: _FileGraph, members: list[str], self_segments: set[str]) -> str:+ def _name_token(self, fg: _FileGraph, members: list[str], self_segments: set[str]) -> str:+ """The plurality name token, when it is not part of the file's own path."""+ token = _dominant_token([self._sym_name(fg.defined, m) for m in members])+ return token if token and token not in self_segments else ""++ def _group_label(+ self,+ fg: _FileGraph,+ members: list[str],+ self_segments: set[str],+ shared_modules: frozenset[str] = frozenset(),+ ) -> str:"""Deterministic file name for a group: the plurality name token when it isnot part of the file's own path, else a clean dominant foreign-module- label, else the token (possibly ``""``, meaning no name).+ label that no other group shares, else the token (possibly ``""``,+ meaning no name).Module labels often name the repo's own package with a size suffix, sothe name vote leads."""token = _dominant_token([self._sym_name(fg.defined, m) for m in members])if token and token not in self_segments:return token- return _module_label(fg.signals.foreign_of, members, self_segments) or token+ return (+ _module_label(fg.signals.foreign_of, members, self_segments, shared_modules) or token+ )@staticmethoddef _unique_filename(stem: str, ext: str, used: set[str]) -> str:diff --git a/tests/unit/health/test_refactoring_split_file.py b/tests/unit/health/test_refactoring_split_file.pyindex 5a7a1aad7..80a79a20a 100644--- a/tests/unit/health/test_refactoring_split_file.py+++ b/tests/unit/health/test_refactoring_split_file.py@@ -595,3 +595,58 @@ def test_a_two_area_community_label_never_names_a_group():foreign_of = {"a": {"tpl, resources"}, "b": {"tpl, resources", "path/to/layout.go"}}assert _module_label(foreign_of, ["a"], set()) == ""assert _module_label(foreign_of, ["a", "b"], set()) == "layout"+++# --- a module label two groups share names neither (#2933) --------------------+++def _names(out: list) -> list[tuple[str | None, str | None]]:+ return [(grp["name"], grp["suggested_file"]) for grp in out[0].plan["groups"]]++[email protected]("header", ["utils.h", "common.h", "types.h", "platform.h"])+def test_a_module_every_group_calls_names_none_of_them(header):+ out = _detect(_two_cpp_clusters(header), _CPP, language="cpp")+ assert len(out) == 1+ assert _names(out) == [(None, None), (None, None)]+++def test_groups_sharing_a_top_module_take_their_next_one():+ g = _two_cpp_clusters("utils.h")+ 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"]["suggested_file"] == "src/Workspaces/registry.cpp"+ assert by_first["fn_4"]["suggested_file"] == "src/Workspaces/layout.cpp"+++def test_a_second_shared_module_is_dropped_too():+ g = _two_cpp_clusters("utils.h")+ # Both groups' runner-up is the same module as well.+ for i in (0, 1, 2, 4, 5, 6):+ _add_foreign_call(g, f"{_CPP}::fn_{i}", "src/Workspaces/common.h", "helper")+ for i in (0, 1):+ _add_foreign_call(g, f"{_CPP}::fn_{i}", "src/Workspaces/registry.h", "open_key")+ 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"]["suggested_file"] == "src/Workspaces/registry.cpp"+ assert by_first["fn_4"]["suggested_file"] is None+ assert not any("_2" in (grp["suggested_file"] or "") for grp in out[0].plan["groups"])+++def test_a_module_only_one_group_leans_on_still_names_it():+ g = _two_cpp_clusters("pch.h")+ for i in range(4):+ _add_foreign_call(g, f"{_CPP}::fn_{i}", "src/Workspaces/utils.h", "trim")+ for i in range(4, 8):+ _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"]["suggested_file"] == "src/Workspaces/utils.cpp"+ assert by_first["fn_4"]["suggested_file"] == "src/Workspaces/layout.cpp"