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(dead-code): root Spring servlet initializers as entry points (#3921)
Yunus Ozenc9f59e6665f4
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/spring.py b/packages/core/src/repowise/core/ingestion/framework_edges/spring.pyindex fb2f240d1..b46493c35 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/spring.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/spring.py@@ -108,6 +108,15 @@ _SPRING_DATA_BASES: frozenset[str] = frozenset({"JpaSpecificationExecutor",})+# Spring base classes the servlet container instantiates without any source+# naming the subclass: Spring Boot's WAR bootstrap, and the classic Spring MVC+# ``WebApplicationInitializer`` implementations it finds on the classpath.+_SERVLET_INITIALIZER_BASES: frozenset[str] = frozenset({+ "SpringBootServletInitializer",+ "AbstractAnnotationConfigDispatcherServletInitializer",+ "AbstractDispatcherServletInitializer",+})+# Java field declaration with optional ``final`` modifier — used for# Lombok RAC ctor-param inference. Captures the type's head identifier._JAVA_FINAL_FIELD_RE = re.compile(@@ -127,18 +136,32 @@ def _has_spring_imports(parsed_files: dict[str, Any]) -> bool:return False-def _is_spring_data_repo(parsed: Any) -> bool:- """True if *parsed* is a Java/Kotlin interface extending a Spring Data base."""+def _extends_any(parsed: Any, bases: frozenset[str]) -> bool:+ """True if a Java/Kotlin type in *parsed* extends or implements one of *bases*.++ The parent is matched by its simple name, without generic arguments or a+ package.+ """if parsed.file_info.language not in ("java", "kotlin"):return Falsefor rel in parsed.heritage:if rel.kind in ("extends", "implements"):base = rel.parent_name.split("<")[0].rsplit(".", 1)[-1].strip()- if base in _SPRING_DATA_BASES:+ if base in bases:return Truereturn False+def _is_spring_data_repo(parsed: Any) -> bool:+ """True if *parsed* is a Java/Kotlin interface extending a Spring Data base."""+ return _extends_any(parsed, _SPRING_DATA_BASES)+++def _is_servlet_initializer(parsed: Any) -> bool:+ """True if *parsed* declares a class the servlet container bootstraps."""+ return _extends_any(parsed, _SERVLET_INITIALIZER_BASES)++def _owner_at_offset(parsed: Any, text: str, offset: int) -> str | None:"""The innermost declared type whose body contains *offset*.@@ -266,6 +289,17 @@ def _add_spring_edges(node["is_entry_point"] = Truenode["framework_role"] = "spring_data_repository"+ # ---- 1b. Servlet initializers ----+ # ``SpringBootServletInitializer`` (WAR deployment) and the Spring MVC+ # dispatcher initializers are instantiated by the servlet container, so+ # no source names them.+ for path, parsed in parsed_files.items():+ if _is_servlet_initializer(parsed):+ node = graph.nodes.get(path)+ if node is not None:+ node["is_entry_point"] = True+ node["framework_role"] = "spring_servlet_initializer"+# ---- 2. Per-class DI + @Bean factory edges ----for path, parsed in parsed_files.items():if parsed.file_info.language not in ("java", "kotlin"):diff --git a/tests/unit/dead_code/test_jvm_build_roots.py b/tests/unit/dead_code/test_jvm_build_roots.pyindex b6b2b121e..cf7a87f4a 100644--- a/tests/unit/dead_code/test_jvm_build_roots.py+++ b/tests/unit/dead_code/test_jvm_build_roots.py@@ -232,3 +232,56 @@ def test_each_writer_is_read_once(monkeypatch):writers = set(source_map)assert not any(scope.can_refer("Foo", _DECLARING, writers, w) for w in writers - {_DECLARING})assert calls <= len(writers)+++_SERVLET_FILES = {+ "src/main/java/com/example/admin/AdminApplication.java": (+ "package com.example.admin;\n\n"+ "import org.springframework.boot.SpringApplication;\n"+ "import org.springframework.boot.autoconfigure.SpringBootApplication;\n\n"+ "@SpringBootApplication\npublic class AdminApplication {\n"+ " public static void main(String[] args) {\n"+ " SpringApplication.run(AdminApplication.class, args);\n }\n}\n"+ ),+ "src/main/java/com/example/admin/ServletInitializer.java": (+ "package com.example.admin;\n\n"+ "import org.springframework.boot.builder.SpringApplicationBuilder;\n"+ "import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;\n\n"+ "public class ServletInitializer extends SpringBootServletInitializer {\n"+ " @Override\n"+ " protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {\n"+ " return application.sources(AdminApplication.class);\n }\n}\n"+ ),+ # Control: a class extending some other external base is still judged on+ # its own uses.+ "src/main/java/com/example/admin/Leftover.java": (+ "package com.example.admin;\n\n"+ "import org.springframework.boot.builder.SpringApplicationBuilder;\n\n"+ "public class Leftover extends SpringApplicationBuilder {\n}\n"+ ),+}+++def _spring_report(root: Path):+ from repowise.core.pipeline.incremental import build_repo_graph++ for rel, text in _SERVLET_FILES.items():+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ _, sources, builder, _, _ = build_repo_graph(+ root, [], collect_sources=True, log=lambda *a, **k: None, read_only=True+ )+ return DeadCodeAnalyzer(+ builder.graph(),+ {},+ parsed_files=builder._parsed_files,+ source_map=sources,+ repo_root=root,+ ).analyze({"min_confidence": 0.0})+++def test_spring_boot_servlet_initializer_is_not_reported(tmp_path: Path):+ report = _spring_report(tmp_path)+ assert not [f for f in report.findings if "ServletInitializer" in f.file_path]+ assert "Leftover" in _named(report, DeadCodeKind.UNUSED_EXPORT)diff --git a/tests/unit/ingestion/test_spring_framework_edges.py b/tests/unit/ingestion/test_spring_framework_edges.pyindex 58207acdb..c8958b351 100644--- a/tests/unit/ingestion/test_spring_framework_edges.py+++ b/tests/unit/ingestion/test_spring_framework_edges.py@@ -140,6 +140,81 @@ class TestSpringKotlin:assert graph.number_of_nodes() == 2+class TestServletInitializer:+ """A class the servlet container bootstraps is a root; no source names it."""++ def _graph(self, tmp_path: Path, files: dict[str, str]) -> nx.DiGraph:+ for rel, text in files.items():+ (tmp_path / rel).write_text(text)+ parsed = _build_parsed(tmp_path)+ graph = nx.DiGraph()+ for p in parsed:+ graph.add_node(p)+ add_framework_edges(graph, parsed, _ctx(tmp_path, parsed), tech_stack=["spring"])+ return graph++ def test_spring_boot_servlet_initializer_is_an_entry_point(self, tmp_path: Path) -> None:+ graph = self._graph(+ tmp_path,+ {+ "ServletInitializer.java": (+ "import org.springframework.boot.builder.SpringApplicationBuilder;\n"+ "import org.springframework.boot.web.servlet.support"+ ".SpringBootServletInitializer;\n"+ "public class ServletInitializer extends SpringBootServletInitializer {\n"+ " @Override\n"+ " protected SpringApplicationBuilder configure("+ "SpringApplicationBuilder application) {\n"+ " return application.sources(AdminApplication.class);\n"+ " }\n"+ "}\n"+ ),+ },+ )+ node = graph.nodes["ServletInitializer.java"]+ assert node.get("is_entry_point") is True+ assert node.get("framework_role") == "spring_servlet_initializer"++ def test_mvc_dispatcher_initializer_is_an_entry_point(self, tmp_path: Path) -> None:+ graph = self._graph(+ tmp_path,+ {+ "WebInit.java": (+ "import org.springframework.web.servlet.support"+ ".AbstractAnnotationConfigDispatcherServletInitializer;\n"+ "public class WebInit\n"+ " extends AbstractAnnotationConfigDispatcherServletInitializer {}\n"+ ),+ },+ )+ assert graph.nodes["WebInit.java"].get("is_entry_point") is True++ def test_kotlin_servlet_initializer_is_an_entry_point(self, tmp_path: Path) -> None:+ graph = self._graph(+ tmp_path,+ {+ "ServletInitializer.kt": (+ "import org.springframework.boot.web.servlet.support"+ ".SpringBootServletInitializer\n"+ "class ServletInitializer : SpringBootServletInitializer()\n"+ ),+ },+ )+ assert graph.nodes["ServletInitializer.kt"].get("is_entry_point") is True++ def test_another_base_is_not_an_entry_point(self, tmp_path: Path) -> None:+ graph = self._graph(+ tmp_path,+ {+ "Widget.java": (+ "import org.springframework.stereotype.Component;\n"+ "public class Widget extends BaseWidget {}\n"+ ),+ },+ )+ assert not graph.nodes["Widget.java"].get("is_entry_point")++class TestSpringGate:def test_non_spring_unaffected(self, tmp_path: Path) -> None:(tmp_path / "Plain.java").write_text("public class Plain {}\n")