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.

refactor(server,core): resolve webhook keys and remote names through forges (#3351)

Raghav Chamadiyac1d62ffdbe9d
diff --git a/packages/core/src/repowise/core/git_refs.py b/packages/core/src/repowise/core/git_refs.py
index e790c30fb..42a0adea4 100644
--- a/packages/core/src/repowise/core/git_refs.py
+++ b/packages/core/src/repowise/core/git_refs.py
@@ -14,6 +14,7 @@ from dataclasses import dataclass
from pathlib import PurePosixPath
from .analysis.change_risk.features import _git, split_revspec
+from .forges import parse_remote
__all__ = [
"BranchRef",
@@ -79,10 +80,14 @@ def remote_name(repo_path: str) -> str:
"""The repository's name on its ``origin`` remote, ``""`` when it has none.
The checkout folder is not the name in a worktree or a renamed clone; the
- remote URL's last segment is, for every host's URL shape.
+ remote's repo is. A remote no forge parses (a local path) falls back to
+ its last segment.
"""
- url = _read(repo_path, ["config", "--get", "remote.origin.url"]).rstrip("/")
- name = url.replace("\\", "/").replace(":", "/").rsplit("/", 1)[-1]
+ url = _read(repo_path, ["config", "--get", "remote.origin.url"])
+ ref = parse_remote(url)
+ if ref is not None:
+ return ref.repo
+ name = url.rstrip("/").replace("\\", "/").replace(":", "/").rsplit("/", 1)[-1]
return name[: -len(".git")] if name.endswith(".git") else name
diff --git a/packages/server/src/repowise/server/routers/webhooks.py b/packages/server/src/repowise/server/routers/webhooks.py
index 99ad9bede..1ced9cff6 100644
--- a/packages/server/src/repowise/server/routers/webhooks.py
+++ b/packages/server/src/repowise/server/routers/webhooks.py
@@ -6,13 +6,12 @@ import hashlib
import hmac
import json
import os
-import re
-from urllib.parse import urlparse
from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.forges import canonical_key
from repowise.core.persistence import crud
from repowise.core.persistence.models import Repository
from repowise.server.deps import auth_is_open, get_db_session
@@ -28,27 +27,13 @@ router = APIRouter(prefix="/api/webhooks", tags=["webhooks"])
def _normalize_scm_url(url: str) -> str:
"""Collapse clone / web URL variants to a comparable host/path key.
- Strips scheme, userinfo, ``.git`` suffix, trailing slashes, and lowercases
- the **whole** key (host and path). GitHub and GitLab resolve repo paths
- case-insensitively; the previous ``contains`` match was also case-insensitive
- under SQLite, so preserving path case would silently stop syncing when a
- hand-registered URL differed only in casing from the webhook's ``clone_url``.
+ ``canonical_key`` lowercases the **whole** key (host and path): GitHub and
+ GitLab resolve repo paths case-insensitively, and the previous ``contains``
+ match was also case-insensitive under SQLite, so preserving path case would
+ silently stop syncing when a hand-registered URL differed only in casing
+ from the webhook's ``clone_url``. ``""`` when the URL names no remote.
"""
- raw = (url or "").strip()
- if not raw:
- return ""
- # git@host:path → host/path
- scp = re.match(r"^git@([^:]+):(.+)$", raw)
- if scp:
- host, path = scp.group(1), scp.group(2)
- else:
- parsed = urlparse(raw if "://" in raw else f"https://{raw}")
- host = parsed.hostname or ""
- path = parsed.path or ""
- path = path.strip("/")
- if path.endswith(".git"):
- path = path[: -len(".git")]
- return f"{host}/{path}".rstrip("/").lower()
+ return canonical_key(url) or ""
async def _find_repo_by_scm_url(session: AsyncSession, url: str) -> Repository | None:
diff --git a/tests/unit/server/test_webhooks.py b/tests/unit/server/test_webhooks.py
index 614bd02eb..6f3019a6f 100644
--- a/tests/unit/server/test_webhooks.py
+++ b/tests/unit/server/test_webhooks.py
@@ -401,3 +401,23 @@ def test_normalize_scm_url_variants() -> None:
_normalize_scm_url("https://github.com/org/repowise.git")
)
assert _normalize_scm_url("") == ""
+ assert _normalize_scm_url("/srv/git/repo.git") == ""
+
+
+def test_normalize_scm_url_folds_azure_shapes_to_one_key() -> None:
+ """An Azure push names the repo by one URL shape, the stored repo may use another."""
+ from repowise.server.routers.webhooks import _normalize_scm_url
+
+ key = "dev.azure.com/org/my%20project/_git/repo"
+ for url in (
+ "https://[email protected]/org/My%20Project/_git/repo",
+ "[email protected]:v3/org/My%20Project/repo",
+ "https://org.visualstudio.com/DefaultCollection/My Project/_git/repo",
+ ):
+ assert _normalize_scm_url(url) == key
+
+
+def test_normalize_scm_url_drops_gitlab_web_routes() -> None:
+ from repowise.server.routers.webhooks import _normalize_scm_url
+
+ assert _normalize_scm_url("https://gitlab.com/G/Sub/P/-/tree/main") == "gitlab.com/g/sub/p"
diff --git a/tests/unit/test_git_refs.py b/tests/unit/test_git_refs.py
index 426d8a023..973c5467a 100644
--- a/tests/unit/test_git_refs.py
+++ b/tests/unit/test_git_refs.py
@@ -269,6 +269,9 @@ class TestFindPathRemoval:
"https://github.com/pallets/flask.git",
"[email protected]:pallets/flask.git",
"https://gitlab.example.com/group/sub/flask/",
+ "https://gitlab.com/group/flask/-/tree/main",
+ "[email protected]:v3/org/project/flask",
+ "/srv/git/flask.git",
],
)
def test_remote_name_is_the_last_url_segment(tmp_path: Path, url: str) -> None:
@@ -279,6 +282,12 @@ def test_remote_name_is_the_last_url_segment(tmp_path: Path, url: str) -> None:
assert remote_name(str(root)) == "flask"
+def test_remote_name_unescapes_a_name_with_spaces(tmp_path: Path) -> None:
+ _run(tmp_path, "init", "-b", "main")
+ _run(tmp_path, "remote", "add", "origin", "https://dev.azure.com/org/p/_git/My%20Repo")
+ assert remote_name(str(tmp_path)) == "My Repo"
+
+
def test_remote_name_is_empty_without_a_remote(tmp_path: Path) -> None:
_run(tmp_path, "init", "-b", "main")
assert remote_name(str(tmp_path)) == ""