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(workspace): read Rails, Sinatra and Grape routes as HTTP providers (#4739)

Rishabh Mishraf056d55977c7
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index d19423d96..827f3d8ca 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -144,7 +144,7 @@ Scans source files for HTTP routes, gRPC services, database tables, message topi
| Java / Kotlin | Spring, JAX-RS, Micronaut, Ktor server routing (Kotlin), Javalin (`app.get`, v7 `config.routes`, `ApiBuilder` paths) | 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, 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; `new Uri(base, path)` and `CombineUri` joins; typed, named and Refit client `BaseAddress`; HttpClient wrapper methods), Refit attributes, YARP `MapForwarder`, UnityWebRequest, Best.HTTP |
-| Ruby | | HTTParty, RestClient, Faraday, Net::HTTP |
+| Ruby | Rails (`config/routes.rb`), Sinatra, Grape | HTTParty, RestClient, Faraday, Net::HTTP |
| Rust | Axum, Actix, Rocket | reqwest |
| Apex | `@RestResource` classes (`/services/apexrest` + `urlMapping`) | `HttpRequest` callouts (literal endpoint and verb) |
| C# (Azure Functions) | `[HttpTrigger]` routes under the default `/api` prefix; the function name when no `Route` is set | |
diff --git a/packages/core/src/repowise/core/workspace/extractors/base.py b/packages/core/src/repowise/core/workspace/extractors/base.py
index 34ccd59a0..559234853 100644
--- a/packages/core/src/repowise/core/workspace/extractors/base.py
+++ b/packages/core/src/repowise/core/workspace/extractors/base.py
@@ -70,9 +70,8 @@ def make_exclude_predicate(
#: Where comments are ``//`` and ``/* */`` and ``#`` is code (a C# directive, a
-#: Rust or PHP attribute). Ruby is left out: its ``/.../`` regex literals would
-#: open a comment the masker cannot close. VB and SQL are left out too. A match
-#: in an unmasked file is never treated as commented out.
+#: Rust or PHP attribute). VB and SQL are left out. A match in an unmasked
+#: file is never treated as commented out.
_SLASH_COMMENT_SUFFIXES = JAVA | KOTLIN | GO | CSHARP | RUST | PHP | APEX | PROTO | {".prisma"}
_XML_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
@@ -86,6 +85,10 @@ def _comment_mask(suffix: str, content: str) -> str | None:
return mask_source(content, suffix)
if suffix in JS_TS:
return mask_source(content, ".js")
+ if suffix == ".rb":
+ from repowise.core.analysis.security.masking import mask_comments_and_strings
+
+ return mask_comments_and_strings(content, strings=False, hash_comments=True)
if suffix == ".xml":
return _XML_COMMENT_RE.sub(lambda m: " " * len(m.group(0)), content)
if suffix not in _SLASH_COMMENT_SUFFIXES:
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
index 61cafe7d7..326c5cea0 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
@@ -31,6 +31,7 @@ from .fastify import FastifyDialect
from .flask import FlaskDialect
from .go import GoDialect
from .go_clients import GoClientsDialect
+from .grape import GrapeDialect
from .hapi import HapiDialect
from .java_clients import JavaClientsDialect, MicroProfileClientsDialect, SpringClientsDialect
from .javalin import JavalinDialect
@@ -47,11 +48,13 @@ from .next_app import NextAppDialect
from .paths import normalize_http_path
from .php_clients import PhpClientsDialect
from .python_clients import PythonClientsDialect
+from .rails_routes import RailsRoutesDialect
from .refit import RefitDialect
from .remix import RemixDialect
from .ruby_clients import RubyClientsDialect
from .rust_axum import RustAxumDialect
from .rust_clients import RustClientsDialect
+from .sinatra import SinatraDialect
from .spring import SpringDialect
if TYPE_CHECKING:
@@ -86,6 +89,9 @@ PROVIDER_DIALECTS: tuple[ContractDialect, ...] = (
FastifyDialect(),
HapiDialect(),
KoaDialect(),
+ RailsRoutesDialect(),
+ SinatraDialect(),
+ GrapeDialect(),
)
# HTTP-client call recognisers (one client/language each).
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/grape.py b/packages/core/src/repowise/core/workspace/extractors/http/grape.py
new file mode 100644
index 000000000..766dc1247
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/grape.py
@@ -0,0 +1,185 @@
+"""Grape (Ruby) HTTP provider dialect — ``class API < Grape::API``.
+
+Recognises Grape API routes with ``prefix``, path-based ``version``,
+nested ``resource`` / ``namespace`` / ``route_param`` scopes, and verb declarations.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING
+
+from ..langs import RUBY
+from .dialect import build_provider_contract
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+
+_PREFIX_RE = re.compile(r"\bprefix\s+(?::(\w+)|\"([^\"]+)\"|'([^']+)')")
+_VERSION_RE = re.compile(
+ r"\bversion\s+(?:(?::(\w+)|\"([^\"]+)\"|'([^']+)'|\[[^\]]+\]))[^\n]*?using:\s*:path"
+)
+_RESOURCE_RE = re.compile(
+ r"\b(?:resource|resources|namespace|group|segment)\s+(?::(\w+)|\"([^\"]+)\"|'([^']+)')"
+)
+_ROUTE_PARAM_RE = re.compile(r"\broute_param\s+(?::(\w+)|\"([^\"]+)\"|'([^']+)')")
+_VERB_RE = re.compile(
+ r"\b(get|post|put|patch|delete|options|head)"
+ r"(?:\s+(?:(?::(\w+)|\"([^\"]+)\"|'([^']+)'|(?:\(\s*[\"']([^\"']+)[\"']\s*\)))))?"
+ r"(?:\s*(?:do|\{)|$)"
+)
+_DO_BLOCK_RE = re.compile(r"\bdo(?:\s*\|[^|]*\|)?\s*$")
+
+
+@dataclass
+class _GrapeState:
+ prefix: str = ""
+ version: str = ""
+ stack: list[str] = field(default_factory=list)
+ out: list[Contract] = field(default_factory=list)
+
+
+def _strip_inline_end(raw: str) -> tuple[str, bool]:
+ clean = raw
+ has_inline_end = False
+ if "; end" in clean:
+ clean = clean.split("; end")[0].strip()
+ has_inline_end = True
+ elif re.search(r"\s+end$", clean):
+ clean = re.sub(r"\s+end$", "", clean).strip()
+ has_inline_end = True
+ return clean, has_inline_end
+
+
+def _handle_config(line: str, state: _GrapeState) -> bool:
+ m = _PREFIX_RE.search(line)
+ if m:
+ val = next(g for g in m.groups() if g is not None)
+ state.prefix = "/" + val.strip("/")
+ return True
+
+ m = _VERSION_RE.search(line)
+ if m:
+ val = next((g for g in m.groups() if g is not None), "")
+ if val:
+ state.version = "/" + val.strip("/")
+ return True
+
+ return False
+
+
+def _handle_scope(line: str, push_block: bool, state: _GrapeState) -> bool:
+ m = _RESOURCE_RE.search(line)
+ if m:
+ res = next(g for g in m.groups() if g is not None).strip("/")
+ if push_block:
+ state.stack.append(res)
+ return True
+
+ m = _ROUTE_PARAM_RE.search(line)
+ if m:
+ p_name = next(g for g in m.groups() if g is not None).strip("/")
+ if push_block:
+ state.stack.append(":" + p_name)
+ return True
+
+ return False
+
+
+def _handle_verb(
+ line: str,
+ line_no: int,
+ push_block: bool,
+ state: _GrapeState,
+ ctx: ScanContext,
+) -> bool:
+ m = _VERB_RE.search(line)
+ if not m:
+ return False
+
+ verb = m.group(1).upper()
+ sub = next((g for g in m.groups()[1:] if g is not None), "")
+ path_parts = [p for p in [state.prefix, state.version, *state.stack, sub] if p]
+ full = "/" + "/".join(s.strip("/") for s in path_parts)
+
+ c = build_provider_contract(
+ ctx,
+ method=verb,
+ path_raw=full,
+ framework="grape",
+ line=line_no,
+ )
+ if c is not None:
+ state.out.append(c)
+ if push_block:
+ state.stack.append("")
+ return True
+
+
+def _process_statement(
+ line: str,
+ line_no: int,
+ push_block: bool,
+ state: _GrapeState,
+ ctx: ScanContext,
+) -> bool:
+ if _handle_config(line, state):
+ return True
+
+ if _handle_scope(line, push_block, state):
+ return True
+
+ return _handle_verb(line, line_no, push_block, state, ctx)
+
+
+class GrapeDialect:
+ name = "grape"
+ extensions = RUBY
+ requires = ("Grape::API",)
+
+ def _step_line(
+ self,
+ raw: str,
+ line_no: int,
+ state: _GrapeState,
+ ctx: ScanContext,
+ ) -> None:
+ if raw == "end" or raw.startswith("end "):
+ if state.stack:
+ state.stack.pop()
+ return
+
+ line, has_inline_end = _strip_inline_end(raw)
+ if not line:
+ if has_inline_end and state.stack:
+ state.stack.pop()
+ return
+
+ had_do = bool(_DO_BLOCK_RE.search(line))
+ push_block = had_do and not has_inline_end
+ pop_enclosing = has_inline_end and not had_do
+
+ handled = _process_statement(line, line_no, push_block, state, ctx)
+ if not handled and push_block:
+ state.stack.append("")
+
+ if pop_enclosing and state.stack:
+ state.stack.pop()
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ mask = ctx._mask()
+ code = mask if mask is not None else ctx.content
+ lines = code.splitlines()
+
+ state = _GrapeState()
+
+ for line_no, mask_line in enumerate(lines, 1):
+ raw = mask_line.strip()
+ if not raw or ctx.comment_only_line(line_no):
+ continue
+ self._step_line(raw, line_no, state, ctx)
+
+ return state.out
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/rails_routes.py b/packages/core/src/repowise/core/workspace/extractors/http/rails_routes.py
new file mode 100644
index 000000000..eda852493
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/rails_routes.py
@@ -0,0 +1,384 @@
+"""Rails (Ruby) HTTP provider dialect — ``config/routes.rb``.
+
+Reads routes declared via ``resources``/``resource`` (with ``only`` and
+``except`` options), ``namespace``, ``scope``, ``member``, ``collection``,
+direct verb helpers (``get``, ``post``, etc.), and ``match ... via:``.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+from ..langs import RUBY
+from .dialect import build_provider_contract
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+
+_PLURAL_ACTIONS: tuple[tuple[str, tuple[str, ...], str], ...] = (
+ ("index", ("GET",), ""),
+ ("new", ("GET",), "/new"),
+ ("create", ("POST",), ""),
+ ("show", ("GET",), "/:id"),
+ ("edit", ("GET",), "/:id/edit"),
+ ("update", ("PUT", "PATCH"), "/:id"),
+ ("destroy", ("DELETE",), "/:id"),
+)
+
+_SINGULAR_ACTIONS: tuple[tuple[str, tuple[str, ...], str], ...] = (
+ ("new", ("GET",), "/new"),
+ ("create", ("POST",), ""),
+ ("show", ("GET",), ""),
+ ("edit", ("GET",), "/edit"),
+ ("update", ("PUT", "PATCH"), ""),
+ ("destroy", ("DELETE",), ""),
+)
+
+_NAMESPACE_RE = re.compile(r"\bnamespace\s+(?::(\w+)|\"([^\"]+)\"|'([^']+)')")
+_SCOPE_RE = re.compile(
+ r"\bscope\s+(?:path:\s*[\"']([^\"']+)[\"']|(?::(\w+)|\"([^\"]+)\"|'([^']+)'))"
+)
+_RESOURCES_RE = re.compile(r"\b(resources|resource)\s+([^\n]+)")
+_DIRECT_RE = re.compile(r"\b(get|post|put|patch|delete)\s+(?:[\"']([^\"']+)[\"']|:(\w+))")
+_ROOT_RE = re.compile(r"\broot\b")
+_MATCH_RE = re.compile(
+ r"\bmatch\s+[\"']([^\"']+)[\"'][^\n]*?(?:via:\s*|:via\s*=>\s*)(?:\[([^\]]*)\]|%i\[([^\]]*)\]|:(\w+))"
+)
+_DO_BLOCK_RE = re.compile(r"\bdo(?:\s*\|[^|]*\|)?\s*$")
+
+
+@dataclass
+class _Scope:
+ kind: str
+ prefix: str = ""
+ resource: str = ""
+ singular: bool = False
+
+
+def _parse_options(text: str) -> tuple[set[str] | None, set[str]]:
+ only_m = re.search(
+ r"only:\s*(?:\[([^\]]*)\]|%i\[([^\]]*)\]|:(\w+)|\"(\w+)\"|'(\w+)')", text
+ )
+ except_m = re.search(
+ r"except:\s*(?:\[([^\]]*)\]|%i\[([^\]]*)\]|:(\w+)|\"(\w+)\"|'(\w+)')", text
+ )
+ only: set[str] | None = None
+ if only_m:
+ raw = next(g for g in only_m.groups() if g is not None)
+ only = set(re.findall(r"\w+", raw))
+ excluded: set[str] = set()
+ if except_m:
+ raw = next(g for g in except_m.groups() if g is not None)
+ excluded = set(re.findall(r"\w+", raw))
+ return only, excluded
+
+
+def _current_base(stack: list[_Scope]) -> str:
+ parts: list[str] = []
+ for s in stack:
+ if s.prefix:
+ parts.append(s.prefix.strip("/"))
+ elif s.resource:
+ parts.append(s.resource.strip("/"))
+ if not s.singular:
+ parts.append(":id")
+ return "/" + "/".join(parts) if parts else ""
+
+
+def _read_statements(lines: list[str], ctx: ScanContext) -> list[tuple[int, str]]:
+ """Join continued lines and filter empty/comment-only lines."""
+ statements: list[tuple[int, str]] = []
+ buf = ""
+ start_line = 1
+ for line_no, mask_line in enumerate(lines, 1):
+ line = mask_line.strip()
+ if not line or ctx.comment_only_line(line_no):
+ continue
+ if not buf:
+ start_line = line_no
+ buf = line
+ else:
+ buf += " " + line
+ if not buf.endswith(","):
+ statements.append((start_line, buf))
+ buf = ""
+ if buf:
+ statements.append((start_line, buf))
+ return statements
+
+
+def _strip_inline_end(raw: str) -> tuple[str, bool]:
+ clean = raw
+ has_inline_end = False
+ if "; end" in clean:
+ clean = clean.split("; end")[0].strip()
+ has_inline_end = True
+ elif re.search(r"\s+end$", clean):
+ clean = re.sub(r"\s+end$", "", clean).strip()
+ has_inline_end = True
+ return clean, has_inline_end
+
+
+def _pop_if_enclosing(
+ has_inline_end: bool, had_do: bool, stack: list[_Scope]
+) -> None:
+ if has_inline_end and not had_do and stack:
+ stack.pop()
+
+
+def _match_scope(line: str) -> _Scope | None:
+ if "routes.draw" in line:
+ return _Scope(kind="drawer")
+
+ m = _NAMESPACE_RE.search(line)
+ if m:
+ ns = next(g for g in m.groups() if g is not None)
+ return _Scope(kind="namespace", prefix=f"/{ns}")
+
+ m = _SCOPE_RE.search(line)
+ if m:
+ sc = next(g for g in m.groups() if g is not None)
+ prefix = f"/{sc.strip('/')}" if sc else ""
+ return _Scope(kind="scope", prefix=prefix)
+
+ if re.search(r"\bmember\b", line):
+ return _Scope(kind="member")
+
+ if re.search(r"\bcollection\b", line):
+ return _Scope(kind="collection")
+
+ return None
+
+
+def _handle_scope(line: str, push_block: bool, stack: list[_Scope]) -> bool:
+ scope = _match_scope(line)
+ if scope is None:
+ return False
+ if push_block:
+ stack.append(scope)
+ return True
+
+
+def _build_action_contracts(
+ res_path: str,
+ verbs: tuple[str, ...],
+ line_no: int,
+ ctx: ScanContext,
+) -> list[Contract]:
+ contracts: list[Contract] = []
+ for v in verbs:
+ c = build_provider_contract(
+ ctx,
+ method=v,
+ path_raw=res_path,
+ framework="rails",
+ line=line_no,
+ )
+ if c is not None:
+ contracts.append(c)
+ return contracts
+
+
+def _expand_actions(
+ actions: tuple[tuple[str, tuple[str, ...], str], ...],
+ res_names: list[str],
+ base: str,
+ filter_opts: tuple[set[str] | None, set[str]],
+ line_no: int,
+ ctx: ScanContext,
+) -> list[Contract]:
+ only, excluded = filter_opts
+ out: list[Contract] = []
+ for name in res_names:
+ for act_name, verbs, suffix in actions:
+ if (only is not None and act_name not in only) or act_name in excluded:
+ continue
+ res_path = f"{base}/{name}{suffix}"
+ out.extend(_build_action_contracts(res_path, verbs, line_no, ctx))
+ return out
+
+
+def _handle_resources(
+ line: str,
+ line_no: int,
+ push_block: bool,
+ stack: list[_Scope],
+ ctx: ScanContext,
+) -> list[Contract] | None:
+ m = _RESOURCES_RE.search(line)
+ if not m:
+ return None
+
+ kind = m.group(1)
+ rest = m.group(2)
+ first_arg = rest.split(",")[0]
+ names = re.findall(r":(\w+)|[\"']([^\"']+)[\"']", first_arg)
+ res_names = [g[0] or g[1] for g in names]
+ filter_opts = _parse_options(rest)
+ is_singular = kind == "resource"
+ actions = _SINGULAR_ACTIONS if is_singular else _PLURAL_ACTIONS
+
+ base = _current_base(stack)
+ out = _expand_actions(actions, res_names, base, filter_opts, line_no, ctx)
+ if push_block:
+ for name in res_names:
+ stack.append(_Scope(kind="resource", resource=name, singular=is_singular))
+ return out
+
+
+def _handle_match(
+ line: str,
+ line_no: int,
+ ctx: ScanContext,
+) -> list[Contract] | None:
+ m = _MATCH_RE.search(line)
+ if not m:
+ return None
+
+ path = m.group(1)
+ v_list = next(g for g in m.groups()[1:] if g is not None)
+ verbs = (
+ ["GET", "POST", "PUT", "PATCH", "DELETE"]
+ if v_list == "all"
+ else [v.upper() for v in re.findall(r"\w+", v_list)]
+ )
+
+ out: list[Contract] = []
+ for v in verbs:
+ c = build_provider_contract(
+ ctx,
+ method=v,
+ path_raw=path,
+ framework="rails",
+ line=line_no,
+ )
+ if c is not None:
+ out.append(c)
+ return out
+
+
+def _direct_verb_path(line: str, p: str, stack: list[_Scope]) -> str:
+ prefixes = "".join(s.prefix for s in stack if s.prefix)
+ if p.startswith("/"):
+ return f"{prefixes}{p}"
+
+ res = next((s for s in reversed(stack) if s.resource), None)
+ if res is None:
+ return f"{_current_base(stack)}/{p}"
+
+ in_coll = any(s.kind == "collection" for s in stack) or "on: :collection" in line
+ id_part = "" if in_coll or res.singular else "/:id"
+ return f"{prefixes}/{res.resource}{id_part}/{p}"
+
+
+def _handle_direct_verb(
+ line: str,
+ line_no: int,
+ push_block: bool,
+ stack: list[_Scope],
+ ctx: ScanContext,
+) -> list[Contract] | None:
+ m = _DIRECT_RE.search(line)
+ if not m:
+ return None
+
+ verb = m.group(1).upper()
+ p = m.group(2) or m.group(3)
+ full = _direct_verb_path(line, p, stack)
+
+ out: list[Contract] = []
+ c = build_provider_contract(
+ ctx,
+ method=verb,
+ path_raw=full,
+ framework="rails",
+ line=line_no,
+ )
+ if c is not None:
+ out.append(c)
+ if push_block:
+ stack.append(_Scope(kind="other"))
+ return out
+
+
+def _handle_root(
+ line_no: int,
+ stack: list[_Scope],
+ ctx: ScanContext,
+) -> list[Contract]:
+ base = _current_base(stack) or "/"
+ c = build_provider_contract(
+ ctx,
+ method="GET",
+ path_raw=base,
+ framework="rails",
+ line=line_no,
+ )
+ return [c] if c is not None else []
+
+
+def _process_statement(
+ line: str,
+ line_no: int,
+ push_block: bool,
+ stack: list[_Scope],
+ ctx: ScanContext,
+) -> list[Contract] | None:
+ if _handle_scope(line, push_block, stack):
+ return []
+
+ res_contracts = _handle_resources(line, line_no, push_block, stack, ctx)
+ if res_contracts is not None:
+ return res_contracts
+
+ if _ROOT_RE.search(line):
+ return _handle_root(line_no, stack, ctx)
+
+ match_contracts = _handle_match(line, line_no, ctx)
+ if match_contracts is not None:
+ return match_contracts
+
+ return _handle_direct_verb(line, line_no, push_block, stack, ctx)
+
+
+class RailsRoutesDialect:
+ name = "rails"
+ extensions = RUBY
+ requires = ("routes.draw",)
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ mask = ctx._mask()
+ code = mask if mask is not None else ctx.content
+ lines = code.splitlines()
+
+ stack: list[_Scope] = []
+ out: list[Contract] = []
+ statements = _read_statements(lines, ctx)
+
+ for line_no, raw in statements:
+ if raw == "end" or raw.startswith("end "):
+ if stack:
+ stack.pop()
+ continue
+
+ line, has_inline_end = _strip_inline_end(raw)
+ if not line:
+ _pop_if_enclosing(has_inline_end, False, stack)
+ continue
+
+ had_do = bool(_DO_BLOCK_RE.search(line))
+ push_block = had_do and not has_inline_end
+
+ contracts = _process_statement(line, line_no, push_block, stack, ctx)
+ if contracts is not None:
+ out.extend(contracts)
+ elif push_block:
+ stack.append(_Scope(kind="other"))
+
+ _pop_if_enclosing(has_inline_end, had_do, stack)
+
+ return out
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/sinatra.py b/packages/core/src/repowise/core/workspace/extractors/http/sinatra.py
new file mode 100644
index 000000000..c873bc82f
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/sinatra.py
@@ -0,0 +1,51 @@
+"""Sinatra (Ruby) HTTP provider dialect — ``get '/path' do ... end``.
+
+Recognises Sinatra routes declared top-level or within ``Sinatra::Base`` /
+``Sinatra::Application`` classes.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+from ..base import line_at
+from ..calls import code_matches
+from ..langs import RUBY
+from .dialect import build_provider_contract
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+
+_SINATRA_ROUTE_RE = re.compile(
+ r"\b(?P<verb>get|post|put|patch|delete|options|head)\s*"
+ r"(?:\(\s*)?"
+ r"(?:[\"'](?P<path>[^\"']+)[\"']|:(?P<sym>\w+))"
+ r"(?:\s*,\s*[^do{\n]+)?"
+ r"\s*\)?"
+ r"\s*(?:do|\{)"
+)
+
+
+class SinatraDialect:
+ name = "sinatra"
+ extensions = RUBY
+ requires = ("sinatra", "Sinatra::")
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ out: list[Contract] = []
+ for m in code_matches(ctx, _SINATRA_ROUTE_RE):
+ verb = m.group("verb").upper()
+ path = m.group("path") or f"/{m.group('sym')}"
+ c = build_provider_contract(
+ ctx,
+ method=verb,
+ path_raw=path,
+ framework="sinatra",
+ line=line_at(ctx.content, m.start()),
+ )
+ if c is not None:
+ out.append(c)
+ return out
diff --git a/tests/fixtures/workspace_http/rails/config/routes.rb b/tests/fixtures/workspace_http/rails/config/routes.rb
new file mode 100644
index 000000000..38d20115c
--- /dev/null
+++ b/tests/fixtures/workspace_http/rails/config/routes.rb
@@ -0,0 +1,40 @@
+Rails.application.routes.draw do
+ root to: "home#index"
+
+ get "/404" => "about#four_oh_four", :via => :all
+
+ get "/rss" => "home#index", :format => "rss"
+ get "/hottest" => "home#index", :format => "json"
+
+ get "/page/:page" => "home#index"
+ get "/active" => "home#active"
+
+ # get "/commented_out" => "home#commented"
+
+ match "/login/set_new_password" => "login#set_new_password",
+ :as => "set_new_password", :via => [:get, :post]
+
+ resources :stories, except: [:index] do
+ post "upvote"
+ resources :suggestions, only: [:new, :create]
+ end
+
+ resources :comments, except: [:new, :destroy] do
+ member do
+ get "reply"
+ post "delete"
+ end
+ collection do
+ get "search"
+ end
+ end
+
+ namespace :admin do
+ resources :users, only: [:index, :show]
+ get "/dashboard" => "dashboard#index"
+ end
+
+ scope "/v1" do
+ get "/status" => "status#show"
+ end
+end
diff --git a/tests/unit/workspace/test_ruby_routes.py b/tests/unit/workspace/test_ruby_routes.py
new file mode 100644
index 000000000..4f9eb7e23
--- /dev/null
+++ b/tests/unit/workspace/test_ruby_routes.py
@@ -0,0 +1,270 @@
+"""Ruby HTTP providers: Rails routes.rb, Sinatra and Grape."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.workspace.extractors.http import HttpExtractor
+from repowise.core.workspace.extractors.http.rails_routes import (
+ _current_base,
+ _parse_options,
+ _Scope,
+)
+from repowise.core.workspace.origins import ContractOrigin
+
+
+def _providers(repo: Path) -> dict[str, ContractOrigin]:
+ return {
+ c.contract_id: c.origin
+ for c in HttpExtractor().extract(repo, "api")
+ if c.role == "provider"
+ }
+
+
+def _provider_ids(repo: Path) -> set[str]:
+ return set(_providers(repo).keys())
+
+
+def _write(repo: Path, rel: str, text: str) -> None:
+ path = repo / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+
+
+class TestRailsHelpers:
+ def test_parse_options(self) -> None:
+ assert _parse_options("resources :users") == (None, set())
+ assert _parse_options("resources :users, only: %i[index show]") == (
+ {"index", "show"},
+ set(),
+ )
+ assert _parse_options("resources :users, except: :destroy") == (
+ None,
+ {"destroy"},
+ )
+ assert _parse_options("resources :users, only: 'index'") == (
+ {"index"},
+ set(),
+ )
+
+ def test_current_base(self) -> None:
+ # Singular resource does not add :id
+ stack_singular = [_Scope(kind="resource", resource="profile", singular=True)]
+ assert _current_base(stack_singular) == "/profile"
+
+ # Plural resource adds :id
+ stack_plural = [_Scope(kind="resource", resource="users", singular=False)]
+ assert _current_base(stack_plural) == "/users/:id"
+
+ # Namespace nested inside a non-singular resource adds :id
+ stack_nested = [
+ _Scope(kind="resource", resource="projects", singular=False),
+ _Scope(kind="namespace", prefix="/admin"),
+ ]
+ assert _current_base(stack_nested) == "/projects/:id/admin"
+
+
+class TestRailsRoutes:
+ def test_fixture_extracts_expected_contracts(self) -> None:
+ fixture_repo = Path(__file__).parents[2] / "fixtures" / "workspace_http" / "rails"
+ providers = _providers(fixture_repo)
+ ids = set(providers.keys())
+
+ # Root route
+ assert "http::GET::/" in ids
+ assert providers["http::GET::/"] == ContractOrigin.ROUTE_REGISTRATION
+
+ # Direct routes
+ assert "http::GET::/rss" in ids
+ assert "http::GET::/hottest" in ids
+ assert "http::GET::/page/{param}" in ids
+ assert "http::GET::/active" in ids
+
+ # Match ... via:
+ assert "http::GET::/login/set_new_password" in ids
+ assert "http::POST::/login/set_new_password" in ids
+
+ # Resources with except: [:index]
+ assert "http::GET::/stories" not in ids
+ assert "http::POST::/stories" in ids
+ assert "http::GET::/stories/{param}" in ids
+ assert "http::PUT::/stories/{param}" in ids
+ assert "http::DELETE::/stories/{param}" in ids
+ assert "http::POST::/stories/{param}/upvote" in ids
+
+ # Nested resources with only: [:new, :create]
+ assert "http::GET::/stories/{param}/suggestions/new" in ids
+ assert "http::POST::/stories/{param}/suggestions" in ids
+ assert "http::GET::/stories/{param}/suggestions" not in ids
+
+ # Member block and collection block
+ assert "http::GET::/comments/{param}/reply" in ids
+ assert "http::POST::/comments/{param}/delete" in ids
+ assert "http::GET::/comments/search" in ids
+
+ # Namespaced routes
+ assert "http::GET::/admin/users" in ids
+ assert "http::GET::/admin/users/{param}" in ids
+ assert "http::GET::/admin/dashboard" in ids
+
+ # Scoped routes
+ assert "http::GET::/v1/status" in ids
+
+ # Commented-out route yields nothing
+ assert not any("commented" in cid for cid in ids)
+
+ def test_singular_resource(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "config/routes.rb",
+ """Rails.application.routes.draw do
+ resource :profile, only: [:show, :update] do
+ member do
+ get :settings
+ end
+ end
+end
+""",
+ )
+ ids = _provider_ids(tmp_path)
+ assert ids == {
+ "http::GET::/profile",
+ "http::PUT::/profile",
+ "http::PATCH::/profile",
+ "http::GET::/profile/settings",
+ }
+
+ def test_scope_namespace_and_member_inline_end(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "config/routes.rb",
+ """Rails.application.routes.draw do
+ scope "/api" do
+ namespace :admin do
+ resources :users, only: [:index]
+ end
+ end
+
+ resource :profile, except: [:destroy] do
+ member do
+ get :status; end
+ end
+end
+""",
+ )
+ ids = _provider_ids(tmp_path)
+ assert "http::GET::/api/admin/users" in ids
+ assert "http::GET::/profile" in ids
+ assert "http::PUT::/profile" in ids
+ assert "http::PATCH::/profile" in ids
+ assert "http::POST::/profile" in ids
+ assert "http::DELETE::/profile" not in ids
+ assert "http::GET::/profile/status" in ids
+
+
+class TestSinatraRoutes:
+ def test_basic_and_modular_sinatra(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "app.rb",
+ """require 'sinatra'
+
+get '/hello' do
+ 'world'
+end
+
+post '/items' do
+ 'created'
+end
+
+# get '/commented' do
+# 'nope'
+# end
+
+class AdminApp < Sinatra::Base
+ delete '/users/:id' do
+ 'deleted'
+ end
+end
+""",
+ )
+ providers = _providers(tmp_path)
+ ids = set(providers.keys())
+ assert ids == {
+ "http::GET::/hello",
+ "http::POST::/items",
+ "http::DELETE::/users/{param}",
+ }
+ assert providers["http::GET::/hello"] == ContractOrigin.ROUTE_REGISTRATION
+
+
+class TestGrapeRoutes:
+ def test_grape_api_structure(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "api.rb",
+ """module Shop
+ class API < Grape::API
+ prefix :api
+ version 'v1', using: :path
+
+ resource :orders do
+ get do
+ # all orders
+ end
+
+ post '/new' do
+ # new order
+ end
+
+ # get '/commented' do
+ # end
+
+ route_param :id do
+ get do
+ # one order
+ end
+
+ delete do
+ # delete order
+ end
+ end
+ end
+ end
+end
+""",
+ )
+ providers = _providers(tmp_path)
+ ids = set(providers.keys())
+ assert ids == {
+ "http::GET::/api/v1/orders",
+ "http::POST::/api/v1/orders/new",
+ "http::GET::/api/v1/orders/{param}",
+ "http::DELETE::/api/v1/orders/{param}",
+ }
+ assert providers["http::GET::/api/v1/orders"] == ContractOrigin.ROUTE_REGISTRATION
+
+ def test_grape_prefix_version_and_inline_end(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "api.rb",
+ """class CustomAPI < Grape::API
+ prefix :api
+ version 'v1', using: :path
+
+ resource :orders do
+ get :status do; end
+
+ route_param :id do
+ get do; end
+ end
+
+ get :ping do end
+ end
+end
+""",
+ )
+ ids = _provider_ids(tmp_path)
+ assert "http::GET::/api/v1/orders/status" in ids
+ assert "http::GET::/api/v1/orders/{param}" in ids
+ assert "http::GET::/api/v1/orders/ping" in ids