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(components): name derived components past route params and qualify collisions by parent (#3809)
Raghav Chamadiya218745be8d39
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.mdindex c3213f268..165ab5483 100644--- a/docs/reference/CONFIG.md+++ b/docs/reference/CONFIG.md@@ -573,7 +573,7 @@ re-extraction.### `.repowise/components.yaml`-Components name the parts of a repository that health, hotspots, bus factor, test reach and dead code roll up to. The file is multi-document Backstage YAML (`Component`, `System` and `Group` on `backstage.io/v1alpha1`), with Repowise data in `repowise.dev/paths` (gitignore-style globs written with `/`, matched case-sensitively), `repowise.dev/criticality` (`low`, `medium`, `high`, `critical`), `repowise.dev/tags` and `repowise.dev/capability` annotations; a repo-root `catalog-info.yaml` is read the same way, so a developer portal and Repowise share one file. Without a file, components are derived from workspace services, then module pages, then top-level directories; a declared component claims the files its globs match (where two match a file, the first declared wins), and one named like a derived component replaces it and, with no paths of its own, keeps its directory. See [examples/components](../../examples/components/components.yaml) and `repowise components check`.+Components name the parts of a repository that health, hotspots, bus factor, test reach and dead code roll up to. The file is multi-document Backstage YAML (`Component`, `System` and `Group` on `backstage.io/v1alpha1`), with Repowise data in `repowise.dev/paths` (gitignore-style globs written with `/`, matched case-sensitively), `repowise.dev/criticality` (`low`, `medium`, `high`, `critical`), `repowise.dev/tags` and `repowise.dev/capability` annotations; a repo-root `catalog-info.yaml` is read the same way, so a developer portal and Repowise share one file. Without a file, components are derived from workspace services, then module pages, then top-level directories; a declared component claims the files its globs match (where two match a file, the first declared wins), and one named like a derived component replaces it and, with no paths of its own, keeps its directory. A derived component is named after its directory, skipping route parameters and groups such as `[id]` or `(group)`; where two would share a name, the shallowest keeps it and each other adds its nearest parent directory other than `src`, `lib` or `app` (`workspace-web`), so a name a catalog already uses stays the same. See [examples/components](../../examples/components/components.yaml) and `repowise components check`.### `.repowise/policies.yaml`diff --git a/packages/core/src/repowise/core/components/resolve.py b/packages/core/src/repowise/core/components/resolve.pyindex 97523cb8d..1bd4f6022 100644--- a/packages/core/src/repowise/core/components/resolve.py+++ b/packages/core/src/repowise/core/components/resolve.py@@ -22,6 +22,7 @@ Declared components merge over derived ones:from __future__ import annotations+import hashlibimport refrom collections.abc import Iterablefrom dataclasses import dataclass, field, replace@@ -82,25 +83,90 @@ def _derived(roots: Iterable[tuple[str, str | None]], source: str) -> list[Comporoot = (root or "").replace("\\", "/").strip("/")if root and root != ".":cleaned.setdefault(root, title)- taken: set[str] = set()- out: list[Component] = []- # Shallow roots first, so a short name goes to the outer directory.- for root in sorted(cleaned, key=lambda r: (r.count("/"), r)):- name = _slug(root.rsplit("/", 1)[-1])- if not name or name.lower() in taken:- name = _slug(root)- if name.lower() in taken:- continue- taken.add(name.lower())- out.append(- Component(- name=name,- title=cleaned[root],- paths=(f"{root}/**",),- source=source,- root=root,- )+ names = _assign_names(list(cleaned))+ return [+ Component(+ name=names[root],+ title=cleaned[root],+ paths=(f"{root}/**",),+ source=source,+ root=root,)+ for root in sorted(cleaned, key=lambda r: (r.count("/"), r))+ ]+++def _assign_names(roots: list[str]) -> dict[str, str]:+ """A unique name per root.++ The bare name goes to the shallowest root that wants it (ties by path), so+ a name a catalog may already use to annotate a derived component stays put.+ The roots that lose it move through their other candidates together: when+ two or more want the same name, all of them take their next one, so the+ qualified names depend only on the set of roots, never on input order. The+ last candidate (a hash of the root) is unique, so no root is dropped.+ """+ cands = {r: _names(r) for r in roots}+ names: dict[str, str] = {}+ for r in sorted(roots, key=lambda r: (r.count("/"), r)):+ if cands[r][0].lower() not in {n.lower() for n in names.values()}:+ names[r] = cands[r][0]+ taken = {n.lower() for n in names.values()}+ level = {r: min(1, len(cands[r]) - 1) for r in roots if r not in names}+ while level:+ for r in level:+ while level[r] < len(cands[r]) - 1 and cands[r][level[r]].lower() in taken:+ level[r] += 1+ wanting: dict[str, list[str]] = {}+ for r in level:+ wanting.setdefault(cands[r][level[r]].lower(), []).append(r)+ moved = False+ for group in wanting.values():+ if len(group) < 2:+ continue+ for r in group:+ if level[r] < len(cands[r]) - 1:+ level[r] += 1+ moved = True+ if not moved: # no clash left (two equal 6-hex hashes are not worth a loop)+ break+ names.update({r: cands[r][i] for r, i in level.items()})+ return names+++#: A framework route segment that names a parameter or a group, not a place:+#: ``[id]``, ``[...slug]``, ``[[...opt]]``, ``(group)``, ``{id}``, ``:id``, ``$id``.+#: Braces and prefixes take a bare identifier only, so a template directory+#: such as ``{{cookiecutter.name}}`` is not a route.+_ROUTE_SEGMENT = re.compile(r"^(\[.*\]|\(.*\)|\{[\w.-]+\}|[:$][\w-]+)$")+#: Layout directories too generic to tell two same-named components apart.+_LAYOUT_SEGMENTS = frozenset({"src", "lib", "app", "apps", "packages", "pkg", "internal", "source"})+++def _names(root: str) -> list[str]:+ """Candidate names for *root*, best first.++ The last segment that is not a route parameter or group, then that name+ qualified by one ancestor, nearest first and skipping layout directories+ (``packages/web/src/app/workspace`` becomes ``workspace-web``), then the+ whole path, then the name with a hash of the root. A root made only of+ route segments is named from them. A layout leaf such as ``src`` keeps its+ name: its parent usually names the parent's own component.+ """+ parts = root.split("/")+ places = [p for p in parts if not _ROUTE_SEGMENT.match(p)] or parts+ leaf = _slug(places[-1])+ qualified = (+ [_slug(f"{leaf}-{p}") for p in reversed(places[:-1]) if p.lower() not in _LAYOUT_SEGMENTS]+ if leaf+ else []+ )+ digest = hashlib.sha1(root.encode("utf-8")).hexdigest()[:6]+ hashed = f"{(leaf or _slug(root))[:56].strip('-')}-{digest}".lstrip("-")+ out: list[str] = []+ for name in (leaf, *qualified, _slug(root), hashed):+ if name and name.lower() not in {n.lower() for n in out}:+ out.append(name)return outdiff --git a/tests/unit/core/test_components_resolve.py b/tests/unit/core/test_components_resolve.pyindex efccf1b8c..e3f828cf0 100644--- a/tests/unit/core/test_components_resolve.py+++ b/tests/unit/core/test_components_resolve.py@@ -53,9 +53,93 @@ def test_module_pages_assign_each_file_to_the_deepest_module():assert resolved.unassigned == ["README.md", "tools/gen.py"]-def test_colliding_names_fall_back_to_the_full_path():- derived = derive_from_modules([("a/core", None), ("b/core", None)])- assert [c.name for c in derived] == ["core", "b-core"]+def _names(roots):+ return {c.root: c.name for c in derive_from_modules((r, None) for r in roots)}+++def test_the_shallowest_root_keeps_a_name_and_the_others_take_a_parent():+ assert _names(["a/core", "b/core"]) == {"a/core": "core", "b/core": "core-b"}+ # Layout directories (src, app, ...) do not qualify; the nearest real one does.+ assert _names(["packages/ui/src/workspace", "packages/web/src/app/workspace"]) == {+ "packages/ui/src/workspace": "workspace",+ "packages/web/src/app/workspace": "workspace-web",+ }+ # Losers still tied after one parent both go one parent further out.+ assert _names(["core", "a/x/core", "b/x/core"]) == {+ "core": "core",+ "a/x/core": "core-a",+ "b/x/core": "core-b",+ }+++def test_a_declared_component_without_paths_still_annotates_the_derived_one():+ derived = derive_from_modules([("packages/ui", None), ("packages/cli/ui", None)])+ files = ["packages/ui/button.ts", "packages/cli/ui/menu.py"]+ resolved = resolve_components(+ [Component(name="ui", owner="design", criticality="high")], derived, files+ )+ ui = resolved.get("ui")+ assert (ui.root, ui.owner) == ("packages/ui", "design")+ assert resolved.files["ui"] == ["packages/ui/button.ts"]+ assert resolved.files["ui-cli"] == ["packages/cli/ui/menu.py"]+++def test_route_parameter_and_group_segments_never_name_a_component():+ assert _names(+ [+ "web/app/repos/[id]",+ "web/app/(marketing)",+ "web/app/docs/[...slug]",+ "web/app/shop/[[...filters]]",+ "api/users/{userId}",+ "(marketing)",+ ]+ ) == {+ "web/app/repos/[id]": "repos",+ "web/app/(marketing)": "app",+ "web/app/docs/[...slug]": "docs",+ "web/app/shop/[[...filters]]": "shop",+ "api/users/{userId}": "users",+ "(marketing)": "marketing", # a group that is the whole root still names it+ }+++def test_template_directories_are_not_route_segments():+ assert _names(["tpl/{{cookiecutter.name}}"]) == {+ "tpl/{{cookiecutter.name}}": "cookiecutter-name"+ }+++def test_a_route_under_a_parameter_is_qualified_past_it():+ assert _names(["web/components/settings", "web/app/repos/[id]/settings"]) == {+ "web/components/settings": "settings",+ "web/app/repos/[id]/settings": "settings-repos",+ }+++def test_no_component_is_dropped_when_every_readable_name_is_taken():+ # a-b/c and a_b/c lose "c" and slug alike at every level: only the hash tells them apart.+ assert _names(["c", "a-b/c", "a_b/c"]) == {+ "c": "c",+ "a-b/c": "c-1c7275",+ "a_b/c": "c-9eddec",+ }+ # A leaf that slugs to nothing goes straight to the whole path.+ assert _names(["x/__"]) == {"x/__": "x"}+++def test_derived_names_depend_only_on_the_set_of_roots():+ import itertools++ roots = ["a/core", "b/x/core", "c/x/core", "web/app/repos/[id]", "lib/util", "d/util"]+ names = _names(roots)+ assert names["b/x/core"] == "core-b" and names["c/x/core"] == "core-c"+ for order in itertools.permutations(roots):+ assert _names(order) == names+ # A deeper same-name root leaves every existing name alone.+ grown = _names([*roots, "e/f/core"])+ assert grown["e/f/core"] == "core-f"+ assert {r: grown[r] for r in roots} == namesdef test_services_come_from_the_repo_s_own_system_graph_nodes():