From 54de6bde141e3cbc75ac163323be7f25b0c59979 Mon Sep 17 00:00:00 2001 From: Aviad Shiber Date: Tue, 29 Sep 2026 14:06:35 +0300 Subject: [PATCH 1/3] fix: import missing in-repo Maven modules so cross-group symbols resolve (#110) jdtls imports only the opened file's Maven group. A dependency on a reactor module in another group is resolved by m2e from the local repository at ${revision}, where it is usually missing, so every symbol from it is a false "cannot be resolved" / "undefined for the type" error. - reactor.py: GA -> module dir index of the modules reachable through (profiles unioned), contained in the reactor root, no symlinked poms, DOCTYPE/ENTITY and >1 MB poms rejected, inherited groupId, duplicate GAs dropped, bounded to 5000 poms / 10 s; "Missing artifact" parser (optional "Offline / " prefix). - dependency_modules.py: on a pom.xml "Missing artifact" error for an in-repo, uncovered module, add its folder via one debounced, batched didChangeWorkspaceFolders; separate registry; session budget (default 60, JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES or jdtls.dependencyModules, 0 disables, max 200) with a WARNING listing unresolved GAs; a group expansion removes the dependency folders it covers in the same event and they are never re-added. - On language/eventNotification 100 (ClasspathUpdated) or when a pom's missing-artifact errors clear, send java.project.refreshDiagnostics for each open .java file under that project (debounced per project); the results go through the #109 hold unchanged. - e2e regression test on a two-group ${revision} reactor with an isolated, primed, offline local repository; it fails on PR A's head. - Version 0.14.0; README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 38 +- pyproject.toml | 2 +- src/java_functional_lsp/__init__.py | 2 +- src/java_functional_lsp/dependency_modules.py | 342 ++++++++++++++ src/java_functional_lsp/proxy.py | 88 +++- src/java_functional_lsp/reactor.py | 227 +++++++++ src/java_functional_lsp/server.py | 8 + tests/test_dependency_modules.py | 433 ++++++++++++++++++ tests/test_e2e_dependency_modules.py | 354 ++++++++++++++ tests/test_reactor.py | 224 +++++++++ uv.lock | 2 +- 11 files changed, 1714 insertions(+), 6 deletions(-) create mode 100644 src/java_functional_lsp/dependency_modules.py create mode 100644 src/java_functional_lsp/reactor.py create mode 100644 tests/test_dependency_modules.py create mode 100644 tests/test_e2e_dependency_modules.py create mode 100644 tests/test_reactor.py diff --git a/README.md b/README.md index db39f6e..0a8f6fb 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,7 @@ moving on. Fix any type errors or missing imports immediately. | Plugin not active | Run `claude plugin list` to verify, then `/reload-plugins` | | Diagnostics slow on first open | Normal — tree-sitter parses on first load, then incremental | | Java errors show up one tool call after the edit | Claude Code doesn't wait for LSP diagnostics after Edit/Write ([anthropics/claude-code#93321](https://github.com/anthropics/claude-code/issues/93321)). The plugin's hook waits up to 3s for them; if jdtls is slower (large projects), raise `JAVA_FUNCTIONAL_LSP_HOOK_WAIT` (max 4). See [Fresh jdtls diagnostics after edits](#fresh-jdtls-diagnostics-after-edits) | -| False "X cannot be resolved" / "The hierarchy of the type X is inconsistent" on classes from another Maven group of the same repository | jdtls imports only the opened file's Maven group, so a sibling module from another group must come from the local Maven repository; if it was never installed at the reactor's version, its types are missing. Check the server's log (stderr, as captured by your LSP client) for `jdtls: pom.xml errors changed for /pom.xml: ... Missing artifact g:a:jar:v`, `jdtls[log:1]: ...` and `jdtls[status:Error]: ...` lines, and `jdtls: group scope: ...` for which folder was imported. Workaround: `mvn install` the missing modules. Automatic import of in-repo dependencies is tracked in [#110](https://github.com/aviadshiber/java-functional-lsp/issues/110) | +| False "X cannot be resolved" / "The hierarchy of the type X is inconsistent" on classes from another Maven group of the same repository | The server imports such modules automatically when m2e reports them missing. See [Dependencies on modules in other Maven groups](#dependencies-on-modules-in-other-maven-groups) for the log lines to check, the budget (`JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES`) and the stale-install case | ### Other Editors @@ -308,6 +308,42 @@ The jdtls Eclipse workspace index is cached in `~/.cache/jdtls-data/`. Warm star To force a clean rebuild: `rm -rf ~/.cache/jdtls-data/` +### Dependencies on modules in other Maven groups + +To keep jdtls fast and within its heap, the server imports only the Maven *group* of the file you open (its tightest parent pom with ``), plus up to 5 more groups as you navigate. A module in that group can depend on a reactor module in *another* group. m2e then looks that dependency up in the local Maven repository at the reactor's version, often a `${revision}` default that is never installed. Every symbol from that module then shows as a false error: "cannot be resolved", "is undefined for the type", or "The hierarchy of the type X is inconsistent" ([#110](https://github.com/aviadshiber/java-functional-lsp/issues/110)). The server fixes this by importing the missing module itself. + +How it works: + +1. m2e reports the dependency as an error on the dependent's `pom.xml`: `Missing artifact com.example:common:jar:1.0` (prefixed with `Offline / ` when offline). +2. The server looks the `groupId:artifactId` up in an index of the reactor. The index is built once per session and covers the modules reachable from the reactor root through ``, with all profiles included. +3. If the artifact is a module of the repository and no imported folder covers it yet, the server adds the module's directory as a jdtls workspace folder. Additions are batched into one `didChangeWorkspaceFolders` per 500 ms. An added module that is missing its own in-repo dependencies reports them the same way, so the dependency closure is imported only as far as it is actually missing. +4. jdtls fixes the dependent's classpath within a fraction of a second, but it does not re-check files that are already open. When jdtls reports that a project's classpath was updated, the server asks it to re-validate every open `.java` file of that project (`java.project.refreshDiagnostics`). Those results go through the [diagnostics hold](#fresh-jdtls-diagnostics-after-edits). + +If you later open a file in a group that contains one of these modules, the group folder replaces the module folder in the same workspace change. That module folder is never re-added. + +Configuration: + +| Setting | Values | Effect | +|---------|--------|--------| +| `JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES` (environment) | `0`–`200` (default `60`) | Session budget of dependency-module folders; `0` disables the import | +| `{"jdtls": {"dependencyModules": N}}` in `.java-functional-lsp.json` | same | Same budget; the environment variable wins | + +Limits: + +- **Budget.** At most N module folders are added per session. A folder that a group later replaces still counts. When the budget runs out, the log shows a `WARNING` listing the modules left unresolved. Raise the budget, or open a file in those modules' group. +- **Stale local installs are not detected.** If an old build of the sibling is installed at the same version in your local repository, m2e resolves the dependency from that jar and reports nothing. You then see the installed version's API, not the source. Run `mvn install` for that module again, or delete it from the local repository. +- **Maven only.** Gradle projects are unchanged. +- **Index bounds.** The index skips poms larger than 1 MB, poms with `: … Missing artifact g:a:…` means m2e could not resolve that dependency. +- `jdtls: reactor index of : N modules from M poms` means the index was built. `(truncated)` means it hit a bound. +- `jdtls: importing K dependency module(s) (used/budget): g:a (path), …` means those modules were added. +- `jdtls: classpath of updated, refreshing K open file(s)` means open files were re-checked. +- If the errors stay and nothing was imported, the artifact is not a module of this reactor (check the `` path that should reach it), or it is a real external artifact missing from your repository. +- m2e caches failed lookups: `*.lastUpdated` files in the local repository, and the jdtls workspace in `~/.cache/jdtls-data/`. If errors persist after the module is imported, clear the jdtls cache as described above. + ### Fresh jdtls diagnostics after edits jdtls re-validates a file 0.4–2.4s after the last edit to *any* file, and its results carry no document version. So after an edit, java-functional-lsp holds back jdtls diagnostics for that file until jdtls publishes again, rather than re-sending the previous edit's results as if they were current ([#109](https://github.com/aviadshiber/java-functional-lsp/issues/109)): diff --git a/pyproject.toml b/pyproject.toml index 4f74831..6f34e6d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "java-functional-lsp" -version = "0.13.1" +version = "0.14.0" description = "Java LSP server enforcing functional programming best practices — null safety, immutability, no exceptions" readme = "README.md" license = { text = "MIT" } diff --git a/src/java_functional_lsp/__init__.py b/src/java_functional_lsp/__init__.py index 46c01e4..7aa5dc1 100644 --- a/src/java_functional_lsp/__init__.py +++ b/src/java_functional_lsp/__init__.py @@ -1,3 +1,3 @@ """java-functional-lsp: A Java LSP server enforcing functional programming best practices.""" -__version__ = "0.13.1" +__version__ = "0.14.0" diff --git a/src/java_functional_lsp/dependency_modules.py b/src/java_functional_lsp/dependency_modules.py new file mode 100644 index 0000000..1347fd3 --- /dev/null +++ b/src/java_functional_lsp/dependency_modules.py @@ -0,0 +1,342 @@ +"""Import missing in-repo Maven modules as jdtls workspace folders (#110). + +jdtls imports only the opened file's Maven group. A dependency on a reactor module in +another group is then resolved by m2e from the local repository at ``${revision}``, +where it is usually missing, and every symbol from it is "cannot be resolved". m2e +reports it as an Error diagnostic on the dependent's pom.xml +(``[Offline / ]Missing artifact g:a:type:version``). + +``DependencyModules`` turns that signal into a batched, debounced +``workspace/didChangeWorkspaceFolders`` add of the module directories found in the +reactor index, within a session budget. Modules added this way report their own +missing dependencies through the same signal, so the closure is imported round by +round, only as far as it is actually missing. + +jdtls fixes the dependent's classpath within a fraction of a second, but it never +republishes diagnostics for documents that are already open. ``ClasspathRefresher`` +therefore sends ``java.project.refreshDiagnostics`` for every open ``.java`` file +under a project whose classpath was updated. + +Both classes are asyncio-only (no locks) and take their side effects as callables, +so they are unit-testable without jdtls. +""" + +from __future__ import annotations + +import asyncio +import logging +import os +from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping +from pathlib import Path +from typing import Any +from urllib.parse import unquote, urlparse + +from .reactor import ReactorIndex, build_reactor_index + +logger = logging.getLogger(__name__) + +ENV_BUDGET = "JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES" +DEFAULT_BUDGET = 60 +MAX_BUDGET = 200 +ADD_DEBOUNCE_SEC = 0.5 +REFRESH_DEBOUNCE_SEC = 1.0 +REFRESH_TIMEOUT_SEC = 10.0 +_WARN_LIST_MAX = 20 + +Folder = dict[str, str] +SendFolders = Callable[[list[Folder], list[Folder]], Awaitable[None]] + + +def resolve_budget(config: Mapping[str, Any] | None = None, environ: Mapping[str, str] | None = None) -> int: + """Session budget of dependency-module folders. + + ``JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES`` wins over ``{"jdtls": {"dependencyModules": N}}`` + in ``.java-functional-lsp.json``. 0 disables the feature; values are clamped to + ``[0, MAX_BUDGET]``; an invalid value logs a warning and uses ``DEFAULT_BUDGET``. + """ + env = environ if environ is not None else os.environ + raw: object = env.get(ENV_BUDGET) + source = ENV_BUDGET + if raw is None or raw == "": + jdtls_cfg = (config or {}).get("jdtls") + raw = jdtls_cfg.get("dependencyModules") if isinstance(jdtls_cfg, Mapping) else None + source = "jdtls.dependencyModules" + if raw is None: + return DEFAULT_BUDGET + try: + if isinstance(raw, bool) or not isinstance(raw, (int, str)): + raise ValueError + value = int(raw) + except ValueError: + logger.warning("jdtls: invalid %s %r, using default %d", source, raw, DEFAULT_BUDGET) + return DEFAULT_BUDGET + if value > MAX_BUDGET: + logger.warning("jdtls: %s %d is above the maximum, using %d", source, value, MAX_BUDGET) + return MAX_BUDGET + return max(value, 0) + + +def path_from_uri(uri: str) -> Path | None: + """Filesystem path of a ``file:`` URI in any of jdtls's forms (``file:/x/``, ``file:///x``).""" + if not isinstance(uri, str) or not uri.startswith("file:"): + return None + path = unquote(urlparse(uri).path) + if not path: + return None + return Path(path.rstrip("/") or "/") + + +def _is_under(path: Path, folder: Path) -> bool: + return path == folder or path.is_relative_to(folder) + + +def _display(path: Path, root: Path) -> str: + try: + return str(path.relative_to(root)) or "." + except ValueError: + return path.name + + +class DependencyModules: + """Session registry and importer of dependency-module folders.""" + + def __init__( + self, + send_folders: SendFolders, + covered_roots: Callable[[], Iterable[Path]], + reactor_root_for: Callable[[Path], Path], + to_uri: Callable[[Path], str], + *, + budget: int = DEFAULT_BUDGET, + debounce: float = ADD_DEBOUNCE_SEC, + index_builder: Callable[[Path], ReactorIndex] = build_reactor_index, + ) -> None: + self._send_folders = send_folders + self._covered_roots = covered_roots + self._reactor_root_for = reactor_root_for + self._to_uri = to_uri + self._index_builder = index_builder + self.budget = budget + self.debounce = debounce + self._indexes: dict[Path, asyncio.Task[ReactorIndex | None]] = {} + #: GA → module dir, folders currently added by this class. + self.registry: dict[str, Path] = {} + #: Folders removed because a group expansion covered them; never re-added. + self._retired: set[Path] = set() + self._pending: dict[str, Path] = {} + self._unresolved: list[str] = [] + self._used = 0 + self._flush_task: asyncio.Task[None] | None = None + self._tasks: set[asyncio.Task[Any]] = set() + self._roots: dict[Path, Path] = {} + + @property + def enabled(self) -> bool: + return self.budget > 0 + + @property + def used(self) -> int: + return self._used + + def folders(self) -> list[Path]: + return list(self.registry.values()) + + def _spawn(self, coro: Coroutine[Any, Any, Any]) -> None: + try: + task: asyncio.Task[Any] = asyncio.get_running_loop().create_task(coro) + except RuntimeError: # no running loop (sync unit test): nothing to schedule + coro.close() + return + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) + + def note_missing(self, pom_path: Path, gas: list[str]) -> None: + """m2e reported *gas* missing for the module of *pom_path*: queue the in-repo ones.""" + if not self.enabled or not gas: + return + self._spawn(self._consider(pom_path.parent, gas)) + + async def _index_for(self, module_dir: Path) -> ReactorIndex | None: + """Reactor index for *module_dir*, built once per reactor root (single flight).""" + root = self._roots.get(module_dir) + if root is None: + root = self._reactor_root_for(module_dir) + self._roots[module_dir] = root + task = self._indexes.get(root) + if task is None: + task = asyncio.get_running_loop().create_task(self._build_index(root)) + self._indexes[root] = task + self._tasks.add(task) + return await asyncio.shield(task) + + async def _build_index(self, root: Path) -> ReactorIndex | None: + try: + index = await asyncio.get_running_loop().run_in_executor(None, self._index_builder, root) + except Exception: + logger.warning("jdtls: reactor index of %s failed", root.name, exc_info=True) + return None + logger.info( + "jdtls: reactor index of %s: %d modules from %d poms%s", + root.name, + len(index.modules), + index.poms_read, + " (truncated)" if index.truncated else "", + ) + return index + + def _is_covered(self, module_dir: Path) -> bool: + if any(_is_under(module_dir, folder) for folder in self.registry.values()): + return True + return any(_is_under(module_dir, folder) for folder in self._covered_roots()) + + async def _consider(self, module_dir: Path, gas: list[str]) -> None: + index = await self._index_for(module_dir) + if index is None: + return + queued = False + for ga in gas: + target = index.get(ga) + if target is None: + continue # not an in-repo module (a real external artifact, or ambiguous) + if ga in self.registry or ga in self._pending or target in self._retired: + continue + if self._is_covered(target): + continue + self._pending[ga] = target + queued = True + if queued and (self._flush_task is None or self._flush_task.done()): + self._flush_task = asyncio.get_running_loop().create_task(self._flush_after_debounce(index.root)) + self._tasks.add(self._flush_task) + self._flush_task.add_done_callback(self._tasks.discard) + + async def _flush_after_debounce(self, root: Path) -> None: + await asyncio.sleep(self.debounce) + await self.flush(root) + + async def flush(self, root: Path) -> None: + """Send one didChangeWorkspaceFolders add for the queued modules, within the budget.""" + pending, self._pending = self._pending, {} + added: list[Folder] = [] + shown: list[str] = [] + overflow: list[str] = [] + for ga, target in pending.items(): + if ga in self.registry or target in self._retired or self._is_covered(target): + continue + if self._used >= self.budget: + overflow.append(ga) + continue + self._used += 1 + self.registry[ga] = target + added.append({"uri": self._to_uri(target), "name": target.name}) + shown.append(f"{ga} ({_display(target, root)})") + if added: + logger.info( + "jdtls: importing %d dependency module(s) (%d/%d used): %s", + len(added), + self._used, + self.budget, + ", ".join(shown), + ) + await self._send_folders(added, []) + new_unresolved = [ga for ga in overflow if ga not in self._unresolved] + if new_unresolved: + self._unresolved.extend(new_unresolved) + listed = ", ".join(new_unresolved[:_WARN_LIST_MAX]) + more = f" (+{len(new_unresolved) - _WARN_LIST_MAX} more)" if len(new_unresolved) > _WARN_LIST_MAX else "" + logger.warning( + "jdtls: dependency-module budget exhausted (%d); these in-repo modules stay unresolved: %s%s. " + "Raise %s (max %d) or open a file in their group.", + self.budget, + listed, + more, + ENV_BUDGET, + MAX_BUDGET, + ) + + def take_covered_by(self, folder: Path) -> list[Folder]: + """A group folder is being added: retire the dependency folders it covers. + + Returns them as ``removed`` entries for the same didChangeWorkspaceFolders event. + """ + removed: list[Folder] = [] + for ga, target in list(self.registry.items()): + if _is_under(target, folder): + del self.registry[ga] + self._retired.add(target) + removed.append({"uri": self._to_uri(target), "name": target.name}) + for ga, target in list(self._pending.items()): + if _is_under(target, folder): + del self._pending[ga] + if removed: + logger.info("jdtls: group %s covers %d dependency module folder(s)", folder.name, len(removed)) + return removed + + def reset(self) -> None: + """Forget the session (jdtls stopped).""" + for task in list(self._tasks): + task.cancel() + self._tasks.clear() + self._flush_task = None + self._indexes.clear() + self._roots.clear() + self.registry.clear() + self._retired.clear() + self._pending.clear() + self._unresolved.clear() + self._used = 0 + + +class ClasspathRefresher: + """Re-validate open files after their project's classpath changed (debounced per project).""" + + def __init__( + self, + open_uris: Callable[[], Iterable[str]], + send_refresh: Callable[[str], Awaitable[Any]], + *, + debounce: float = REFRESH_DEBOUNCE_SEC, + ) -> None: + self._open_uris = open_uris + self._send_refresh = send_refresh + self.debounce = debounce + self._timers: dict[Path, asyncio.Task[None]] = {} + + def note_updated(self, project_dir: Path) -> None: + """The classpath of *project_dir* changed; refresh its open files after the debounce.""" + timer = self._timers.get(project_dir) + if timer is not None and not timer.done(): + timer.cancel() + try: + self._timers[project_dir] = asyncio.get_running_loop().create_task(self._refresh_later(project_dir)) + except RuntimeError: + return + + def open_files_under(self, project_dir: Path) -> list[str]: + result: list[str] = [] + try: + uris = list(self._open_uris()) + except Exception: + return result + for uri in uris: + if not uri.endswith(".java"): + continue + path = path_from_uri(uri) + if path is not None and path.is_relative_to(project_dir): + result.append(uri) + return result + + async def _refresh_later(self, project_dir: Path) -> None: + await asyncio.sleep(self.debounce) + if self._timers.get(project_dir) is asyncio.current_task(): + del self._timers[project_dir] + uris = self.open_files_under(project_dir) + if not uris: + return + logger.info("jdtls: classpath of %s updated, refreshing %d open file(s)", project_dir.name, len(uris)) + for uri in uris: + await self._send_refresh(uri) + + def reset(self) -> None: + for timer in self._timers.values(): + timer.cancel() + self._timers.clear() diff --git a/src/java_functional_lsp/proxy.py b/src/java_functional_lsp/proxy.py index b29dfa5..9935cfc 100644 --- a/src/java_functional_lsp/proxy.py +++ b/src/java_functional_lsp/proxy.py @@ -14,12 +14,14 @@ import subprocess import time from collections import deque -from collections.abc import Callable, Mapping +from collections.abc import Callable, Iterable, Mapping from functools import lru_cache from pathlib import Path from typing import Any +from .dependency_modules import ClasspathRefresher, DependencyModules, path_from_uri, resolve_budget from .merkle import _BUILD_FILES, ModuleSnapshot, TreeDiff +from .reactor import find_reactor_root, parse_missing_artifacts logger = logging.getLogger(__name__) @@ -346,6 +348,8 @@ async def read_message(reader: asyncio.StreamReader) -> dict[str, Any] | None: _WORKSPACE_DID_CHANGE_FOLDERS = "workspace/didChangeWorkspaceFolders" +#: jdtls ``language/eventNotification`` eventType for "classpath of project updated". +_EVENT_CLASSPATH_UPDATED = 100 _MAX_QUEUED_NOTIFICATIONS = 200 _MODULE_READY_TIMEOUT = 30.0 @@ -962,6 +966,7 @@ def __init__( on_diagnostics: Callable[[str, list[Any]], None] | None = None, uri_key: Callable[[str], str] = lambda uri: uri, on_stopped: Callable[[], None] | None = None, + open_uris: Callable[[], Iterable[str]] | None = None, ) -> None: self._process: asyncio.subprocess.Process | None = None self._reader_task: asyncio.Task[None] | None = None @@ -1004,6 +1009,18 @@ def __init__( self._pending_diff_tasks: dict[str, asyncio.Task[None]] = {} # Background tasks created by this proxy (prevents GC of fire-and-forget tasks). self._proxy_bg_tasks: set[asyncio.Task[Any]] = set() + # In-repo modules imported because m2e reported them missing (#110). Own registry: + # never part of ``modules`` / ``_expanded_groups``. + self.dependency_modules = DependencyModules( + send_folders=self._send_folder_change, + covered_roots=self._imported_folder_paths, + reactor_root_for=_reactor_root_for, + to_uri=_path_to_uri, + ) + self._classpath_refresher = ClasspathRefresher( + open_uris=open_uris or (lambda: ()), + send_refresh=self._refresh_file_diagnostics, + ) @property def is_available(self) -> bool: @@ -1028,6 +1045,8 @@ def _mark_stopped(self) -> None: self._diagnostics_cache.clear() self._pom_errors.clear() self._log_forwarder.flush() + self.dependency_modules.reset() + self._classpath_refresher.reset() if cached: logger.info("jdtls stopped: cleared cached diagnostics for %d files", cached) if self._on_stopped: @@ -1065,6 +1084,10 @@ async def start( # from concurrent coroutines during the executor yield below. self._initial_module_uri = module_root_uri self.modules.mark_added(effective_root_uri) + self.dependency_modules.reset() + self.dependency_modules.budget = resolve_budget(config) + if not self.dependency_modules.enabled: + logger.info("jdtls: importing missing in-repo dependency modules is disabled") # All blocking startup I/O in a single executor call: cache version check # (may rmtree on upgrade), Lombok discovery, and jdtls env build. @@ -1301,6 +1324,7 @@ async def add_module_if_new(self, file_uri: str) -> str | None: p = Path(to_fs_path(uri) or uri) if p == group_path or p.is_relative_to(group_path): removed.append({"uri": uri, "name": p.name}) + removed.extend(self.dependency_modules.take_covered_by(group_path)) # Mark ADDED before await — atomic in asyncio, prevents duplicate sends. self.modules.mark_added(module_uri) @@ -1371,6 +1395,7 @@ async def expand_full_workspace(self) -> None: p = Path(to_fs_path(uri) or uri) if p == root_path_obj or p.is_relative_to(root_path_obj): removed.append({"uri": uri, "name": p.name}) + removed.extend(self.dependency_modules.take_covered_by(root_path_obj)) logger.info("jdtls: expanding workspace to module group %s", _redact_path(root_path)) await self.send_notification( @@ -1561,6 +1586,11 @@ def _handle_notification(self, msg: dict[str, Any]) -> None: level = logging.INFO if status_type == "Error" else logging.DEBUG kind = f"status:{status_type}" if status_type in _LANGUAGE_STATUS_TYPES else "status:other" self._log_forwarder.forward(level, kind, params.get("message", "")) + elif method == "language/eventNotification" and isinstance(params, dict): + if params.get("eventType") == _EVENT_CLASSPATH_UPDATED: + project = path_from_uri(params.get("data")) # type: ignore[arg-type] + if project is not None: + self._classpath_refresher.note_updated(project) # Other notifications are silently ignored def _note_pom_diagnostics(self, uri: str, diagnostics: Any) -> None: @@ -1580,8 +1610,10 @@ def _note_pom_diagnostics(self, uri: str, diagnostics: Any) -> None: if isinstance(d, dict) and d.get("severity") == 1 # DiagnosticSeverity.Error ) key = self._uri_key(uri) - if self._pom_errors.get(key, ()) == errors: + previous = self._pom_errors.get(key, ()) + if previous == errors: return + self._react_to_missing_artifacts(uri, previous, errors) if errors: self._pom_errors[key] = errors else: @@ -1608,3 +1640,55 @@ def _pom_display_path(self, uri: str) -> str: except ValueError: pass return _sanitize_jdtls_log(_redact_path(path), _POM_DIAG_MSG_MAX_CHARS) + + def _react_to_missing_artifacts(self, uri: str, previous: tuple[str, ...], errors: tuple[str, ...]) -> None: + """Import in-repo modules m2e reports missing; refresh open files once they resolve.""" + pom = path_from_uri(uri) + if pom is None: + return + missing = parse_missing_artifacts(errors) + if missing: + self.dependency_modules.note_missing(pom, missing) + elif parse_missing_artifacts(previous): + self._classpath_refresher.note_updated(pom.parent) + + def _imported_folder_paths(self) -> list[Path]: + """Folders jdtls imported for groups/modules (the dependency registry is separate).""" + from pygls.uris import to_fs_path + + paths: list[Path] = [] + for uri in {*self.modules.uris(), *self._expanded_groups}: + fs = to_fs_path(uri) + if fs: + paths.append(Path(fs)) + return paths + + async def _send_folder_change(self, added: list[dict[str, str]], removed: list[dict[str, str]]) -> None: + if not self._available: + return + await self.send_notification(_WORKSPACE_DID_CHANGE_FOLDERS, {"event": {"added": added, "removed": removed}}) + + async def _refresh_file_diagnostics(self, uri: str) -> None: + """jdtls does not republish diagnostics for open files after a classpath change; ask it to.""" + if not self._available: + return + await self.send_request( + "workspace/executeCommand", + {"command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", False]}, + timeout=_REFRESH_DIAGNOSTICS_TIMEOUT, + ) + + +_REFRESH_DIAGNOSTICS_TIMEOUT = 10.0 + + +def _path_to_uri(path: Path) -> str: + from pygls.uris import from_fs_path + + return from_fs_path(str(path)) or path.as_uri() + + +def _reactor_root_for(module_dir: Path) -> Path: + """Reactor root of *module_dir*, bounded by its repository (``.git``) boundary.""" + resolved = module_dir.resolve() + return find_reactor_root(resolved, _find_repo_boundary(resolved)) diff --git a/src/java_functional_lsp/reactor.py b/src/java_functional_lsp/reactor.py new file mode 100644 index 0000000..4f2db48 --- /dev/null +++ b/src/java_functional_lsp/reactor.py @@ -0,0 +1,227 @@ +"""Maven reactor index and m2e "Missing artifact" parsing (#110). + +Pure functions, no jdtls. ``build_reactor_index`` maps ``groupId:artifactId`` to the +module directory of every module reachable from a reactor root through ```` +(all profiles unioned). The proxy uses it to turn m2e's pom.xml diagnostic +``Missing artifact g:a:type:version`` into "import that in-repo module as a +workspace folder". + +The poms come from the user's checkout, so parsing is defensive: files over +``MAX_POM_BYTES`` or containing a `` / ]Missing artifact g:a:type[:classifier]:version". ``${revision}`` is +#: already interpolated. Only groupId and artifactId are kept. +_MISSING_ARTIFACT_RE = re.compile(r"(?:^|/\s*)Missing artifact ([A-Za-z0-9_.\-]+):([A-Za-z0-9_.\-]+):\S+") + + +@dataclass +class ReactorIndex: + """``groupId:artifactId`` → module directory for one reactor root.""" + + root: Path + modules: dict[str, Path] = field(default_factory=dict) + #: GAs declared by more than one module directory (never resolved). + ambiguous: set[str] = field(default_factory=set) + poms_read: int = 0 + #: True when the walk stopped early at the pom-count or time bound. + truncated: bool = False + + def get(self, ga: str) -> Path | None: + return self.modules.get(ga) + + +@dataclass(frozen=True) +class _Pom: + group_id: str | None + artifact_id: str | None + modules: tuple[str, ...] + + +def _local(tag: object) -> str: + """Tag name without its ``{namespace}``.""" + return tag.rsplit("}", 1)[-1] if isinstance(tag, str) else "" + + +def _child(elem: ET.Element, name: str) -> ET.Element | None: + for c in elem: + if _local(c.tag) == name: + return c + return None + + +def _children(elem: ET.Element | None, name: str) -> list[ET.Element]: + if elem is None: + return [] + return [c for c in elem if _local(c.tag) == name] + + +def _text(elem: ET.Element | None) -> str | None: + if elem is None or elem.text is None: + return None + value = elem.text.strip() + return value or None + + +def _read_pom_bytes(pom: Path) -> bytes | None: + """Raw bytes of *pom*, or None when it is a symlink, too large, or declares a DOCTYPE/ENTITY.""" + try: + if pom.is_symlink() or not pom.is_file() or pom.stat().st_size > MAX_POM_BYTES: + return None + data = pom.read_bytes() + except OSError: + return None + if len(data) > MAX_POM_BYTES: + return None + if _FORBIDDEN_MARKUP.search(data): + logger.info("reactor: skipping %s (DOCTYPE/ENTITY declarations are not allowed)", pom.name) + return None + return data + + +def parse_pom(pom: Path) -> _Pom | None: + """Parse the coordinates and ```` (all profiles) of *pom*; None if rejected or invalid.""" + data = _read_pom_bytes(pom) + if data is None: + return None + try: + project = ET.fromstring(data) + except ET.ParseError: + return None + if _local(project.tag) != "project": + return None + parent = _child(project, "parent") + group_id = _text(_child(project, "groupId")) or _text(_child(parent, "groupId") if parent is not None else None) + artifact_id = _text(_child(project, "artifactId")) + module_lists = [_child(project, "modules")] + for profile in _children(_child(project, "profiles"), "profile"): + module_lists.append(_child(profile, "modules")) + modules: list[str] = [] + for modules_elem in module_lists: + for m in _children(modules_elem, "module"): + value = _text(m) + if value and value not in modules: + modules.append(value) + return _Pom(group_id, artifact_id, tuple(modules)) + + +def _module_pom(base: Path, entry: str) -> Path: + """```` is a directory (holding pom.xml) or, rarely, a path to a pom file.""" + candidate = base / entry + return candidate if entry.endswith(".xml") else candidate / "pom.xml" + + +def _contained_dir(pom: Path, real_root: Path) -> Path | None: + """Resolved directory of *pom* if it is inside *real_root* and *pom* is not a symlink.""" + try: + if pom.is_symlink(): + return None + module_dir = pom.parent.resolve() + except (OSError, RuntimeError): # RuntimeError: symlink loop on older Pythons + return None + return module_dir if module_dir.is_relative_to(real_root) else None + + +def build_reactor_index( + root: Path, + *, + max_poms: int = MAX_POMS, + max_seconds: float = MAX_SECONDS, + clock: Callable[[], float] = time.monotonic, +) -> ReactorIndex: + """Index the modules reachable from ``root/pom.xml`` through ````. + + Breadth-first; each pom is read at most once. A module whose resolved directory + is outside the resolved root, or whose pom is a symlink, is skipped. Coordinates + containing ``${`` are skipped. A GA declared by two directories is dropped + entirely and logged once. Blocking: run it in an executor. + """ + try: + real_root = root.resolve() + except (OSError, RuntimeError): + return ReactorIndex(root) + index = ReactorIndex(real_root) + deadline = clock() + max_seconds + seen: set[Path] = set() + found: dict[str, set[Path]] = {} + queue: deque[Path] = deque([real_root / "pom.xml"]) + while queue: + if index.poms_read >= max_poms or clock() > deadline: + index.truncated = True + logger.warning( + "reactor: index of %s stopped early after %d poms (bounds: %d poms, %.0fs)", + real_root.name, + index.poms_read, + max_poms, + max_seconds, + ) + break + pom = queue.popleft() + module_dir = _contained_dir(pom, real_root) + if module_dir is None or module_dir in seen: + continue + seen.add(module_dir) + parsed = parse_pom(module_dir / pom.name) + index.poms_read += 1 + if parsed is None: + continue + g, a = parsed.group_id, parsed.artifact_id + if g and a and "${" not in g and "${" not in a: + found.setdefault(f"{g}:{a}", set()).add(module_dir) + for entry in parsed.modules: + if "${" in entry: + continue + queue.append(_module_pom(module_dir, entry)) + for ga, dirs in found.items(): + if len(dirs) == 1: + index.modules[ga] = next(iter(dirs)) + else: + index.ambiguous.add(ga) + logger.info("reactor: ignoring %s, declared by %d module directories", ga, len(dirs)) + return index + + +def find_reactor_root(module_dir: Path, boundary: Path | None = None) -> Path: + """Topmost ancestor of *module_dir* reachable through consecutive pom.xml directories. + + Never goes above *boundary* (e.g. the repository's ``.git`` directory) when given. + """ + top = module_dir + while top.parent != top and (top.parent / "pom.xml").is_file(): + if boundary is not None and top == boundary: + break + top = top.parent + return top + + +def parse_missing_artifacts(messages: tuple[str, ...] | list[str]) -> list[str]: + """Return the ``groupId:artifactId`` of every m2e "Missing artifact" message, in order, deduped.""" + result: list[str] = [] + for message in messages: + match = _MISSING_ARTIFACT_RE.search(message) + if match: + ga = f"{match.group(1)}:{match.group(2)}" + if ga not in result: + result.append(ga) + return result diff --git a/src/java_functional_lsp/server.py b/src/java_functional_lsp/server.py index 0e47f95..e513eb4 100644 --- a/src/java_functional_lsp/server.py +++ b/src/java_functional_lsp/server.py @@ -283,6 +283,7 @@ def __init__(self) -> None: on_diagnostics=self._on_jdtls_diagnostics, uri_key=_normalize_uri, on_stopped=self._on_jdtls_stopped, + open_uris=self._open_document_uris, ) self._user_suppress_patterns: list[re.Pattern[str]] = [] self._skip_jdtls: bool = False @@ -311,6 +312,13 @@ def __init__(self) -> None: # the filesystem and didChange arrives per keystroke in IDEs. self._module_uris: dict[str, str | None] = {} + def _open_document_uris(self) -> list[str]: + """URIs the client currently has open (as the client sent them).""" + try: + return list(self.workspace.text_documents) + except Exception: # workspace not set up yet (before initialize) + return [] + def _record_opened(self, uri: str) -> None: """Record *uri* as opened this session, evicting the oldest entry at cap. diff --git a/tests/test_dependency_modules.py b/tests/test_dependency_modules.py new file mode 100644 index 0000000..e6c1a51 --- /dev/null +++ b/tests/test_dependency_modules.py @@ -0,0 +1,433 @@ +"""Tests for importing missing in-repo Maven modules and refreshing open files (#110 part B).""" + +from __future__ import annotations + +import asyncio +import logging +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from java_functional_lsp.dependency_modules import ( + DEFAULT_BUDGET, + ENV_BUDGET, + MAX_BUDGET, + ClasspathRefresher, + DependencyModules, + path_from_uri, + resolve_budget, +) +from java_functional_lsp.proxy import JdtlsProxy, _find_maven_group_root, _find_repo_boundary +from java_functional_lsp.reactor import ReactorIndex + + +class TestBudget: + def test_default(self) -> None: + assert resolve_budget({}, {}) == DEFAULT_BUDGET == 60 + + def test_env(self) -> None: + assert resolve_budget({}, {ENV_BUDGET: "7"}) == 7 + + def test_config(self) -> None: + assert resolve_budget({"jdtls": {"dependencyModules": 9}}, {}) == 9 + + def test_env_wins_over_config(self) -> None: + assert resolve_budget({"jdtls": {"dependencyModules": 9}}, {ENV_BUDGET: "3"}) == 3 + + def test_zero_disables(self) -> None: + assert resolve_budget({}, {ENV_BUDGET: "0"}) == 0 + + def test_clamped_to_max(self, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING): + assert resolve_budget({}, {ENV_BUDGET: "5000"}) == MAX_BUDGET == 200 + assert "above the maximum" in caplog.text + + def test_negative_is_zero(self) -> None: + assert resolve_budget({}, {ENV_BUDGET: "-4"}) == 0 + + @pytest.mark.parametrize("raw", ["lots", "1.5"]) + def test_invalid_env_uses_default(self, raw: str, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING): + assert resolve_budget({}, {ENV_BUDGET: raw}) == DEFAULT_BUDGET + assert "invalid" in caplog.text + + @pytest.mark.parametrize("raw", [True, [1], {"max": 1}]) + def test_invalid_config_uses_default(self, raw: Any) -> None: + assert resolve_budget({"jdtls": {"dependencyModules": raw}}, {}) == DEFAULT_BUDGET + + def test_reads_os_environ_by_default(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv(ENV_BUDGET, "11") + assert resolve_budget() == 11 + + +class TestPathFromUri: + @pytest.mark.parametrize( + ("uri", "expected"), + [ + ("file:/a/b/it/", "/a/b/it"), + ("file:///a/b/it", "/a/b/it"), + ("file:///a/with%20space/", "/a/with space"), + ], + ) + def test_forms(self, uri: str, expected: str) -> None: + assert path_from_uri(uri) == Path(expected) + + @pytest.mark.parametrize("uri", ["jdt://contents/x", "", None, 5]) + def test_non_file(self, uri: Any) -> None: + assert path_from_uri(uri) is None + + +ROOT = Path("/repo") +COMMON = ROOT / "groupA" / "common" +UTIL = ROOT / "groupA" / "util" +IT = ROOT / "groupB" / "it" + + +def _index() -> ReactorIndex: + return ReactorIndex( + ROOT, + {"com.example:common": COMMON, "com.example:util": UTIL, "com.example:it": IT}, + ) + + +class _Harness: + def __init__(self, *, budget: int = DEFAULT_BUDGET, covered: list[Path] | None = None) -> None: + self.sent: list[tuple[list[dict[str, str]], list[dict[str, str]]]] = [] + self.covered = covered if covered is not None else [ROOT / "groupB"] + self.builds = 0 + + async def send(added: list[dict[str, str]], removed: list[dict[str, str]]) -> None: + self.sent.append((added, removed)) + + def build(_root: Path) -> ReactorIndex: + self.builds += 1 + return _index() + + self.deps = DependencyModules( + send_folders=send, + covered_roots=lambda: self.covered, + reactor_root_for=lambda _d: ROOT, + to_uri=lambda p: f"file://{p}", + budget=budget, + debounce=0.01, + index_builder=build, + ) + + async def settle(self) -> None: + for _ in range(5): + await asyncio.sleep(0.03) + + +class TestDependencyModules: + async def test_batches_candidates_into_one_add(self) -> None: + h = _Harness() + h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) + h.deps.note_missing(IT / "pom.xml", ["com.example:util", "com.example:common"]) + await h.settle() + assert len(h.sent) == 1 + added, removed = h.sent[0] + assert {a["uri"] for a in added} == {f"file://{COMMON}", f"file://{UTIL}"} + assert removed == [] + assert h.deps.used == 2 + assert h.builds == 1 # single flight + + async def test_external_and_covered_artifacts_are_ignored(self) -> None: + h = _Harness() + h.deps.note_missing(IT / "pom.xml", ["org.external:lib", "com.example:it"]) # it: under groupB + await h.settle() + assert h.sent == [] + assert h.deps.used == 0 + + async def test_already_added_is_not_re_added(self) -> None: + h = _Harness() + h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) + await h.settle() + h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) + await h.settle() + assert len(h.sent) == 1 + + async def test_disabled_does_nothing(self) -> None: + h = _Harness(budget=0) + h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) + await h.settle() + assert h.sent == [] + assert h.builds == 0 + + async def test_budget_exhaustion_warns_with_unresolved_gas(self, caplog: pytest.LogCaptureFixture) -> None: + h = _Harness(budget=1) + with caplog.at_level(logging.WARNING, logger="java_functional_lsp.dependency_modules"): + h.deps.note_missing(IT / "pom.xml", ["com.example:common", "com.example:util"]) + await h.settle() + h.deps.note_missing(IT / "pom.xml", ["com.example:util"]) + await h.settle() + assert len(h.sent) == 1 + assert len(h.sent[0][0]) == 1 + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] + assert len(warnings) == 1 # the same GA is reported once + assert "com.example:util" in warnings[0] + assert ENV_BUDGET in warnings[0] + + async def test_group_expansion_retires_covered_folders(self) -> None: + h = _Harness() + h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) + await h.settle() + removed = h.deps.take_covered_by(ROOT / "groupA") + assert removed == [{"uri": f"file://{COMMON}", "name": "common"}] + assert h.deps.registry == {} + # Never re-added, even if the covering folder is not reported as covered. + h.covered = [] + h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) + await h.settle() + assert len(h.sent) == 1 + assert h.deps.used == 1 # removal does not refund the budget + + async def test_group_expansion_drops_pending_candidates(self) -> None: + h = _Harness() + h.deps.debounce = 0.2 + h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) + await asyncio.sleep(0.05) # indexed and pending, not flushed yet + assert h.deps.take_covered_by(ROOT / "groupA") == [] + await asyncio.sleep(0.3) + assert h.sent == [] + + async def test_group_expanded_before_flush_skips_candidate(self) -> None: + h = _Harness() + h.deps.debounce = 0.1 + h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) + await asyncio.sleep(0.03) + h.covered.append(ROOT / "groupA") + await asyncio.sleep(0.2) + assert h.sent == [] + + async def test_index_failure_is_contained(self, caplog: pytest.LogCaptureFixture) -> None: + def boom(_root: Path) -> ReactorIndex: + raise OSError("disk") + + deps = DependencyModules( + send_folders=AsyncMock(), + covered_roots=list, + reactor_root_for=lambda _d: ROOT, + to_uri=str, + debounce=0, + index_builder=boom, + ) + with caplog.at_level(logging.WARNING): + deps.note_missing(IT / "pom.xml", ["com.example:common"]) + await asyncio.sleep(0.05) + assert "reactor index" in caplog.text + + async def test_reset_forgets_session(self) -> None: + h = _Harness() + h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) + await h.settle() + h.deps.reset() + assert h.deps.used == 0 + assert h.deps.registry == {} + h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) + await h.settle() + assert len(h.sent) == 2 + assert h.builds == 2 + + def test_note_missing_without_loop_is_a_no_op(self) -> None: + _Harness().deps.note_missing(IT / "pom.xml", ["com.example:common"]) + + +class TestClasspathRefresher: + async def test_refreshes_open_java_files_under_project_once(self) -> None: + sent: list[str] = [] + opened = [ + f"file://{IT}/src/test/java/A.java", + f"file://{IT}/src/test/java/B.java", + f"file://{IT}/pom.xml", + f"file://{COMMON}/src/main/java/C.java", + ] + + async def refresh(uri: str) -> None: + sent.append(uri) + + r = ClasspathRefresher(lambda: opened, refresh, debounce=0.02) + r.note_updated(IT) + r.note_updated(IT) # debounced + await asyncio.sleep(0.1) + assert sent == opened[:2] + + async def test_projects_are_debounced_separately(self) -> None: + sent: list[str] = [] + + async def refresh(uri: str) -> None: + sent.append(uri) + + opened = [f"file://{IT}/A.java", f"file://{COMMON}/C.java"] + r = ClasspathRefresher(lambda: opened, refresh, debounce=0.02) + r.note_updated(IT) + r.note_updated(COMMON) + await asyncio.sleep(0.1) + assert sorted(sent) == sorted(opened) + + async def test_open_uris_failure_is_contained(self) -> None: + def broken() -> list[str]: + raise RuntimeError("no workspace") + + send = AsyncMock() + r = ClasspathRefresher(broken, send, debounce=0) + r.note_updated(IT) + await asyncio.sleep(0.02) + send.assert_not_called() + + async def test_reset_cancels_pending(self) -> None: + send = AsyncMock() + r = ClasspathRefresher(lambda: [f"file://{IT}/A.java"], send, debounce=0.05) + r.note_updated(IT) + r.reset() + await asyncio.sleep(0.1) + send.assert_not_called() + + +# --- proxy wiring --------------------------------------------------------------------------- + + +def _pom_diag(message: str, severity: int = 1) -> dict[str, Any]: + return {"severity": severity, "message": message, "range": {}} + + +class TestProxyWiring: + def test_classpath_updated_event_triggers_refresh(self) -> None: + proxy = JdtlsProxy() + proxy._classpath_refresher = MagicMock() + proxy._handle_notification( + {"method": "language/eventNotification", "params": {"eventType": 100, "data": "file:/repo/groupB/it/"}} + ) + proxy._classpath_refresher.note_updated.assert_called_once_with(Path("/repo/groupB/it")) + + @pytest.mark.parametrize("params", [{"eventType": 200, "data": ["file:/x/"]}, {"eventType": 100, "data": 3}, []]) + def test_other_events_are_ignored(self, params: Any) -> None: + proxy = JdtlsProxy() + proxy._classpath_refresher = MagicMock() + proxy._handle_notification({"method": "language/eventNotification", "params": params}) + proxy._classpath_refresher.note_updated.assert_not_called() + + def test_missing_artifact_on_pom_queues_import_and_clearing_refreshes(self) -> None: + proxy = JdtlsProxy() + proxy.dependency_modules = MagicMock() + proxy._classpath_refresher = MagicMock() + uri = "file:///repo/groupB/it/pom.xml" + msg = "Offline / Missing artifact com.example:common:jar:X-DEFAULT" + proxy._handle_notification( + {"method": "textDocument/publishDiagnostics", "params": {"uri": uri, "diagnostics": [_pom_diag(msg)]}} + ) + proxy.dependency_modules.note_missing.assert_called_once_with( + Path("/repo/groupB/it/pom.xml"), ["com.example:common"] + ) + proxy._classpath_refresher.note_updated.assert_not_called() + proxy._handle_notification( + {"method": "textDocument/publishDiagnostics", "params": {"uri": uri, "diagnostics": []}} + ) + proxy._classpath_refresher.note_updated.assert_called_once_with(Path("/repo/groupB/it")) + + def test_other_pom_errors_do_not_trigger(self) -> None: + proxy = JdtlsProxy() + proxy.dependency_modules = MagicMock() + proxy._classpath_refresher = MagicMock() + uri = "file:///repo/it/pom.xml" + for diags in ([_pom_diag("Non-resolvable parent POM")], []): + proxy._handle_notification( + {"method": "textDocument/publishDiagnostics", "params": {"uri": uri, "diagnostics": diags}} + ) + proxy.dependency_modules.note_missing.assert_not_called() + proxy._classpath_refresher.note_updated.assert_not_called() + + async def test_refresh_sends_execute_command(self) -> None: + proxy = JdtlsProxy() + proxy._available = True + proxy.send_request = AsyncMock(return_value=None) # type: ignore[method-assign] + await proxy._refresh_file_diagnostics("file:///repo/A.java") + proxy.send_request.assert_awaited_once() + method, params = proxy.send_request.await_args.args + assert method == "workspace/executeCommand" + assert params == { + "command": "java.project.refreshDiagnostics", + "arguments": ["file:///repo/A.java", "thisFile", False], + } + + async def test_refresh_skipped_when_unavailable(self) -> None: + proxy = JdtlsProxy() + proxy.send_request = AsyncMock() # type: ignore[method-assign] + await proxy._refresh_file_diagnostics("file:///repo/A.java") + proxy.send_request.assert_not_called() + + async def test_open_uris_callback_reaches_refresher(self) -> None: + proxy = JdtlsProxy(open_uris=lambda: ["file:///repo/it/A.java"]) + assert proxy._classpath_refresher.open_files_under(Path("/repo/it")) == ["file:///repo/it/A.java"] + + +@pytest.fixture +def two_groups(tmp_path: Path) -> dict[str, Path]: + _find_maven_group_root.cache_clear() + _find_repo_boundary.cache_clear() + root = tmp_path / "root" + agg = "x" + leaf = "leaf" + for rel, text in {"": agg, "groupA": agg, "groupB": agg, "groupA/common": leaf, "groupB/it": leaf}.items(): + d = root / rel + d.mkdir(parents=True, exist_ok=True) + (d / "pom.xml").write_text(text) + src = root / "groupA" / "common" / "src" / "A.java" + src.parent.mkdir(parents=True) + src.write_text("class A {}") + return {"root": root, "common": root / "groupA" / "common", "it": root / "groupB" / "it", "src": src} + + +class TestProxyGroupDedupe: + async def test_group_expansion_removes_dependency_folders_in_same_event(self, two_groups: dict[str, Path]) -> None: + proxy = JdtlsProxy() + proxy._available = True + proxy._original_root_uri = two_groups["root"].as_uri() + proxy.send_notification = AsyncMock() # type: ignore[method-assign] + common = two_groups["common"].resolve() + proxy.dependency_modules.registry["com.example:common"] = common + await proxy.add_module_if_new(two_groups["src"].as_uri()) + method, params = proxy.send_notification.await_args.args + assert method == "workspace/didChangeWorkspaceFolders" + assert [a["name"] for a in params["event"]["added"]] == ["groupA"] + assert [r["name"] for r in params["event"]["removed"]] == ["common"] + assert proxy.dependency_modules.registry == {} + + async def test_expand_full_workspace_removes_covered_dependency_folders(self, two_groups: dict[str, Path]) -> None: + proxy = JdtlsProxy() + proxy._available = True + proxy._original_root_uri = two_groups["root"].as_uri() + proxy._initial_module_uri = two_groups["it"].as_uri() + proxy.modules.mark_added(two_groups["it"].as_uri()) + proxy.send_notification = AsyncMock() # type: ignore[method-assign] + # A dependency folder inside groupB (e.g. added while the group expansion was pending). + proxy.dependency_modules.registry["com.example:it2"] = (two_groups["root"] / "groupB" / "it2").resolve() + proxy.dependency_modules.registry["com.example:common"] = two_groups["common"].resolve() + await proxy.expand_full_workspace() + params = proxy.send_notification.await_args.args[1] + assert "it2" in [r["name"] for r in params["event"]["removed"]] + assert "com.example:common" in proxy.dependency_modules.registry + + async def test_dependency_folders_are_not_in_group_registries(self, two_groups: dict[str, Path]) -> None: + proxy = JdtlsProxy() + proxy._available = True + proxy.send_notification = AsyncMock() # type: ignore[method-assign] + proxy.modules.mark_added(two_groups["it"].as_uri()) + deps = proxy.dependency_modules + deps.debounce = 0 + deps._index_builder = lambda _r: ReactorIndex(two_groups["root"], {"com.example:common": two_groups["common"]}) + deps.note_missing(two_groups["it"] / "pom.xml", ["com.example:common"]) + for _ in range(5): + await asyncio.sleep(0.02) + proxy.send_notification.assert_awaited_once() + assert proxy._expanded_groups == set() + assert two_groups["common"].as_uri() not in proxy.modules.uris() + assert "com.example:common" in deps.registry + + async def test_stop_resets_dependency_state(self) -> None: + proxy = JdtlsProxy() + proxy._available = True + proxy.dependency_modules.registry["g:a"] = Path("/x") + await proxy.stop() + assert proxy.dependency_modules.registry == {} diff --git a/tests/test_e2e_dependency_modules.py b/tests/test_e2e_dependency_modules.py new file mode 100644 index 0000000..4c8ce4e --- /dev/null +++ b/tests/test_e2e_dependency_modules.py @@ -0,0 +1,354 @@ +"""E2E (#110): a dependency on a reactor module in another Maven group resolves. + +Real server + real jdtls on a two-group reactor with ``${revision}``:: + + root/pom.xml (revision X-DEFAULT, modules groupA, groupB) + root/groupA/common BaseIntegrationTest + root/groupB/it MyIntegrationTest extends BaseIntegrationTest (depends on common) + +The client root is ``root``; the group walk scopes jdtls to ``groupB``, so ``common`` is +not imported and m2e looks for ``com.example:common:jar:X-DEFAULT`` in the local +repository. That repository is isolated (never ``~/.m2``), primed with Maven's plugins +only, and used offline, so the artifact is missing, as it is for an unpublished sibling. +Without the fix the test file keeps four false errors next to its one deliberate error ("cannot be resolved", +"undefined for the type"). With it, the proxy imports ``common`` from the pom.xml +"Missing artifact" diagnostic and refreshes the open file. + +Skipped when jdtls, Java 21+, or Maven (for the one-time priming) is unavailable. +The primed repository is cached in ``~/.cache/java-functional-lsp/`` (override with +``JAVA_FUNCTIONAL_LSP_E2E_M2``). +""" + +from __future__ import annotations + +import asyncio +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest +from lsprotocol import types as lsp +from pygls.lsp.client import LanguageClient + +from java_functional_lsp.proxy import find_jdtls_java_home + +pytestmark = [ + pytest.mark.e2e, + pytest.mark.skipif(shutil.which("jdtls") is None, reason="jdtls binary not found on PATH"), + pytest.mark.skipif(find_jdtls_java_home() is None, reason="no Java 21+ found"), +] + +_ROOT_POM = """\ + + + 4.0.0 + com.example + root + ${revision} + pom + + X-DEFAULT + 17 + 17 + 17 + + + + + org.apache.maven.pluginsmaven-compiler-plugin\ +3.11.0 + org.apache.maven.pluginsmaven-resources-plugin\ +3.3.1 + org.apache.maven.pluginsmaven-surefire-plugin\ +3.5.4 + + + + + groupA + groupB + + +""" + + +def _group_pom(name: str, module: str) -> str: + return f"""\ + + + 4.0.0 + + com.example + root + ${{revision}} + + {name} + pom + + {module} + + +""" + + +def _leaf_pom(parent: str, name: str, deps: str = "") -> str: + return f"""\ + + + 4.0.0 + + com.example + {parent} + ${{revision}} + + {name}{deps} + +""" + + +_IT_DEPS = """ + + + com.example + common + ${revision} + + """ + +_BASE = """\ +package com.example.common; + +public abstract class BaseIntegrationTest { + protected String sut = "system-under-test"; + + protected void cleanCaches() { + sut = null; + } +} +""" + +# The type mismatch is a deterministic jdtls error that needs a resolved JRE: its presence proves a +# publish came from jdtls's semantic pass (the server's custom-only publish and jdtls's non-project, +# syntax-only publish both lack it). It is the only error the file should keep. +_TEST = """\ +package com.example.it; + +import com.example.common.BaseIntegrationTest; + +public class MyIntegrationTest extends BaseIntegrationTest { + public int run() { + cleanCaches(); + return this.sut.length(); + } + + public int marker() { + return "marker"; + } +} +""" +_JDTLS_MARKER = "Type mismatch" +_FALSE_ERRORS = ("cannot be resolved", "is undefined for the type", "hierarchy of the type") + +_SEMANTIC_TIMEOUT_SEC = 150 +_CLEAN_TIMEOUT_SEC = 60 +_PRIME_TIMEOUT_SEC = 300 + + +def _write_fixture(root: Path) -> Path: + """Write the reactor under *root* and return MyIntegrationTest.java.""" + files = { + "pom.xml": _ROOT_POM, + "groupA/pom.xml": _group_pom("groupA", "common"), + "groupB/pom.xml": _group_pom("groupB", "it"), + "groupA/common/pom.xml": _leaf_pom("groupA", "common"), + "groupB/it/pom.xml": _leaf_pom("groupB", "it", _IT_DEPS), + "groupA/common/src/main/java/com/example/common/BaseIntegrationTest.java": _BASE, + "groupB/it/src/test/java/com/example/it/MyIntegrationTest.java": _TEST, + } + for rel, text in files.items(): + path = root / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + return root / "groupB/it/src/test/java/com/example/it/MyIntegrationTest.java" + + +def _settings_xml(path: Path, repo: Path, *, offline: bool) -> Path: + path.write_text( + '\n' + '\n' + f" {repo}\n" + f" {'true' if offline else 'false'}\n" + "\n" + ) + return path + + +def _primed_repo(work: Path, fake_home: Path) -> Path: + """Return a local repository holding Maven's plugins but no com.example artifacts. + + With a truly empty offline repository m2e cannot compute a build plan and creates no + Java project at all, so the plugins are fetched once (online) by building the fixture. + """ + repo = Path( + os.environ.get("JAVA_FUNCTIONAL_LSP_E2E_M2") + or Path.home() / ".cache" / "java-functional-lsp" / "e2e-m2-issue110-v1" + ) + stamp = repo / ".primed" + if not stamp.is_file(): + mvn = shutil.which("mvn") + java_home = find_jdtls_java_home() + if mvn is None or java_home is None: + pytest.skip("Maven is needed once to prime the isolated local repository") + repo.mkdir(parents=True, exist_ok=True) + prime_root = work / "prime" + _write_fixture(prime_root) + settings = _settings_xml(work / "settings-online.xml", repo, offline=False) + env = { + **os.environ, + "JAVA_HOME": java_home, + "HOME": str(fake_home), + "MAVEN_OPTS": f"-Duser.home={fake_home}", + } + for goal in ("test-compile", "clean"): + cmd = [mvn, "-B", "-q", "-s", str(settings), "-gs", str(settings), f"-Dmaven.repo.local={repo}"] + try: + proc = subprocess.run( + [*cmd, "-f", str(prime_root / "pom.xml"), goal], + capture_output=True, + text=True, + timeout=_PRIME_TIMEOUT_SEC, + check=False, + env=env, + ) + except (OSError, subprocess.SubprocessError) as e: + pytest.skip(f"priming the local repository failed: {e}") + if proc.returncode != 0: + pytest.skip(f"priming the local repository failed (offline?): {proc.stdout[-500:]}") + stamp.write_text("ok\n") + # The reactor build never installs, but a stale com.example would make the test vacuous. + shutil.rmtree(repo / "com" / "example", ignore_errors=True) + return repo + + +class _Watch: + def __init__(self) -> None: + self.history: dict[str, list[list[lsp.Diagnostic]]] = {} + self.changed = asyncio.Event() + + def on_publish(self, params: lsp.PublishDiagnosticsParams) -> None: + self.history.setdefault(params.uri, []).append(list(params.diagnostics)) + self.changed.set() + + def latest(self, uri: str) -> list[lsp.Diagnostic]: + return self.history.get(uri, [[]])[-1] + + async def wait_for(self, uri: str, predicate: object, timeout: float) -> bool: + assert callable(predicate) + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while not (self.history.get(uri) and predicate(self.latest(uri))): + remaining = deadline - loop.time() + if remaining <= 0: + return False + self.changed.clear() + try: + await asyncio.wait_for(self.changed.wait(), timeout=remaining) + except asyncio.TimeoutError: + return False + return True + + +def _errors(diags: list[lsp.Diagnostic]) -> list[str]: + """Error messages other than the deliberate marker.""" + return [d.message for d in diags if d.severity == lsp.DiagnosticSeverity.Error and _JDTLS_MARKER not in d.message] + + +def _semantic(diags: list[lsp.Diagnostic]) -> bool: + return any(_JDTLS_MARKER in d.message for d in diags) + + +@pytest.mark.timeout(_PRIME_TIMEOUT_SEC * 2 + _SEMANTIC_TIMEOUT_SEC + _CLEAN_TIMEOUT_SEC + 60) +async def test_cross_group_dependency_resolves(tmp_path: Path) -> None: + fake_home = tmp_path / "home" + fake_home.mkdir() + markers = tmp_path / "tmp" + markers.mkdir() + repo = _primed_repo(tmp_path, fake_home) + root = tmp_path / "root" + test_file = _write_fixture(root) + settings = _settings_xml(tmp_path / "settings.xml", repo, offline=True) + # jdtls.settings replaces the proxy's defaults, so the defaults are repeated here. + (root / ".java-functional-lsp.json").write_text( + json.dumps( + { + "jdtls": { + "settings": { + "java": { + "import": { + "maven": {"enabled": True, "offline": {"enabled": True}}, + "gradle": {"enabled": False}, + "exclusions": ["**/node_modules/**", "**/.metadata/**", "**/target/**"], + }, + "configuration": { + "updateBuildConfiguration": "automatic", + "maven": {"userSettings": str(settings), "globalSettings": str(settings)}, + }, + "maven": {"downloadSources": False}, + } + } + } + } + ) + ) + + watch = _Watch() + client = LanguageClient("e2e-dependency-modules", "1.0") + + def on_publish(params: lsp.PublishDiagnosticsParams) -> None: # pygls needs a plain function + watch.on_publish(params) + + client.feature(lsp.TEXT_DOCUMENT_PUBLISH_DIAGNOSTICS)(on_publish) + env = { + **os.environ, + # Keep jdtls, m2e and the proxy (Lombok lookup, jdtls data cache) away from the real ~/.m2 and ~/.cache. + "HOME": str(fake_home), + "JAVA_TOOL_OPTIONS": f"-Duser.home={fake_home}", + "TMPDIR": str(markers), + } + env.pop("JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES", None) + await client.start_io(sys.executable, "-m", "java_functional_lsp", env=env) + uri = test_file.as_uri() + try: + await client.initialize_async( + lsp.InitializeParams( + process_id=os.getpid(), + root_uri=root.as_uri(), + capabilities=lsp.ClientCapabilities(), + client_info=lsp.ClientInfo(name="Claude Code"), + ) + ) + client.initialized(lsp.InitializedParams()) + client.text_document_did_open( + lsp.DidOpenTextDocumentParams( + text_document=lsp.TextDocumentItem(uri=uri, language_id="java", version=1, text=_TEST) + ) + ) + if not await watch.wait_for(uri, _semantic, _SEMANTIC_TIMEOUT_SEC): + pytest.skip(f"jdtls never analyzed the test file (import too slow?): {watch.history.get(uri)}") + clean = await watch.wait_for(uri, lambda d: _semantic(d) and not _errors(d), _CLEAN_TIMEOUT_SEC) + errors = _errors(watch.latest(uri)) + assert clean, f"cross-group symbols still unresolved: {errors}" + assert not any(marker in e for e in errors for marker in _FALSE_ERRORS) + finally: + try: + await asyncio.wait_for(client.shutdown_async(None), timeout=5.0) + client.exit(None) + except Exception: + pass + try: + await asyncio.wait_for(client.stop(), timeout=5.0) + except Exception: + pass diff --git a/tests/test_reactor.py b/tests/test_reactor.py new file mode 100644 index 0000000..52339cf --- /dev/null +++ b/tests/test_reactor.py @@ -0,0 +1,224 @@ +"""Tests for the Maven reactor index and the m2e "Missing artifact" parser (#110 part B).""" + +from __future__ import annotations + +import logging +import os +from pathlib import Path + +import pytest + +from java_functional_lsp.reactor import ( + MAX_POM_BYTES, + build_reactor_index, + find_reactor_root, + parse_missing_artifacts, + parse_pom, +) + +_NS = ' xmlns="http://maven.apache.org/POM/4.0.0"' + + +def _pom( + artifact: str, + *, + group: str | None = None, + parent_group: str | None = "com.example", + modules: tuple[str, ...] = (), + profile_modules: tuple[str, ...] = (), + ns: bool = True, +) -> str: + parts = [f"", "4.0.0"] + if parent_group: + parts.append(f"{parent_group}p") + if group: + parts.append(f"{group}") + parts.append(f"{artifact}") + if modules: + parts.append("" + "".join(f"{m}" for m in modules) + "") + if profile_modules: + parts.append( + "jars" + + "".join(f"{m}" for m in profile_modules) + + "" + ) + parts.append("") + return "\n".join(parts) + + +def _write(root: Path, rel: str, text: str) -> Path: + path = root / rel / "pom.xml" if rel else root / "pom.xml" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + return path.parent + + +@pytest.fixture +def reactor(tmp_path: Path) -> Path: + root = tmp_path / "root" + _write(root, "", _pom("root", group="com.example", parent_group=None, modules=("groupA", "groupB"))) + _write(root, "groupA", _pom("groupA", modules=("common",))) + _write(root, "groupA/common", _pom("common")) + _write(root, "groupB", _pom("groupB", modules=("it",), ns=False)) + _write(root, "groupB/it", _pom("it", ns=False)) + return root + + +class TestIndex: + def test_maps_reachable_modules_with_inherited_group(self, reactor: Path) -> None: + index = build_reactor_index(reactor) + real = reactor.resolve() + assert index.get("com.example:common") == real / "groupA" / "common" + assert index.get("com.example:it") == real / "groupB" / "it" # namespace-less pom + assert index.get("com.example:root") == real + assert index.poms_read == 5 + assert not index.truncated + + def test_own_group_id_wins_over_parent(self, reactor: Path) -> None: + _write(reactor, "groupA/common", _pom("common", group="org.other")) + index = build_reactor_index(reactor) + assert index.get("org.other:common") is not None + assert index.get("com.example:common") is None + + def test_unreachable_pom_is_not_indexed(self, reactor: Path) -> None: + _write(reactor, "groupA/orphan", _pom("orphan")) + assert build_reactor_index(reactor).get("com.example:orphan") is None + + def test_profile_modules_are_unioned(self, reactor: Path) -> None: + _write(reactor, "groupA", _pom("groupA", modules=("common",), profile_modules=("extra",))) + _write(reactor, "groupA/extra", _pom("extra")) + assert build_reactor_index(reactor).get("com.example:extra") is not None + + def test_module_entry_may_name_a_pom_file(self, reactor: Path) -> None: + _write(reactor, "groupA", _pom("groupA", modules=("common", "alt/pom.xml"))) + _write(reactor, "groupA/alt", _pom("alt")) + assert build_reactor_index(reactor).get("com.example:alt") is not None + + @pytest.mark.parametrize( + "declaration", + [ + ']>', + '', + '', + ], + ) + def test_doctype_or_entity_pom_is_rejected(self, reactor: Path, declaration: str) -> None: + malicious = _pom("groupA", modules=("common",)).replace(" None: + big = _pom("groupA", modules=("common",)).replace("", "") + _write(reactor, "groupA", big) + assert build_reactor_index(reactor).get("com.example:groupA") is None + + def test_malformed_pom_is_tolerated(self, reactor: Path) -> None: + _write(reactor, "groupA/common", "common") + index = build_reactor_index(reactor) + assert index.get("com.example:common") is None + assert index.get("com.example:it") is not None + + def test_placeholder_coordinates_are_skipped(self, reactor: Path) -> None: + _write(reactor, "groupA/common", _pom("common-${suffix}")) + assert not [ga for ga in build_reactor_index(reactor).modules if "common" in ga] + + def test_duplicate_ga_is_dropped_and_logged_once(self, reactor: Path, caplog: pytest.LogCaptureFixture) -> None: + _write(reactor, "groupB", _pom("groupB", modules=("it", "copy"))) + _write(reactor, "groupB/copy", _pom("common")) + with caplog.at_level(logging.INFO, logger="java_functional_lsp.reactor"): + index = build_reactor_index(reactor) + assert index.get("com.example:common") is None + assert "com.example:common" in index.ambiguous + assert sum("com.example:common" in r.getMessage() for r in caplog.records) == 1 + + def test_module_outside_root_is_skipped(self, reactor: Path, tmp_path: Path) -> None: + _write(tmp_path, "outside", _pom("outside")) + _write(reactor, "groupA", _pom("groupA", modules=("common", "../../outside"))) + assert build_reactor_index(reactor).get("com.example:outside") is None + + @pytest.mark.skipif(os.name == "nt", reason="symlinks") + def test_symlinked_dir_pointing_outside_is_skipped(self, reactor: Path, tmp_path: Path) -> None: + target = _write(tmp_path, "elsewhere", _pom("elsewhere")) + (reactor / "groupA" / "link").symlink_to(target, target_is_directory=True) + _write(reactor, "groupA", _pom("groupA", modules=("common", "link"))) + assert build_reactor_index(reactor).get("com.example:elsewhere") is None + + @pytest.mark.skipif(os.name == "nt", reason="symlinks") + def test_symlinked_pom_is_skipped(self, reactor: Path) -> None: + real = _write(reactor, "groupA/real", _pom("viaLink")) + (reactor / "groupA" / "lnk").mkdir() + (reactor / "groupA" / "lnk" / "pom.xml").symlink_to(real / "pom.xml") + _write(reactor, "groupA", _pom("groupA", modules=("common", "lnk"))) + assert build_reactor_index(reactor).get("com.example:viaLink") is None + + @pytest.mark.skipif(os.name == "nt", reason="symlinks") + def test_symlink_loop_terminates(self, reactor: Path) -> None: + (reactor / "groupA" / "common" / "loop").symlink_to(reactor / "groupA", target_is_directory=True) + _write(reactor, "groupA/common", _pom("common", modules=("loop",))) + index = build_reactor_index(reactor) + assert index.get("com.example:common") is not None + assert index.poms_read == 5 + + def test_pom_count_bound(self, reactor: Path) -> None: + index = build_reactor_index(reactor, max_poms=2) + assert index.truncated + assert index.poms_read == 2 + + def test_time_bound(self, reactor: Path) -> None: + ticks = iter([0.0, 0.0, 0.0, 99.0, 99.0, 99.0, 99.0, 99.0]) + index = build_reactor_index(reactor, max_seconds=10.0, clock=lambda: next(ticks)) + assert index.truncated + assert index.poms_read == 2 + + def test_missing_root_pom_gives_empty_index(self, tmp_path: Path) -> None: + assert build_reactor_index(tmp_path).modules == {} + + def test_parse_pom_rejects_non_project_root(self, tmp_path: Path) -> None: + pom = tmp_path / "pom.xml" + pom.write_text("") + assert parse_pom(pom) is None + + +class TestReactorRoot: + def test_topmost_consecutive_pom(self, reactor: Path) -> None: + assert find_reactor_root(reactor / "groupB" / "it") == reactor + + def test_stops_at_boundary(self, reactor: Path) -> None: + assert find_reactor_root(reactor / "groupB" / "it", boundary=reactor / "groupB") == reactor / "groupB" + + +class TestMissingArtifactParser: + @pytest.mark.parametrize( + "message", + [ + "Missing artifact com.example:common:jar:X-DEFAULT", + "Offline / Missing artifact com.example:common:jar:X-DEFAULT", + "Offline /Missing artifact com.example:common:jar:X-DEFAULT", + "Missing artifact com.example:common:test-jar:tests:X-DEFAULT", + ], + ) + def test_extracts_group_and_artifact(self, message: str) -> None: + assert parse_missing_artifacts([message]) == ["com.example:common"] + + @pytest.mark.parametrize( + "message", + [ + "Project build error: Non-resolvable parent POM", + "Missing artifact com.example", + "The container 'Maven Dependencies' references non existing library", + "see Missing artifact com.example:common:jar:1", # not at the start or after a prefix + ], + ) + def test_ignores_other_messages(self, message: str) -> None: + assert parse_missing_artifacts([message]) == [] + + def test_dedupes_in_order(self) -> None: + messages = ( + "Missing artifact a.b:x:jar:1", + "Missing artifact a.b:y:jar:1", + "Missing artifact a.b:x:test-jar:tests:1", + ) + assert parse_missing_artifacts(messages) == ["a.b:x", "a.b:y"] diff --git a/uv.lock b/uv.lock index 98af412..8b3bbc8 100644 --- a/uv.lock +++ b/uv.lock @@ -184,7 +184,7 @@ wheels = [ [[package]] name = "java-functional-lsp" -version = "0.13.1" +version = "0.14.0" source = { editable = "." } dependencies = [ { name = "pygls" }, From ea8df0bf51f569234f8c42fa8f7bac298534b7f9 Mon Sep 17 00:00:00 2001 From: Aviad Shiber Date: Tue, 29 Sep 2026 14:12:21 +0300 Subject: [PATCH 2/3] fix: never import aggregator poms as dependency modules (#110) A missing pom-type dependency on a group or the reactor root would add its whole subtree as one folder, bypassing the group cap. The index now records aggregators (poms with ) and never resolves them. Co-Authored-By: Claude Opus 5.5 --- src/java_functional_lsp/reactor.py | 24 ++++++++++++++++++------ tests/test_dependency_modules.py | 25 +++++++++++++++++++++++++ tests/test_reactor.py | 15 ++++++++++----- 3 files changed, 53 insertions(+), 11 deletions(-) diff --git a/src/java_functional_lsp/reactor.py b/src/java_functional_lsp/reactor.py index 4f2db48..47d189d 100644 --- a/src/java_functional_lsp/reactor.py +++ b/src/java_functional_lsp/reactor.py @@ -44,6 +44,9 @@ class ReactorIndex: modules: dict[str, Path] = field(default_factory=dict) #: GAs declared by more than one module directory (never resolved). ambiguous: set[str] = field(default_factory=set) + #: GAs of aggregator poms (with ````). Never resolved: importing one would pull + #: in its whole subtree (a group, or the entire reactor) as a single folder. + aggregators: set[str] = field(default_factory=set) poms_read: int = 0 #: True when the walk stopped early at the pom-count or time bound. truncated: bool = False @@ -143,6 +146,18 @@ def _contained_dir(pom: Path, real_root: Path) -> Path | None: return module_dir if module_dir.is_relative_to(real_root) else None +def _resolve_found(index: ReactorIndex, found: dict[str, set[Path]]) -> None: + """Keep GAs declared by exactly one non-aggregator directory; log the ambiguous ones once.""" + for ga, dirs in found.items(): + if ga in index.aggregators: + continue + if len(dirs) == 1: + index.modules[ga] = next(iter(dirs)) + else: + index.ambiguous.add(ga) + logger.info("reactor: ignoring %s, declared by %d module directories", ga, len(dirs)) + + def build_reactor_index( root: Path, *, @@ -189,16 +204,13 @@ def build_reactor_index( g, a = parsed.group_id, parsed.artifact_id if g and a and "${" not in g and "${" not in a: found.setdefault(f"{g}:{a}", set()).add(module_dir) + if parsed.modules: + index.aggregators.add(f"{g}:{a}") for entry in parsed.modules: if "${" in entry: continue queue.append(_module_pom(module_dir, entry)) - for ga, dirs in found.items(): - if len(dirs) == 1: - index.modules[ga] = next(iter(dirs)) - else: - index.ambiguous.add(ga) - logger.info("reactor: ignoring %s, declared by %d module directories", ga, len(dirs)) + _resolve_found(index, found) return index diff --git a/tests/test_dependency_modules.py b/tests/test_dependency_modules.py index e6c1a51..507be44 100644 --- a/tests/test_dependency_modules.py +++ b/tests/test_dependency_modules.py @@ -140,6 +140,31 @@ async def test_external_and_covered_artifacts_are_ignored(self) -> None: assert h.sent == [] assert h.deps.used == 0 + async def test_aggregators_are_never_imported(self, tmp_path: Path) -> None: + from java_functional_lsp.reactor import build_reactor_index + + agg = "g{a}{m}" + root = tmp_path / "root" + for rel, text in { + "": agg.format(a="root", m="grp"), + "grp": agg.format(a="grp", m="leaf"), + "grp/leaf": "gleaf", + }.items(): + (root / rel).mkdir(parents=True, exist_ok=True) + (root / rel / "pom.xml").write_text(text) + send = AsyncMock() + deps = DependencyModules( + send_folders=send, + covered_roots=list, + reactor_root_for=lambda _d: root, + to_uri=str, + debounce=0, + index_builder=build_reactor_index, + ) + deps.note_missing(tmp_path / "other" / "pom.xml", ["g:root", "g:grp"]) + await asyncio.sleep(0.1) + send.assert_not_called() + async def test_already_added_is_not_re_added(self) -> None: h = _Harness() h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) diff --git a/tests/test_reactor.py b/tests/test_reactor.py index 52339cf..5412b10 100644 --- a/tests/test_reactor.py +++ b/tests/test_reactor.py @@ -70,10 +70,15 @@ def test_maps_reachable_modules_with_inherited_group(self, reactor: Path) -> Non real = reactor.resolve() assert index.get("com.example:common") == real / "groupA" / "common" assert index.get("com.example:it") == real / "groupB" / "it" # namespace-less pom - assert index.get("com.example:root") == real assert index.poms_read == 5 assert not index.truncated + def test_aggregators_are_never_resolved(self, reactor: Path) -> None: + index = build_reactor_index(reactor) + assert index.get("com.example:root") is None + assert index.get("com.example:groupA") is None + assert index.aggregators == {"com.example:root", "com.example:groupA", "com.example:groupB"} + def test_own_group_id_wins_over_parent(self, reactor: Path) -> None: _write(reactor, "groupA/common", _pom("common", group="org.other")) index = build_reactor_index(reactor) @@ -106,14 +111,14 @@ def test_doctype_or_entity_pom_is_rejected(self, reactor: Path, declaration: str malicious = _pom("groupA", modules=("common",)).replace(" None: big = _pom("groupA", modules=("common",)).replace("", "") _write(reactor, "groupA", big) - assert build_reactor_index(reactor).get("com.example:groupA") is None + assert build_reactor_index(reactor).get("com.example:common") is None def test_malformed_pom_is_tolerated(self, reactor: Path) -> None: _write(reactor, "groupA/common", "common") @@ -159,8 +164,8 @@ def test_symlink_loop_terminates(self, reactor: Path) -> None: (reactor / "groupA" / "common" / "loop").symlink_to(reactor / "groupA", target_is_directory=True) _write(reactor, "groupA/common", _pom("common", modules=("loop",))) index = build_reactor_index(reactor) - assert index.get("com.example:common") is not None - assert index.poms_read == 5 + assert index.poms_read == 5 # groupA is not read a second time through the link + assert index.get("com.example:it") is not None def test_pom_count_bound(self, reactor: Path) -> None: index = build_reactor_index(reactor, max_poms=2) From 1cc6880523be5a31a3b5a3c637e16978de9af81f Mon Sep 17 00:00:00 2001 From: Aviad Shiber Date: Tue, 29 Sep 2026 14:33:10 +0300 Subject: [PATCH 3/3] fix: address review findings on PR B (round 1) - Compare dependency-module folders and imported/group folders resolved, so a client root reached through a symlink still retires and dedupes them. - Keep flushing while candidates arrive during an in-flight send. - Reject DOCTYPE/ENTITY declarations at the expat level too (UTF-16 poms), and tolerate poms in encodings expat refuses instead of aborting the index. - Ignore coordinates outside Maven's character set, so no raw pom text is logged. - Tests: symlinked-root cases, send race, UTF-16 poms, guard log assertions, positive controls for negative assertions, e2e log check of the import path. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/java_functional_lsp/dependency_modules.py | 26 ++- src/java_functional_lsp/reactor.py | 48 ++++- tests/test_dependency_modules.py | 173 ++++++++++++++++-- tests/test_e2e_dependency_modules.py | 28 +++ tests/test_reactor.py | 58 +++++- 6 files changed, 309 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 0a8f6fb..874358e 100644 --- a/README.md +++ b/README.md @@ -333,7 +333,7 @@ Limits: - **Budget.** At most N module folders are added per session. A folder that a group later replaces still counts. When the budget runs out, the log shows a `WARNING` listing the modules left unresolved. Raise the budget, or open a file in those modules' group. - **Stale local installs are not detected.** If an old build of the sibling is installed at the same version in your local repository, m2e resolves the dependency from that jar and reports nothing. You then see the installed version's API, not the source. Run `mvn install` for that module again, or delete it from the local repository. - **Maven only.** Gradle projects are unchanged. -- **Index bounds.** The index skips poms larger than 1 MB, poms with ` bool: return path == folder or path.is_relative_to(folder) +def _real(path: Path) -> Path: + """*path* with symlinks resolved, or unchanged when it cannot be resolved. + + Registry entries come from the reactor index, which is always resolved; folders the + proxy imported are spelled as the client sent them. Both sides are compared resolved, + so a client root reached through a symlink still matches (#110). + """ + try: + return path.resolve() + except (OSError, RuntimeError): + return path + + def _display(path: Path, root: Path) -> str: try: return str(path.relative_to(root)) or "." @@ -185,9 +198,10 @@ async def _build_index(self, root: Path) -> ReactorIndex | None: return index def _is_covered(self, module_dir: Path) -> bool: + module_dir = _real(module_dir) if any(_is_under(module_dir, folder) for folder in self.registry.values()): return True - return any(_is_under(module_dir, folder) for folder in self._covered_roots()) + return any(_is_under(module_dir, _real(folder)) for folder in self._covered_roots()) async def _consider(self, module_dir: Path, gas: list[str]) -> None: index = await self._index_for(module_dir) @@ -210,8 +224,13 @@ async def _consider(self, module_dir: Path, gas: list[str]) -> None: self._flush_task.add_done_callback(self._tasks.discard) async def _flush_after_debounce(self, root: Path) -> None: - await asyncio.sleep(self.debounce) - await self.flush(root) + # Candidates queued while a flush awaits its send see this task still running and do + # not schedule a flush of their own, so keep flushing until nothing is pending. + while True: + await asyncio.sleep(self.debounce) + await self.flush(root) + if not self._pending: + return async def flush(self, root: Path) -> None: """Send one didChangeWorkspaceFolders add for the queued modules, within the budget.""" @@ -258,6 +277,7 @@ def take_covered_by(self, folder: Path) -> list[Folder]: Returns them as ``removed`` entries for the same didChangeWorkspaceFolders event. """ + folder = _real(folder) removed: list[Folder] = [] for ga, target in list(self.registry.items()): if _is_under(target, folder): diff --git a/src/java_functional_lsp/reactor.py b/src/java_functional_lsp/reactor.py index 47d189d..d371352 100644 --- a/src/java_functional_lsp/reactor.py +++ b/src/java_functional_lsp/reactor.py @@ -8,9 +8,12 @@ The poms come from the user's checkout, so parsing is defensive: files over ``MAX_POM_BYTES`` or containing a `` / ]Missing artifact g:a:type[:classifier]:version". ``${revision}`` is #: already interpolated. Only groupId and artifactId are kept. -_MISSING_ARTIFACT_RE = re.compile(r"(?:^|/\s*)Missing artifact ([A-Za-z0-9_.\-]+):([A-Za-z0-9_.\-]+):\S+") +_MISSING_ARTIFACT_RE = re.compile(rf"(?:^|/\s*)Missing artifact ({_COORDINATE}):({_COORDINATE}):\S+") + + +class _ForbiddenDeclarationError(Exception): + pass + + +def _forbid(*_args: object) -> None: + raise _ForbiddenDeclarationError + + +def _declares_dtd(data: bytes) -> bool: + """True when expat meets a doctype or entity declaration in *data*, in any encoding. + + Only declarations are rejected here; a malformed document is left to ElementTree. + """ + parser = expat.ParserCreate() + parser.StartDoctypeDeclHandler = _forbid + parser.EntityDeclHandler = _forbid + try: + parser.Parse(data, True) + except _ForbiddenDeclarationError: + return True + except (expat.ExpatError, ValueError): # ValueError: an encoding expat cannot decode + return False + return False @dataclass @@ -97,7 +128,7 @@ def _read_pom_bytes(pom: Path) -> bytes | None: return None if len(data) > MAX_POM_BYTES: return None - if _FORBIDDEN_MARKUP.search(data): + if _FORBIDDEN_MARKUP.search(data) or _declares_dtd(data): logger.info("reactor: skipping %s (DOCTYPE/ENTITY declarations are not allowed)", pom.name) return None return data @@ -110,7 +141,7 @@ def parse_pom(pom: Path) -> _Pom | None: return None try: project = ET.fromstring(data) - except ET.ParseError: + except (ET.ParseError, ValueError): # ValueError: e.g. encoding="UTF-16-BE" return None if _local(project.tag) != "project": return None @@ -169,8 +200,9 @@ def build_reactor_index( Breadth-first; each pom is read at most once. A module whose resolved directory is outside the resolved root, or whose pom is a symlink, is skipped. Coordinates - containing ``${`` are skipped. A GA declared by two directories is dropped - entirely and logged once. Blocking: run it in an executor. + with characters outside ``[A-Za-z0-9_.-]`` (such as ``${...}`` placeholders) are + skipped. A GA declared by two directories is dropped entirely and logged once. + Blocking: run it in an executor. """ try: real_root = root.resolve() @@ -202,7 +234,7 @@ def build_reactor_index( if parsed is None: continue g, a = parsed.group_id, parsed.artifact_id - if g and a and "${" not in g and "${" not in a: + if g and a and _COORDINATE_RE.fullmatch(g) and _COORDINATE_RE.fullmatch(a): found.setdefault(f"{g}:{a}", set()).add(module_dir) if parsed.modules: index.aggregators.add(f"{g}:{a}") diff --git a/tests/test_dependency_modules.py b/tests/test_dependency_modules.py index 507be44..d82485d 100644 --- a/tests/test_dependency_modules.py +++ b/tests/test_dependency_modules.py @@ -4,6 +4,7 @@ import asyncio import logging +import os from pathlib import Path from typing import Any from unittest.mock import AsyncMock, MagicMock @@ -118,6 +119,17 @@ def build(_root: Path) -> ReactorIndex: async def settle(self) -> None: for _ in range(5): await asyncio.sleep(0.03) + await _drain(self.deps) + + +async def _drain(deps: DependencyModules) -> None: + """Wait until every background task of *deps* has finished (absence is then meaningful).""" + for _ in range(200): + running = [t for t in deps._tasks if not t.done()] + if not running: + return + await asyncio.gather(*running, return_exceptions=True) + raise AssertionError("dependency-module tasks never settled") class TestDependencyModules: @@ -137,6 +149,7 @@ async def test_external_and_covered_artifacts_are_ignored(self) -> None: h = _Harness() h.deps.note_missing(IT / "pom.xml", ["org.external:lib", "com.example:it"]) # it: under groupB await h.settle() + assert h.builds == 1 # positive control: the index was built and consulted assert h.sent == [] assert h.deps.used == 0 @@ -153,17 +166,26 @@ async def test_aggregators_are_never_imported(self, tmp_path: Path) -> None: (root / rel).mkdir(parents=True, exist_ok=True) (root / rel / "pom.xml").write_text(text) send = AsyncMock() + indexes: list[ReactorIndex] = [] + + def build(r: Path) -> ReactorIndex: + indexes.append(build_reactor_index(r)) + return indexes[-1] + deps = DependencyModules( send_folders=send, covered_roots=list, reactor_root_for=lambda _d: root, to_uri=str, debounce=0, - index_builder=build_reactor_index, + index_builder=build, ) - deps.note_missing(tmp_path / "other" / "pom.xml", ["g:root", "g:grp"]) - await asyncio.sleep(0.1) - send.assert_not_called() + deps.note_missing(tmp_path / "other" / "pom.xml", ["g:root", "g:grp", "g:leaf"]) + await _drain(deps) + assert [i.aggregators for i in indexes] == [{"g:root", "g:grp"}] + # Positive control: the leaf in the same batch was imported, the aggregators were not. + send.assert_awaited_once() + assert [a["name"] for a in send.await_args.args[0]] == ["leaf"] async def test_already_added_is_not_re_added(self) -> None: h = _Harness() @@ -214,17 +236,54 @@ async def test_group_expansion_drops_pending_candidates(self) -> None: h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) await asyncio.sleep(0.05) # indexed and pending, not flushed yet assert h.deps.take_covered_by(ROOT / "groupA") == [] - await asyncio.sleep(0.3) + await h.settle() assert h.sent == [] async def test_group_expanded_before_flush_skips_candidate(self) -> None: h = _Harness() - h.deps.debounce = 0.1 - h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) - await asyncio.sleep(0.03) - h.covered.append(ROOT / "groupA") - await asyncio.sleep(0.2) - assert h.sent == [] + h.deps.debounce = 0.2 + h.deps.note_missing(IT / "pom.xml", ["com.example:common", "com.example:util"]) + for _ in range(100): # until both are queued, well before the debounce ends + if len(h.deps._pending) == 2: + break + await asyncio.sleep(0.005) + assert set(h.deps._pending) == {"com.example:common", "com.example:util"} + h.covered.append(COMMON) # the group holding common was imported meanwhile + await h.settle() + # Positive control: the flush ran and sent util; only the covered candidate was skipped. + assert [[a["name"] for a in added] for added, _ in h.sent] == [["util"]] + + async def test_candidate_queued_during_a_send_is_flushed(self) -> None: + release = asyncio.Event() + sent: list[list[str]] = [] + + async def slow_send(added: list[dict[str, str]], _removed: list[dict[str, str]]) -> None: + sent.append([a["name"] for a in added]) + if len(sent) == 1: + await release.wait() # e.g. stdin.drain() in the real proxy + + deps = DependencyModules( + send_folders=slow_send, + covered_roots=list, + reactor_root_for=lambda _d: ROOT, + to_uri=str, + debounce=0.01, + index_builder=lambda _r: _index(), + ) + deps.note_missing(IT / "pom.xml", ["com.example:common"]) + for _ in range(100): + if sent: + break + await asyncio.sleep(0.005) + assert sent == [["common"]] + deps.note_missing(IT / "pom.xml", ["com.example:util"]) # while the first send is in flight + for _ in range(10): + await asyncio.sleep(0.01) + release.set() + await _drain(deps) + assert sent == [["common"], ["util"]] + assert deps._pending == {} + assert set(deps.registry) == {"com.example:common", "com.example:util"} async def test_index_failure_is_contained(self, caplog: pytest.LogCaptureFixture) -> None: def boom(_root: Path) -> ReactorIndex: @@ -256,7 +315,63 @@ async def test_reset_forgets_session(self) -> None: assert h.builds == 2 def test_note_missing_without_loop_is_a_no_op(self) -> None: - _Harness().deps.note_missing(IT / "pom.xml", ["com.example:common"]) + h = _Harness() + h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) + assert h.deps._tasks == set() + assert h.deps._pending == {} + assert h.deps.registry == {} + assert h.deps.used == 0 + assert h.builds == 0 + assert h.sent == [] + + +@pytest.mark.skipif(os.name == "nt", reason="symlinks") +class TestSymlinkedRoot: + """Registry entries are resolved; folders the proxy imported may be spelled through a symlink.""" + + @pytest.fixture + def linked(self, tmp_path: Path) -> tuple[Path, Path]: + real = tmp_path / "real" + (real / "groupA" / "common").mkdir(parents=True) + (real / "groupB" / "it").mkdir(parents=True) + link = tmp_path / "link" + link.symlink_to(real, target_is_directory=True) + return real.resolve(), link + + def _deps(self, real: Path, covered: list[Path], sent: list[list[str]]) -> DependencyModules: + async def send(added: list[dict[str, str]], _removed: list[dict[str, str]]) -> None: + sent.append([a["name"] for a in added]) + + return DependencyModules( + send_folders=send, + covered_roots=lambda: covered, + reactor_root_for=lambda _d: real, + to_uri=str, + debounce=0, + index_builder=lambda _r: ReactorIndex(real, {"com.example:common": real / "groupA" / "common"}), + ) + + def test_take_covered_by_matches_the_symlinked_spelling(self, linked: tuple[Path, Path]) -> None: + real, link = linked + deps = self._deps(real, [], []) + deps.registry["com.example:common"] = real / "groupA" / "common" + removed = deps.take_covered_by(link / "groupA") + assert [r["name"] for r in removed] == ["common"] + assert deps.registry == {} + + async def test_symlinked_covered_root_prevents_import(self, linked: tuple[Path, Path]) -> None: + real, link = linked + sent: list[list[str]] = [] + deps = self._deps(real, [link / "groupA"], sent) + deps.note_missing(link / "groupB" / "it" / "pom.xml", ["com.example:common"]) + await _drain(deps) + assert sent == [] + assert deps.registry == {} + # Positive control: with nothing covering it, the same report imports it. + deps2 = self._deps(real, [], sent) + deps2.note_missing(link / "groupB" / "it" / "pom.xml", ["com.example:common"]) + await _drain(deps2) + assert sent == [["common"]] class TestClasspathRefresher: @@ -450,6 +565,40 @@ async def test_dependency_folders_are_not_in_group_registries(self, two_groups: assert two_groups["common"].as_uri() not in proxy.modules.uris() assert "com.example:common" in deps.registry + @pytest.mark.skipif(os.name == "nt", reason="symlinks") + async def test_symlinked_client_root_still_retires_dependency_folders( + self, two_groups: dict[str, Path], tmp_path: Path + ) -> None: + link = tmp_path / "link" + link.symlink_to(two_groups["root"], target_is_directory=True) + proxy = JdtlsProxy() + proxy._available = True + proxy._original_root_uri = link.as_uri() # the client reaches the checkout through a symlink + proxy.send_notification = AsyncMock() # type: ignore[method-assign] + proxy.dependency_modules.registry["com.example:common"] = two_groups["common"].resolve() + await proxy.expand_full_workspace() # no initial module: the root keeps the client's spelling + params = proxy.send_notification.await_args.args[1] + assert [r["name"] for r in params["event"]["removed"]] == ["common"] + assert proxy.dependency_modules.registry == {} + + @pytest.mark.skipif(os.name == "nt", reason="symlinks") + async def test_symlinked_module_folder_counts_as_covered(self, two_groups: dict[str, Path], tmp_path: Path) -> None: + link = tmp_path / "link" + link.symlink_to(two_groups["root"], target_is_directory=True) + proxy = JdtlsProxy() + proxy._available = True + proxy.send_notification = AsyncMock() # type: ignore[method-assign] + proxy.modules.mark_added((link / "groupA" / "common").as_uri()) # imported via the symlink + proxy.modules.mark_added((link / "groupB" / "it").as_uri()) + deps = proxy.dependency_modules + deps.debounce = 0 + common = two_groups["common"].resolve() + deps._index_builder = lambda _r: ReactorIndex(two_groups["root"].resolve(), {"com.example:common": common}) + deps.note_missing(link / "groupB" / "it" / "pom.xml", ["com.example:common"]) + await _drain(deps) + proxy.send_notification.assert_not_called() + assert deps.registry == {} + async def test_stop_resets_dependency_state(self) -> None: proxy = JdtlsProxy() proxy._available = True diff --git a/tests/test_e2e_dependency_modules.py b/tests/test_e2e_dependency_modules.py index 4c8ce4e..0898086 100644 --- a/tests/test_e2e_dependency_modules.py +++ b/tests/test_e2e_dependency_modules.py @@ -261,6 +261,29 @@ async def wait_for(self, uri: str, predicate: object, timeout: float) -> bool: return True +async def _collect(stream: asyncio.StreamReader | None, lines: list[str]) -> None: + """Keep the server's stderr (its log) drained and captured.""" + if stream is None: + return + while line := await stream.readline(): + lines.append(line.decode(errors="replace").rstrip()) + + +async def _assert_dependency_module_imported(server_log: list[str]) -> None: + """The fix itself resolved it: common was imported as a dependency module and the open + file refreshed, rather than jdtls resolving it some other way (e.g. a leaked artifact).""" + imports = [line for line in server_log if "importing 1 dependency module(s)" in line] + assert imports, "\n".join(server_log)[-4000:] + assert "com.example:common" in imports[0] + # The refresh follows the pom's "Missing artifact" clearing after a debounce, and may land + # after jdtls's own clean publish. + for _ in range(100): + if any("classpath of it updated, refreshing" in line for line in server_log): + return + await asyncio.sleep(0.1) + raise AssertionError("open file never refreshed:\n" + "\n".join(server_log)[-4000:]) + + def _errors(diags: list[lsp.Diagnostic]) -> list[str]: """Error messages other than the deliberate marker.""" return [d.message for d in diags if d.severity == lsp.DiagnosticSeverity.Error and _JDTLS_MARKER not in d.message] @@ -319,7 +342,10 @@ def on_publish(params: lsp.PublishDiagnosticsParams) -> None: # pygls needs a p "TMPDIR": str(markers), } env.pop("JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES", None) + env["JAVA_FUNCTIONAL_LSP_LOG_LEVEL"] = "INFO" await client.start_io(sys.executable, "-m", "java_functional_lsp", env=env) + server_log: list[str] = [] + stderr_task = asyncio.create_task(_collect(client._server.stderr, server_log)) uri = test_file.as_uri() try: await client.initialize_async( @@ -342,6 +368,7 @@ def on_publish(params: lsp.PublishDiagnosticsParams) -> None: # pygls needs a p errors = _errors(watch.latest(uri)) assert clean, f"cross-group symbols still unresolved: {errors}" assert not any(marker in e for e in errors for marker in _FALSE_ERRORS) + await _assert_dependency_module_imported(server_log) finally: try: await asyncio.wait_for(client.shutdown_async(None), timeout=5.0) @@ -352,3 +379,4 @@ def on_publish(params: lsp.PublishDiagnosticsParams) -> None: # pygls needs a p await asyncio.wait_for(client.stop(), timeout=5.0) except Exception: pass + stderr_task.cancel() diff --git a/tests/test_reactor.py b/tests/test_reactor.py index 5412b10..064bc6e 100644 --- a/tests/test_reactor.py +++ b/tests/test_reactor.py @@ -107,13 +107,67 @@ def test_module_entry_may_name_a_pom_file(self, reactor: Path) -> None: '', ], ) - def test_doctype_or_entity_pom_is_rejected(self, reactor: Path, declaration: str) -> None: + def test_doctype_or_entity_pom_is_rejected( + self, reactor: Path, declaration: str, caplog: pytest.LogCaptureFixture + ) -> None: malicious = _pom("groupA", modules=("common",)).replace(" None: + # The byte regex cannot see "groupA", "&a;", 1 + ) + body = '\n]>\n' + text + data = bom + body.encode(codec) + pom = reactor / "groupA" / "pom.xml" + pom.write_bytes(data) + with caplog.at_level(logging.INFO, logger="java_functional_lsp.reactor"): + assert parse_pom(pom) is None + index = build_reactor_index(reactor) + assert index.get("com.example:common") is None + assert index.get("com.example:it") is not None + assert "DOCTYPE/ENTITY declarations are not allowed" in caplog.text + + def test_pom_in_an_encoding_expat_rejects_does_not_abort_the_index(self, reactor: Path) -> None: + text = '\n' + _pom("groupA", modules=("common",)) + (reactor / "groupA" / "pom.xml").write_bytes(b"\xfe\xff" + text.encode("utf-16-be")) + index = build_reactor_index(reactor) # expat raises ValueError for this declaration + assert index.get("com.example:common") is None + assert index.get("com.example:it") is not None + + def test_utf16_pom_without_declarations_still_parses(self, reactor: Path) -> None: + text = '\n' + _pom("groupA", modules=("common",)) + (reactor / "groupA" / "pom.xml").write_bytes(text.encode("utf-16")) + assert build_reactor_index(reactor).get("com.example:common") is not None + + @pytest.mark.parametrize("artifact", ["com\nmon", "com mon", "jdtls: importing"]) + def test_coordinates_outside_the_maven_charset_are_skipped( + self, reactor: Path, artifact: str, caplog: pytest.LogCaptureFixture + ) -> None: + # Declared by two directories, so it would be logged as ambiguous if it were kept. + _write(reactor, "groupA/common", _pom(artifact)) + _write(reactor, "groupB", _pom("groupB", modules=("it", "copy"))) + _write(reactor, "groupB/copy", _pom(artifact)) + with caplog.at_level(logging.INFO, logger="java_functional_lsp.reactor"): + index = build_reactor_index(reactor) + assert not [ga for ga in [*index.modules, *index.ambiguous] if "mon" in ga or "importing" in ga] + assert index.get("com.example:it") is not None + assert "ignoring" not in caplog.text def test_oversized_pom_is_rejected(self, reactor: Path) -> None: big = _pom("groupA", modules=("common",)).replace("", "")