Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(graph): link Spring routes to their handler methods (#3650)

Swati Ahujafec0f8219800
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/spring.py b/packages/core/src/repowise/core/ingestion/framework_edges/spring.py
index 797ee70b1..fb2f240d1 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/spring.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/spring.py
@@ -16,6 +16,9 @@ Expanded in Phase 4 of the JVM parity plan. The handler now covers:
- **Spring Data repositories** — any interface extending
``CrudRepository`` / ``JpaRepository`` / ``MongoRepository`` /
friends becomes an entry point (the impl is generated at runtime).
+- **Route handlers**: every ``@GetMapping`` / ``@RequestMapping`` method is
+ bound from its file's module symbol, the shape Express routes take, read
+ through the recogniser the HTTP contract dialect shares.
- **Autoconfig consumer edges** — emit edges from each
``META-INF/spring/...AutoConfiguration.imports`` file (and
``spring.factories``) to the listed FQNs so the resource file
@@ -29,6 +32,7 @@ import re
from pathlib import Path
from typing import TYPE_CHECKING, Any
+from ..framework_routes import spring_routes
from ..resolvers import ResolverContext
from ..type_names import strip_type_arguments
from .base import (
@@ -39,6 +43,7 @@ from .base import (
add_symbol_edge,
build_type_to_symbol,
read_text,
+ source_text,
)
if TYPE_CHECKING:
@@ -181,6 +186,33 @@ def _scan_lombok_ctor_params(text: str) -> list[tuple[str, int]]:
return params
+def _add_route_handler_edges(
+ graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext
+) -> int:
+ """Bind each mapped method from its file's module symbol.
+
+ The route is declared on the handler itself, so no call site names it;
+ the edge is what says the framework dispatches to it. Not gated on a
+ stereotype: an OpenAPI-generated ``*Api`` interface carries the mappings
+ its ``@RestController`` implementation serves.
+ """
+ count = 0
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ text = source_text(path, parsed, ctx.source_map or {})
+ methods = [s for s in parsed.symbols if s.kind in ("method", "function")]
+ for route in spring_routes(text):
+ line = text.count("\n", 0, route.offset) + 1
+ # A JVM method's span starts at its annotations, so the innermost
+ # method holding the annotation's line is the one it sits on.
+ holders = [s for s in methods if s.start_line <= line <= s.end_line]
+ if holders:
+ handler = max(holders, key=lambda s: s.start_line)
+ count += add_symbol_edge(graph, f"{path}::__module__", handler.id)
+ return count
+
+
def _bind_injected_symbol(
graph: nx.DiGraph, type_to_symbol: dict[str, str], owner: str | None, type_name: str
) -> int:
@@ -376,7 +408,9 @@ class _SpringHandler:
ctx: ResolverContext,
path_set: set[str],
) -> int:
- return _add_spring_edges(graph, parsed_files, path_set, ctx)
+ return _add_spring_edges(graph, parsed_files, path_set, ctx) + _add_route_handler_edges(
+ graph, parsed_files, ctx
+ )
class _JvmAutoconfigHandler:
diff --git a/packages/core/src/repowise/core/ingestion/framework_routes.py b/packages/core/src/repowise/core/ingestion/framework_routes.py
index 028e666d1..1d6198cac 100644
--- a/packages/core/src/repowise/core/ingestion/framework_routes.py
+++ b/packages/core/src/repowise/core/ingestion/framework_routes.py
@@ -267,10 +267,15 @@ def match_paren(
text: str, open_idx: int, *, quotes: str = "\"'`", hash_comments: bool = False
) -> int:
"""Index of the bracket closing the ``(``, ``[`` or ``{`` at *open_idx*, or -1."""
- opener = text[open_idx]
+ scan = scan_code(text, open_idx, quotes=quotes, hash_comments=hash_comments)
+ return _closing(text[open_idx], scan)
+
+
+def _closing(opener: str, scan: Iterable[tuple[int, str, int]]) -> int:
+ """Index of the bracket closing *opener*, the first character *scan* yields."""
closer = _CLOSERS.get(opener, ")")
nest = 0
- for i, c, _depth in scan_code(text, open_idx, quotes=quotes, hash_comments=hash_comments):
+ for i, c, _depth in scan:
if c == opener:
nest += 1
elif c == closer:
@@ -283,6 +288,21 @@ def match_paren(
_CLOSERS = {"(": ")", "[": "]", "{": "}"}
+def _jvm_code(text: str, start: int = 0) -> Iterator[tuple[int, str, int]]:
+ """:func:`scan_code` for Java and Kotlin.
+
+ ``'`` opens a char literal there, and one holding a quote (``'"'``) read
+ as a string start masks the rest of the file. Text blocks and Kotlin raw
+ strings are both ``\"\"\"``.
+ """
+ return scan_code(text, start, quotes="\"'", text_blocks=True)
+
+
+def _jvm_match_paren(text: str, open_idx: int) -> int:
+ """:func:`match_paren` over :func:`_jvm_code`."""
+ return _closing(text[open_idx], _jvm_code(text, open_idx))
+
+
# ---------------------------------------------------------------------------
# Go — gin / echo / chi routers and stdlib net/http
# ---------------------------------------------------------------------------
@@ -926,7 +946,7 @@ def _jaxrs_decl_end(content: str, start: int) -> int:
(``@Produces(MediaType.APPLICATION_JSON)``) and swagger nests them several
deep, so anything that stops at the first paren stops inside the run.
"""
- for i, c, depth in scan_code(content, start, quotes='"', text_blocks=True):
+ for i, c, depth in _jvm_code(content, start):
if depth == 0 and c in ";{":
return i
return len(content)
@@ -1262,7 +1282,7 @@ _MICRONAUT_PATH_KEY_RE = re.compile(r"\b(?:uri|uris|value)\s*=")
# line-anchored match reads as no declaration at all. Java's `record` and `enum`
# count: both carry controller annotations, and a spelling left out here is a
# controller the graph reads as an ordinary file.
-_MICRONAUT_TYPE_RE = re.compile(r"\b(?:class|interface|object|record|enum)\s+\w+")
+_JVM_TYPE_RE = re.compile(r"\b(?:class|interface|object|record|enum)\s+\w+")
# An RFC 6570 query or fragment expansion. Micronaut route templates carry
# their query parameters in the path string (`/list{?args*}`), where
@@ -1286,7 +1306,7 @@ def micronaut_annotations(content: str) -> set[int]:
The scan reads the whole file, so a consumer wanting more than one of the
three readers below computes this once and hands it to each of them.
"""
- return {i for i, c, _ in scan_code(content, quotes='"', text_blocks=True) if c == "@"}
+ return {i for i, c, _ in _jvm_code(content) if c == "@"}
def micronaut_path(raw: str) -> str:
@@ -1309,7 +1329,7 @@ def _micronaut_annotation_path(content: str, at: int) -> str | None:
m = _MICRONAUT_ARG_RE.match(content, at)
if m is not None:
return m.group("path")
- close = match_paren(content, opened.end() - 1, quotes='"')
+ close = _jvm_match_paren(content, opened.end() - 1)
args = content[opened.end() - 1 : len(content) if close == -1 else close]
if _MICRONAUT_PATH_KEY_RE.search(args) or not _MICRONAUT_NAMED_ARG_RE.match(args):
return None
@@ -1330,7 +1350,7 @@ def _micronaut_annotated_types(
if m.start() not in code:
continue
end = _jaxrs_decl_end(content, m.start())
- if not _MICRONAUT_TYPE_RE.search(content, m.end(), end):
+ if not _JVM_TYPE_RE.search(content, m.end(), end):
continue
yield m.start(), _micronaut_annotation_path(content, m.end())
@@ -1400,6 +1420,189 @@ def micronaut_routes(content: str, annotations: set[int] | None = None) -> Itera
)
+# ---------------------------------------------------------------------------
+# Spring MVC / WebFlux
+# ---------------------------------------------------------------------------
+
+# `@GetMapping("/{id}")` on a method names the verb and the sub-path. The
+# `@RequestMapping` spelling names neither: on a type it is the prefix, on a
+# method a route whose verbs sit in `method = ...`, every verb when absent.
+_SPRING_MAPPING_RE = re.compile(r"@(?P<verb>Get|Post|Put|Delete|Patch|Request)Mapping\b")
+_SPRING_CLASS_RE = re.compile(r"@RequestMapping\b")
+
+# A declarative HTTP client written with the controller's annotations: its
+# mappings are calls out, not endpoints served.
+_SPRING_CLIENT_RE = re.compile(r"@FeignClient\b")
+
+_SPRING_OPEN_RE = re.compile(r"\s*\(")
+_JVM_STRING_RE = re.compile(r'"(?:[^"\\\n]|\\.)*"')
+
+# Where an argument's value starts, matched with string bodies blanked so text
+# inside a literal is never a key. The path is positional, `value =` or `path =`.
+_SPRING_PATH_KEY_RE = re.compile(r"[(,]\s*(?:value|path)\s*=\s*")
+_SPRING_POSITIONAL_RE = re.compile(r"\(\s*(?![\w.]+\s*=)(?=[^\s)])")
+_SPRING_METHOD_KEY_RE = re.compile(r"[(,]\s*method\s*=\s*")
+
+# One literal, or an array of them: Java `{...}`, Kotlin `[...]` or `arrayOf(...)`.
+_SPRING_VALUE_RE = re.compile(r'"(?P<one>[^"]*)"|(?:arrayOf\s*)?(?P<open>[{\[(])')
+_SPRING_ARRAY_REST_RE = re.compile(r'"\s*"|[\s,]')
+_SPRING_VERB_WORD_RE = re.compile(r"\b(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|TRACE)\b")
+
+
+def _blank_strings(text: str) -> str:
+ """*text* with every string literal's body blanked, offsets kept."""
+ return _JVM_STRING_RE.sub(lambda m: '"' + " " * (len(m.group()) - 2) + '"', text)
+
+
+def _spring_args(content: str, at: int) -> str:
+ """The parenthesised argument list of the annotation named up to *at*, or ``""``."""
+ opened = _SPRING_OPEN_RE.match(content, at)
+ if opened is None:
+ return ""
+ close = _jvm_match_paren(content, opened.end() - 1)
+ return content[opened.end() - 1 : len(content) if close == -1 else close + 1]
+
+
+def _spring_paths(args: str) -> tuple[str, ...] | None:
+ """The paths a mapping's *args* declare.
+
+ ``("",)`` when they name none, which Spring serves at the type prefix.
+ ``None`` when they name one this cannot read: a constant or a concatenation
+ is a path, just not this file's to know.
+ """
+ masked = _blank_strings(args)
+ key = _SPRING_PATH_KEY_RE.search(masked) or _SPRING_POSITIONAL_RE.match(masked)
+ if key is None:
+ return ("",)
+ read = _spring_literals(args, masked, key.end())
+ if read is None or not masked[read[1] :].lstrip().startswith((",", ")")):
+ return None
+ return read[0] or ("",)
+
+
+def _spring_literals(args: str, masked: str, at: int) -> tuple[tuple[str, ...], int] | None:
+ """``(literals, end)`` of the value at *at*, or ``None`` when it is not literals alone."""
+ m = _SPRING_VALUE_RE.match(args, at)
+ if m is None:
+ return None
+ if m.group("one") is not None:
+ return (m.group("one"),), m.end()
+ close = _jvm_match_paren(masked, m.start("open"))
+ if close == -1 or _SPRING_ARRAY_REST_RE.sub("", masked[m.end() : close]):
+ return None
+ return tuple(s.group()[1:-1] for s in _JVM_STRING_RE.finditer(args, m.end(), close)), close + 1
+
+
+def _spring_verbs(verb: str, args: str) -> tuple[str, ...]:
+ """The verbs a mapping serves; ``ALL`` for a ``@RequestMapping`` naming none."""
+ if verb != "Request":
+ return (verb.upper(),)
+ masked = _blank_strings(args)
+ key = _SPRING_METHOD_KEY_RE.search(masked)
+ if key is None:
+ return ("ALL",)
+ if masked.startswith(("{", "["), key.end()):
+ value = masked[key.end() : _jvm_match_paren(masked, key.end()) + 1]
+ else:
+ value = re.split(r"[,)]", masked[key.end() :], maxsplit=1)[0]
+ return tuple(dict.fromkeys(_SPRING_VERB_WORD_RE.findall(value))) or ("ALL",)
+
+
+def _spring_type_bodies(
+ content: str, annotations: set[int], pattern: re.Pattern[str]
+) -> Iterator[tuple[int, int, int]]:
+ """``(annotation name end, body start, body end)`` per type annotated *pattern*.
+
+ The declaration scan is JAX-RS's. The body span, not the nearest type
+ above, is what a member sits under: a class with no mapping of its own
+ must not inherit the prefix of the class declared before it.
+ """
+ for m in pattern.finditer(content):
+ if m.start() not in annotations:
+ continue
+ start = _jaxrs_decl_end(content, m.start())
+ if not _JVM_TYPE_RE.search(content, m.end(), start):
+ continue
+ close = (
+ _jvm_match_paren(content, start)
+ if content.startswith("{", start)
+ else -1
+ )
+ yield m.end(), start, len(content) if close == -1 else close
+
+
+def spring_class_paths(
+ content: str, annotations: set[int] | None = None
+) -> list[tuple[int, int, tuple[str, ...] | None]]:
+ """``(body start, body end, prefixes)`` per type-level ``@RequestMapping``, ascending.
+
+ ``prefixes`` is ``None`` when the mapping names a path this cannot read; the
+ routes under it are refused rather than served at their bare sub-path.
+ """
+ if "@RequestMapping" not in content:
+ return []
+ code = micronaut_annotations(content) if annotations is None else annotations
+ out: list[tuple[int, int, tuple[str, ...] | None]] = []
+ for name_end, start, end in _spring_type_bodies(content, code, _SPRING_CLASS_RE):
+ paths = _spring_paths(_spring_args(content, name_end))
+ out.append((start, end, None if paths is None else tuple(p.rstrip("/") for p in paths)))
+ return out
+
+
+def spring_route_prefixes(
+ class_paths: list[tuple[int, int, tuple[str, ...] | None]], offset: int
+) -> tuple[str, ...] | None:
+ """The prefixes of the innermost mapped type around *offset*; ``("",)`` under none."""
+ found: tuple[str, ...] | None = ("",)
+ for start, end, prefixes in class_paths:
+ if start < offset < end:
+ found = prefixes # ascending, so a later container is a nested one
+ return found
+
+
+def _spring_method_mappings(content: str, annotations: set[int]) -> Iterator[re.Match[str]]:
+ """Mapping annotations written as code on a method outside any Feign client."""
+ clients = (
+ [(s, e) for _, s, e in _spring_type_bodies(content, annotations, _SPRING_CLIENT_RE)]
+ if "@FeignClient" in content
+ else []
+ )
+ for m in _SPRING_MAPPING_RE.finditer(content):
+ if m.start() not in annotations or any(s < m.start() < e for s, e in clients):
+ continue
+ # A type's own mapping is its prefix, read by spring_class_paths.
+ if not _JVM_TYPE_RE.search(content, m.end(), _jaxrs_decl_end(content, m.start())):
+ yield m
+
+
+def spring_routes(content: str, annotations: set[int] | None = None) -> Iterator[RouteMatch]:
+ """Method-level mappings in *content*, one per verb and path.
+
+ ``path`` is the method's own sub-path, ``""`` when it names none and
+ ``None`` when it names one this cannot read; the type prefix is the
+ consumer's to stitch, from :func:`spring_class_paths`. The handler is the
+ method the annotation sits on, which every Spring route has, so ``offset``
+ is all a consumer needs to find it. Mappings inside a ``@FeignClient`` type
+ are calls out and are skipped.
+ """
+ if "Mapping" not in content:
+ return
+ code = micronaut_annotations(content) if annotations is None else annotations
+ for m in _spring_method_mappings(content, code):
+ args = _spring_args(content, m.end())
+ paths: tuple[str | None, ...] = _spring_paths(args) or (None,)
+ for verb in _spring_verbs(m.group("verb"), args):
+ for path in paths:
+ yield RouteMatch(
+ verb=verb,
+ path=path,
+ receiver=None,
+ handler=None,
+ offset=m.start(),
+ paren_offset=m.start(),
+ )
+
+
# ---------------------------------------------------------------------------
# Remix
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/spring.py b/packages/core/src/repowise/core/workspace/extractors/http/spring.py
index 87e16c11c..88e1b8216 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/spring.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/spring.py
@@ -1,62 +1,58 @@
-"""Spring (Java) HTTP provider dialect.
+"""Spring (Java / Kotlin) HTTP provider dialect.
-Handles method-level ``@GetMapping("/users")`` annotations and stitches on the
-nearest preceding class-level ``@RequestMapping("/api/v1")`` prefix.
+``@GetMapping("/users")`` names the verb and sub-path; the ``@RequestMapping``
+on the type around it is the prefix. The annotations are recognised by
+``ingestion.framework_routes``, shared with the graph-edge builder that links
+each route to its handler method.
"""
from __future__ import annotations
-import re
from typing import TYPE_CHECKING
+from repowise.core.ingestion.framework_routes import (
+ HTTP_METHODS,
+ micronaut_annotations,
+ spring_class_paths,
+ spring_route_prefixes,
+ spring_routes,
+)
+
from ..base import line_at
-from ..langs import JAVA
-from .dialect import build_provider_contract, nearest_prefix
+from ..langs import JAVA, KOTLIN
+from .dialect import build_provider_contract
+from .mounts import compose_prefix
if TYPE_CHECKING:
from repowise.core.workspace.contracts import Contract
from ..base import ScanContext
-# @GetMapping("/path"), @PostMapping(value="/path"), etc.
-_SPRING_METHOD_RE = re.compile(
- r"""@(Get|Post|Put|Delete|Patch)Mapping\s*\(\s*(?:value\s*=\s*)?['"]([^'"]+)['"]""",
- re.IGNORECASE,
-)
-
-# Class-level prefix: @RequestMapping("/api/v1")
-_SPRING_CLASS_RE = re.compile(
- r"""@RequestMapping\s*\(\s*(?:value\s*=\s*)?['"]([^'"]+)['"]""",
-)
-
class SpringDialect:
name = "spring"
- extensions = JAVA
+ extensions = JAVA | KOTLIN
def extract(self, ctx: ScanContext) -> list[Contract]:
content = ctx.content
- # Collect every class-level @RequestMapping so each method annotation
- # gets the prefix from its nearest preceding class declaration rather
- # than always the first one in the file.
- class_mappings: list[tuple[int, str]] = [
- (cm.start(), cm.group(1).rstrip("/")) for cm in _SPRING_CLASS_RE.finditer(content)
- ]
-
+ if "Mapping" not in content:
+ return []
+ annotations = micronaut_annotations(content)
+ class_paths = spring_class_paths(content, annotations)
out: list[Contract] = []
- for m in _SPRING_METHOD_RE.finditer(content):
- method = m.group(1).upper()
- path_raw = m.group(2)
- prefix = nearest_prefix(class_mappings, m.start())
- if prefix:
- path_raw = prefix + "/" + path_raw.lstrip("/")
- c = build_provider_contract(
- ctx,
- method=method,
- path_raw=path_raw,
- framework="spring",
- line=line_at(content, m.start()),
- )
- if c is not None:
- out.append(c)
+ for route in spring_routes(content, annotations):
+ # An unrestricted `@RequestMapping` serves every verb, which the
+ # contract layer has no method for; an unreadable path is refused.
+ if route.verb not in HTTP_METHODS or route.path is None:
+ continue
+ for prefix in spring_route_prefixes(class_paths, route.offset) or ():
+ c = build_provider_contract(
+ ctx,
+ method=route.verb,
+ path_raw=compose_prefix(prefix, route.path),
+ framework="spring",
+ line=line_at(content, route.offset),
+ )
+ if c is not None:
+ out.append(c)
return out
diff --git a/tests/unit/ingestion/test_spring_framework_edges.py b/tests/unit/ingestion/test_spring_framework_edges.py
index 6418efecf..58207acdb 100644
--- a/tests/unit/ingestion/test_spring_framework_edges.py
+++ b/tests/unit/ingestion/test_spring_framework_edges.py
@@ -262,3 +262,68 @@ class TestSpringSymbolEdges:
bound = _bound(_build_graph(tmp_path))
assert ("UserResource.java::UserResource", "MailService.java::MailService") in bound
assert ("UserResource.java::UserResource", "User.java::User") not in bound
+
+
+class TestSpringRouteHandlers:
+ def test_each_mapped_method_is_bound_from_its_module(self, tmp_path: Path) -> None:
+ (tmp_path / "OwnerController.java").write_text(
+ "import org.springframework.web.bind.annotation.*;\n"
+ "@RestController\n"
+ '@RequestMapping("/owners")\n'
+ "public class OwnerController {\n"
+ " @GetMapping\n"
+ " public String list() { return \"\"; }\n"
+ ' @PostMapping(value = {"/new", "/create"})\n'
+ ' @PreAuthorize("hasRole(\'ADMIN\')")\n'
+ " public String create(@RequestBody String body) { return body; }\n"
+ ' @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)\n'
+ " public void delete() {}\n"
+ " private void helper() {}\n"
+ "}\n"
+ )
+
+ bound = _bound(_build_graph(tmp_path))
+ module = "OwnerController.java::__module__"
+ handlers = {t.rsplit("::", 1)[-1] for s, t in bound if s == module}
+ assert handlers == {"list", "create", "delete"}
+
+ def test_a_kotlin_handler_and_a_commented_mapping(self, tmp_path: Path) -> None:
+ (tmp_path / "PetController.kt").write_text(
+ "import org.springframework.web.bind.annotation.*\n"
+ "@RestController\n"
+ "class PetController {\n"
+ ' // @GetMapping("/old")\n'
+ " fun old(): String = \"\"\n"
+ ' @GetMapping(value = ["/pets"])\n'
+ " fun pets(): String = \"\"\n"
+ "}\n"
+ )
+
+ bound = _bound(_build_graph(tmp_path))
+ assert bound == {("PetController.kt::__module__", "PetController.kt::PetController::pets")}
+
+ def test_a_one_line_kotlin_expression_body(self, tmp_path: Path) -> None:
+ (tmp_path / "Ping.kt").write_text(
+ "import org.springframework.web.bind.annotation.*\n"
+ "@RestController\n"
+ "class Ping {\n"
+ ' @GetMapping("/ping") fun ping() = "pong"\n'
+ ' @GetMapping("/pong")\n'
+ ' fun pong() = "ping"\n'
+ "}\n"
+ )
+
+ bound = _bound(_build_graph(tmp_path))
+ assert bound == {
+ ("Ping.kt::__module__", "Ping.kt::Ping::ping"),
+ ("Ping.kt::__module__", "Ping.kt::Ping::pong"),
+ }
+
+ def test_a_feign_client_serves_nothing(self, tmp_path: Path) -> None:
+ (tmp_path / "Owners.java").write_text(
+ "import org.springframework.web.bind.annotation.GetMapping;\n"
+ '@FeignClient("owners")\n'
+ 'public interface Owners { @GetMapping("/owners") String all(); }\n'
+ )
+
+ assert not _bound(_build_graph(tmp_path))
diff --git a/tests/unit/workspace/test_framework_routes.py b/tests/unit/workspace/test_framework_routes.py
index 237b50a31..5f0a87dff 100644
--- a/tests/unit/workspace/test_framework_routes.py
+++ b/tests/unit/workspace/test_framework_routes.py
@@ -796,3 +796,119 @@ class TestQualifiedHandlerBinding:
# discriminates rather than merely finding something.
assert "app" in builder
assert bound["http::GET::/ping"] == expected["ping"]
+
+
+# ---------------------------------------------------------------------------
+# Spring
+# ---------------------------------------------------------------------------
+
+SPRING_CONTROLLER = """\
+/** @GetMapping("/doc") is documentation. */
+@RestController
+@RequestMapping({"/api", "/v2/"})
+public class OwnerController {
+ @GetMapping
+ public String root() { return "{"; }
+ @PostMapping(value = "/b", produces = "text/plain")
+ public String b() { char c = '}'; return ""; }
+ @RequestMapping(path = {"/c", "/d"}, method = {RequestMethod.GET, RequestMethod.PUT})
+ public String c() { return ""; }
+ @RequestMapping("/any")
+ public String any() { return ""; }
+ @DeleteMapping(PATH)
+ public void del() {}
+}
+
+class Plain {
+ @GetMapping("/plain")
+ public void plain() {}
+}
+"""
+
+
+def test_spring_routes_read_every_argument_shape() -> None:
+ from repowise.core.ingestion.framework_routes import (
+ spring_class_paths,
+ spring_route_prefixes,
+ spring_routes,
+ )
+
+ class_paths = spring_class_paths(SPRING_CONTROLLER)
+ got = [
+ (r.verb, r.path, spring_route_prefixes(class_paths, r.offset))
+ for r in spring_routes(SPRING_CONTROLLER)
+ ]
+ prefixes = ("/api", "/v2")
+ assert got == [
+ ("GET", "", prefixes),
+ ("POST", "/b", prefixes),
+ ("GET", "/c", prefixes),
+ ("GET", "/d", prefixes),
+ ("PUT", "/c", prefixes),
+ ("PUT", "/d", prefixes),
+ ("ALL", "/any", prefixes),
+ ("DELETE", None, prefixes),
+ # A class after the mapped one does not inherit its prefix.
+ ("GET", "/plain", ("",)),
+ ]
+
+
+def test_spring_contracts_compose_each_prefix_and_skip_what_they_cannot_read(
+ tmp_path: Path,
+) -> None:
+ (tmp_path / "OwnerController.java").write_text(SPRING_CONTROLLER)
+ (tmp_path / "PetController.kt").write_text(
+ '@RestController\n@RequestMapping("/pets")\nclass PetController {\n'
+ ' @GetMapping(path = ["/{id}"])\n fun one(): String = ""\n}\n'
+ )
+ # A root route, bare or spelled "/", is dropped as JAX-RS and Micronaut roots
+ # are: build_provider_contract refuses a path that normalizes to "/".
+ (tmp_path / "Welcome.java").write_text(
+ "@RestController\npublic class Welcome {\n"
+ " @GetMapping\n public String a() { return null; }\n"
+ ' @GetMapping("/")\n public String b() { return null; }\n}\n'
+ )
+ ids = {
+ c.contract_id
+ for c in HttpExtractor().extract(tmp_path, "backend")
+ if c.role == "provider"
+ }
+ assert ids == {
+ "http::GET::/api",
+ "http::GET::/v2",
+ "http::POST::/api/b",
+ "http::POST::/v2/b",
+ "http::GET::/api/c",
+ "http::GET::/v2/c",
+ "http::GET::/api/d",
+ "http::GET::/v2/d",
+ "http::PUT::/api/c",
+ "http::PUT::/v2/c",
+ "http::PUT::/api/d",
+ "http::PUT::/v2/d",
+ "http::GET::/plain",
+ "http::GET::/pets/{param}",
+ }
+
+
+def test_spring_routes_survive_char_literals_and_raw_strings() -> None:
+ from repowise.core.ingestion.framework_routes import spring_routes
+
+ def paths(src: str) -> list[str | None]:
+ return [r.path for r in spring_routes(src)]
+
+ # A char literal holding a quote read as a string start masks the rest.
+ assert paths("""class A { char c='"'; @GetMapping("/real") void a(){} }""") == ["/real"]
+ assert paths(
+ """class A { @GetMapping("/real") void a(){ char c='"'; } """
+ """@GetMapping("/two") void b(){} }"""
+ ) == ["/real", "/two"]
+ assert paths(
+ r"""class A { char q='\''; char b='\\'; @GetMapping("/esc") void a(){} }"""
+ ) == ["/esc"]
+ # A mapping quoted in a Java text block or a Kotlin raw string is no route.
+ block = '"' * 3
+ java = 'class A { String s = BLOCK\n @GetMapping("/no") "x" BLOCK; @GetMapping("/yes") void a(){} }'
+ kotlin = 'class A { val s = BLOCK@GetMapping("/no")BLOCK\n @GetMapping("/yes") fun a() = 1 }'
+ assert paths(java.replace("BLOCK", block)) == ["/yes"]
+ assert paths(kotlin.replace("BLOCK", block)) == ["/yes"]