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
feat: JVM workspace model and import-graph correctness for Java + Kotlin (#273)
Raghav Chamadiya72640a4313b1
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 69610bc82..19a676b71 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -105,6 +105,10 @@ class CallResolver:self._go_index: Any = Noneself._go_index_built = False+ # JVM same-package resolution (lazy JvmWorkspaceIndex)+ self._jvm_index: Any = None+ self._jvm_index_built = False+self._build_indices(parsed_files)self._follow_barrel_exports()@@ -205,6 +209,53 @@ class CallResolver:parsed = self._parsed_files.get(file_path)return bool(parsed and parsed.file_info.language == "go")+ def _is_jvm(self, file_path: str) -> bool:+ parsed = self._parsed_files.get(file_path)+ return bool(parsed and parsed.file_info.language in ("java", "kotlin"))++ def _get_jvm_index(self) -> Any:+ """Lazily build the JvmWorkspaceIndex (or None if unavailable)."""+ if self._jvm_index_built:+ return self._jvm_index+ self._jvm_index_built = True+ if not self._repo_path:+ return None+ from pathlib import Path++ from .resolvers.jvm_workspace import build_jvm_workspace_index++ class _Ctx:+ def __init__(self, rp: str, pf: dict[str, ParsedFile]) -> None:+ self.repo_path = Path(rp)+ self.path_set = set(pf.keys())+ self.parsed_files = pf++ self._jvm_index = build_jvm_workspace_index(_Ctx(self._repo_path, self._parsed_files))+ return self._jvm_index++ def _resolve_jvm_same_package(+ self,+ file_path: str,+ call: CallSite,+ caller_id: str,+ ) -> ResolvedCall | None:+ """Resolve a bare call to a symbol defined in a same-package sibling.++ JVM files in the same package share a namespace — an unqualified+ identifier ``Helper`` may be a class or method defined in any sibling+ file of the same package, with no import statement.+ """+ index = self._get_jvm_index()+ if index is None:+ return None+ siblings = index.same_package_files(file_path)+ for sibling in siblings:+ syms = self._file_symbols.get(sibling, {})+ sym_id = syms.get(call.target_name)+ if sym_id is not None and sym_id != caller_id:+ return ResolvedCall(caller_id, sym_id, 0.90, call.line)+ return None+def _resolve_go_package_call(self,file_path: str,@@ -361,6 +412,13 @@ class CallResolver:if go_same_pkg is not None:return go_same_pkg+ # JVM: same-package implicit access — classes in the same package+ # reference each other with no import statement.+ if self._is_jvm(file_path):+ jvm_same_pkg = self._resolve_jvm_same_package(file_path, call, caller_id)+ if jvm_same_pkg is not None:+ return jvm_same_pkg+# Tier 2: import-scoped# 2a: Check specific imported name → source file (binding-aware)binding = self._import_bindings.get(file_path, {}).get(target_name)@@ -425,6 +483,22 @@ class CallResolver:if go_pkg_call is not None:return go_pkg_call+ # JVM: receiver may be a class in the same package (no import needed)+ if self._is_jvm(file_path):+ index = self._get_jvm_index()+ if index is not None:+ siblings = index.same_package_files(file_path)+ for sibling in siblings:+ methods = self._file_methods.get(sibling, {})+ key = (receiver_name, method_name)+ if key in methods:+ return ResolvedCall(caller_id, methods[key], 0.90, call.line)+ syms = self._file_symbols.get(sibling, {})+ if receiver_name in syms:+ # Found the class; look for the method on it+ if key in methods:+ return ResolvedCall(caller_id, methods[key], 0.88, call.line)+# Strategy 1: receiver is a module alias (e.g. "import models" → "models.User()")module_file = self._module_aliases.get(file_path, {}).get(receiver_name)if module_file:diff --git a/packages/core/src/repowise/core/ingestion/external_systems/__init__.py b/packages/core/src/repowise/core/ingestion/external_systems/__init__.pyindex 482b15e5c..de918a7c0 100644--- a/packages/core/src/repowise/core/ingestion/external_systems/__init__.py+++ b/packages/core/src/repowise/core/ingestion/external_systems/__init__.py@@ -18,7 +18,7 @@ from collections.abc import Iterablefrom pathlib import Pathfrom types import ModuleType-from . import cargo, go, npm, nuget, pypi+from . import cargo, go, maven, npm, nuget, pypifrom .base import ExternalSystemRecord, ManifestParser__all__ = [@@ -27,7 +27,7 @@ __all__ = ["extract_external_systems",]-_PARSERS: tuple[ModuleType, ...] = (npm, pypi, cargo, go, nuget)+_PARSERS: tuple[ModuleType, ...] = (npm, pypi, cargo, go, nuget, maven)# Map exact filename → parser module_FILENAME_PARSERS: dict[str, ModuleType] = {diff --git a/packages/core/src/repowise/core/ingestion/external_systems/maven.py b/packages/core/src/repowise/core/ingestion/external_systems/maven.pynew file mode 100644index 000000000..eb0958a28--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/external_systems/maven.py@@ -0,0 +1,143 @@+"""Parse Maven ``pom.xml`` manifests.++Reads ``<dependency>`` entries from ``<dependencies>`` blocks and handles+``<modules>`` for reactor discovery. Properties (``${...}``) are resolved+when declared in the same POM or a parent POM within the same repo.+"""++from __future__ import annotations++import re+import xml.etree.ElementTree as ET+from pathlib import Path++from .base import ExternalSystemRecord+from .classifier import classify, display_name_for++filenames: tuple[str, ...] = ("pom.xml",)+ecosystem: str = "maven"++_NS = re.compile(r"\{[^}]*\}")+++def _strip_ns(tag: str) -> str:+ return _NS.sub("", tag)+++def _find(el: ET.Element, local_name: str) -> ET.Element | None:+ for child in el:+ if _strip_ns(child.tag) == local_name:+ return child+ return None+++def _find_text(el: ET.Element, local_name: str) -> str:+ child = _find(el, local_name)+ return (child.text or "").strip() if child is not None else ""+++def _find_all(el: ET.Element, local_name: str) -> list[ET.Element]:+ return [child for child in el if _strip_ns(child.tag) == local_name]+++def _collect_properties(root: ET.Element) -> dict[str, str]:+ props: dict[str, str] = {}+ props_el = _find(root, "properties")+ if props_el is not None:+ for child in props_el:+ key = _strip_ns(child.tag)+ if child.text:+ props[key] = child.text.strip()+ gid = _find_text(root, "groupId")+ aid = _find_text(root, "artifactId")+ ver = _find_text(root, "version")+ if gid:+ props.setdefault("project.groupId", gid)+ if aid:+ props.setdefault("project.artifactId", aid)+ if ver:+ props.setdefault("project.version", ver)+ return props+++_PROP_RE = re.compile(r"\$\{([^}]+)\}")+++def _resolve_props(value: str, props: dict[str, str]) -> str:+ def _repl(m: re.Match) -> str:+ return props.get(m.group(1), m.group(0))++ resolved = _PROP_RE.sub(_repl, value)+ if resolved != value and "${" in resolved:+ resolved = _PROP_RE.sub(_repl, resolved)+ return resolved+++_TEST_SCOPES = frozenset({"test", "provided", "system"})+++def parse(manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:+ try:+ tree = ET.parse(manifest_path) # noqa: S314+ except Exception:+ return []++ root = tree.getroot()+ declared_in = manifest_path.relative_to(repo_root).as_posix()+ props = _collect_properties(root)++ # Inherit parent properties+ parent = _find(root, "parent")+ if parent is not None:+ parent_ver = _find_text(parent, "version")+ if parent_ver:+ props.setdefault("project.parent.version", parent_ver)+ props.setdefault("project.version", parent_ver)++ # Collect managed dependency versions+ dep_mgmt = _find(root, "dependencyManagement")+ managed: dict[str, str] = {}+ if dep_mgmt is not None:+ deps_el = _find(dep_mgmt, "dependencies")+ if deps_el is not None:+ for dep in _find_all(deps_el, "dependency"):+ g = _resolve_props(_find_text(dep, "groupId"), props)+ a = _resolve_props(_find_text(dep, "artifactId"), props)+ v = _resolve_props(_find_text(dep, "version"), props)+ if g and a and v:+ managed[f"{g}:{a}"] = v++ records: list[ExternalSystemRecord] = []+ seen: set[str] = set()++ for deps_el in _find_all(root, "dependencies"):+ for dep in _find_all(deps_el, "dependency"):+ group_id = _resolve_props(_find_text(dep, "groupId"), props)+ artifact_id = _resolve_props(_find_text(dep, "artifactId"), props)+ if not group_id or not artifact_id:+ continue+ name = f"{group_id}:{artifact_id}"+ if name in seen:+ continue+ seen.add(name)++ version = _resolve_props(_find_text(dep, "version"), props)+ if not version or "${" in version:+ version = managed.get(name, version or None)++ scope = _find_text(dep, "scope").lower()+ is_dev = scope in _TEST_SCOPES++ records.append(+ ExternalSystemRecord(+ name=name,+ ecosystem=ecosystem,+ declared_in=declared_in,+ version=version if version and "${" not in version else None,+ display_name=display_name_for(artifact_id),+ category=classify(artifact_id),+ is_dev_dep=is_dev,+ )+ )++ return recordsdiff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.pyindex a18dbcd00..a98da77d4 100644--- a/packages/core/src/repowise/core/ingestion/graph/builder.py+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py@@ -232,14 +232,21 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd_t0 = _t.monotonic()file_imports: set[str] = set()for imp in parsed.imports:- # Go imports name a package *directory*; fan the edge out to- # every ``.go`` file in the resolved package so sibling files- # share importers (otherwise they look unreachable). Other- # languages resolve to a single representative target.+ # Go and JVM imports name a package *directory*; fan the edge+ # out to every file in the resolved package so sibling files+ # share importers (otherwise they look unreachable).if _lang == "go":from ..resolvers.go import resolve_go_import_alltargets = resolve_go_import_all(imp.module_path, path, ctx)+ elif _lang == "java":+ from ..resolvers.java import resolve_java_import_all++ targets = resolve_java_import_all(imp.module_path, path, ctx)+ elif _lang == "kotlin":+ from ..resolvers.kotlin import resolve_kotlin_import_all++ targets = resolve_kotlin_import_all(imp.module_path, path, ctx)else:single = resolve_import(imp.module_path, path, _lang, ctx)targets = (single,) if single else ()diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.pyindex 776bebb7e..07164e5a9 100644--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py@@ -34,6 +34,12 @@ if TYPE_CHECKING:Warmup = Callable[["ResolverContext"], None]+def _warmup_jvm(ctx: "ResolverContext") -> None:+ from .resolvers.jvm_workspace import get_or_build_jvm_index++ get_or_build_jvm_index(ctx)++def _warmup_dotnet(ctx: "ResolverContext") -> None:from .resolvers.dotnet import get_or_build_index@@ -98,6 +104,8 @@ def _warmup_typescript(ctx: "ResolverContext") -> None:# same for both languages. The dispatcher registers under each tag so# a JS-only repo still triggers the index build._WARMUPS: dict[str, tuple[str, Warmup]] = {+ "java": ("graph.jvm_index", _warmup_jvm),+ "kotlin": ("graph.jvm_index", _warmup_jvm),"csharp": ("graph.dotnet_index", _warmup_dotnet),"go": ("graph.go_index", _warmup_go),"typescript": ("graph.ts_index", _warmup_typescript),diff --git a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/__init__.pyindex 142b72475..efb13b3e4 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py@@ -9,6 +9,7 @@ from .cpp import resolve_cpp_importfrom .csharp import resolve_csharp_importfrom .generic import resolve_generic_importfrom .go import resolve_go_import+from .java import resolve_java_importfrom .kotlin import resolve_kotlin_importfrom .luau import resolve_luau_importfrom .php import resolve_php_import@@ -29,6 +30,7 @@ _RESOLVERS: dict[str, ResolverFn] = {"rust": resolve_rust_import,"cpp": resolve_cpp_import,"c": resolve_cpp_import,+ "java": resolve_java_import,"kotlin": resolve_kotlin_import,"luau": resolve_luau_import,"ruby": resolve_ruby_import,diff --git a/packages/core/src/repowise/core/ingestion/resolvers/java.py b/packages/core/src/repowise/core/ingestion/resolvers/java.pynew file mode 100644index 000000000..7122dee7b--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/java.py@@ -0,0 +1,100 @@+"""Java import resolution with package fan-out and wildcard expansion.++Resolves Java imports to repo-relative file paths using the+:class:`JvmWorkspaceIndex` for package-aware resolution.++Handles:+- ``import com.foo.Bar`` → file(s) defining ``Bar`` in package ``com.foo``+- ``import com.foo.*`` → all files in package ``com.foo``+- ``import static com.foo.Bar.*`` → file(s) defining ``Bar``+- ``java.lang.*`` filtering (no edges for builtin types)+- Cross-language resolution (Java importing Kotlin and vice versa)+"""++from __future__ import annotations++from pathlib import PurePosixPath+from typing import TYPE_CHECKING++from .jvm_gradle import resolve_via_jvm_gradle_index+from .jvm_workspace import get_or_build_jvm_index++if TYPE_CHECKING:+ from .context import ResolverContext+++def resolve_java_import(+ module_path: str, importer_path: str, ctx: ResolverContext+) -> str | None:+ """Resolve a Java import to a single representative repo-relative file.++ For the graph builder's fan-out path, use :func:`resolve_java_import_all`+ which returns all target files.+ """+ targets = resolve_java_import_all(module_path, importer_path, ctx)+ return targets[0] if targets else None+++def resolve_java_import_all(+ module_path: str, importer_path: str, ctx: ResolverContext+) -> tuple[str, ...]:+ """Resolve a Java import to all matching repo-relative file paths.++ Returns a tuple of repo-relative paths (potentially multiple for+ wildcard imports and package fan-out). External packages resolve+ to a single ``external:`` node.+ """+ if not module_path:+ return ()++ jvm_index = get_or_build_jvm_index(ctx)++ # Filter java.lang.* builtins+ if jvm_index.is_java_lang(module_path):+ return ()++ parts = module_path.split(".")++ # Handle wildcard import: import com.foo.*+ if parts[-1] == "*":+ pkg_fqn = ".".join(parts[:-1])+ if not pkg_fqn:+ return ()+ files = jvm_index.wildcard_expand(pkg_fqn)+ if files:+ return files+ # External package+ return (ctx.add_external_node(module_path),)++ # Handle static wildcard: import static com.foo.Bar.*+ # (parsed as "com.foo.Bar.*" by the import extractor, or+ # the static keyword is stripped leaving "com.foo.Bar")+ # Also handles: import static com.foo.Bar.CONSTANT → resolve Bar++ # Try direct FQN resolution first+ files = jvm_index.files_for_fqn(module_path)+ if files:+ return files++ # Try Gradle index (handles cases where workspace index missed something)+ gradle_match = resolve_via_jvm_gradle_index(module_path, ctx)+ if gradle_match is not None:+ return (gradle_match,)++ # Try stem lookup (class name)+ local = parts[-1]+ result = ctx.stem_lookup(local.lower())+ if result and (result.endswith(".java") or result.endswith(".kt")):+ return (result,)++ # Try matching package path as directory structure+ if len(parts) > 1:+ dir_suffix = "/".join(parts[:-1])+ for p in ctx.path_set:+ if (p.endswith(".java") or p.endswith(".kt")) and dir_suffix in p:+ stem = PurePosixPath(p).stem+ if stem.lower() == local.lower():+ return (p,)++ # External+ return (ctx.add_external_node(module_path),)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py b/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.pynew file mode 100644index 000000000..cc09adbd1--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py@@ -0,0 +1,430 @@+"""Gradle multi-module index for JVM (Java + Kotlin) import resolution.++Parses ``settings.gradle(.kts)`` for subprojects, discovers source-set+directories (main, test, integrationTest, etc.), reads ``package``+declarations from ``.java`` and ``.kt`` files, and builds a unified+lookup index consumed by both the Java and Kotlin import resolvers.++Superset of the previous ``kotlin_gradle.py`` (which is now a thin+re-export facade for backwards compatibility).+"""++from __future__ import annotations++import re+from dataclasses import dataclass, field+from functools import lru_cache+from pathlib import Path+from typing import TYPE_CHECKING++import structlog++if TYPE_CHECKING:+ from .context import ResolverContext++log = structlog.get_logger(__name__)++# ---------------------------------------------------------------------------+# Regex patterns+# ---------------------------------------------------------------------------++_INCLUDE_RE = re.compile(r'include\s*\(\s*((?:"[^"]+"\s*,?\s*)+)\)')+_INCLUDE_ITEM_RE = re.compile(r'"([^"]+)"')+_INCLUDE_LINE_RE = re.compile(r'include\s+([\'"])([^\'"]+)\1')+_INCLUDE_BUILD_RE = re.compile(r'includeBuild\s*\(\s*"([^"]+)"\s*\)')+_PROJECT_DIR_RE = re.compile(+ r'project\s*\(\s*"([^"]+)"\s*\)\s*\.\s*projectDir\s*=\s*file\s*\(\s*"([^"]+)"\s*\)'+)+_SRCDIRS_RE = re.compile(+ r'srcDirs?\s*[=(]\s*((?:listOf|setOf)?\s*\(?\s*(?:"[^"]+"\s*,?\s*)+\)?)',+ re.DOTALL,+)+_SOURCESET_BLOCK_RE = re.compile(r'sourceSets\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}', re.DOTALL)+_SOURCESET_NAME_RE = re.compile(+ r'(?:val\s+|getByName\s*\(\s*"|named\s*\(\s*"|create\s*\(\s*"|register\s*\(\s*")?'+ r'(\w+)(?:"\s*\))?\s*\{',+)+_PLUGIN_ID_RE = re.compile(r'id\s*\(\s*"([^"]+)"\s*\)')+_PLUGIN_ID_GROOVY_RE = re.compile(r"id\s+['\"]([^'\"]+)['\"]")+_APPLY_PLUGIN_RE = re.compile(r"apply\s+plugin:\s*['\"]([^'\"]+)['\"]")+_PACKAGE_RE = re.compile(r"^\s*package\s+([\w.]+)", re.MULTILINE)+_ROOT_PROJECT_NAME_RE = re.compile(r'rootProject\s*\.\s*name\s*=\s*"([^"]+)"')++_DEFAULT_MAIN_SRC_ROOTS = ("src/main/java", "src/main/kotlin")+_DEFAULT_TEST_SRC_ROOTS = ("src/test/java", "src/test/kotlin")++_TEST_SOURCESET_MARKERS = frozenset({+ "test", "it", "jmh", "functional", "smoke", "acceptance",+ "integration", "e2e", "perf", "benchmark", "fray",+})++_JVM_EXTENSIONS = frozenset({".java", ".kt"})+++# ---------------------------------------------------------------------------+# Data model+# ---------------------------------------------------------------------------++@dataclass(frozen=True)+class SourceSet:+ name: str+ is_main: bool+ is_test: bool+ src_dirs: tuple[str, ...]+ resource_dirs: tuple[str, ...] = ()+++@dataclass(frozen=True)+class JvmGradleProject:+ id: str+ root_dir: str+ source_sets: dict[str, SourceSet] = field(default_factory=dict)+ plugins: frozenset[str] = frozenset()+++@dataclass+class JvmGradleIndex:+ """Unified package-to-files index for Java + Kotlin Gradle projects."""++ modules: dict[str, list[str]] = field(default_factory=dict)+ package_to_files: dict[str, list[str]] = field(default_factory=dict)+ projects: dict[str, JvmGradleProject] = field(default_factory=dict)++ # Custom project-dir overrides from settings.gradle+ _project_dir_overrides: dict[str, str] = field(default_factory=dict)++ def lookup_class(self, fqn: str) -> list[str]:+ """Match ``com.example.Foo`` to files declaring ``package com.example``+ and named ``Foo.java`` / ``Foo.kt`` / ``Foo.kts``.+ """+ if "." not in fqn:+ return self.package_to_files.get(fqn, [])+ package, local = fqn.rsplit(".", 1)+ candidates = self.package_to_files.get(package, [])+ local_lower = local.lower()+ return [+ p for p in candidates+ if p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower() == local_lower+ ]++ def files_in_package(self, package_fqn: str) -> list[str]:+ """Return all files declaring the given package."""+ return self.package_to_files.get(package_fqn, [])+++# ---------------------------------------------------------------------------+# Settings parsing+# ---------------------------------------------------------------------------++def _parse_settings(settings_file: Path) -> tuple[list[str], dict[str, str]]:+ """Return (module_names, project_dir_overrides) from settings.gradle(.kts)."""+ if not settings_file.is_file():+ return [], {}+ try:+ text = settings_file.read_text(encoding="utf-8", errors="ignore")+ except Exception:+ return [], {}++ modules: list[str] = []+ for match in _INCLUDE_RE.finditer(text):+ for item in _INCLUDE_ITEM_RE.findall(match.group(1)):+ modules.append(item.lstrip(":"))+ for match in _INCLUDE_LINE_RE.finditer(text):+ modules.append(match.group(2).lstrip(":"))++ # Dedupe preserving order+ seen: set[str] = set()+ result: list[str] = []+ for m in modules:+ if m not in seen:+ seen.add(m)+ result.append(m)++ # Project-dir overrides: project(":foo").projectDir = file("custom/path")+ overrides: dict[str, str] = {}+ for match in _PROJECT_DIR_RE.finditer(text):+ mod = match.group(1).lstrip(":")+ overrides[mod] = match.group(2)++ return result, overrides+++def _module_dir(repo_path: Path, module_name: str, overrides: dict[str, str]) -> Path:+ if module_name in overrides:+ return repo_path / overrides[module_name]+ return repo_path / module_name.replace(":", "/")+++# ---------------------------------------------------------------------------+# Source-set discovery+# ---------------------------------------------------------------------------++def _is_test_source_set(name: str) -> bool:+ lower = name.lower()+ for marker in _TEST_SOURCESET_MARKERS:+ if marker in lower:+ return True+ return False+++def _detect_source_sets_from_dirs(module_dir: Path) -> list[SourceSet]:+ """Detect source sets by scanning src/<name>/{java,kotlin} directories."""+ src_dir = module_dir / "src"+ if not src_dir.is_dir():+ return []+ source_sets: list[SourceSet] = []+ try:+ entries = sorted(src_dir.iterdir())+ except OSError:+ return []+ for entry in entries:+ if not entry.is_dir():+ continue+ name = entry.name+ sub_dirs: list[str] = []+ for lang_dir in ("java", "kotlin"):+ candidate = entry / lang_dir+ if candidate.is_dir():+ sub_dirs.append(f"src/{name}/{lang_dir}")+ # Also check for files directly in src/<name> (some projects put .kt/.java there)+ if not sub_dirs:+ has_jvm = any(+ f.suffix in _JVM_EXTENSIONS+ for f in entry.iterdir()+ if f.is_file()+ ) if entry.is_dir() else False+ if has_jvm:+ sub_dirs.append(f"src/{name}")+ if sub_dirs:+ is_main = name == "main"+ is_test = _is_test_source_set(name) if not is_main else False+ source_sets.append(SourceSet(+ name=name,+ is_main=is_main,+ is_test=is_test,+ src_dirs=tuple(sub_dirs),+ ))+ return source_sets+++def _source_roots_for_module(module_dir: Path) -> list[str]:+ """Return source-root paths (relative to module_dir).++ Honours explicit ``srcDirs(...)`` overrides in ``build.gradle(.kts)``;+ falls back to standard defaults.+ """+ overrides: list[str] = []+ for build_name in ("build.gradle.kts", "build.gradle"):+ build = module_dir / build_name+ if not build.is_file():+ continue+ try:+ text = build.read_text(encoding="utf-8", errors="ignore")+ except Exception:+ continue+ for match in _SRCDIRS_RE.finditer(text):+ for item in _INCLUDE_ITEM_RE.findall(match.group(1)):+ overrides.append(item)+ if overrides:+ seen: set[str] = set()+ return [o for o in overrides if not (o in seen or seen.add(o))] # type: ignore[func-returns-value]+ return list(_DEFAULT_MAIN_SRC_ROOTS)+++def _detect_plugins(module_dir: Path) -> frozenset[str]:+ """Extract plugin IDs from build.gradle(.kts)."""+ plugins: list[str] = []+ for build_name in ("build.gradle.kts", "build.gradle"):+ build = module_dir / build_name+ if not build.is_file():+ continue+ try:+ text = build.read_text(encoding="utf-8", errors="ignore")+ except Exception:+ continue+ for pat in (_PLUGIN_ID_RE, _PLUGIN_ID_GROOVY_RE, _APPLY_PLUGIN_RE):+ for m in pat.finditer(text):+ plugins.append(m.group(1))+ return frozenset(plugins)+++# ---------------------------------------------------------------------------+# Package extraction (cached per file)+# ---------------------------------------------------------------------------++@lru_cache(maxsize=8192)+def _extract_file_info(abs_path: str) -> tuple[str, tuple[str, ...], bool, bool]:+ """Return (package_decl, top_level_types, is_module_info, is_package_info).++ Reads the file once and caches the result. Cheap line scan, no AST.+ """+ path = Path(abs_path)+ name = path.name+ is_module_info = name == "module-info.java"+ is_package_info = name == "package-info.java"++ try:+ text = path.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ return "", (), is_module_info, is_package_info++ package = ""+ pkg_match = _PACKAGE_RE.search(text)+ if pkg_match:+ package = pkg_match.group(1)++ top_level: list[str] = []+ _TYPE_DECL_RE = re.compile(+ r"^\s*(?:public\s+|private\s+|protected\s+|internal\s+|abstract\s+|final\s+|sealed\s+|open\s+|data\s+)*"+ r"(?:class|interface|enum|object|record|annotation)\s+(\w+)",+ re.MULTILINE,+ )+ for m in _TYPE_DECL_RE.finditer(text):+ top_level.append(m.group(1))++ return package, tuple(top_level), is_module_info, is_package_info+++# ---------------------------------------------------------------------------+# Index building+# ---------------------------------------------------------------------------++def build_jvm_gradle_index(repo_path: Path | None) -> JvmGradleIndex:+ """Walk Gradle config + JVM sources to build the package-resolution index."""+ index = JvmGradleIndex()+ if repo_path is None or not repo_path.is_dir():+ return index++ settings_paths = [repo_path / "settings.gradle.kts", repo_path / "settings.gradle"]+ modules: list[str] = []+ project_dir_overrides: dict[str, str] = {}+ for sp in settings_paths:+ mods, ovr = _parse_settings(sp)+ modules.extend(mods)+ project_dir_overrides.update(ovr)++ if not modules:+ if (repo_path / "build.gradle").is_file() or (repo_path / "build.gradle.kts").is_file():+ modules = [""]++ resolved_repo = repo_path.resolve()++ for module_name in modules:+ mod_dir = _module_dir(repo_path, module_name, project_dir_overrides) if module_name else repo_path+ if not mod_dir.is_dir():+ continue++ plugins = _detect_plugins(mod_dir)++ # Discover source sets+ source_sets = _detect_source_sets_from_dirs(mod_dir)+ if not source_sets:+ # Fallback: use explicit srcDirs or defaults+ roots = _source_roots_for_module(mod_dir)+ source_sets = [SourceSet(+ name="main",+ is_main=True,+ is_test=False,+ src_dirs=tuple(roots),+ )]++ ss_map: dict[str, SourceSet] = {ss.name: ss for ss in source_sets}+ project = JvmGradleProject(+ id=module_name or "<root>",+ root_dir=mod_dir.relative_to(resolved_repo).as_posix() if module_name else "",+ source_sets=ss_map,+ plugins=plugins,+ )+ index.projects[project.id] = project++ rel_roots: list[str] = []+ for ss in source_sets:+ for src_dir in ss.src_dirs:+ root_path = (mod_dir / src_dir).resolve()+ if not root_path.is_dir():+ continue+ try:+ rel = root_path.relative_to(resolved_repo).as_posix()+ except ValueError:+ continue+ rel_roots.append(rel)++ for jvm_file in root_path.rglob("*"):+ if jvm_file.suffix not in _JVM_EXTENSIONS or not jvm_file.is_file():+ continue+ try:+ rel_file = jvm_file.relative_to(resolved_repo).as_posix()+ except ValueError:+ continue+ package, _types, _is_mod, _is_pkg = _extract_file_info(str(jvm_file.resolve()))+ if not package:+ continue+ index.package_to_files.setdefault(package, []).append(rel_file)++ if rel_roots:+ index.modules[module_name or "<root>"] = rel_roots++ _extract_file_info.cache_clear()++ log.debug(+ "Built JVM Gradle index",+ modules=len(index.modules),+ packages=len(index.package_to_files),+ projects=len(index.projects),+ )+ return index+++def get_or_build_jvm_gradle_index(ctx: "ResolverContext") -> JvmGradleIndex:+ """Return the cached JvmGradleIndex, building it on first access."""+ cached = getattr(ctx, "_jvm_gradle_index", None)+ if cached is not None:+ return cached+ index = build_jvm_gradle_index(ctx.repo_path)+ ctx._jvm_gradle_index = index # type: ignore[attr-defined]+ return index+++def resolve_via_jvm_gradle_index(module_path: str, ctx: "ResolverContext") -> str | None:+ """Resolve an FQN to a single file via the Gradle index."""+ index = get_or_build_jvm_gradle_index(ctx)+ matches = index.lookup_class(module_path)+ return matches[0] if matches else None+++# ---------------------------------------------------------------------------+# Back-compat: KotlinProjectIndex facade for kotlin_gradle.py re-exports+# ---------------------------------------------------------------------------++@dataclass+class KotlinProjectIndex:+ """Thin wrapper for backwards compatibility with kotlin_gradle.py consumers."""++ _inner: JvmGradleIndex = field(default_factory=JvmGradleIndex)++ @property+ def modules(self) -> dict[str, list[str]]:+ return self._inner.modules++ @property+ def package_to_files(self) -> dict[str, list[str]]:+ return self._inner.package_to_files++ def lookup_class(self, fqn: str) -> list[str]:+ return self._inner.lookup_class(fqn)+++def build_kotlin_index(repo_path: Path | None) -> KotlinProjectIndex:+ """Back-compat: build a KotlinProjectIndex wrapping the JVM Gradle index."""+ return KotlinProjectIndex(_inner=build_jvm_gradle_index(repo_path))+++def get_or_build_kotlin_index(ctx: "ResolverContext") -> KotlinProjectIndex:+ """Back-compat: return a KotlinProjectIndex wrapping the JVM Gradle index."""+ jvm_index = get_or_build_jvm_gradle_index(ctx)+ return KotlinProjectIndex(_inner=jvm_index)+++def resolve_via_kotlin_index(module_path: str, ctx: "ResolverContext") -> str | None:+ """Back-compat: resolve via the JVM Gradle index."""+ return resolve_via_jvm_gradle_index(module_path, ctx)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.pynew file mode 100644index 000000000..d74d2b2a8--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py@@ -0,0 +1,337 @@+"""JVM workspace index — unified package model for Java + Kotlin.++Groups ``.java`` and ``.kt`` files by their JVM package declaration,+building a single lookup surface consumed by both the Java and Kotlin+import resolvers, the call resolver (same-package implicit access), and+the dead-code analyzer (package-aware reachability).++The index is the JVM analogue of :class:`GoPackageIndex` (Go),+:class:`DotNetProjectIndex` (C#), and :class:`CargoWorkspaceIndex`+(Rust). Built once per resolver run via :func:`get_or_build_jvm_index`+and cached on the context.+"""++from __future__ import annotations++import re+from dataclasses import dataclass, field+from functools import lru_cache+from pathlib import Path, PurePosixPath+from typing import TYPE_CHECKING++import structlog++if TYPE_CHECKING:+ from .context import ResolverContext++log = structlog.get_logger(__name__)++_PACKAGE_RE = re.compile(r"^\s*package\s+([\w.]+)", re.MULTILINE)+_TOP_LEVEL_TYPE_RE = re.compile(+ r"^\s*(?:public\s+|private\s+|protected\s+|internal\s+|abstract\s+|final\s+|sealed\s+|open\s+|data\s+)*"+ r"(?:class|interface|enum|object|record|annotation)\s+(\w+)",+ re.MULTILINE,+)+_JVM_EXTENSIONS = frozenset({".java", ".kt"})++# Standard-library packages that should never produce import edges+_JAVA_LANG_PACKAGES = frozenset({+ "java.lang",+ "java.lang.annotation",+ "java.lang.invoke",+ "java.lang.reflect",+})++# Types automatically imported via java.lang.*+_JAVA_LANG_TYPES = frozenset({+ "String", "Object", "Class", "System", "Math",+ "Integer", "Long", "Double", "Float", "Boolean", "Character", "Byte", "Short",+ "Number", "Void",+ "Thread", "Runnable", "Process", "ProcessBuilder", "Runtime",+ "Throwable", "Exception", "RuntimeException", "Error",+ "IllegalArgumentException", "IllegalStateException", "NullPointerException",+ "UnsupportedOperationException", "IndexOutOfBoundsException",+ "ClassCastException", "ArithmeticException", "SecurityException",+ "ClassNotFoundException", "InterruptedException", "CloneNotSupportedException",+ "StringBuilder", "StringBuffer", "StringIndexOutOfBoundsException",+ "Enum", "Record", "Comparable", "Iterable", "AutoCloseable", "Cloneable",+ "Override", "Deprecated", "SuppressWarnings", "FunctionalInterface", "SafeVarargs",+})+++@dataclass(frozen=True)+class JvmPackage:+ """A single JVM package — a directory of ``.java`` + ``.kt`` sibling files."""++ fqn: str+ files: tuple[str, ...]+ exported_top_level: dict[str, tuple[str, ...]] = field(default_factory=dict)+++@dataclass+class JvmWorkspaceIndex:+ """Repo-scoped view of every local JVM package."""++ packages: dict[str, JvmPackage] = field(default_factory=dict)+ """Keyed by fully-qualified package name."""++ file_to_package: dict[str, str] = field(default_factory=dict)+ """Maps repo-relative file path → package FQN."""++ fqn_to_files: dict[str, list[str]] = field(default_factory=dict)+ """Maps a fully-qualified class name → defining file(s)."""++ services: dict[str, tuple[str, ...]] = field(default_factory=dict)+ """META-INF/services/<Iface> → impl FQNs (for Phase 3/4 reachability)."""++ autoconfig_imports: dict[str, tuple[str, ...]] = field(default_factory=dict)+ """Spring Boot autoconfig import files → listed FQNs (for Phase 3/4)."""++ def files_for_package(self, fqn: str) -> tuple[str, ...]:+ """Return all files in the package."""+ pkg = self.packages.get(fqn)+ return pkg.files if pkg else ()++ def files_for_fqn(self, fqn: str) -> tuple[str, ...]:+ """Resolve a fully-qualified name to its defining file(s)."""+ direct = self.fqn_to_files.get(fqn)+ if direct:+ return tuple(direct)++ # Fall back: split into package + type name, search package files+ if "." not in fqn:+ return ()+ package, type_name = fqn.rsplit(".", 1)+ pkg = self.packages.get(package)+ if pkg is None:+ return ()+ files = pkg.exported_top_level.get(type_name)+ return files if files else ()++ def wildcard_expand(self, pkg_fqn: str) -> tuple[str, ...]:+ """Expand ``import pkg.*`` → all files in the package."""+ return self.files_for_package(pkg_fqn)++ def static_wildcard_expand(self, type_fqn: str) -> tuple[str, ...]:+ """Expand ``import static pkg.Type.*`` → file(s) defining Type."""+ return self.files_for_fqn(type_fqn)++ def package_for_file(self, file_path: str) -> str | None:+ """Return the package FQN for a file, or None."""+ return self.file_to_package.get(file_path)++ def same_package_files(self, file_path: str) -> tuple[str, ...]:+ """Return all sibling files in the same package (excluding the file itself)."""+ pkg_fqn = self.file_to_package.get(file_path)+ if not pkg_fqn:+ return ()+ pkg = self.packages.get(pkg_fqn)+ if not pkg:+ return ()+ return tuple(f for f in pkg.files if f != file_path)++ def is_java_lang(self, import_path: str) -> bool:+ """Return True if the import is a java.lang.* builtin."""+ if import_path.startswith("java.lang."):+ remainder = import_path[len("java.lang."):]+ if "." not in remainder:+ return True+ # java.lang.annotation.*, java.lang.reflect.*, etc.+ pkg = import_path.rsplit(".", 1)[0]+ return pkg in _JAVA_LANG_PACKAGES+ # Unqualified types in java.lang+ parts = import_path.split(".")+ if len(parts) == 1 and parts[0] in _JAVA_LANG_TYPES:+ return True+ return False+++@lru_cache(maxsize=16384)+def _scan_jvm_file(abs_path: str) -> tuple[str, tuple[str, ...]]:+ """Return (package_fqn, top_level_type_names) for a JVM source file.++ Reads the file once and caches the result. Cheap line scan — no AST.+ """+ try:+ text = Path(abs_path).read_text(encoding="utf-8", errors="ignore")+ except OSError:+ return "", ()++ package = ""+ pkg_match = _PACKAGE_RE.search(text)+ if pkg_match:+ package = pkg_match.group(1)++ types: list[str] = []+ for m in _TOP_LEVEL_TYPE_RE.finditer(text):+ types.append(m.group(1))++ return package, tuple(types)+++def _scan_meta_inf_services(repo_path: Path) -> dict[str, tuple[str, ...]]:+ """Scan META-INF/services/ directories for SPI declarations."""+ services: dict[str, list[str]] = {}+ for services_dir in repo_path.rglob("META-INF/services"):+ if not services_dir.is_dir():+ continue+ try:+ for entry in services_dir.iterdir():+ if not entry.is_file():+ continue+ iface_fqn = entry.name+ try:+ text = entry.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ impls: list[str] = []+ for line in text.splitlines():+ line = line.strip()+ if line and not line.startswith("#"):+ # Remove inline comments+ line = line.split("#")[0].strip()+ if line:+ impls.append(line)+ if impls:+ services.setdefault(iface_fqn, []).extend(impls)+ except OSError:+ continue+ return {k: tuple(v) for k, v in services.items()}+++def _scan_spring_autoconfig(repo_path: Path) -> dict[str, tuple[str, ...]]:+ """Scan spring.factories and Boot 3 AutoConfiguration.imports."""+ result: dict[str, list[str]] = {}++ # spring.factories (Boot 2 style)+ for factories in repo_path.rglob("META-INF/spring.factories"):+ if not factories.is_file():+ continue+ try:+ text = factories.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ current_key = ""+ current_values: list[str] = []+ for line in text.splitlines():+ line = line.strip()+ if not line or line.startswith("#"):+ continue+ if "=" in line and not line.startswith("\\"):+ if current_key and current_values:+ rel = str(factories.relative_to(repo_path).as_posix())+ result.setdefault(rel, []).extend(current_values)+ key, _, val = line.partition("=")+ current_key = key.strip()+ val = val.strip().rstrip("\\").strip()+ current_values = [v.strip() for v in val.split(",") if v.strip()]+ elif line.startswith("\\") or (current_key and line):+ val = line.lstrip("\\").strip()+ current_values.extend(v.strip() for v in val.split(",") if v.strip())+ if current_key and current_values:+ rel = str(factories.relative_to(repo_path).as_posix())+ result.setdefault(rel, []).extend(current_values)++ # Boot 3 style: META-INF/spring/*.imports+ for imports_file in repo_path.rglob("META-INF/spring/*.imports"):+ if not imports_file.is_file():+ continue+ try:+ text = imports_file.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ fqns: list[str] = []+ for line in text.splitlines():+ line = line.strip()+ if line and not line.startswith("#"):+ fqns.append(line)+ if fqns:+ rel = str(imports_file.relative_to(repo_path).as_posix())+ result.setdefault(rel, []).extend(fqns)++ return {k: tuple(v) for k, v in result.items()}+++def build_jvm_workspace_index(ctx: "ResolverContext") -> JvmWorkspaceIndex:+ """Build the JVM workspace index from all ``.java`` and ``.kt`` files in the path set.++ One walk over the path set; each file read at most once (via+ ``_scan_jvm_file`` LRU cache). The index groups files by package+ and builds FQN → file mappings.+ """+ index = JvmWorkspaceIndex()++ if ctx.repo_path is None:+ return index++ repo_path = ctx.repo_path.resolve()++ # Group files by package+ pkg_files: dict[str, list[str]] = {}+ pkg_types: dict[str, dict[str, list[str]]] = {}++ for path in ctx.path_set:+ if not (path.endswith(".java") or path.endswith(".kt")):+ continue++ abs_path = str((repo_path / path).resolve())+ package, top_types = _scan_jvm_file(abs_path)+ if not package:+ continue++ pkg_files.setdefault(package, []).append(path)+ index.file_to_package[path] = package++ type_map = pkg_types.setdefault(package, {})+ for type_name in top_types:+ type_map.setdefault(type_name, []).append(path)+ fqn = f"{package}.{type_name}"+ index.fqn_to_files.setdefault(fqn, []).append(path)++ # Build JvmPackage objects+ for pkg_fqn, files in pkg_files.items():+ files.sort()+ exported = {+ name: tuple(file_list)+ for name, file_list in pkg_types.get(pkg_fqn, {}).items()+ }+ index.packages[pkg_fqn] = JvmPackage(+ fqn=pkg_fqn,+ files=tuple(files),+ exported_top_level=exported,+ )++ # Scan META-INF resources (cheap glob, O(matching files))+ try:+ index.services = _scan_meta_inf_services(repo_path)+ except Exception:+ pass+ try:+ index.autoconfig_imports = _scan_spring_autoconfig(repo_path)+ except Exception:+ pass++ _scan_jvm_file.cache_clear()++ log.debug(+ "Built JVM workspace index",+ packages=len(index.packages),+ fqns=len(index.fqn_to_files),+ files=len(index.file_to_package),+ services=len(index.services),+ autoconfig=len(index.autoconfig_imports),+ )+ return index+++_INDEX_KEY = "_jvm_workspace_index"+++def get_or_build_jvm_index(ctx: "ResolverContext") -> JvmWorkspaceIndex:+ """Return the cached JvmWorkspaceIndex, building it on first access."""+ cached = getattr(ctx, _INDEX_KEY, None)+ if cached is not None:+ return cached+ index = build_jvm_workspace_index(ctx)+ setattr(ctx, _INDEX_KEY, index)+ return indexdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.pyindex b06bb9fe3..436b7fee3 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py@@ -1,40 +1,82 @@-"""Kotlin import resolution."""+"""Kotlin import resolution with JVM workspace awareness.++Resolves Kotlin imports using the shared JVM workspace index for+package-aware cross-language resolution (Kotlin ↔ Java), fan-out to+package siblings, and wildcard imports.+"""from __future__ import annotationsfrom pathlib import PurePosixPath+from typing import TYPE_CHECKING-from .context import ResolverContext+from .jvm_workspace import get_or_build_jvm_indexfrom .kotlin_gradle import resolve_via_kotlin_index+if TYPE_CHECKING:+ from .context import ResolverContext+++def resolve_kotlin_import(+ module_path: str, importer_path: str, ctx: ResolverContext+) -> str | None:+ """Resolve a Kotlin import to a single representative repo-relative file."""+ targets = resolve_kotlin_import_all(module_path, importer_path, ctx)+ return targets[0] if targets else None+++def resolve_kotlin_import_all(+ module_path: str, importer_path: str, ctx: ResolverContext+) -> tuple[str, ...]:+ """Resolve a Kotlin import to all matching repo-relative file paths.++ Fan-out semantics mirror Java: wildcard imports expand to all+ package files; single-class imports resolve across both .kt and+ .java files in the same package.+ """+ if not module_path:+ return ()-def resolve_kotlin_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:- """Resolve a Kotlin import to a repo-relative file path."""parts = module_path.split(".")local = parts[-1]+ jvm_index = get_or_build_jvm_index(ctx)++ # Filter java.lang.* builtins+ if jvm_index.is_java_lang(module_path):+ return ()++ # Handle wildcard import: import com.foo.*if local == "*":- return None+ pkg_fqn = ".".join(parts[:-1])+ if pkg_fqn:+ files = jvm_index.wildcard_expand(pkg_fqn)+ if files:+ return files+ return (ctx.add_external_node(module_path),) if module_path else ()++ # Try JVM workspace index first (handles cross-language Java ↔ Kotlin)+ files = jvm_index.files_for_fqn(module_path)+ if files:+ return files- # Gradle-aware resolution: settings.gradle subprojects + per-module- # sourceSets parsing yields a {package → files} index. Consult it first- # so multi-module Android/JVM layouts resolve correctly.+ # Gradle-aware resolution (settings.gradle subprojects)gradle_match = resolve_via_kotlin_index(module_path, ctx)if gradle_match is not None:- return gradle_match+ return (gradle_match,)# Try stem lookup on the class/function nameresult = ctx.stem_lookup(local.lower())- if result and (result.endswith(".kt") or result.endswith(".kts")):- return result+ if result and (result.endswith(".kt") or result.endswith(".kts") or result.endswith(".java")):+ return (result,)# Try matching the package path as a directory structureif len(parts) > 1:dir_suffix = "/".join(parts[:-1])for p in ctx.path_set:- if p.endswith(".kt") and dir_suffix in p:+ if (p.endswith(".kt") or p.endswith(".java")) and dir_suffix in p:stem = PurePosixPath(p).stemif stem.lower() == local.lower():- return p+ return (p,)- return ctx.add_external_node(module_path)+ return (ctx.add_external_node(module_path),)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/kotlin_gradle.py b/packages/core/src/repowise/core/ingestion/resolvers/kotlin_gradle.pyindex 1de656e7c..91f6f0650 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/kotlin_gradle.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/kotlin_gradle.py@@ -1,187 +1,23 @@"""Gradle multi-module / sourceSets index for Kotlin import resolution.-Real Android and JVM projects use Gradle layouts where source roots live-under per-module directories: ``app/src/main/kotlin/...``,-``feature-foo/src/main/kotlin/...``. The default ``resolve_kotlin_import``-relies on stem matching, which fails when two modules contain a class of-the same name.--This module:-- enumerates Gradle subprojects from ``settings.gradle(.kts)`` ``include(...)``- declarations,-- collects source roots per subproject (defaults: ``src/main/kotlin``,- ``src/main/java``; explicit ``srcDirs`` overrides honoured),-- scans each source file's ``package`` declaration to build a- ``{fully.qualified.Name → [path, ...]}`` map.+This module is a thin re-export facade over :mod:`.jvm_gradle`, which+provides the full Gradle index for both Java and Kotlin. All public+symbols and function signatures are preserved so existing callers+(e.g. ``kotlin.py``) continue to work unchanged."""from __future__ import annotations-import re-from dataclasses import dataclass, field-from pathlib import Path-from typing import TYPE_CHECKING--if TYPE_CHECKING:- from .context import ResolverContext---_INCLUDE_RE = re.compile(r'include\s*\(\s*((?:"[^"]+"\s*,?\s*)+)\)')-_INCLUDE_ITEM_RE = re.compile(r'"([^"]+)"')-_INCLUDE_LINE_RE = re.compile(r'include\s+([\'"])([^\'"]+)\1')-_SRCDIRS_RE = re.compile(- r'srcDirs?\s*[=(]\s*((?:listOf|setOf)?\s*\(?\s*(?:"[^"]+"\s*,?\s*)+\)?)',- re.DOTALL,+from .jvm_gradle import (+ KotlinProjectIndex,+ build_kotlin_index,+ get_or_build_kotlin_index,+ resolve_via_kotlin_index,)-_PACKAGE_RE = re.compile(r"^\s*package\s+([\w.]+)", re.MULTILINE)-_DEFAULT_SRC_ROOTS = ("src/main/kotlin", "src/main/java")---@dataclass-class KotlinProjectIndex:- modules: dict[str, list[str]] = field(default_factory=dict)- package_to_files: dict[str, list[str]] = field(default_factory=dict)-- def lookup_class(self, fqn: str) -> list[str]:- """Match ``com.example.Foo`` → files declaring ``package com.example``- and named ``Foo.kt``/``Foo.kts``.- """- if "." not in fqn:- return self.package_to_files.get(fqn, [])- package, local = fqn.rsplit(".", 1)- candidates = self.package_to_files.get(package, [])- local_lower = local.lower()- return [- p for p in candidates- if p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower() == local_lower- ]---def _parse_settings(settings_file: Path) -> list[str]:- """Return Gradle module names from ``include(...)`` lines.-- Module names use ``:foo:bar`` syntax; we keep them as-written so callers- can map ``:foo:bar`` → ``foo/bar`` directory.- """- if not settings_file.is_file():- return []- try:- text = settings_file.read_text(encoding="utf-8", errors="ignore")- except Exception:- return []- modules: list[str] = []- for match in _INCLUDE_RE.finditer(text):- for item in _INCLUDE_ITEM_RE.findall(match.group(1)):- modules.append(item.lstrip(":"))- for match in _INCLUDE_LINE_RE.finditer(text):- modules.append(match.group(2).lstrip(":"))- # Dedupe preserving order- seen: set[str] = set()- result: list[str] = []- for m in modules:- if m not in seen:- seen.add(m)- result.append(m)- return result---def _module_dir(repo_path: Path, module_name: str) -> Path:- return repo_path / module_name.replace(":", "/")---def _source_roots_for_module(module_dir: Path) -> list[str]:- """Return source-root paths (relative to module_dir) for *module_dir*.-- Honours explicit ``srcDirs(...)`` overrides in ``build.gradle(.kts)``;- falls back to standard ``src/main/{kotlin,java}`` defaults.- """- overrides: list[str] = []- for build_name in ("build.gradle.kts", "build.gradle"):- build = module_dir / build_name- if not build.is_file():- continue- try:- text = build.read_text(encoding="utf-8", errors="ignore")- except Exception:- continue- for match in _SRCDIRS_RE.finditer(text):- for item in _INCLUDE_ITEM_RE.findall(match.group(1)):- overrides.append(item)- if overrides:- # Dedupe + return verbatim (caller resolves relative-to-module)- seen: set[str] = set()- return [o for o in overrides if not (o in seen or seen.add(o))]- return list(_DEFAULT_SRC_ROOTS)---def build_kotlin_index(repo_path: Path | None) -> KotlinProjectIndex:- """Walk Gradle config + Kotlin sources to build the package-resolution index."""- index = KotlinProjectIndex()- if repo_path is None or not repo_path.is_dir():- return index-- # Discover modules. Root-level Gradle build with no settings.gradle still- # counts as a single anonymous module rooted at repo_path.- settings_paths = [repo_path / "settings.gradle.kts", repo_path / "settings.gradle"]- modules: list[str] = []- for sp in settings_paths:- modules.extend(_parse_settings(sp))- if not modules:- # Single-module fallback: only consider the repo itself when a- # build.gradle is present.- if (- (repo_path / "build.gradle").is_file()- or (repo_path / "build.gradle.kts").is_file()- ):- modules = [""]-- for module_name in modules:- mod_dir = _module_dir(repo_path, module_name) if module_name else repo_path- if not mod_dir.is_dir():- continue- roots = _source_roots_for_module(mod_dir)- rel_roots: list[str] = []- for root in roots:- root_path = (mod_dir / root).resolve()- if not root_path.is_dir():- continue- try:- rel = root_path.relative_to(repo_path.resolve()).as_posix()- except ValueError:- continue- rel_roots.append(rel)- # Walk Kotlin files under this root- for kt in root_path.rglob("*.kt"):- try:- rel_kt = kt.relative_to(repo_path.resolve()).as_posix()- except ValueError:- continue- try:- text = kt.read_text(encoding="utf-8", errors="ignore")- except Exception:- continue- pkg_match = _PACKAGE_RE.search(text)- if not pkg_match:- continue- package = pkg_match.group(1)- index.package_to_files.setdefault(package, []).append(rel_kt)- if rel_roots:- index.modules[module_name or "<root>"] = rel_roots- return index---def get_or_build_kotlin_index(ctx: "ResolverContext") -> KotlinProjectIndex:- cached = getattr(ctx, "_kotlin_index", None)- if cached is not None:- return cached- index = build_kotlin_index(ctx.repo_path)- ctx._kotlin_index = index # type: ignore[attr-defined]- return index--def resolve_via_kotlin_index(module_path: str, ctx: "ResolverContext") -> str | None:- index = get_or_build_kotlin_index(ctx)- matches = index.lookup_class(module_path)- if matches:- return matches[0]- return None+__all__ = [+ "KotlinProjectIndex",+ "build_kotlin_index",+ "get_or_build_kotlin_index",+ "resolve_via_kotlin_index",+]diff --git a/tests/unit/ingestion/test_java_resolver.py b/tests/unit/ingestion/test_java_resolver.pynew file mode 100644index 000000000..ac5bfc267--- /dev/null+++ b/tests/unit/ingestion/test_java_resolver.py@@ -0,0 +1,101 @@+"""Unit tests for the Java import resolver."""++from __future__ import annotations++from pathlib import Path++import networkx as nx++from repowise.core.ingestion.resolvers.context import ResolverContext+from repowise.core.ingestion.resolvers.java import (+ resolve_java_import,+ resolve_java_import_all,+)+++def _ctx(repo: Path, paths: list[str]) -> ResolverContext:+ path_set = set(paths)+ stem_map: dict[str, list[str]] = {}+ for p in paths:+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()+ stem_map.setdefault(stem, []).append(p)+ return ResolverContext(+ path_set=path_set,+ stem_map=stem_map,+ graph=nx.DiGraph(),+ repo_path=repo,+ )+++def _make_java(repo: Path, rel_path: str, package: str, class_name: str) -> str:+ full = repo / rel_path+ full.parent.mkdir(parents=True, exist_ok=True)+ full.write_text(f"package {package};\n\npublic class {class_name} {{}}\n")+ return rel_path+++def _make_kotlin(repo: Path, rel_path: str, package: str, class_name: str) -> str:+ full = repo / rel_path+ full.parent.mkdir(parents=True, exist_ok=True)+ full.write_text(f"package {package}\n\nclass {class_name}\n")+ return rel_path+++class TestJavaImportResolution:+ def test_single_class_import(self, tmp_path: Path) -> None:+ a = _make_java(tmp_path, "src/main/java/com/foo/Bar.java", "com.foo", "Bar")+ ctx = _ctx(tmp_path, [a])+ result = resolve_java_import("com.foo.Bar", "src/main/java/Main.java", ctx)+ assert result == a++ def test_wildcard_import_fans_out(self, tmp_path: Path) -> None:+ a = _make_java(tmp_path, "src/main/java/com/foo/A.java", "com.foo", "A")+ b = _make_java(tmp_path, "src/main/java/com/foo/B.java", "com.foo", "B")+ ctx = _ctx(tmp_path, [a, b])+ targets = resolve_java_import_all("com.foo.*", "src/main/java/Main.java", ctx)+ assert len(targets) == 2+ assert a in targets+ assert b in targets++ def test_java_lang_filtered(self, tmp_path: Path) -> None:+ ctx = _ctx(tmp_path, [])+ result = resolve_java_import("java.lang.String", "Main.java", ctx)+ assert result is None++ def test_java_lang_object_filtered(self, tmp_path: Path) -> None:+ ctx = _ctx(tmp_path, [])+ targets = resolve_java_import_all("java.lang.Object", "Main.java", ctx)+ assert targets == ()++ def test_cross_language_java_to_kotlin(self, tmp_path: Path) -> None:+ kt = _make_kotlin(tmp_path, "src/main/java/com/foo/Service.kt", "com.foo", "Service")+ ctx = _ctx(tmp_path, [kt])+ result = resolve_java_import("com.foo.Service", "src/main/java/Main.java", ctx)+ assert result == kt++ def test_external_package(self, tmp_path: Path) -> None:+ ctx = _ctx(tmp_path, [])+ result = resolve_java_import("org.springframework.boot.SpringApplication", "Main.java", ctx)+ assert result is not None+ assert result.startswith("external:")++ def test_static_wildcard(self, tmp_path: Path) -> None:+ a = _make_java(tmp_path, "src/main/java/com/foo/Constants.java", "com.foo", "Constants")+ ctx = _ctx(tmp_path, [a])+ # import static com.foo.Constants.* → resolve to Constants file+ targets = resolve_java_import_all("com.foo.Constants", "Main.java", ctx)+ assert a in targets++ def test_stem_fallback(self, tmp_path: Path) -> None:+ a = _make_java(tmp_path, "src/Util.java", "com.foo", "Util")+ ctx = _ctx(tmp_path, [a])+ result = resolve_java_import("com.bar.Util", "Main.java", ctx)+ assert result == a++ def test_package_fan_out_single_import(self, tmp_path: Path) -> None:+ """A single-class import resolves to the specific file, not all package files."""+ a = _make_java(tmp_path, "src/main/java/com/foo/A.java", "com.foo", "A")+ b = _make_java(tmp_path, "src/main/java/com/foo/B.java", "com.foo", "B")+ ctx = _ctx(tmp_path, [a, b])+ targets = resolve_java_import_all("com.foo.A", "Main.java", ctx)+ assert targets == (a,)diff --git a/tests/unit/ingestion/test_jvm_gradle.py b/tests/unit/ingestion/test_jvm_gradle.pynew file mode 100644index 000000000..91faee899--- /dev/null+++ b/tests/unit/ingestion/test_jvm_gradle.py@@ -0,0 +1,130 @@+"""Unit tests for the JVM Gradle index builder."""++from __future__ import annotations++from pathlib import Path++import networkx as nx++from repowise.core.ingestion.resolvers.context import ResolverContext+from repowise.core.ingestion.resolvers.jvm_gradle import (+ JvmGradleIndex,+ build_jvm_gradle_index,+)+++def _ctx(repo: Path, paths: list[str]) -> ResolverContext:+ path_set = set(paths)+ stem_map: dict[str, list[str]] = {}+ for p in paths:+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()+ stem_map.setdefault(stem, []).append(p)+ return ResolverContext(+ path_set=path_set,+ stem_map=stem_map,+ graph=nx.DiGraph(),+ repo_path=repo,+ )+++def _make_java_class(repo: Path, module: str, package: str, class_name: str) -> str:+ pkg_dir = package.replace(".", "/")+ src_dir = repo / module / "src" / "main" / "java" / pkg_dir+ src_dir.mkdir(parents=True, exist_ok=True)+ file_path = src_dir / f"{class_name}.java"+ file_path.write_text(f"package {package};\n\npublic class {class_name} {{}}\n")+ return file_path.relative_to(repo).as_posix()+++def _make_kotlin_class(repo: Path, module: str, package: str, class_name: str) -> str:+ pkg_dir = package.replace(".", "/")+ src_dir = repo / module / "src" / "main" / "kotlin" / pkg_dir+ src_dir.mkdir(parents=True, exist_ok=True)+ file_path = src_dir / f"{class_name}.kt"+ file_path.write_text(f"package {package}\n\nclass {class_name}\n")+ return file_path.relative_to(repo).as_posix()+++class TestJvmGradleIndex:+ def test_discovers_java_and_kotlin_files(self, tmp_path: Path) -> None:+ (tmp_path / "settings.gradle.kts").write_text('include("app")\n')+ (tmp_path / "build.gradle.kts").write_text("// root\n")+ java_path = _make_java_class(tmp_path, "app", "com.example", "Foo")+ kt_path = _make_kotlin_class(tmp_path, "app", "com.example", "Bar")++ index = build_jvm_gradle_index(tmp_path)++ assert "app" in index.modules+ pkg_files = index.package_to_files.get("com.example", [])+ assert java_path in pkg_files+ assert kt_path in pkg_files++ def test_lookup_class_java(self, tmp_path: Path) -> None:+ (tmp_path / "settings.gradle.kts").write_text('include("lib")\n')+ (tmp_path / "build.gradle.kts").write_text("// root\n")+ java_path = _make_java_class(tmp_path, "lib", "com.example.lib", "Engine")++ index = build_jvm_gradle_index(tmp_path)+ matches = index.lookup_class("com.example.lib.Engine")+ assert java_path in matches++ def test_lookup_class_kotlin(self, tmp_path: Path) -> None:+ (tmp_path / "settings.gradle.kts").write_text('include("lib")\n')+ (tmp_path / "build.gradle.kts").write_text("// root\n")+ kt_path = _make_kotlin_class(tmp_path, "lib", "com.example.lib", "Engine")++ index = build_jvm_gradle_index(tmp_path)+ matches = index.lookup_class("com.example.lib.Engine")+ assert kt_path in matches++ def test_files_in_package(self, tmp_path: Path) -> None:+ (tmp_path / "settings.gradle.kts").write_text('include("app")\n')+ (tmp_path / "build.gradle.kts").write_text("// root\n")+ _make_java_class(tmp_path, "app", "com.example.app", "A")+ _make_java_class(tmp_path, "app", "com.example.app", "B")++ index = build_jvm_gradle_index(tmp_path)+ files = index.files_in_package("com.example.app")+ assert len(files) == 2++ def test_single_module_fallback(self, tmp_path: Path) -> None:+ (tmp_path / "build.gradle.kts").write_text("// single\n")+ java_path = _make_java_class(tmp_path, "", "com.example", "App")++ index = build_jvm_gradle_index(tmp_path)+ assert "<root>" in index.modules+ assert index.lookup_class("com.example.App") == [java_path]++ def test_groovy_include(self, tmp_path: Path) -> None:+ (tmp_path / "settings.gradle").write_text("include 'core'\n")+ (tmp_path / "build.gradle").write_text("// root\n")+ _make_java_class(tmp_path, "core", "com.example", "Core")++ index = build_jvm_gradle_index(tmp_path)+ assert "core" in index.modules++ def test_detects_test_source_sets(self, tmp_path: Path) -> None:+ (tmp_path / "build.gradle.kts").write_text("// root\n")+ # Create integrationTest source set via directory convention+ it_dir = tmp_path / "src" / "integrationTest" / "java" / "com" / "example"+ it_dir.mkdir(parents=True)+ (it_dir / "IT.java").write_text("package com.example;\n\npublic class IT {}\n")++ index = build_jvm_gradle_index(tmp_path)+ project = index.projects.get("<root>")+ assert project is not None+ it_ss = project.source_sets.get("integrationTest")+ assert it_ss is not None+ assert it_ss.is_test++ def test_project_dir_override(self, tmp_path: Path) -> None:+ (tmp_path / "settings.gradle.kts").write_text(+ 'include("mymod")\n'+ 'project(":mymod").projectDir = file("custom/location")\n'+ )+ (tmp_path / "build.gradle.kts").write_text("// root\n")+ java_path = _make_java_class(tmp_path, "custom/location", "com.example", "Custom")++ index = build_jvm_gradle_index(tmp_path)+ matches = index.lookup_class("com.example.Custom")+ assert java_path in matchesdiff --git a/tests/unit/ingestion/test_jvm_workspace.py b/tests/unit/ingestion/test_jvm_workspace.pynew file mode 100644index 000000000..702d9178d--- /dev/null+++ b/tests/unit/ingestion/test_jvm_workspace.py@@ -0,0 +1,159 @@+"""Unit tests for the JVM workspace index."""++from __future__ import annotations++from pathlib import Path++import networkx as nx++from repowise.core.ingestion.resolvers.context import ResolverContext+from repowise.core.ingestion.resolvers.jvm_workspace import (+ JvmWorkspaceIndex,+ build_jvm_workspace_index,+)+++def _ctx(repo: Path, paths: list[str]) -> ResolverContext:+ path_set = set(paths)+ stem_map: dict[str, list[str]] = {}+ for p in paths:+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()+ stem_map.setdefault(stem, []).append(p)+ return ResolverContext(+ path_set=path_set,+ stem_map=stem_map,+ graph=nx.DiGraph(),+ repo_path=repo,+ )+++def _make_java(repo: Path, rel_path: str, package: str, class_name: str) -> str:+ full = repo / rel_path+ full.parent.mkdir(parents=True, exist_ok=True)+ full.write_text(f"package {package};\n\npublic class {class_name} {{}}\n")+ return rel_path+++def _make_kotlin(repo: Path, rel_path: str, package: str, class_name: str) -> str:+ full = repo / rel_path+ full.parent.mkdir(parents=True, exist_ok=True)+ full.write_text(f"package {package}\n\nclass {class_name}\n")+ return rel_path+++class TestJvmWorkspaceIndex:+ def test_groups_files_by_package(self, tmp_path: Path) -> None:+ a = _make_java(tmp_path, "src/main/java/com/foo/A.java", "com.foo", "A")+ b = _make_java(tmp_path, "src/main/java/com/foo/B.java", "com.foo", "B")+ c = _make_java(tmp_path, "src/main/java/com/bar/C.java", "com.bar", "C")++ ctx = _ctx(tmp_path, [a, b, c])+ index = build_jvm_workspace_index(ctx)++ assert "com.foo" in index.packages+ assert len(index.packages["com.foo"].files) == 2+ assert "com.bar" in index.packages+ assert len(index.packages["com.bar"].files) == 1++ def test_mixed_java_kotlin_same_package(self, tmp_path: Path) -> None:+ j = _make_java(tmp_path, "src/main/java/com/foo/Foo.java", "com.foo", "Foo")+ k = _make_kotlin(tmp_path, "src/main/java/com/foo/Bar.kt", "com.foo", "Bar")++ ctx = _ctx(tmp_path, [j, k])+ index = build_jvm_workspace_index(ctx)++ pkg = index.packages["com.foo"]+ assert j in pkg.files+ assert k in pkg.files++ def test_files_for_fqn(self, tmp_path: Path) -> None:+ a = _make_java(tmp_path, "src/main/java/com/foo/MyClass.java", "com.foo", "MyClass")++ ctx = _ctx(tmp_path, [a])+ index = build_jvm_workspace_index(ctx)++ assert index.files_for_fqn("com.foo.MyClass") == (a,)++ def test_wildcard_expand(self, tmp_path: Path) -> None:+ a = _make_java(tmp_path, "src/main/java/com/foo/A.java", "com.foo", "A")+ b = _make_java(tmp_path, "src/main/java/com/foo/B.java", "com.foo", "B")++ ctx = _ctx(tmp_path, [a, b])+ index = build_jvm_workspace_index(ctx)++ files = index.wildcard_expand("com.foo")+ assert len(files) == 2++ def test_same_package_files(self, tmp_path: Path) -> None:+ a = _make_java(tmp_path, "src/main/java/com/foo/A.java", "com.foo", "A")+ b = _make_java(tmp_path, "src/main/java/com/foo/B.java", "com.foo", "B")++ ctx = _ctx(tmp_path, [a, b])+ index = build_jvm_workspace_index(ctx)++ siblings = index.same_package_files(a)+ assert b in siblings+ assert a not in siblings++ def test_is_java_lang(self, tmp_path: Path) -> None:+ ctx = _ctx(tmp_path, [])+ index = build_jvm_workspace_index(ctx)++ assert index.is_java_lang("java.lang.String")+ assert index.is_java_lang("java.lang.Object")+ assert not index.is_java_lang("com.foo.Bar")+ assert not index.is_java_lang("java.util.List")++ def test_file_to_package(self, tmp_path: Path) -> None:+ a = _make_java(tmp_path, "src/main/java/com/foo/A.java", "com.foo", "A")++ ctx = _ctx(tmp_path, [a])+ index = build_jvm_workspace_index(ctx)++ assert index.package_for_file(a) == "com.foo"++ def test_exported_top_level_types(self, tmp_path: Path) -> None:+ a = _make_java(tmp_path, "src/main/java/com/foo/Foo.java", "com.foo", "Foo")+ b = _make_kotlin(tmp_path, "src/main/kotlin/com/foo/Bar.kt", "com.foo", "Bar")++ ctx = _ctx(tmp_path, [a, b])+ index = build_jvm_workspace_index(ctx)++ pkg = index.packages["com.foo"]+ assert "Foo" in pkg.exported_top_level+ assert "Bar" in pkg.exported_top_level++ def test_meta_inf_services(self, tmp_path: Path) -> None:+ services_dir = tmp_path / "src" / "main" / "resources" / "META-INF" / "services"+ services_dir.mkdir(parents=True)+ (services_dir / "com.example.Plugin").write_text(+ "com.example.impl.PluginA\n# comment\ncom.example.impl.PluginB\n"+ )+ a = _make_java(tmp_path, "src/main/java/com/example/impl/PluginA.java",+ "com.example.impl", "PluginA")++ ctx = _ctx(tmp_path, [a])+ index = build_jvm_workspace_index(ctx)++ assert "com.example.Plugin" in index.services+ impls = index.services["com.example.Plugin"]+ assert "com.example.impl.PluginA" in impls+ assert "com.example.impl.PluginB" in impls++ def test_spring_autoconfig_imports(self, tmp_path: Path) -> None:+ imports_dir = tmp_path / "src" / "main" / "resources" / "META-INF" / "spring"+ imports_dir.mkdir(parents=True)+ (imports_dir / "org.springframework.boot.autoconfigure.AutoConfiguration.imports").write_text(+ "com.example.MyAutoConfig\n# another\ncom.example.OtherConfig\n"+ )+ a = _make_java(tmp_path, "src/main/java/com/example/MyAutoConfig.java",+ "com.example", "MyAutoConfig")++ ctx = _ctx(tmp_path, [a])+ index = build_jvm_workspace_index(ctx)++ assert len(index.autoconfig_imports) == 1+ key = list(index.autoconfig_imports.keys())[0]+ fqns = index.autoconfig_imports[key]+ assert "com.example.MyAutoConfig" in fqns+ assert "com.example.OtherConfig" in fqnsdiff --git a/tests/unit/ingestion/test_maven_reader.py b/tests/unit/ingestion/test_maven_reader.pynew file mode 100644index 000000000..fa6ea79f8--- /dev/null+++ b/tests/unit/ingestion/test_maven_reader.py@@ -0,0 +1,140 @@+"""Unit tests for the Maven pom.xml manifest parser."""++from __future__ import annotations++from pathlib import Path++from repowise.core.ingestion.external_systems.maven import parse+++def _pom(tmp_path: Path, xml: str) -> Path:+ pom = tmp_path / "pom.xml"+ pom.write_text(xml, encoding="utf-8")+ return pom+++class TestMavenParse:+ def test_basic_dependencies(self, tmp_path: Path) -> None:+ pom = _pom(tmp_path, """\+<?xml version="1.0" encoding="UTF-8"?>+<project>+ <groupId>com.example</groupId>+ <artifactId>myapp</artifactId>+ <version>1.0.0</version>+ <dependencies>+ <dependency>+ <groupId>org.springframework.boot</groupId>+ <artifactId>spring-boot-starter-web</artifactId>+ <version>3.2.0</version>+ </dependency>+ <dependency>+ <groupId>junit</groupId>+ <artifactId>junit</artifactId>+ <version>4.13.2</version>+ <scope>test</scope>+ </dependency>+ </dependencies>+</project>""")+ records = parse(pom, tmp_path)+ assert len(records) == 2+ web = next(r for r in records if "spring-boot" in r.name)+ assert web.name == "org.springframework.boot:spring-boot-starter-web"+ assert web.version == "3.2.0"+ assert web.ecosystem == "maven"+ assert not web.is_dev_dep+ junit = next(r for r in records if "junit" in r.name)+ assert junit.is_dev_dep++ def test_property_substitution(self, tmp_path: Path) -> None:+ pom = _pom(tmp_path, """\+<?xml version="1.0" encoding="UTF-8"?>+<project>+ <groupId>com.example</groupId>+ <artifactId>myapp</artifactId>+ <version>1.0.0</version>+ <properties>+ <guava.version>32.1.3-jre</guava.version>+ </properties>+ <dependencies>+ <dependency>+ <groupId>com.google.guava</groupId>+ <artifactId>guava</artifactId>+ <version>${guava.version}</version>+ </dependency>+ </dependencies>+</project>""")+ records = parse(pom, tmp_path)+ assert len(records) == 1+ assert records[0].version == "32.1.3-jre"++ def test_dependency_management(self, tmp_path: Path) -> None:+ pom = _pom(tmp_path, """\+<?xml version="1.0" encoding="UTF-8"?>+<project>+ <groupId>com.example</groupId>+ <artifactId>myapp</artifactId>+ <version>1.0.0</version>+ <dependencyManagement>+ <dependencies>+ <dependency>+ <groupId>com.google.guava</groupId>+ <artifactId>guava</artifactId>+ <version>32.1.3-jre</version>+ </dependency>+ </dependencies>+ </dependencyManagement>+ <dependencies>+ <dependency>+ <groupId>com.google.guava</groupId>+ <artifactId>guava</artifactId>+ </dependency>+ </dependencies>+</project>""")+ records = parse(pom, tmp_path)+ assert len(records) == 1+ assert records[0].version == "32.1.3-jre"++ def test_malformed_xml_returns_empty(self, tmp_path: Path) -> None:+ pom = _pom(tmp_path, "not xml at all")+ assert parse(pom, tmp_path) == []++ def test_namespace_prefix(self, tmp_path: Path) -> None:+ pom = _pom(tmp_path, """\+<?xml version="1.0" encoding="UTF-8"?>+<project xmlns="http://maven.apache.org/POM/4.0.0">+ <groupId>com.example</groupId>+ <artifactId>myapp</artifactId>+ <version>1.0.0</version>+ <dependencies>+ <dependency>+ <groupId>org.slf4j</groupId>+ <artifactId>slf4j-api</artifactId>+ <version>2.0.9</version>+ </dependency>+ </dependencies>+</project>""")+ records = parse(pom, tmp_path)+ assert len(records) == 1+ assert records[0].name == "org.slf4j:slf4j-api"++ def test_parent_version_inheritance(self, tmp_path: Path) -> None:+ pom = _pom(tmp_path, """\+<?xml version="1.0" encoding="UTF-8"?>+<project>+ <parent>+ <groupId>com.example</groupId>+ <artifactId>parent</artifactId>+ <version>2.0.0</version>+ </parent>+ <artifactId>child</artifactId>+ <dependencies>+ <dependency>+ <groupId>com.example</groupId>+ <artifactId>sibling</artifactId>+ <version>${project.version}</version>+ </dependency>+ </dependencies>+</project>""")+ records = parse(pom, tmp_path)+ assert len(records) == 1+ assert records[0].version == "2.0.0"