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): read and scrub remotes through the forges package (#3355)

Raghav Chamadiya1eb62ca2e425
diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.py
index 41d9c7433..109c844dd 100644
--- a/packages/server/src/repowise/server/routers/overview.py
+++ b/packages/server/src/repowise/server/routers/overview.py
@@ -10,7 +10,6 @@ decisions slice, savings headline, and health KPIs.
from __future__ import annotations
import asyncio
-import configparser
import contextlib
import json
from pathlib import Path
@@ -24,6 +23,7 @@ from repowise.core.analysis.health.aggregation import (
severity_breakdown as health_severity_breakdown,
)
from repowise.core.analysis.health.scoring import hotspot_health
+from repowise.core.forges import read_remote_url, strip_credentials
from repowise.core.persistence import crud
from repowise.core.persistence.crud.analysis.queue_counts import unit_counts
from repowise.core.persistence.models import (
@@ -36,7 +36,6 @@ from repowise.core.persistence.models import (
from repowise.core.stats_highlights import file_mix
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.routers.git import _hotspot_from_row
-from repowise.server.schemas.repository import strip_credentials
from repowise.server.services.attention import build_attention
from repowise.server.services.knowledge_map import (
compute_knowledge_silos,
@@ -96,58 +95,8 @@ def _remote_url(stored_url: str | None, local_path: str | None) -> str | None:
and the UI falls back to initials. The value is sent to the browser, so it
passes through ``strip_credentials`` first.
"""
- return strip_credentials(_read_remote_url(stored_url, local_path))
-
-
-def _read_remote_url(stored_url: str | None, local_path: str | None) -> str | None:
- if stored_url:
- return stored_url
- if not local_path:
- return None
-
- git_path = Path(local_path) / ".git"
- # Worktrees and submodules use a `.git` FILE holding `gitdir: <path>`; the
- # config lives in the main checkout, so follow the pointer before reading.
- if git_path.is_file():
- try:
- pointer = git_path.read_text(encoding="utf-8").strip()
- except OSError:
- return None
- if not pointer.startswith("gitdir:"):
- return None
- resolved = Path(pointer.split(":", 1)[1].strip())
- if not resolved.is_absolute():
- resolved = (Path(local_path) / resolved).resolve()
- # A worktree's gitdir is `<main>/.git/worktrees/<name>`; config is two
- # levels up. Fall back to the pointed-at dir for the submodule case.
- git_path = resolved.parent.parent if resolved.parent.name == "worktrees" else resolved
-
- config_path = git_path / "config"
- if not config_path.is_file():
- return None
-
- # Both flags are load-bearing, not defensive boilerplate:
- #
- # strict=False — git tolerates duplicate keys and writes them routinely. A
- # remote with two `fetch` refspecs is normal, and VS Code writes
- # `vscode-merge-base` twice under a branch section. Strict parsing raises
- # DuplicateOptionError on both, which would mean this project's own
- # checkout never resolves a remote.
- #
- # interpolation=None — ConfigParser expands `%` at get() time, so a
- # perfectly valid remote like `https://user%[email protected]/...`
- # raises InterpolationSyntaxError. Left on, that exception escapes the
- # endpoint and turns the whole Overview into a 404 in order to render an
- # avatar.
- parser = configparser.ConfigParser(strict=False, interpolation=None)
- try:
- parser.read(config_path, encoding="utf-8")
- for section in ('remote "origin"', 'remote "upstream"'):
- if parser.has_option(section, "url"):
- return parser.get(section, "url").strip() or None
- except (OSError, configparser.Error):
- return None
- return None
+ url = stored_url or (read_remote_url(local_path) if local_path else None)
+ return strip_credentials(url) if url else None
def _decision_slim(d: Any) -> dict:
diff --git a/packages/server/src/repowise/server/schemas/repository.py b/packages/server/src/repowise/server/schemas/repository.py
index 44981d6b6..8a46aa7b9 100644
--- a/packages/server/src/repowise/server/schemas/repository.py
+++ b/packages/server/src/repowise/server/schemas/repository.py
@@ -3,66 +3,15 @@
from __future__ import annotations
import json
-import re
from datetime import datetime
from pathlib import Path
from pydantic import BaseModel, field_validator
from repowise.core.docs_mode import DocsMode
+from repowise.core.forges import strip_credentials
from repowise.core.index_scope import load_index_scope
-_URL_SCHEME_RE = re.compile(r"([A-Za-z][A-Za-z0-9+.-]*)://")
-_QUERY_RE = re.compile(r"[?#]")
-_SSH_SCHEMES = frozenset({"ssh", "git+ssh", "ssh+git"})
-
-
-def strip_credentials(url: str | None) -> str | None:
- """Drop secrets from a remote before it leaves the server.
-
- A token can sit in the userinfo (``https://user:glpat-x@host/...``,
- ``git+https://ghp_x@host/...``) or the query (``?private_token=``). Every
- scheme loses its query, fragment and userinfo, except that ssh keeps a bare
- username: ``ssh://git@host/...`` and scp-style ``git@host:path`` name an
- account, not a secret, and the UI's avatar parser expects ``git@``.
- """
- if not url:
- return url
- url = url.strip()
- scheme_match = _URL_SCHEME_RE.match(url)
- if not scheme_match:
- # scp-style `user[:password]@host:path`. Git never sends a password here,
- # but one typed in (even with a `/`) would still reach the browser. A
- # local path (`/srv/a:b@c`, `.\x`, `C:\x`) is not a remote, and without a
- # `host:` after the `@` the `@` is in the path (`host:org/[email protected]`).
- userinfo, at, rest = url.partition("@")
- local = "\\" in userinfo or userinfo[:1] in ("/", ".")
- if at and ":" in userinfo and ":" in rest and not local:
- return f"{userinfo.split(':', 1)[0]}@{rest}"
- return url
- scheme = scheme_match.group(1)
- rest = url[scheme_match.end() :]
- userinfo, hostpart = "", rest
- # Userinfo is found before the query is cut, so a `?` or `#` typed into a
- # password cannot split it and leave a prefix behind.
- head = rest.split("/", 1)[0]
- if "@" in head:
- userinfo, _, host = head.rpartition("@")
- hostpart = host + rest[len(head) :]
- elif ":" in head:
- # An unencoded `/` in a password moves the authority past the first
- # `/`, and `user:123/x` even passes for host:port. Such a password
- # always leaves a `:` before that `/`, so only then is a later `@` the
- # end of the userinfo; `host/[email protected]` keeps its path. Ceiling:
- # `host:8443/[email protected]` loses its host. A port plus a path `@` is
- # rare, and losing a host beats a leak.
- before_query = _QUERY_RE.split(rest, maxsplit=1)[0]
- if "@" in before_query:
- userinfo, _, hostpart = before_query.partition("@")
- hostpart = _QUERY_RE.split(hostpart, maxsplit=1)[0]
- user = userinfo.split(":", 1)[0] if scheme.lower() in _SSH_SCHEMES else ""
- return f"{scheme}://{user + '@' if user else ''}{hostpart}"
-
class RepoCreate(BaseModel):
name: str
@@ -136,7 +85,7 @@ class RepoResponse(BaseModel):
return cls(
id=obj.id, # type: ignore[attr-defined]
name=obj.name, # type: ignore[attr-defined]
- url=strip_credentials(obj.url) or "", # type: ignore[attr-defined]
+ url=strip_credentials(obj.url or ""), # type: ignore[attr-defined]
local_path=local_path,
default_branch=obj.default_branch, # type: ignore[attr-defined]
head_commit=obj.head_commit, # type: ignore[attr-defined]
diff --git a/tests/unit/server/test_overview_remote_url.py b/tests/unit/server/test_overview_remote_url.py
index 552743f6f..7c755eab0 100644
--- a/tests/unit/server/test_overview_remote_url.py
+++ b/tests/unit/server/test_overview_remote_url.py
@@ -56,6 +56,8 @@ def test_follows_a_worktree_gitdir_pointer(tmp_path: Path) -> None:
_write_config(main / ".git", f'[remote "origin"]\n\turl = {_ORIGIN}\n')
worktree_gitdir = main / ".git" / "worktrees" / "feature"
worktree_gitdir.mkdir(parents=True)
+ # git writes this into every linked worktree's gitdir.
+ (worktree_gitdir / "commondir").write_text("../..\n", encoding="utf-8")
linked = tmp_path / "linked"
linked.mkdir()