Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(workspace): read chi, fiber and gorilla/mux routes and Go 1.22 method patterns (#4539)
Raghav Chamadiya718eeefb6003
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 8df73eea6..92fb59ebc 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -203,7 +203,7 @@ reported as unreachable.| Ruby | Rails (routes to controller actions, Zeitwerk), RSpec mirror edges || Java / Kotlin | Spring, Jakarta / JPA, Quarkus, Micronaut, Android manifest || C# | ASP.NET (attribute and minimal API), EF Core, gRPC-dotnet, host-builder extensions, CommunityToolkit MVVM |-| Go | net/http, gin, echo, chi, gRPC server registration |+| Go | net/http, gin, echo, chi, fiber, gorilla/mux, gRPC server registration || Rust | Axum, Actix || JS / TS / Svelte | Next.js App Router, Hono / Fastify / Koa / Elysia, Remix / SvelteKit / Astro, tRPC, Express / NestJS, Angular || C++ | GoogleTest, Catch2, Boost.Test, doctest, Google Benchmark, libFuzzer |diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex bb7d3024d..46d2b91f2 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -142,7 +142,7 @@ Scans source files for HTTP routes, gRPC services, database tables, message topi| Python | FastAPI, Flask, Django | requests, httpx (aiohttp through wrappers the index confirms); Locust user `client` calls || PHP | Laravel | Guzzle, Laravel `Http` || Java / Kotlin | Spring, JAX-RS, Micronaut | Feign (`@RequestLine`, and `@FeignClient` with Spring MVC annotations, its `name` read as the host), Spring `@HttpExchange` interfaces, Spring `WebClient` and `RestClient`, `RestTemplate` (also through a getter or a `RequestEntity`), `java.net.http`, Apache HttpClient (`new HttpPost(url)`, with a base URL passed to a helper's constructor in another file), MicroProfile `@RegisterRestClient` interfaces, Ktor (Kotlin) |-| Go | gin, echo, chi, net/http | net/http |+| Go | gin, echo, chi, fiber, gorilla/mux, net/http (Go 1.22 method patterns) | net/http || C# | ASP.NET (attribute and minimal API) | HttpClient (`GetAsync`, `GetFromJsonAsync`, `PostAsJsonAsync`, `GetStringAsync`, `new HttpRequestMessage(HttpMethod.X, url)`; a URL held in a local or a `const` / `readonly` field), UnityWebRequest, Best.HTTP || Ruby | | HTTParty, RestClient, Faraday, Net::HTTP || Rust | Axum, Actix, Rocket | reqwest |diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/go.py b/packages/core/src/repowise/core/ingestion/framework_edges/go.pyindex 6d2b5c911..f514c87e7 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/go.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/go.py@@ -2,7 +2,8 @@Covers the route/handler wiring that carries no import edge:-* **Router frameworks** — Gin / Echo / Chi ``r.GET("/path", handler)``.+* **Router frameworks** — Gin / Echo ``r.GET("/path", handler)``, chi / fiber+ ``r.Get("/path", handler)``, gorilla/mux ``r.Path("/x").Handler(h)`` chains.* **stdlib ``net/http``** — ``http.HandleFunc("/path", handler)`` and``mux.Handle("/path", handler)`` (same ``.HandleFunc`` / ``.Handle``selector shape as the router frameworks, so one regex serves both —@@ -19,9 +20,12 @@ Go-parity work (Phase 4).from __future__ import annotationsimport re+from itertools import chainfrom typing import TYPE_CHECKING, Anyfrom ..framework_routes import go_routes+from ..framework_routes_chi import title_case_routes+from ..framework_routes_gorilla import gorilla_routesfrom ..resolvers import ResolverContextfrom .base import (DetectionContext,@@ -40,6 +44,8 @@ _GO_ROUTER_PKG_PATTERNS = ("github.com/gin-gonic/gin","github.com/labstack/echo","github.com/go-chi/chi",+ "github.com/gofiber/fiber",+ "github.com/gorilla/mux",)# stdlib net/http is gated separately: its handler-registration calls share# the ``.HandleFunc`` / ``.Handle`` selector shape with the router frameworks.@@ -92,7 +98,7 @@ def _add_go_route_edges(if not text:continue- for route in go_routes(text):+ for route in chain(go_routes(text), title_case_routes(text), gorilla_routes(text)):if not route.handler:continue # an inline `func(c *gin.Context)` names nothing to link totargets = _resolve_go_handler(@@ -170,7 +176,7 @@ def _resolve_go_handler(class _GoWebHandler:def detect(self, dctx: DetectionContext) -> bool:go_web_in_stack = any(- token in dctx.stack_lower for token in ("gin", "echo", "chi", "grpc")+ token in dctx.stack_lower for token in ("gin", "echo", "chi", "fiber", "gorilla", "grpc"))return go_web_in_stack or _has_go_web_imports(dctx.parsed_files)diff --git a/packages/core/src/repowise/core/ingestion/framework_routes.py b/packages/core/src/repowise/core/ingestion/framework_routes.pyindex ce347330e..d9d072d24 100644--- a/packages/core/src/repowise/core/ingestion/framework_routes.py+++ b/packages/core/src/repowise/core/ingestion/framework_routes.py@@ -304,22 +304,44 @@ def _jvm_match_paren(text: str, open_idx: int) -> int:# ----------------------------------------------------------------------------# Go — gin / echo / chi routers and stdlib net/http+# Go — gin / echo routers and stdlib net/http. chi and fiber's title-case verbs+# are in `framework_routes_chi`, gorilla/mux route chains in+# `framework_routes_gorilla`; both build on the pieces here.# ---------------------------------------------------------------------------# `HandleFunc` precedes `Handle` so the longer name wins the alternation._GO_VERBS = "GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD|Any|HandleFunc|Handle"-# r.GET("/users", GetUsers). The receiver may be empty on an inline chain. The-# handler may be wrapped (`api.RequireSession(h)`) or a composite literal-# (`healthHandler{}`). The two keywords that can open one are excluded: they name-# no symbol, and `r.GET("/x", func(c *gin.Context) {...})` otherwise yields the-# handler `func`.-_GO_ROUTE_RE = re.compile(- rf"(?P<receiver>\w*)\s*\.\s*(?P<verb>{_GO_VERBS})\s*(?P<paren>\()"- r"""\s*(?P<q>["'])(?P<path>[^"']*)(?P=q)"""- r"(?:\s*,\s*(?P<handler>(?!(?:func|struct)\b)[A-Za-z_][\w.]*)\s*(?P<after>[,)({]))?"-)+# Registration selectors that carry no verb of their own.+GO_VERBLESS = frozenset({"HANDLE", "HANDLEFUNC"})++#: A string-literal path argument, its body captured as ``path``. A literal+#: something is appended to (`"/api" + v`) is only the path's head, not a path.+GO_PATH_LITERAL = r"""(?P<q>["'`])(?P<path>[^"'`]*)(?P=q)(?!\s*\+)"""++# `base + "/x"`: a path stitched onto a name. `path` stays None and a consumer+# resolves the argument from `paren_offset` against the file's constants. A+# handler argument must follow, so a one-argument `log.Handle(p + "/x")` is not+# a route.+_GO_PATH_CONCAT = r"""[A-Za-z_][\w.]*\s*\+\s*["`][^"`]*["`](?=\s*,)"""+++def go_route_pattern(verbs: str, path: str) -> re.Pattern[str]:+ """``recv.Verb(path, handler)`` for the *verbs* alternation and *path* fragment.++ The receiver may be empty on an inline chain. The handler may be wrapped+ (``api.RequireSession(h)``) or a composite literal (``healthHandler{}``). The+ two keywords that can open one are excluded: they name no symbol, and+ ``r.GET("/x", func(c *gin.Context) {...})`` otherwise yields the handler+ ``func``.+ """+ return re.compile(+ rf"(?<!\w)(?P<receiver>\w*)\s*\.\s*(?P<verb>{verbs})\s*(?P<paren>\()\s*(?:{path})"+ r"(?:\s*,\s*(?P<handler>(?!(?:func|struct)\b)[A-Za-z_][\w.]*)\s*(?P<after>[,)({]))?"+ )+++_GO_ROUTE_RE = go_route_pattern(_GO_VERBS, f"{GO_PATH_LITERAL}|{_GO_PATH_CONCAT}")# api := r.Group("/v1") — groups nest, so the parent is captured for transitive# composition by `mounts.group_prefixes`.@@ -327,19 +349,90 @@ _GO_GROUP_RE = re.compile(r"""(?P<var>\w+)\s*:?=\s*(?P<parent>\w+)\s*\.\s*Group\s*\(\s*["'](?P<prefix>[^"']+)["']""")+# Go 1.22 net/http patterns: `"GET /items/{id}"`, `"POST api.example.com/x"`.+_GO_METHOD_PATTERN_RE = re.compile(+ r"(?P<method>GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|CONNECT|TRACE)\s+[^/\s]*(?P<path>/\S*)"+)+# `{name...}` matches the rest of the path; `{$}` only anchors the end.+_GO_WILDCARD_RE = re.compile(r"\{(\w+)\.\.\.\}")++# `.Methods(http.MethodGet, "POST")`, gorilla/mux's verb restriction on a route.+_GO_METHODS_CHAIN_RE = re.compile(r"\s*\.\s*Methods\s*\(")+_GO_METHOD_ARG_RE = re.compile(r"""^(?:http\.Method(?P<const>\w+)|["'`](?P<lit>\w+)["'`])$""")+++def go_match_paren(content: str, open_idx: int) -> int:+ """:func:`match_paren` for Go, where ``'`` opens a rune and `` ` `` a raw string."""+ return match_paren(content, open_idx, quotes="\"'`")+++def go_methods(content: str, open_paren: int) -> tuple[str, ...] | None:+ """The upper-cased verbs a ``Methods(`` call at *open_paren* names.++ ``None`` when an argument is not a verb literal or ``http.Method*``+ constant: the restriction exists but this cannot read it.+ """+ close = go_match_paren(content, open_paren)+ if close < 0:+ return None+ out: list[str] = []+ for arg in content[open_paren + 1 : close].split(","):+ m = _GO_METHOD_ARG_RE.match(arg.strip())+ if m is None:+ return None+ out.append((m.group("const") or m.group("lit")).upper())+ return tuple(out) or None+++def _trailing_methods(content: str, paren: int) -> tuple[str, ...] | None:+ """The verbs of a ``.Methods(...)`` chained onto the call opened at *paren*."""+ close = go_match_paren(content, paren)+ if close < 0:+ return None+ m = _GO_METHODS_CHAIN_RE.match(content, close + 1)+ return go_methods(content, m.end() - 1) if m else None+++def _go_pattern(verb: str, path: str) -> tuple[str, str]:+ """``(verb, path)`` for a verbless registration's path, reading a Go 1.22 pattern."""+ m = _GO_METHOD_PATTERN_RE.fullmatch(path)+ if m is not None:+ verb, path = m.group("method"), m.group("path")+ return verb, _GO_WILDCARD_RE.sub(r"{\1}", path).replace("{$}", "")+++def go_route_matches(pattern: re.Pattern[str], content: str) -> Iterator[RouteMatch]:+ """The :class:`RouteMatch` rows of a :func:`go_route_pattern` over *content*.++ A verbless registration (``HandleFunc``) reads a Go 1.22 method pattern+ from its path, and a gorilla/mux ``.Methods(...)`` chained after it, one+ row per verb.+ """+ chained = "Methods(" in content+ for m in pattern.finditer(content):+ verb, path = m.group("verb").upper(), m.group("path")+ verbs: tuple[str, ...] = (verb,)+ if verb in GO_VERBLESS:+ if path is not None:+ verb, path = _go_pattern(verb, path)+ verbs = (verb,)+ if verb in GO_VERBLESS and chained:+ verbs = _trailing_methods(content, m.start("paren")) or verbs+ for one in verbs:+ yield RouteMatch(+ verb=one,+ path=path,+ receiver=_opt(m.group("receiver")),+ handler=m.group("handler"),+ offset=m.start(),+ paren_offset=m.start("paren"),+ handler_call=m.group("after") == "(",+ )+def go_routes(content: str) -> Iterator[RouteMatch]:"""Router and ``net/http`` handler registrations in *content*."""- for m in _GO_ROUTE_RE.finditer(content):- yield RouteMatch(- verb=m.group("verb").upper(),- path=m.group("path"),- receiver=_opt(m.group("receiver")),- handler=m.group("handler"),- offset=m.start(),- paren_offset=m.start("paren"),- handler_call=m.group("after") == "(",- )+ return go_route_matches(_GO_ROUTE_RE, content)def go_groups(content: str) -> Iterator[GroupMatch]:diff --git a/packages/core/src/repowise/core/ingestion/framework_routes_chi.py b/packages/core/src/repowise/core/ingestion/framework_routes_chi.pynew file mode 100644index 000000000..1b0ad8ea1--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_routes_chi.py@@ -0,0 +1,187 @@+"""chi and fiber routes: title-case verbs and ``Route`` closures.++Both routers spell a verb ``r.Get("/x", h)``, which is also how a Go cache, a+config map or an HTTP client is called. So a call counts only in a file that+imports the router, on a receiver bound to one at that point of the file+(``chi.NewRouter()``, ``fiber.New()``, a router's ``Group``, a parameter or+field typed ``chi.Router``), with a path that starts with ``/``. Not read: a+router reached through a field typed in another file, a chain such as+``r.With(mw).Get(...)``, and a ``Mount`` prefix, so a sub-router mounted+elsewhere records its routes without the mount's prefix.++``r.Route("/api", func(r chi.Router) {...})`` serves the closure's routes under+``/api``; :func:`route_scopes` returns those blocks for the contract consumer to+stitch. Each framework is one row of :data:`_ROUTERS`.+"""++from __future__ import annotations++import heapq+import re+from collections.abc import Iterator+from dataclasses import dataclass++from .framework_routes import RouteMatch, go_match_paren, go_route_matches, go_route_pattern++# (import path, package name, router constructors, router types)+_ROUTERS: tuple[tuple[str, str, str, str], ...] = (+ ("github.com/go-chi/chi", "chi", "NewRouter|NewMux", "Router|Mux"),+ ("github.com/gofiber/fiber", "fiber", "New", "Router|App"),+)++_TITLE_VERBS = "Get|Post|Put|Delete|Patch|Head|Options|Connect|Trace|All"+_TITLE_ROUTE_RE = go_route_pattern(+ _TITLE_VERBS, r"""(?P<q>["`])(?P<path>/[^"`]*)(?P=q)(?!\s*\+)"""+)++# What a name is bound to, in file order: `r := chi.NewRouter()` assigns it,+# `func(r chi.Router)` or a struct field `mux *chi.Mux` declares its type.+_ASSIGN_RE = re.compile(r"(?<![\w.])(?P<var>\w+)\s*:?=(?!=)\s*(?P<rhs>[^\n]{0,120})")+_TYPED_RE = re.compile(r"(?<![\w.])(?P<var>\w+)\s+(?P<type>\*?[A-Za-z_][\w.]*)\s*(?=[,)\n;])")+_GROUP_CALL_RE = re.compile(r"(?P<parent>\w+)\s*\.\s*(?:Group|Route)\s*\(")+++def _router_res(pkg: str, ctors: str, types: str) -> tuple[re.Pattern[str], re.Pattern[str]]:+ return (+ re.compile(rf"{pkg}\s*\.\s*(?:{ctors})\s*\("),+ re.compile(rf"\*?{pkg}\s*\.\s*(?:{types})"),+ )+++_ROUTER_RES = tuple((path, *_router_res(pkg, c, t)) for path, pkg, c, t in _ROUTERS)+++# A function's parameter list: `func name(`, `func (s *S) name(`, `func(`.+_FUNC_PARAMS_RE = re.compile(r"\bfunc\s*(?:\([^()]*\)\s*)?\w*\s*\(")+++def _param_scopes(content: str) -> list[tuple[int, int, int]]:+ """``(params_start, params_end, body_end)`` of every function, so a parameter's+ binding ends with its body: a handler literal's ``r *http.Request`` does not+ rebind the router ``r`` it is registered on."""+ out: list[tuple[int, int, int]] = []+ for m in _FUNC_PARAMS_RE.finditer(content):+ close = go_match_paren(content, m.end() - 1)+ brace = content.find("{", close) if close > 0 else -1+ end = go_match_paren(content, brace) if brace > 0 else -1+ if end > 0:+ out.append((m.end(), close, end))+ return out+++def _bindings(content: str) -> list[tuple[int, str, re.Match[str], bool, int | None]]:+ """``(offset, name, match, typed, scope_end)`` for every binding, in file order.++ *scope_end* is where a parameter's binding stops holding; ``None`` for an+ assignment or a struct field.+ """+ scopes = _param_scopes(content)+ found: list[tuple[int, str, re.Match[str], bool, int | None]] = [+ (m.start(), m.group("var"), m, False, None) for m in _ASSIGN_RE.finditer(content)+ ]+ for m in _TYPED_RE.finditer(content):+ at = m.start()+ end = next((e for s, c, e in scopes if s <= at < c), None)+ found.append((at, m.group("var"), m, True, end))+ return sorted(found, key=lambda b: b[0])+++def _is_router(+ match: re.Match[str],+ typed: bool,+ imported: list[tuple[re.Pattern[str], re.Pattern[str]]],+ routers: dict[str, bool],+) -> bool:+ if typed:+ return any(t.fullmatch(match.group("type")) for _ctor, t in imported)+ rhs = match.group("rhs")+ if any(ctor.match(rhs) for ctor, _t in imported):+ return True+ group = _GROUP_CALL_RE.match(rhs)+ return group is not None and routers.get(group.group("parent"), False)+++def _imported(content: str) -> list[tuple[re.Pattern[str], re.Pattern[str]]]:+ return [(ctor, typed) for path, ctor, typed in _ROUTER_RES if f'"{path}' in content]+++class _RouterNames:+ """Which names hold a router, replayed through the file's bindings in order."""++ def __init__(self, content: str, imported: list[tuple[re.Pattern[str], re.Pattern[str]]]):+ self._bindings = _bindings(content)+ self._imported = imported+ self._next = 0+ self._routers: dict[str, bool] = {}+ # A parameter's binding is undone at its body's end: (end, seq, name, prior).+ self._restores: list[tuple[int, int, str, bool]] = []++ def _step(self, offset: int) -> bool:+ """Apply the next restore or binding before *offset*; False when none is left."""+ nxt = self._bindings[self._next][0] if self._next < len(self._bindings) else offset+ if self._restores and self._restores[0][0] < min(nxt, offset):+ _end, _seq, name, prior = heapq.heappop(self._restores)+ self._routers[name] = prior+ return True+ if nxt >= offset:+ return False+ _at, name, m, typed, scope_end = self._bindings[self._next]+ if scope_end is not None:+ prior = self._routers.get(name, False)+ heapq.heappush(self._restores, (scope_end, self._next, name, prior))+ self._routers[name] = _is_router(m, typed, self._imported, self._routers)+ self._next += 1+ return True++ def is_router(self, name: str | None, offset: int) -> bool:+ """Whether *name* holds a router at *offset*; offsets must not decrease."""+ while self._step(offset):+ pass+ return self._routers.get(name or "", False)+++def title_case_routes(content: str) -> Iterator[RouteMatch]:+ """chi / fiber ``router.Get("/path", handler)`` registrations in *content*.++ The receiver's binding is the nearest one before the call, so a name a+ later function rebinds (``func b(r *Client)``) is not read as the router+ an earlier one built.+ """+ imported = _imported(content)+ if not imported:+ return+ names = _RouterNames(content, imported)+ for route in go_route_matches(_TITLE_ROUTE_RE, content):+ if names.is_router(route.receiver, route.offset):+ yield route+++_ROUTE_SCOPE_RE = re.compile(+ r"""(?<!\w)(?P<outer>\w+)\s*\.\s*Route\s*\(\s*["`](?P<prefix>[^"`]*)["`]\s*,\s*"""+ r"func\s*\(\s*(?P<inner>\w+)\s+\*?\w+\s*\.\s*Router\s*\)\s*(?:error\s*)?(?P<brace>\{)"+)+++@dataclass(frozen=True)+class RouteScope:+ """``outer.Route(prefix, func(inner Router) {...})``; *start*/*end* bound the body."""++ outer: str+ inner: str+ prefix: str+ start: int+ end: int+++def route_scopes(content: str) -> list[RouteScope]:+ """Every ``Route`` closure in a chi or fiber file, outermost first."""+ if not _imported(content):+ return []+ out: list[RouteScope] = []+ for m in _ROUTE_SCOPE_RE.finditer(content):+ end = go_match_paren(content, m.start("brace"))+ if end > 0:+ out.append(+ RouteScope(m.group("outer"), m.group("inner"), m.group("prefix"), m.start("brace"), end)+ )+ return outdiff --git a/packages/core/src/repowise/core/ingestion/framework_routes_gorilla.py b/packages/core/src/repowise/core/ingestion/framework_routes_gorilla.pynew file mode 100644index 000000000..94b55977b--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_routes_gorilla.py@@ -0,0 +1,130 @@+"""gorilla/mux route chains.++A gorilla route is a chain of matchers ending in a handler, in any order::++ r.Methods("GET").Path("/catalogue/{id}").Handler(h)+ r.Path("/x").Methods(http.MethodPost).HandlerFunc(f)+ r.PathPrefix("/static/").Handler(fs)+ api := r.PathPrefix("/api").Subrouter()++``r.HandleFunc("/x", h).Methods("GET")`` starts with a ``net/http``-shaped+registration, so :func:`.framework_routes.go_routes` reads it, trailing+``Methods`` included. A ``PathPrefix`` route is recorded at its prefix. Read only+in a file importing gorilla/mux.+"""++from __future__ import annotations++import re+from collections.abc import Iterator++from .framework_routes import (+ GroupMatch,+ RouteMatch,+ go_match_paren,+ go_methods,+)++_IMPORT = '"github.com/gorilla/mux'++# A chain opens on one of the matchers a route builder starts with. The+# receiver must start a word, so a link in the middle of a chain is not+# re-read as a chain of its own; an assignment before it binds a subrouter.+_CHAIN_HEAD_RE = re.compile(+ r"(?:(?P<var>\w+)\s*:?=\s*)?(?<!\w)(?P<receiver>\w+)\s*\.\s*"+ r"(?P<link>Methods|Path|PathPrefix|Name|Schemes|Headers|Queries)\s*\("+)+_LINK_RE = re.compile(r"\s*\.\s*(?P<link>\w+)\s*\(")+_LITERAL_RE = re.compile(r"""\s*(?P<q>["`])(?P<body>[^"`]*)(?P=q)\s*""")+_HANDLER_RE = re.compile(r"\s*(?P<handler>(?!(?:func|struct)\b)[A-Za-z_][\w.]*)\s*(?P<after>[,)({])")+++def _links(content: str, paren: int) -> Iterator[tuple[str, int]]:+ """``(name, paren)`` of the call at *paren* and every call chained onto it."""+ link = content[content.rfind(".", 0, paren) + 1 : paren].strip()+ while True:+ yield link, paren+ close = go_match_paren(content, paren)+ if close < 0:+ return+ m = _LINK_RE.match(content, close + 1)+ if m is None:+ return+ link, paren = m.group("link"), m.end() - 1+++def _literal(content: str, paren: int) -> str | None:+ """The single string-literal argument of the call at *paren*, else ``None``."""+ close = go_match_paren(content, paren)+ m = _LITERAL_RE.fullmatch(content, paren + 1, close) if close > 0 else None+ return m.group("body") if m else None+++class _Chain:+ __slots__ = ("handled", "handler", "handler_call", "methods", "path_paren", "subrouter")++ def __init__(self, content: str, paren: int) -> None:+ self.methods: tuple[str, ...] | None = None+ self.path_paren: int | None = None+ self.handler: str | None = None+ self.handler_call = False+ self.handled = False # the chain reaches a Handler/HandlerFunc link+ self.subrouter = False+ for link, at in _links(content, paren):+ if link == "Methods":+ self.methods = go_methods(content, at)+ elif link in ("Path", "PathPrefix"):+ self.path_paren = at+ elif link in ("Handler", "HandlerFunc"):+ m = _HANDLER_RE.match(content, at + 1)+ self.handler = m.group("handler") if m else None+ self.handler_call = bool(m) and m.group("after") == "("+ # Handler returns the *Route, so matchers may follow it.+ self.handled = True+ elif link == "Subrouter":+ self.subrouter = True+ return+++def _chains(content: str) -> Iterator[tuple[re.Match[str], _Chain]]:+ if _IMPORT not in content:+ return+ for m in _CHAIN_HEAD_RE.finditer(content):+ yield m, _Chain(content, m.end() - 1)+++def gorilla_routes(content: str) -> Iterator[RouteMatch]:+ """Route-builder chains ending in a handler, one row per verb.++ ``path`` is the ``Path``/``PathPrefix`` literal, or ``None`` with+ ``paren_offset`` at that call when its argument is an expression. A chain+ with no path matcher or no handler is not a route this can name. An unreadable+ ``Methods`` leaves the route verbless (``HANDLE``).+ """+ for m, chain in _chains(content):+ # No handler link: a route builder bound to a name for later.+ if not chain.handled or chain.path_paren is None:+ continue+ for verb in chain.methods or ("HANDLE",):+ yield RouteMatch(+ verb=verb,+ path=_literal(content, chain.path_paren),+ receiver=m.group("receiver"),+ handler=chain.handler,+ offset=m.start("receiver"),+ paren_offset=chain.path_paren,+ handler_call=chain.handler_call,+ )+++def gorilla_groups(content: str) -> Iterator[GroupMatch]:+ """``sub := r.PathPrefix("/api").Subrouter()`` bindings.++ A subrouter with no ``PathPrefix`` (``r.Methods("GET").Subrouter()``) adds+ no prefix; one whose prefix is an expression is unreadable (``None``).+ """+ for m, chain in _chains(content):+ if not chain.subrouter or m.group("var") is None:+ continue+ prefix = "" if chain.path_paren is None else _literal(content, chain.path_paren)+ yield GroupMatch(var=m.group("var"), parent=m.group("receiver"), prefix=prefix)diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex 9bf3c4f88..1d84caa8d 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -74,6 +74,7 @@ CONTRACTS_FILENAME = "contracts.json"# each repo also counts the files whose network calls produced no contract# (see :mod:`.network_probe`). Gateway routes (Spring Cloud Gateway, Zuul)# rewrite the calls they forward and add gateway-to-service service links.+# Go routes from chi, fiber, gorilla/mux and Go 1.22 method patterns are read.CONTRACTS_VERSION = 15#: ``meta["kind"]`` of a topic contract: the destination a broker call names.diff --git a/packages/core/src/repowise/core/workspace/extractors/http/go.py b/packages/core/src/repowise/core/workspace/extractors/http/go.pyindex 366c8c58e..0b1e284fb 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/go.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/go.py@@ -1,69 +1,135 @@-"""Go HTTP provider dialect — gin/echo/chi ``r.GET("/path", ...)`` and-stdlib ``.HandleFunc("/path", ...)`` (which carries no method, recorded as-``*``).+"""Go HTTP provider dialect — gin/echo ``r.GET("/path", ...)``, chi/fiber+``r.Get("/path", ...)``, gorilla/mux route chains, and stdlib+``.HandleFunc("/path", ...)`` (which carries no method, recorded as ``*``,+unless a Go 1.22 ``"GET /path"`` pattern or a gorilla ``.Methods(...)`` names one).-The route call is recognised by ``ingestion.framework_routes``, shared with the-graph-edge builder that reads the same call for its handler argument.+The route calls are recognised by ``ingestion.framework_routes`` and its+``framework_routes_chi`` / ``framework_routes_gorilla`` siblings, shared with+the graph-edge builder that reads the same calls for their handler argument.-Route groups (``api := r.Group("/api"); v1 := api.Group("/v1")``) are resolved-transitively so a handler on ``v1`` records its full ``/api/v1/...`` path.+Route groups (``api := r.Group("/api"); v1 := api.Group("/v1")``, gorilla+``PathPrefix(...).Subrouter()``) are resolved transitively, and chi/fiber+``Route("/api", func(r chi.Router) {...})`` closures by position, so a handler+records its full ``/api/v1/...`` path. A path built as ``base + "/x"`` is read+through the file's constants; a base the file does not settle (an environment+value) is the service's deployment prefix and is dropped, as a consumer's+leading base is."""from __future__ import annotations+from itertools import chainfrom typing import TYPE_CHECKING-from repowise.core.ingestion.framework_routes import HTTP_METHODS, go_groups, go_routes+from repowise.core.ingestion.framework_routes import (+ GO_VERBLESS,+ HTTP_METHODS,+ go_groups,+ go_routes,+)+from repowise.core.ingestion.framework_routes_chi import route_scopes, title_case_routes+from repowise.core.ingestion.framework_routes_gorilla import gorilla_groups, gorilla_routesfrom ..base import line_at-from ..calls import outside_comments+from ..calls import FileStrings, outside_commentsfrom ..langs import GO+from ..strings import GO_SYNTAX, call_argumentsfrom .dialect import build_provider_contractfrom .mounts import compose_prefix, group_prefixes+from .paths import strip_leading_base_exprif TYPE_CHECKING:+ from collections.abc import Mapping, Sequence++ from repowise.core.ingestion.framework_routes import GroupMatch, RouteMatch+ from repowise.core.ingestion.framework_routes_chi import RouteScopefrom repowise.core.workspace.contracts import Contractfrom ..base import ScanContext-# Registration selectors that carry no verb of their own.-_VERBLESS = ("HANDLE", "HANDLEFUNC")++def _prefix(+ receiver: str, offset: int, scopes: Sequence[RouteScope], groups: Mapping[str, str]+) -> str:+ """The prefix *receiver* serves under at *offset*: its innermost ``Route`` closure, else its group."""+ for scope in reversed(scopes):+ if scope.inner == receiver and scope.start < offset < scope.end:+ return compose_prefix(_prefix(scope.outer, scope.start, scopes, groups), scope.prefix)+ return groups.get(receiver, "")+++def _handler(route: RouteMatch) -> str | None:+ """A wrapped handler names the middleware, not the route's own function."""+ return None if route.handler_call else route.handler+++def _method(verb: str) -> str | None:+ """The recorded method for *verb*: ``*`` when verbless; gin's ``Any``, OPTIONS and HEAD are not recorded."""+ if verb in GO_VERBLESS:+ return "*"+ return verb if verb in HTTP_METHODS else None+++def _unreadable_groups(groups: Sequence[GroupMatch]) -> set[str]:+ """Group variables whose prefix, or an ancestor's, is not a literal."""+ refused = {g.var for g in groups if g.prefix is None}+ grew = True+ while grew:+ before = len(refused)+ refused |= {g.var for g in groups if g.parent in refused}+ grew = len(refused) > before+ return refused+++def _expression_path(route: RouteMatch, strings: FileStrings) -> str | None:+ """The path a ``base + "/x"`` argument denotes, or ``None`` when it is not settled."""+ args = call_arguments(strings.content, route.paren_offset)+ text = strings.text(args[0]) if args else None+ if text is None:+ return None+ path, _base = strip_leading_base_expr(text)+ return None if "${" in path else pathclass GoDialect:name = "go"extensions = GO# The verb opens its call directly, as gofmt writes it; a chain may break- # the line after the receiver's `.`.+ # the line after the receiver's `.`. chi, fiber and gorilla calls are read+ # only in a file importing the router.requires = ("GET(", "POST(", "PUT(", "DELETE(", "PATCH(", "OPTIONS(", "HEAD(", "Any(", "Handle(",- "HandleFunc(",+ "HandleFunc(", "github.com/go-chi/chi", "github.com/gofiber/fiber",+ "github.com/gorilla/mux",) # fmt: skipdef extract(self, ctx: ScanContext) -> list[Contract]:- prefixes = group_prefixes(go_groups(ctx.content))+ content = ctx.content+ groups = [*go_groups(content), *gorilla_groups(content)]+ refused = _unreadable_groups(groups)+ prefixes = group_prefixes(g for g in groups if g.var not in refused)+ scopes = route_scopes(content)+ strings = FileStrings(content, GO_SYNTAX)+ routes = chain(go_routes(content), title_case_routes(content), gorilla_routes(content))out: list[Contract] = []- for route in outside_comments(ctx, go_routes(ctx.content)):- if route.verb in _VERBLESS:- method = "*"- elif route.verb in HTTP_METHODS:- method = route.verb- else:- continue # gin's `Any`, and OPTIONS/HEAD, are not recorded here+ for route in outside_comments(ctx, routes):+ method = _method(route.verb)+ if method is None or route.receiver in refused:+ continue # an unrecorded verb, or a prefix this cannot read+ path = route.path if route.path is not None else _expression_path(route, strings)+ if path is None:+ continue+ # An empty path under a group is still that group's route, so the+ # emptiness rule is `build_provider_contract`'s, after stitching —+ # the same order ASP.NET's MapGroup uses.+ prefix = _prefix(route.receiver or "", route.offset, scopes, prefixes)c = build_provider_contract(ctx,method=method,- # An empty path under a group is still that group's route, so- # the emptiness rule is `build_provider_contract`'s, after- # stitching — the same order ASP.NET's MapGroup uses.- path_raw=compose_prefix(- prefixes.get(route.receiver or "", ""), route.path or ""- ),+ path_raw=compose_prefix(prefix, path),framework="go",- line=line_at(ctx.content, route.offset),- # A wrapped handler names the middleware, not the route's own- # function, so binding by it would be wrong.- handler=None if route.handler_call else route.handler,+ line=line_at(content, route.offset),+ handler=_handler(route),)if c is not None:out.append(c)diff --git a/tests/unit/ingestion/test_go_framework_edges.py b/tests/unit/ingestion/test_go_framework_edges.pyindex ee69f9a53..fab7e2069 100644--- a/tests/unit/ingestion/test_go_framework_edges.py+++ b/tests/unit/ingestion/test_go_framework_edges.py@@ -140,6 +140,49 @@ class TestNetHTTP:add_framework_edges(graph, parsed, ctx, tech_stack=[])+class TestChiFiberGorillaRoutes:+ """The title-case and chained route shapes link their handlers too."""++ def _edges(self, tmp_path: Path, imp: str, body: str) -> nx.DiGraph:+ (tmp_path / "go.mod").write_text("module example.com/app\n\ngo 1.22\n")+ (tmp_path / "handlers.go").write_text(+ "package main\n\nfunc listOrders() {}\nfunc payment() {}\n"+ )+ (tmp_path / "main.go").write_text(+ f'package main\n\nimport "{imp}"\n\nfunc main() {{\n{body}}}\n'+ )+ parsed = _build_parsed(tmp_path)+ graph = nx.DiGraph()+ for p in parsed:+ graph.add_node(p)+ add_framework_edges(graph, parsed, _ctx(tmp_path, parsed), tech_stack=[])+ return graph++ def test_chi_title_case_verb(self, tmp_path: Path) -> None:+ graph = self._edges(+ tmp_path,+ "github.com/go-chi/chi/v5",+ ' r := chi.NewRouter()\n r.Get("/orders", listOrders)\n',+ )+ assert graph.has_edge("main.go", "handlers.go")++ def test_fiber_title_case_verb(self, tmp_path: Path) -> None:+ graph = self._edges(+ tmp_path,+ "github.com/gofiber/fiber/v2",+ ' app := fiber.New()\n app.Get("/orders", listOrders)\n',+ )+ assert graph.has_edge("main.go", "handlers.go")++ def test_gorilla_chain(self, tmp_path: Path) -> None:+ graph = self._edges(+ tmp_path,+ "github.com/gorilla/mux",+ ' r := mux.NewRouter()\n r.Methods("POST").Path("/paymentAuth").HandlerFunc(payment)\n',+ )+ assert graph.has_edge("main.go", "handlers.go")++class TestGoGRPC:def test_register_server_to_impl_file(self, tmp_path: Path) -> None:(tmp_path / "go.mod").write_text("module example.com/app\n\ngo 1.21\n")diff --git a/tests/unit/workspace/test_go_route_frameworks.py b/tests/unit/workspace/test_go_route_frameworks.pynew file mode 100644index 000000000..51b798bd8--- /dev/null+++ b/tests/unit/workspace/test_go_route_frameworks.py@@ -0,0 +1,277 @@+"""Go routers beyond gin and echo: chi, fiber, gorilla/mux and Go 1.22 patterns.++Each produced no provider, or a wrong one, before: chi and fiber spell verbs in+title case, gorilla builds a route as a chain of matchers, and a Go 1.22+``"GET /x"`` pattern was stored as the path ``/get /x``. The snippets are cut+from Sock Shop's catalogue and payment services and Online Boutique's frontend.+"""++from __future__ import annotations++from repowise.core.ingestion.framework_routes import go_routes+from repowise.core.ingestion.framework_routes_chi import route_scopes, title_case_routes+from repowise.core.ingestion.framework_routes_gorilla import gorilla_groups, gorilla_routes+from repowise.core.workspace.extractors.base import ScanContext+from repowise.core.workspace.extractors.dialect import run_dialect+from repowise.core.workspace.extractors.http.go import GoDialect+from repowise.core.workspace.origins import ContractOrigin+++def _provided(src: str, name: str = "routes.go") -> list[tuple[str, int, str | None]]:+ contracts = run_dialect(GoDialect(), ScanContext("svc", name, ".go", src))+ return sorted((c.contract_id, c.line, c.meta.get("handler")) for c in contracts)+++# Sock Shop catalogue/transport.go and payment/transport.go (go-kit on gorilla/mux).+SOCKSHOP_TRANSPORT = """\+package catalogue++import (+ "github.com/gorilla/mux"+ httptransport "github.com/go-kit/kit/transport/http"+)++func MakeHTTPHandler(e Endpoints, imagePath string) *mux.Router {+ r := mux.NewRouter().StrictSlash(false)+ // GET /catalogue List+ r.Methods("GET").Path("/catalogue").Handler(httptransport.NewServer(+ e.ListEndpoint,+ decodeListRequest,+ ))+ r.Methods("GET").Path("/catalogue/{id}").Handler(httptransport.NewServer(+ e.GetEndpoint, decodeGetRequest,+ ))+ r.Methods("POST").Path("/paymentAuth").Handler(authHandler)+ r.Methods("GET").PathPrefix("/health").Handler(healthHandler)+ r.Handle("/metrics", promhttp.Handler())+ return r+}+"""++# Online Boutique frontend/main.go: a prefix variable the deployment sets.+BOUTIQUE_MAIN = """\+package main++import "github.com/gorilla/mux"++var (+ baseUrl = ""+)++func main() {+ baseUrl = os.Getenv("BASE_URL")+ r := mux.NewRouter()+ r.HandleFunc(baseUrl+"/product/{id}", svc.productHandler).Methods(http.MethodGet, http.MethodHead)+ r.HandleFunc(baseUrl+"/cart", svc.addToCartHandler).Methods(http.MethodPost)+ r.HandleFunc(baseUrl+"/_healthz", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "ok") })+}+"""++CHI_ROUTES = """\+package api++import "github.com/go-chi/chi/v5"++type Server struct {+ cache *Cache+}++func (s *Server) Routes() http.Handler {+ r := chi.NewRouter()+ r.Get("/ping", s.ping)+ r.Route("/articles", func(r chi.Router) {+ r.Post("/", s.createArticle)+ r.Route("/{articleID}", func(r chi.Router) {+ r.Get("/", s.getArticle)+ r.Delete("/comments/{id}", s.deleteComment)+ })+ })+ s.cache.Get("/not/a/route")+ return r+}+"""++FIBER_APP = """\+package main++import "github.com/gofiber/fiber/v2"++func main() {+ app := fiber.New()+ api := app.Group("/api")+ api.Get("/users/:id", getUser)+ app.Route("/v2", func(v2 fiber.Router) {+ v2.Put("/orders/:id", updateOrder)+ })+ app.Post("/login", func(c *fiber.Ctx) error {+ token := c.Get("Authorization")+ return nil+ })+}+"""+++class TestGorilla:+ def test_sock_shop_chains_serve_their_paths_and_verbs(self) -> None:+ assert _provided(SOCKSHOP_TRANSPORT) == [+ ("http::*::/metrics", 20, None),+ ("http::GET::/catalogue", 11, None),+ ("http::GET::/catalogue/{param}", 15, None),+ ("http::GET::/health", 19, "healthHandler"),+ ("http::POST::/paymentauth", 18, "authHandler"),+ ]++ def test_a_commented_out_chain_is_not_a_route(self) -> None:+ src = SOCKSHOP_TRANSPORT.replace(+ 'r.Methods("POST")', '// r.Methods("POST")'+ )+ assert "http::POST::/paymentauth" not in {c for c, _, _ in _provided(src)}++ def test_a_prefix_variable_the_file_does_not_settle_is_the_deployment_base(self) -> None:+ # `baseUrl` is reassigned from the environment, so it is dropped as a+ # consumer's leading base is; HEAD is not a recorded method.+ assert _provided(BOUTIQUE_MAIN, "main.go") == [+ ("http::*::/_healthz", 14, None),+ ("http::GET::/product/{param}", 12, "svc.productHandler"),+ ("http::POST::/cart", 13, "svc.addToCartHandler"),+ ]++ def test_a_constant_prefix_is_inlined(self) -> None:+ src = (+ 'import "github.com/gorilla/mux"\n'+ 'const apiBase = "/api/v1"\n'+ 'r.HandleFunc(apiBase+"/orders", h).Methods("POST")\n'+ )+ assert _provided(src) == [("http::POST::/api/v1/orders", 3, "h")]++ def test_a_partly_read_path_is_not_a_route(self) -> None:+ # A literal with more appended is only the path's head, and a+ # one-argument call on a logger is not a registration.+ src = (+ 'r.GET("/api"+ver+"/x", h)\n'+ 'r.GET(base+"/x"+suffix, h)\n'+ 'log.Handle(prefix+"/x")\n'+ )+ assert [(r.verb, r.path) for r in go_routes(src)] == []++ def test_subrouters_compose_and_an_unreadable_prefix_refuses(self) -> None:+ src = (+ 'import "github.com/gorilla/mux"\n'+ 'api := r.PathPrefix("/api").Subrouter()\n'+ 'v1 := api.PathPrefix("/v1").Subrouter()\n'+ 'v1.HandleFunc("/items", items).Methods("GET")\n'+ 'dyn := r.PathPrefix(prefix()).Subrouter()\n'+ 'dyn.HandleFunc("/hidden", hidden)\n'+ 'below := dyn.PathPrefix("/x").Subrouter()\n'+ 'below.HandleFunc("/deeper", deeper)\n'+ )+ assert [(g.var, g.parent, g.prefix) for g in gorilla_groups(src)] == [+ ("api", "r", "/api"),+ ("v1", "api", "/v1"),+ ("dyn", "r", None),+ ("below", "dyn", "/x"),+ ]+ assert _provided(src) == [("http::GET::/api/v1/items", 4, "items")]++ def test_an_unreadable_methods_list_leaves_the_route_verbless(self) -> None:+ src = 'import "github.com/gorilla/mux"\nr.Path("/x").Methods(verbs...).HandlerFunc(h)\n'+ assert _provided(src) == [("http::*::/x", 2, "h")]++ def test_matchers_after_the_handler_are_read(self) -> None:+ # Handler returns the *Route, so gorilla accepts matchers after it.+ src = 'import "github.com/gorilla/mux"\nr.Path("/x").Handler(h).Methods("GET")\n'+ assert _provided(src) == [("http::GET::/x", 2, "h")]++ def test_chains_are_read_only_in_a_gorilla_file(self) -> None:+ src = 'r.Methods("GET").Path("/x").Handler(h)\n'+ assert list(gorilla_routes(src)) == []++ def test_a_builder_with_no_handler_is_not_a_route(self) -> None:+ src = 'import "github.com/gorilla/mux"\nroute := r.Path("/x").Methods("GET")\n'+ assert list(gorilla_routes(src)) == []+++class TestChiAndFiber:+ def test_route_closures_nest_and_only_router_receivers_count(self) -> None:+ # The root `/` of a closure is kept as its prefix; `s.cache.Get` is not+ # a router however its argument looks.+ assert _provided(CHI_ROUTES) == [+ ("http::DELETE::/articles/{param}/comments/{param}", 16, "s.deleteComment"),+ ("http::GET::/articles/{param}", 15, "s.getArticle"),+ ("http::GET::/ping", 11, "s.ping"),+ ("http::POST::/articles", 13, "s.createArticle"),+ ]+ assert [(s.outer, s.inner, s.prefix) for s in route_scopes(CHI_ROUTES)] == [+ ("r", "r", "/articles"),+ ("r", "r", "/{articleID}"),+ ]++ def test_fiber_groups_routes_and_a_header_read(self) -> None:+ assert _provided(FIBER_APP) == [+ ("http::GET::/api/users/{param}", 8, "getUser"),+ ("http::POST::/login", 12, None),+ ("http::PUT::/v2/orders/{param}", 10, "updateOrder"),+ ]++ def test_title_case_verbs_need_the_router_import(self) -> None:+ src = CHI_ROUTES.replace('import "github.com/go-chi/chi/v5"', 'import "example.com/kv"')+ assert list(title_case_routes(src)) == []++ def test_a_receiver_is_read_at_its_nearest_binding(self) -> None:+ # The handler literal's `r *http.Request` holds only inside its body, so+ # the next route on the router `r` still counts; a later function that+ # takes a client named `r`, or groups a non-router, adds no route.+ src = (+ 'import "github.com/go-chi/chi/v5"\n'+ "func routes() {\n"+ "\tr := chi.NewRouter()\n"+ '\tr.Get("/a", func(w http.ResponseWriter, r *http.Request) { r.Context() })\n'+ '\tr.Post("/b", b)\n'+ "}\n"+ "func fetch(r *Client) {\n"+ '\tr.Get("/users/1", nil)\n'+ '\tg := r.Group("/x")\n'+ '\tg.Get("/y", nil)\n'+ "}\n"+ )+ assert [(r.verb, r.path) for r in title_case_routes(src)] == [+ ("GET", "/a"),+ ("POST", "/b"),+ ]++ def test_a_client_call_is_not_a_route(self) -> None:+ # An HTTP client in a chi service: neither receiver is bound to a router.+ src = (+ 'import "github.com/go-chi/chi/v5"\n'+ 'resp, err := client.Get("/users")\n'+ 'resp, err = http.Get("/users")\n'+ )+ assert list(title_case_routes(src)) == []+++class TestGo122Patterns:+ def test_a_method_pattern_names_the_verb(self) -> None:+ src = (+ 'mux.HandleFunc("GET /items/{id}", getItem)\n'+ 'mux.HandleFunc("POST api.example.com/items", createItem)\n'+ 'mux.HandleFunc("/files/{path...}", files)\n'+ 'mux.HandleFunc("GET /{$}", home)\n'+ )+ assert [(r.verb, r.path) for r in go_routes(src)] == [+ ("GET", "/items/{id}"),+ ("POST", "/items"),+ ("HANDLEFUNC", "/files/{path}"),+ ("GET", "/"),+ ]+ assert _provided(src) == [+ ("http::*::/files/{param}", 3, "files"),+ ("http::GET::/items/{param}", 1, "getItem"),+ ("http::POST::/items", 2, "createItem"),+ ]++ def test_origin_is_route_registration(self) -> None:+ (contract,) = run_dialect(+ GoDialect(),+ ScanContext("svc", "m.go", ".go", 'mux.HandleFunc("GET /a", h)\n'),+ )+ assert contract.origin == ContractOrigin.ROUTE_REGISTRATION