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): extract C#/Unity HTTP consumers (#507)

Raghav Chamadiya23f824f3692a
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index 81be09f66..f252ec2f0 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -541,7 +541,7 @@ edits. The current coverage:
| Contract | Providers | Consumers |
|----------|-----------|-----------|
-| **HTTP** | Express, FastAPI, Spring, Laravel, Go (gin/echo/chi/net-http), ASP.NET (attribute + minimal), Rust (Axum routes, Actix/Rocket attribute macros) | `fetch` / `axios` (JS/TS), `requests` / `httpx` (Python), `HttpClient` (C#) |
+| **HTTP** | Express, FastAPI, Spring, Laravel, Go (gin/echo/chi/net-http), ASP.NET (attribute + minimal), Rust (Axum routes, Actix/Rocket attribute macros) | `fetch` / `axios` (JS/TS), `requests` / `httpx` (Python), `HttpClient` / wrapper methods / `UnityWebRequest` / Best.HTTP (C#) |
| **gRPC** | `.proto` IDL, Go, Java, Python, NestJS (`@GrpcMethod`), C# (gRPC-dotnet) | Go, Java, Python, C# |
---
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py b/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py
index f0553b785..15f8810f4 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py
@@ -1,4 +1,17 @@
-"""C# HTTP consumer dialect — ``HttpClient`` ``client.GetAsync("/api/users")``."""
+"""C# HTTP consumer dialect.
+
+Recognises the call shapes common in C# / Unity service clients:
+
+* ``HttpClient`` and wrapper methods — ``GetAsync`` / ``PostAsync`` /
+ ``GetRequest<T>`` / ``PostRequest<T>`` (with or without a generic type arg);
+* ``UnityWebRequest.Get/Post/Put/Delete`` with a literal or interpolated URL;
+* Best.HTTP — ``new HTTPRequest(new Uri("..."), HTTPMethods.Get)``.
+
+C# interpolated strings (``$"{_baseUrl}/path/{id}"``) are normalised by
+rewriting ``{expr}`` to the ``${expr}`` template form the shared path helpers
+already understand, so the leading base placeholder is stripped and interior
+expressions collapse to ``{param}``.
+"""
from __future__ import annotations
@@ -6,37 +19,69 @@ import re
from typing import TYPE_CHECKING
from ..langs import CSHARP
-from .dialect import METHODS, build_consumer_contract
+from .dialect import build_consumer_contract
if TYPE_CHECKING:
from repowise.core.workspace.contracts import Contract
from ..base import ScanContext
-# client.GetAsync("/api/users") / PostAsync / PutAsync / DeleteAsync.
-_HTTPCLIENT_RE = re.compile(
- rf"""\.\s*({METHODS})Async\s*\(\s*['"]([^'"]+)['"]""",
+# A C# string-literal argument with an optional interpolation (`$`) / verbatim
+# (`@`) prefix: capture group 1 = prefix, group 2 = the inner text.
+_STR = r"""(\$?@?)"([^"]*)\""""
+
+# HttpClient + wrapper calls: GetAsync / PostAsync / GetRequest<T> / PostRequest.
+# Method verbs are PascalCase (C# convention); the `Async`/`Request` suffix is
+# required so we don't match unrelated `Get("key")` lookups.
+_WRAPPER_RE = re.compile(
+ rf"""\b(Get|Post|Put|Delete|Patch)(?:Async|Request)\s*(?:<[^>]+>)?\s*\(\s*{_STR}"""
+)
+
+# UnityWebRequest.Get(...) / .Post(...) — only when the first arg is a string.
+_UNITY_RE = re.compile(rf"""\bUnityWebRequest\.(Get|Post|Put|Delete|Head)\s*\(\s*{_STR}""")
+
+# Best.HTTP: new HTTPRequest(new Uri("..."), HTTPMethods.Get) — URL first, then
+# the method enum.
+_BESTHTTP_RE = re.compile(
+ rf"""\bnew\s+HTTPRequest\s*\(\s*new\s+Uri\s*\(\s*{_STR}\s*\)\s*,\s*HTTPMethods\.(Get|Post|Put|Delete|Patch|Head)""",
re.IGNORECASE,
)
+def _to_template(prefix: str, text: str) -> str:
+ """Rewrite a C# interpolated string body into ``${expr}`` template form.
+
+ For a non-interpolated string the text is returned unchanged.
+ """
+ if "$" in prefix:
+ return text.replace("{", "${")
+ return text
+
+
class CSharpHttpDialect:
name = "csharp-http"
extensions = CSHARP
def extract(self, ctx: ScanContext) -> list[Contract]:
+ content = ctx.content
out: list[Contract] = []
- for m in _HTTPCLIENT_RE.finditer(ctx.content):
- url = m.group(2)
+
+ def emit(method: str, prefix: str, text: str, client: str) -> None:
+ url = _to_template(prefix, text)
if "/" not in url:
- continue # Avoid matching non-URL strings.
+ return # Not a URL path — skip non-route strings.
out.append(
build_consumer_contract(
- ctx,
- method=m.group(1).upper(),
- url=url,
- client="httpclient",
- confidence=0.70,
+ ctx, method=method.upper(), url=url, client=client, confidence=0.70
)
)
+
+ for m in _WRAPPER_RE.finditer(content):
+ emit(m.group(1), m.group(2), m.group(3), "httpclient")
+ for m in _UNITY_RE.finditer(content):
+ emit(m.group(1), m.group(2), m.group(3), "unitywebrequest")
+ for m in _BESTHTTP_RE.finditer(content):
+ # Group order: prefix, text, method (method trails the URL here).
+ emit(m.group(3), m.group(1), m.group(2), "besthttp")
+
return out
diff --git a/tests/unit/workspace/test_contracts.py b/tests/unit/workspace/test_contracts.py
index a37b6cce3..b31880f24 100644
--- a/tests/unit/workspace/test_contracts.py
+++ b/tests/unit/workspace/test_contracts.py
@@ -245,6 +245,42 @@ class TestHttpExtractor:
assert len(providers) == 1
assert providers[0].contract_id == "http::GET::/systems/nearby"
+ def test_csharp_wrapper_interpolated_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "ApiClient.cs", """
+ public class ApiClient {
+ public async Task Bids() {
+ return await GetRequest<Response>($"{_baseUrl}/vix/my/bids");
+ }
+ }
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "unity-game")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "http::GET::/vix/my/bids"
+ assert consumers[0].meta.get("base_stripped") is True
+
+ def test_csharp_wrapper_interior_param(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "ApiClient.cs", """
+ await PostRequest<Response>($"{_baseUrl}/vix/listings/{id}/bid", payload);
+ GetAsync<Response>($"{_config.ApiBaseUrl}/fleet/summary/{playerId}", token);
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "unity-game")
+ ids = {c.contract_id for c in contracts if c.role == "consumer"}
+ assert "http::POST::/vix/listings/{param}/bid" in ids
+ assert "http::GET::/fleet/summary/{param}" in ids
+
+ def test_csharp_unitywebrequest_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "Net.cs", """
+ UnityWebRequest.Post($"{_baseUrl}/vix/my/bids", form);
+ var req = UnityWebRequest.Get(url);
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "unity-game")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ # The literal Post call is captured; Get(url) with a variable URL is not.
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "http::POST::/vix/my/bids"
+ assert consumers[0].meta["client"] == "unitywebrequest"
+
def test_empty_file(self, tmp_path: Path) -> None:
self._write_file(tmp_path, "empty.py", "")
contracts = HttpExtractor().extract(tmp_path, "svc")