Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(connector): support more git like platform (#3531)

zihenglia1e468b9821a
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index 5b2154c68..297273ed1 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -836,7 +836,7 @@ When ingesting a resource from a URL, OpenViking rejects loopback, link-local, p
| `github_domains` | list[str] | Allowed GitHub hosts (add your GitHub Enterprise host here) | `["github.com", "www.github.com"]` |
| `gitlab_domains` | list[str] | Allowed GitLab hosts (add your self-hosted GitLab host here) | `["gitlab.com", "www.gitlab.com"]` |
| `azure_devops_domains` | list[str] | Allowed Azure DevOps hosts | `["dev.azure.com", "ssh.dev.azure.com", "vs-ssh.visualstudio.com"]` |
-| `code_hosting_domains` | list[str] | Additional generic code-hosting hosts | `["github.com", "gitlab.com"]` |
+| `code_hosting_domains` | list[str] | Allowed generic code-hosting hosts | `["github.com", "gitlab.com", "gitcode.com", "gitee.com", "bitbucket.org", "codeberg.org", "gitea.com", "atomgit.com", "git.sr.ht"]` |
To ingest from private/internal network addresses (e.g. an internal mirror), set the top-level `allow_private_networks` to `true` (disabled by default, so only public addresses are allowed):
@@ -849,7 +849,9 @@ To ingest from private/internal network addresses (e.g. an internal mirror), set
}
```
-The `PermissionDeniedError` message names the exact key to add for the blocked host.
+Use `github_domains`, `gitlab_domains`, or `azure_devops_domains` when the host
+needs those platform-specific URL semantics. Add other Git hosts to
+`code_hosting_domains`.
### rerank
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index e99e19bae..ec1d016d1 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -804,7 +804,7 @@ AST 提取支持:Python、JavaScript/TypeScript、Java、C/C++、Rust、Go、C
| `github_domains` | list[str] | 允许的 GitHub 主机(在此添加你的 GitHub Enterprise 主机) | `["github.com", "www.github.com"]` |
| `gitlab_domains` | list[str] | 允许的 GitLab 主机(在此添加你的自建 GitLab 主机) | `["gitlab.com", "www.gitlab.com"]` |
| `azure_devops_domains` | list[str] | 允许的 Azure DevOps 主机 | `["dev.azure.com", "ssh.dev.azure.com", "vs-ssh.visualstudio.com"]` |
-| `code_hosting_domains` | list[str] | 额外的通用代码托管主机 | `["github.com", "gitlab.com"]` |
+| `code_hosting_domains` | list[str] | 允许的通用代码托管主机 | `["github.com", "gitlab.com", "gitcode.com", "gitee.com", "bitbucket.org", "codeberg.org", "gitea.com", "atomgit.com", "git.sr.ht"]` |
要从私有/内网地址(例如内部镜像)拉取,请将顶层的 `allow_private_networks` 设为 `true`(默认关闭,因此仅允许公网地址):
@@ -817,7 +817,8 @@ AST 提取支持:Python、JavaScript/TypeScript、Java、C/C++、Rust、Go、C
}
```
-`PermissionDeniedError` 的报错信息会指明针对被拦截主机应添加的具体配置键。
+需要 GitHub、GitLab 或 Azure DevOps 专属 URL 语义时,应配置到对应的平台字段;
+其他 Git 主机统一添加到 `code_hosting_domains`。
### rerank
diff --git a/examples/ov.conf.example b/examples/ov.conf.example
index f1efe9fb8..4527f69ad 100644
--- a/examples/ov.conf.example
+++ b/examples/ov.conf.example
@@ -221,7 +221,17 @@
"truncation_strategy": "head",
"warn_on_truncation": true,
"github_raw_domain": "raw.githubusercontent.com",
- "code_hosting_domains": ["github.com", "gitlab.com"],
+ "code_hosting_domains": [
+ "github.com",
+ "gitlab.com",
+ "gitcode.com",
+ "gitee.com",
+ "bitbucket.org",
+ "codeberg.org",
+ "gitea.com",
+ "atomgit.com",
+ "git.sr.ht"
+ ],
"github_domains": ["github.com", "www.github.com"],
"gitlab_domains": ["gitlab.com", "www.gitlab.com"],
},
diff --git a/openviking/parse/accessors/git_accessor.py b/openviking/parse/accessors/git_accessor.py
index d3c8e715b..8b57621c2 100644
--- a/openviking/parse/accessors/git_accessor.py
+++ b/openviking/parse/accessors/git_accessor.py
@@ -15,18 +15,19 @@ import tempfile
import urllib.request
import zipfile
from pathlib import Path, PurePosixPath
-from typing import Any, Optional, Tuple, Union
-from urllib.parse import quote, unquote, urlparse
-
-from openviking.utils import is_github_url, is_gitlab_url, parse_code_hosting_url
+from typing import Optional, Tuple, Union
+from urllib.parse import quote, urlparse
+
+from openviking.utils import (
+ is_github_url,
+ is_gitlab_url,
+ parse_code_hosting_url,
+ parse_git_repo_url,
+)
from openviking.utils.code_hosting_utils import (
- _domain_matches,
- _extract_azure_devops_repo_parts,
- is_code_hosting_url,
is_git_repo_url,
validate_git_ssh_uri,
)
-from openviking_cli.utils.config import get_openviking_config
from openviking_cli.utils.logger import get_logger
from .base import DataAccessor, LocalResource, SourceType
@@ -58,7 +59,7 @@ class GitAccessor(DataAccessor):
Handles:
- git@ SSH URLs
- git://, ssh:// URLs
- - GitHub/GitLab repository URLs (http/https)
+ - Configured code-hosting repository URLs (http/https)
- Local paths ending with .git (NOT .zip - those go to ZipParser)
"""
source_str = str(source)
@@ -68,7 +69,7 @@ class GitAccessor(DataAccessor):
try:
if source_str.startswith("git@"):
validate_git_ssh_uri(source_str)
- return is_code_hosting_url(source_str)
+ return is_git_repo_url(source_str)
except ValueError:
return False
@@ -146,7 +147,7 @@ class GitAccessor(DataAccessor):
branch=branch,
commit=commit,
)
- elif self._is_gitlab_url(repo_url):
+ elif self._can_use_gitlab_zip(repo_url):
# Try GitLab ZIP API first, fall back to git clone
try:
local_dir, repo_name = await self._gitlab_zip_download(
@@ -173,7 +174,7 @@ class GitAccessor(DataAccessor):
commit=commit,
)
else:
- # Non-GitHub/GitLab URL: use git clone
+ # Other configured code-hosting URLs: use git clone
repo_name = await self._git_clone(
repo_url,
temp_local_dir,
@@ -216,77 +217,31 @@ class GitAccessor(DataAccessor):
"""Parse repository source URL to extract branch/commit info."""
branch = kwargs.get("branch") or kwargs.get("ref")
commit = kwargs.get("commit")
- repo_url = source
- if source.startswith(("http://", "https://", "git://", "ssh://")):
- parsed = urlparse(source)
- repo_url = parsed._replace(query="", fragment="").geturl()
- if commit is None or branch is None:
- branch, commit = self._extract_ref_from_url(parsed, branch, commit)
- repo_url = self._normalize_repo_url(repo_url)
- return repo_url, branch, commit
-
- def _extract_ref_from_url(
- self,
- parsed: Any,
- branch: Optional[str],
- commit: Optional[str],
- ) -> Tuple[Optional[str], Optional[str]]:
- """Extract branch/commit from URL path."""
- if parsed.path:
- path_branch, path_commit = self._parse_ref_from_path(parsed.path)
- commit = path_commit or commit
- # If commit is present in path, ignore branch entirely
+ parsed_source = parse_git_repo_url(source)
+ if parsed_source is None:
+ if source.startswith(("git@", "http://", "https://", "git://", "ssh://")):
+ raise ValueError(f"Unsupported Git repository URL: {source}")
+ return source, branch, commit
+
+ if commit is None or branch is None:
+ commit = parsed_source.commit or commit
+ # Preserve the existing precedence: a commit encoded in the URL
+ # overrides branch selection, while an explicit branch overrides a
+ # branch encoded in the URL.
if commit:
branch = None
else:
- branch = branch or path_branch
- return branch, commit
-
- def _parse_ref_from_path(self, path: str) -> Tuple[Optional[str], Optional[str]]:
- """Parse ref from URL path components."""
- parts = [p for p in path.split("/") if p]
- branch = None
- commit = None
- if "commit" in parts:
- idx = parts.index("commit")
- if idx + 1 < len(parts):
- commit = parts[idx + 1]
- if "tree" in parts:
- idx = parts.index("tree")
- if idx + 1 < len(parts):
- ref = unquote(parts[idx + 1])
- if self._looks_like_sha(ref):
- commit = ref
- else:
- branch = ref
- return branch, commit
-
- @staticmethod
- def _looks_like_sha(ref: str) -> bool:
- """Return True if ref looks like a git commit SHA (7-40 hex chars)."""
- return 7 <= len(ref) <= 40 and all(c in "0123456789abcdefABCDEF" for c in ref)
+ branch = branch or parsed_source.branch
+ return parsed_source.clone_url, branch, commit
def _normalize_repo_url(self, url: str) -> str:
- """Normalize repository URL to base form."""
- if url.startswith(("http://", "https://", "git://", "ssh://")):
- parsed = urlparse(url)
- path_parts = [p for p in parsed.path.split("/") if p]
- base_parts = path_parts
- git_index = next((i for i, p in enumerate(path_parts) if p.endswith(".git")), None)
- if git_index is not None:
- base_parts = path_parts[: git_index + 1]
-
- config = get_openviking_config()
- if _domain_matches(parsed, getattr(config.code, "azure_devops_domains", [])):
- azure_repo_parts = _extract_azure_devops_repo_parts(path_parts)
- if azure_repo_parts:
- base_parts = path_parts[: len(azure_repo_parts) + 1]
-
- if _domain_matches(parsed, config.code.github_domains + config.code.gitlab_domains):
- base_parts = path_parts[:2]
- base_path = "/" + "/".join(base_parts)
- return parsed._replace(path=base_path, query="", fragment="").geturl()
- return url
+ """Normalize a validated repository URL to a cloneable base form."""
+ parsed_source = parse_git_repo_url(url)
+ if parsed_source is not None:
+ return parsed_source.clone_url
+ if not url.startswith(("git@", "http://", "https://", "git://", "ssh://")):
+ return url
+ raise ValueError(f"Unsupported Git repository URL: {url}")
def _get_repo_name(self, url: str) -> str:
"""Get repository name with organization for GitHub/GitLab URLs.
@@ -359,6 +314,13 @@ class GitAccessor(DataAccessor):
"""Return True for gitlab.com URLs (supports ZIP archive API)."""
return is_gitlab_url(url)
+ def _can_use_gitlab_zip(self, url: str) -> bool:
+ """Return True when the URL fits the two-segment GitLab ZIP helper."""
+ if not self._is_gitlab_url(url):
+ return False
+ path_parts = [p for p in urlparse(url).path.split("/") if p]
+ return len(path_parts) == 2
+
async def _git_clone(
self,
url: str,
diff --git a/openviking/parse/parsers/code/code.py b/openviking/parse/parsers/code/code.py
index 89f2538f5..4890cc285 100644
--- a/openviking/parse/parsers/code/code.py
+++ b/openviking/parse/parsers/code/code.py
@@ -147,7 +147,7 @@ class CodeRepositoryParser(BaseParser):
commit = source_meta.get("repo_commit")
# If repo_name is still default, try to extract from original source
- # original_source is the full GitHub/GitLab URL that the user provided
+ # original_source is the full code-hosting URL that the user provided
# (e.g. "https://github.com/volcengine/OpenViking")
if repo_name == "repository":
original_source = kwargs.get("original_source") or source_meta.get(
@@ -193,7 +193,7 @@ class CodeRepositoryParser(BaseParser):
# source_path is CRITICAL:
# 1. TreeBuilder uses source_path to parse org/repo via parse_code_hosting_url()
# 2. If source_path is a local path (like /tmp/.../OpenViking), parsing fails
- # 3. If source_path is the original GitHub URL (https://github.com/volcengine/OpenViking),
+ # 3. If source_path is the original code-hosting URL,
# TreeBuilder can correctly extract "volcengine/OpenViking"
#
# Priority order:
@@ -306,7 +306,7 @@ class CodeRepositoryParser(BaseParser):
return url
def _get_repo_name(self, url: str) -> str:
- """Get repository name with organization for GitHub/GitLab URLs.
+ """Get repository name with organization for configured code-hosting URLs.
For https://github.com/volcengine/OpenViking, returns "volcengine/OpenViking"
For other URLs, falls back to just the repo name.
@@ -323,7 +323,7 @@ class CodeRepositoryParser(BaseParser):
elif ":" in url and not url.startswith("file://"):
name_source = url.split(":", 1)[1]
- # Original logic for non-GitHub/GitLab URLs
+ # Fallback for URLs outside the configured code-hosting domains
name = name_source.rstrip("/").split("/")[-1]
if name.endswith(".git"):
name = name[:-4]
diff --git a/openviking/parse/parsers/directory.py b/openviking/parse/parsers/directory.py
index fd9447c97..b1056aea5 100644
--- a/openviking/parse/parsers/directory.py
+++ b/openviking/parse/parsers/directory.py
@@ -103,7 +103,7 @@ class DirectoryParser(BaseParser):
# Don't add git metadata if we already have _source_meta from DataAccessor
# This is crucial:
# 1. _source_meta already contains repo_name in org/repo format from GitAccessor
- # 2. kwargs also has original_source with the full GitHub/GitLab URL
+ # 2. kwargs also has original_source with the full code-hosting URL
# 3. Calling _add_git_metadata would overwrite repo_name with just directory name
# and lose the org prefix!
if "_source_meta" not in kwargs:
diff --git a/openviking/utils/__init__.py b/openviking/utils/__init__.py
index 8213db8a7..ebe168f08 100644
--- a/openviking/utils/__init__.py
+++ b/openviking/utils/__init__.py
@@ -3,12 +3,14 @@
"""Utility functions and helpers."""
from openviking.utils.code_hosting_utils import (
+ ParsedGitRepoURL,
is_code_hosting_blob_url,
is_code_hosting_url,
is_git_repo_url,
is_github_url,
is_gitlab_url,
parse_code_hosting_url,
+ parse_git_repo_url,
validate_git_ssh_uri,
)
from openviking.utils.time_utils import get_current_timestamp
@@ -26,7 +28,9 @@ __all__ = [
"parse_json_from_response",
"parse_json_to_model",
"run_async",
+ "ParsedGitRepoURL",
"parse_code_hosting_url",
+ "parse_git_repo_url",
"is_github_url",
"is_gitlab_url",
"is_code_hosting_url",
diff --git a/openviking/utils/code_hosting_utils.py b/openviking/utils/code_hosting_utils.py
index 1cb00d826..55fd16f42 100644
--- a/openviking/utils/code_hosting_utils.py
+++ b/openviking/utils/code_hosting_utils.py
@@ -7,13 +7,201 @@ This module provides shared functionality for parsing URLs from code hosting
platforms like GitHub and GitLab.
"""
-from typing import Optional
+from collections.abc import Iterable
+from dataclasses import dataclass
+from typing import Literal, Optional
from urllib.parse import ParseResult, parse_qs, unquote, urlparse
from openviking_cli.utils.config import get_openviking_config
+# Platform-specific domain lists select specialized behavior. All other
+# supported Git hosts live in the generic ``code_hosting_domains`` allowlist.
+_CODE_HOSTING_DOMAIN_CONFIG_FIELDS = (
+ "github_domains",
+ "gitlab_domains",
+ "azure_devops_domains",
+ "code_hosting_domains",
+)
+
+# Repo-page path segments that mark an http(s) URL as a browse page rather
+# than a cloneable repository (github.com/org/repo/issues/123 etc.).
+_NON_REPO_PATH_SEGMENTS = frozenset(
+ {
+ "blob",
+ "commit",
+ "commits",
+ "issues",
+ "merge_requests",
+ "pull",
+ "pulls",
+ "raw",
+ "releases",
+ "wiki",
+ }
+)
+
+# Hosting-specific browse routes for public platforms in the generic domain
+# category. These are URL parsing profiles, not additional allowlists: the host
+# must still be configured in ``code_hosting_domains`` before they apply.
+_KNOWN_PLATFORM_NON_REPO_PATH_SEGMENTS = {
+ "gitcode.com": frozenset({"blob", "raw"}),
+ "bitbucket.org": frozenset({"src"}),
+ "codeberg.org": frozenset({"src"}),
+ "gitea.com": frozenset({"src"}),
+}
+
+# Public platforms where ``owner/repo/tree/ref/...`` is an unambiguous browse
+# route. This profile must not be applied to generic configured Git hosts:
+# there, a nested repository can legitimately contain a ``tree`` namespace.
+_KNOWN_PLATFORM_TREE_ROUTE_HOSTS = frozenset(
+ {"atomgit.com", "git.sr.ht", "gitcode.com", "gitee.com"}
+)
+
+# Top-level namespaces reserved by each hosting platform. Keeping these rules
+# attached to platform categories prevents generic custom hosts from inheriting
+# unrelated GitHub/GitLab route semantics.
+_COMMON_RESERVED_TOP_LEVEL_SEGMENTS = frozenset(
+ {"dashboard", "help", "join", "login", "new", "search", "settings"}
+)
+_PLATFORM_RESERVED_TOP_LEVEL_SEGMENTS = {
+ "github_domains": _COMMON_RESERVED_TOP_LEVEL_SEGMENTS
+ | frozenset(
+ {
+ "apps",
+ "codespaces",
+ "collections",
+ "enterprise",
+ "features",
+ "issues",
+ "marketplace",
+ "notifications",
+ "orgs",
+ "pricing",
+ "pulls",
+ "sponsors",
+ "topics",
+ "trending",
+ }
+ ),
+ "gitlab_domains": _COMMON_RESERVED_TOP_LEVEL_SEGMENTS
+ | frozenset(
+ {
+ "-",
+ "admin",
+ "explore",
+ "groups",
+ "users",
+ }
+ ),
+}
+
+# Public-platform URL profiles are parsing rules, not an allowlist. A host must
+# still be present in one of the configured domain lists before these apply.
+_KNOWN_PLATFORM_RESERVED_TOP_LEVEL_SEGMENTS = {
+ "gitcode.com": _COMMON_RESERVED_TOP_LEVEL_SEGMENTS | frozenset({"explore"}),
+ "gitee.com": _COMMON_RESERVED_TOP_LEVEL_SEGMENTS
+ | frozenset({"enterprise", "explore", "organizations"}),
+ "bitbucket.org": _COMMON_RESERVED_TOP_LEVEL_SEGMENTS | frozenset({"account", "product"}),
+ "codeberg.org": _COMMON_RESERVED_TOP_LEVEL_SEGMENTS | frozenset({"explore"}),
+ "gitea.com": _COMMON_RESERVED_TOP_LEVEL_SEGMENTS | frozenset({"explore"}),
+ "atomgit.com": _COMMON_RESERVED_TOP_LEVEL_SEGMENTS | frozenset({"explore"}),
+}
+
+# Generic Git hosts may use nested namespaces when a clone URL ends in .git.
+# GitHub is explicitly excluded because its archive fast path is owner/repo
+# only; accepting a nested URL would fetch a different repository.
+_NESTED_REPOSITORY_DOMAIN_CONFIG_FIELDS = (
+ "gitlab_domains",
+ "code_hosting_domains",
+)
+
+
+def _get_code_config():
+ return get_openviking_config().code
+
+
+def _get_domains_for_field(field_name: str, code_config=None) -> list[str]:
+ """Return one configured platform-domain category."""
+ if code_config is None:
+ code_config = _get_code_config()
+ return list(getattr(code_config, field_name, []) or [])
+
+
+def get_configured_code_hosting_domains(code_config=None) -> set[str]:
+ """Return the union of every platform-specific and generic domain list."""
+ if code_config is None:
+ code_config = _get_code_config()
+
+ domains: set[str] = set()
+ for field_name in _CODE_HOSTING_DOMAIN_CONFIG_FIELDS:
+ domains.update(domain.lower() for domain in _get_domains_for_field(field_name, code_config))
+ return domains
+
+
+def _matches_domain_field(parsed: ParseResult, field_name: str) -> bool:
+ return _domain_matches(parsed, _get_domains_for_field(field_name))
+
+
+def _get_reserved_top_level_segments(parsed: ParseResult) -> frozenset[str]:
+ """Return reserved first-path segments for the URL's configured platform."""
+ reserved: set[str] = set()
+ for field_name, segments in _PLATFORM_RESERVED_TOP_LEVEL_SEGMENTS.items():
+ if _matches_domain_field(parsed, field_name):
+ reserved.update(segments)
+ reserved.update(
+ _KNOWN_PLATFORM_RESERVED_TOP_LEVEL_SEGMENTS.get(
+ (parsed.hostname or "").lower(), frozenset()
+ )
+ )
+ return frozenset(reserved)
+
+
+def _get_known_platform_non_repo_segments(parsed: ParseResult) -> frozenset[str]:
+ """Return browse-route markers for a configured public platform."""
+ return _KNOWN_PLATFORM_NON_REPO_PATH_SEGMENTS.get((parsed.hostname or "").lower(), frozenset())
+
+
+def _find_known_platform_non_repo_segment(
+ parsed: ParseResult,
+ path_parts: list[str],
+) -> Optional[int]:
+ """Return the index of a known platform browse-route marker, if any.
+
+ Known public platforms can support nested repository paths, so their route
+ marker is not necessarily the third path segment. Generic configured hosts
+ intentionally do not use this scan because a nested namespace may
+ legitimately be named ``blob`` or ``src``.
+ """
+ markers = _get_known_platform_non_repo_segments(parsed)
+ if not markers:
+ return None
+ return next(
+ (index for index, part in enumerate(path_parts[2:], start=2) if part in markers),
+ None,
+ )
+
+
+def _supports_nested_repository_host(host: str) -> bool:
+ return _supports_nested_repository_path(urlparse(f"ssh://{host}"))
+
-def _domain_matches(parsed: ParseResult, domains: list[str]) -> bool:
+def _supports_nested_repository_path(parsed: ParseResult) -> bool:
+ return bool(
+ parsed.hostname
+ and not _matches_domain_field(parsed, "github_domains")
+ and any(
+ _matches_domain_field(parsed, field_name)
+ for field_name in _NESTED_REPOSITORY_DOMAIN_CONFIG_FIELDS
+ )
+ )
+
+
+def _looks_like_commit_sha(ref: str) -> bool:
+ """Return True if ref looks like a git commit SHA (7-40 hex chars)."""
+ return 7 <= len(ref) <= 40 and all(c in "0123456789abcdefABCDEF" for c in ref)
+
+
+def _domain_matches(parsed: ParseResult, domains: Iterable[str]) -> bool:
"""Return True when parsed URL host matches configured domains.
``urlparse().netloc`` includes optional userinfo and port values. Repository
@@ -52,20 +240,11 @@ def _extract_host(url: str) -> str:
def _get_all_domains() -> list[str]:
- config = get_openviking_config()
- return list(
- set(
- config.code.github_domains
- + config.code.gitlab_domains
- + getattr(config.code, "azure_devops_domains", [])
- + config.code.code_hosting_domains
- )
- )
+ return sorted(get_configured_code_hosting_domains())
def _get_azure_devops_domains() -> set[str]:
- config = get_openviking_config()
- return set(getattr(config.code, "azure_devops_domains", []))
+ return set(_get_domains_for_field("azure_devops_domains"))
def _sanitize_segment(segment: str) -> str:
@@ -105,6 +284,287 @@ def _is_azure_devops_browse_url(query: str) -> bool:
return "path" in parse_qs(query, keep_blank_values=True)
+@dataclass(frozen=True)
+class ParsedGitRepoURL:
+ """A validated Git source normalized for cloning and repository metadata."""
+
+ clone_url: str
+ repo_path: str
+ route_kind: Literal["clone", "tree", "commit"]
+ branch: Optional[str] = None
+ commit: Optional[str] = None
+
+
+def _strip_repo_git_suffix(repo_parts: list[str]) -> Optional[list[str]]:
+ """Return repository identity parts with only the final ``.git`` removed."""
+ if not repo_parts:
+ return None
+
+ normalized = list(repo_parts)
+ if normalized[-1].endswith(".git"):
+ normalized[-1] = normalized[-1][:-4]
+ if not normalized[-1]:
+ return None
+ return normalized
+
+
+def _repo_path_from_parts(repo_parts: list[str]) -> Optional[str]:
+ normalized = _strip_repo_git_suffix(repo_parts)
+ if normalized is None:
+ return None
+ return "/".join(_sanitize_segment(part) for part in normalized)
+
+
+def _build_url_git_result(
+ parsed: ParseResult,
+ repo_parts: list[str],
+ *,
+ clone_parts: Optional[list[str]] = None,
+ route_kind: Literal["clone", "tree", "commit"] = "clone",
+ branch: Optional[str] = None,
+ commit: Optional[str] = None,
+) -> Optional[ParsedGitRepoURL]:
+ """Build a strict result for URL-style Git sources."""
+ repo_path = _repo_path_from_parts(repo_parts)
+ if repo_path is None:
+ return None
+
+ clone_path = "/" + "/".join(clone_parts or repo_parts)
+ clone_url = parsed._replace(path=clone_path, params="", query="", fragment="").geturl()
+ return ParsedGitRepoURL(
+ clone_url=clone_url,
+ repo_path=repo_path,
+ route_kind=route_kind,
+ branch=branch,
+ commit=commit,
+ )
+
+
+def _build_scp_git_result(
+ url: str,
+ repo_parts: list[str],
+ *,
+ identity_parts: Optional[list[str]] = None,
+) -> Optional[ParsedGitRepoURL]:
+ """Build a strict result for scp-style ``git@host:path`` sources."""
+ repo_path = _repo_path_from_parts(identity_parts or repo_parts)
+ if repo_path is None:
+ return None
+ return ParsedGitRepoURL(clone_url=url, repo_path=repo_path, route_kind="clone")
+
+
+def _parse_scp_git_repo_url(url: str) -> Optional[ParsedGitRepoURL]:
+ """Parse a strict scp-style Git repository URL."""
+ rest = url[4:]
+ if ":" not in rest:
+ return None
+
+ host, path = rest.split(":", 1)
+ host = host.strip().lower()
+ if not host or host not in get_configured_code_hosting_domains():
+ return None
+
+ path_parts = [part for part in path.split("/") if part]
+ if host in _get_azure_devops_domains():
+ azure_repo_parts = _extract_azure_devops_ssh_repo_parts(path_parts)
+ if azure_repo_parts is None:
+ return None
+ return _build_scp_git_result(
+ url,
+ path_parts,
+ identity_parts=azure_repo_parts,
+ )
+
+ if not path_parts:
+ return None
+
+ # The scp-style form is an explicit Git transport, not an HTTP browse URL.
+ # Preserve the complete path and let the remote decide whether it exists.
+ return _build_scp_git_result(url, path_parts)
+
+
+def _is_known_platform_tree_route(parsed: ParseResult, path_parts: list[str]) -> bool:
+ """Return whether the URL uses a known platform's owner/repo tree route."""
+ return (
+ (parsed.hostname or "").lower() in _KNOWN_PLATFORM_TREE_ROUTE_HOSTS
+ and len(path_parts) >= 3
+ and path_parts[2] == "tree"
+ )
+
+
+def parse_git_repo_url(url: str) -> Optional[ParsedGitRepoURL]:
+ """Parse a whitelisted, cloneable Git source URL.
+
+ Unlike :func:`parse_code_hosting_url`, this is a strict ingress parser.
+ Browse pages and ambiguous paths return ``None``. Accepted tree/commit
+ snapshot URLs are normalized to a cloneable base URL with their ref
+ returned separately. Explicit Git transports preserve any non-empty
+ repository path because they do not share HTTP browse-route ambiguity.
+ """
+ if url.startswith("git@"):
+ return _parse_scp_git_repo_url(url)
+
+ if not url.startswith(("http://", "https://", "git://", "ssh://")):
+ return None
+
+ parsed = urlparse(url)
+ if not _domain_matches(parsed, _get_all_domains()):
+ return None
+
+ path_parts = [part for part in parsed.path.split("/") if part]
+
+ # Azure DevOps has a distinct repository grammar for both HTTPS and SSH.
+ if _domain_matches(parsed, list(_get_azure_devops_domains())):
+ azure_repo_parts = _extract_azure_devops_repo_parts(path_parts)
+ if azure_repo_parts is not None:
+ if _is_azure_devops_browse_url(parsed.query):
+ return None
+ return _build_url_git_result(
+ parsed,
+ azure_repo_parts,
+ clone_parts=path_parts,
+ )
+
+ azure_ssh_repo_parts = _extract_azure_devops_ssh_repo_parts(path_parts)
+ if azure_ssh_repo_parts is not None:
+ return _build_url_git_result(
+ parsed,
+ azure_ssh_repo_parts,
+ clone_parts=path_parts,
+ )
+ return None
+
+ if not path_parts:
+ return None
+
+ # Explicit Git transports have no browser-route ambiguity. Preserve their
+ # complete repository path instead of applying HTTP-only tree/blob/reserved
+ # namespace rules. Azure DevOps remains handled by its grammar above.
+ if parsed.scheme in {"git", "ssh"}:
+ return _build_url_git_result(parsed, path_parts)
+
+ if path_parts[0].lower() in _get_reserved_top_level_segments(parsed):
+ return None
+ if len(path_parts) == 1:
+ return None
+
+ # GitLab's /-/ separator is unambiguous: everything before it is the
+ # possibly nested repository path, and everything after it is a web route.
+ dash_index = (
+ path_parts.index("-")
+ if _matches_domain_field(parsed, "gitlab_domains") and "-" in path_parts
+ else -1
+ )
+ if dash_index >= 2:
+ repo_parts = path_parts[:dash_index]
+ browse_parts = path_parts[dash_index + 1 :]
+ if len(browse_parts) == 2 and browse_parts[0] == "tree":
+ ref = unquote(browse_parts[1])
+ if not ref:
+ return None
+ if _looks_like_commit_sha(ref):
+ return _build_url_git_result(
+ parsed,
+ repo_parts,
+ route_kind="tree",
+ commit=ref,
+ )
+ return _build_url_git_result(
+ parsed,
+ repo_parts,
+ route_kind="tree",
+ branch=ref,
+ )
+ if (
+ len(browse_parts) == 2
+ and browse_parts[0] == "commit"
+ and _looks_like_commit_sha(browse_parts[1])
+ ):
+ return _build_url_git_result(
+ parsed,
+ repo_parts,
+ route_kind="commit",
+ commit=browse_parts[1],
+ )
+ return None
+
+ # A known platform's owner/repo/tree/ref route takes precedence over a
+ # trailing .git filename. This rejects browse files such as config.git.
+ if _is_known_platform_tree_route(parsed, path_parts):
+ if len(path_parts) != 4:
+ return None
+ ref = unquote(path_parts[3])
+ if not ref:
+ return None
+ if _looks_like_commit_sha(ref):
+ return _build_url_git_result(
+ parsed,
+ path_parts[:2],
+ route_kind="tree",
+ commit=ref,
+ )
+ return _build_url_git_result(
+ parsed,
+ path_parts[:2],
+ route_kind="tree",
+ branch=ref,
+ )
+
+ # Exact commit routes are accepted only when the pin is SHA-shaped.
+ if len(path_parts) == 4 and path_parts[2] == "commit" and _looks_like_commit_sha(path_parts[3]):
+ return _build_url_git_result(
+ parsed,
+ path_parts[:2],
+ route_kind="commit",
+ commit=path_parts[3],
+ )
+
+ if _find_known_platform_non_repo_segment(parsed, path_parts) is not None:
+ return None
+
+ has_git_suffix = path_parts[-1].endswith(".git")
+ if (
+ len(path_parts) >= 3
+ and path_parts[2] in _NON_REPO_PATH_SEGMENTS
+ and not (has_git_suffix and len(path_parts) == 3)
+ ):
+ return None
+
+ # A trailing .git is the strong clone signal. It wins over generic route
+ # words on nested-capable hosts, so a subgroup literally named "tree" is
+ # not mistaken for a branch.
+ if has_git_suffix:
+ if len(path_parts) == 2 or (
+ len(path_parts) > 2 and _supports_nested_repository_path(parsed)
+ ):
+ return _build_url_git_result(parsed, path_parts)
+ return None
+
+ if len(path_parts) == 2:
+ return _build_url_git_result(parsed, path_parts)
+
+ # Without the strong .git signal, only an exact single-segment tree ref is
+ # accepted. Longer paths are ambiguous with slashed refs or file browsing.
+ if len(path_parts) == 4 and path_parts[2] == "tree":
+ ref = unquote(path_parts[3])
+ if not ref:
+ return None
+ if _looks_like_commit_sha(ref):
+ return _build_url_git_result(
+ parsed,
+ path_parts[:2],
+ route_kind="tree",
+ commit=ref,
+ )
+ return _build_url_git_result(
+ parsed,
+ path_parts[:2],
+ route_kind="tree",
+ branch=ref,
+ )
+ return None
+
+
def parse_code_hosting_url(url: str) -> Optional[str]:
"""Parse code hosting platform URL to get org/repo path.
@@ -116,6 +576,14 @@ def parse_code_hosting_url(url: str) -> Optional[str]:
org/repo path like "volcengine/OpenViking" or None if not a valid
code hosting URL
"""
+ parsed_git_url = parse_git_repo_url(url)
+ # Keep this metadata helper's historical owner/repo contract. The strict
+ # ingress parser accepts single-segment SSH/git repositories for cloning,
+ # while callers that need a namespaced repository identity continue to use
+ # their existing fallback naming.
+ if parsed_git_url is not None and "/" in parsed_git_url.repo_path:
+ return parsed_git_url.repo_path
+
all_domains = _get_all_domains()
# Handle git@ SSH URLs: git@host:org/repo.git
if url.startswith("git@"):
@@ -133,14 +601,14 @@ def parse_code_hosting_url(url: str) -> Optional[str]:
)
if len(path_parts) < 2:
return None
- # Take only first 2 segments (consistent with HTTP branch)
- org = path_parts[0]
- repo = path_parts[1]
- if repo.endswith(".git"):
- repo = repo[:-4]
- org = _sanitize_segment(org)
- repo = _sanitize_segment(repo)
- return f"{org}/{repo}"
+ # Only platforms configured with nested namespaces keep every segment.
+ if path_parts[-1].endswith(".git") and _supports_nested_repository_host(host_part):
+ repo_parts = list(path_parts)
+ else:
+ repo_parts = path_parts[:2]
+ if repo_parts[-1].endswith(".git"):
+ repo_parts[-1] = repo_parts[-1][:-4]
+ return "/".join(_sanitize_segment(part) for part in repo_parts)
if not url.startswith(("http://", "https://", "git://", "ssh://")):
return None
@@ -158,17 +626,36 @@ def parse_code_hosting_url(url: str) -> Optional[str]:
)
return None
+ # GitLab "/-/" browse separator: everything before "-" is the full
+ # (possibly nested) repository path.
+ from_dash_separator = False
+ if (
+ _matches_domain_field(parsed, "gitlab_domains")
+ and "-" in path_parts
+ and path_parts.index("-") >= 2
+ ):
+ path_parts = path_parts[: path_parts.index("-")]
+ from_dash_separator = True
+
# For code hosting URLs with org/repo structure
if _domain_matches(parsed, all_domains) and len(path_parts) >= 2:
- # Take first two parts: org/repo
- org = path_parts[0]
- repo = path_parts[1]
- if repo.endswith(".git"):
- repo = repo[:-4]
- # Sanitize both parts
- org = _sanitize_segment(org)
- repo = _sanitize_segment(repo)
- return f"{org}/{repo}"
+ has_git_suffix = path_parts[-1].endswith(".git")
+ known_browse_index = _find_known_platform_non_repo_segment(parsed, path_parts)
+ # Segments between repo and filename that mark a browse URL
+ # (org/repo/blob/main/file.git must not be taken as a nested path).
+ browse_markers = set(path_parts[2:-1]) & (_NON_REPO_PATH_SEGMENTS | {"tree"})
+ if known_browse_index is not None:
+ repo_parts = path_parts[:known_browse_index]
+ elif from_dash_separator or (
+ has_git_suffix and not browse_markers and _supports_nested_repository_path(parsed)
+ ):
+ repo_parts = list(path_parts)
+ else:
+ # Plain browser URL: take first two parts (org/repo)
+ repo_parts = path_parts[:2]
+ if repo_parts[-1].endswith(".git"):
+ repo_parts[-1] = repo_parts[-1][:-4]
+ return "/".join(_sanitize_segment(part) for part in repo_parts)
return None
@@ -270,7 +757,24 @@ def is_git_repo_url(url: str) -> bool:
"""Strict check for cloneable git repository URLs.
Distinguishes repo URLs (github.com/org/repo) from non-repo URLs
- (github.com/org/repo/issues/123).
+ (github.com/org/repo/issues/123). The domain must always be whitelisted.
+
+ Accepted http(s) shapes:
+ - owner/repo, with or without a .git suffix
+ - nested clone URLs ending in .git, e.g. GitLab subgroups or
+ GitCode/Gitee nested groups (host/group/subgroup/repo.git)
+ - browser tree URLs with an unambiguous single-segment ref:
+ owner/repo/tree/<ref> and GitLab-style group/.../repo/-/tree/<ref>
+ - commit pins: owner/repo/commit/<sha> and group/.../repo/-/commit/<sha>
+ - Azure DevOps org/project/_git/repo (browse URLs with ?path= excluded)
+
+ Explicit git@, ssh://, and git:// transports accept any non-empty path on
+ a configured host. Their complete path is preserved as the repository
+ identity.
+
+ Rejected: platform-reserved top-level pages (topics, orgs, groups, ...),
+ repo browse pages (issues, pull, blob, ...), and Azure DevOps URLs
+ without the _git form.
Args:
url: URL to check
@@ -278,54 +782,4 @@ def is_git_repo_url(url: str) -> bool:
Returns:
True if the URL points to a cloneable git repository
"""
- # git@/ssh://git:// protocols: always a repo if the domain matches
- if url.startswith(("git@", "ssh://", "git://")):
- return is_code_hosting_url(url)
-
- # http/https: check domain AND require exactly 2 path parts (owner/repo)
- if url.startswith(("http://", "https://")):
- config = get_openviking_config()
- all_domains = _get_all_domains()
- parsed = urlparse(url)
- if not _domain_matches(parsed, all_domains):
- return False
- path_parts = [p for p in parsed.path.split("/") if p]
- # Strip .git suffix from last part for counting
- if path_parts and path_parts[-1].endswith(".git"):
- path_parts[-1] = path_parts[-1][:-4]
-
- if _extract_host(url) in _get_azure_devops_domains():
- azure_repo_parts = _extract_azure_devops_repo_parts(path_parts)
- if azure_repo_parts:
- if _is_azure_devops_browse_url(parsed.query):
- return False
- return True
-
- non_repo_paths = {
- "blob",
- "commit",
- "commits",
- "issues",
- "merge_requests",
- "pull",
- "pulls",
- "raw",
- "releases",
- "wiki",
- }
- if (
- _extract_host(url) in config.code.github_domains + config.code.gitlab_domains
- and len(path_parts) >= 3
- and path_parts[2] in non_repo_paths
- ):
- return False
-
- # owner/repo
- if len(path_parts) == 2:
- return True
- # owner/repo/tree/<ref> (branch name or commit SHA)
- if len(path_parts) == 4 and path_parts[2] == "tree":
- return True
- return False
-
- return False
+ return parse_git_repo_url(url) is not None
diff --git a/openviking/utils/network_guard.py b/openviking/utils/network_guard.py
index e32e7407b..14121a820 100644
--- a/openviking/utils/network_guard.py
+++ b/openviking/utils/network_guard.py
@@ -10,8 +10,10 @@ from collections.abc import Callable
from typing import Optional
from urllib.parse import urlparse
+from openviking.utils.code_hosting_utils import get_configured_code_hosting_domains
from openviking_cli.exceptions import PermissionDeniedError
from openviking_cli.utils.config import get_openviking_config
+from openviking_cli.utils.config.parser_config import CodeHostingConfig
RequestValidator = Callable[[str], None]
@@ -23,33 +25,16 @@ _LOCAL_HOSTNAMES = {
def _get_allowed_code_hosting_domains() -> set[str]:
"""Get allowed code hosting domains from config."""
- allowed = set()
try:
config = get_openviking_config()
- # Add configured code hosting domains
if hasattr(config, "code"):
- if hasattr(config.code, "github_domains"):
- allowed.update(config.code.github_domains)
- if hasattr(config.code, "gitlab_domains"):
- allowed.update(config.code.gitlab_domains)
- if hasattr(config.code, "azure_devops_domains"):
- allowed.update(config.code.azure_devops_domains)
- if hasattr(config.code, "code_hosting_domains"):
- allowed.update(config.code.code_hosting_domains)
+ return get_configured_code_hosting_domains(config.code)
except Exception:
- # If config can't be loaded, use defaults
- allowed.update(
- {
- "github.com",
- "www.github.com",
- "gitlab.com",
- "www.gitlab.com",
- "dev.azure.com",
- "ssh.dev.azure.com",
- "vs-ssh.visualstudio.com",
- }
- )
- return allowed
+ pass
+
+ # Derive the fallback from the config object instead of maintaining a
+ # second hard-coded allowlist in the network layer.
+ return get_configured_code_hosting_domains(CodeHostingConfig())
def _is_allow_private_networks() -> bool:
@@ -115,7 +100,7 @@ def ensure_public_remote_target(source: str) -> None:
Skips validation if:
- allow_private_networks is True in config
- - Host is in configured github_domains/gitlab_domains/azure_devops_domains/code_hosting_domains
+ - Host is in any configured code platform domain list
"""
host = extract_remote_host(source)
if not host:
@@ -149,8 +134,8 @@ def ensure_public_remote_target(source: str) -> None:
raise PermissionDeniedError(
"HTTP server only accepts public remote resource targets; "
f"host '{host}' resolves to non-public address '{non_public[0]}'. "
- "To allow this, add the domain to code.gitlab_domains/code.github_domains/"
- "code.azure_devops_domains/code.code_hosting_domains "
+ "To allow this, add the domain to its code.<platform>_domains list "
+ "or code.code_hosting_domains "
"or set allow_private_networks=true in your ov.conf."
)
diff --git a/openviking_cli/utils/config/parser_config.py b/openviking_cli/utils/config/parser_config.py
index 46fb80b3d..149553896 100644
--- a/openviking_cli/utils/config/parser_config.py
+++ b/openviking_cli/utils/config/parser_config.py
@@ -201,7 +201,7 @@ class CodeHostingConfig(ParserConfig):
Base configuration for code hosting platform domains.
Attributes:
- code_hosting_domains: List of code hosting platform domains (github.com, gitlab.com, etc.)
+ code_hosting_domains: List of allowed generic code hosting domains
github_domains: List of GitHub domains (github.com, www.github.com)
gitlab_domains: List of GitLab domains (gitlab.com, www.gitlab.com)
azure_devops_domains: List of Azure DevOps domains (dev.azure.com, ssh.dev.azure.com)
@@ -216,7 +216,17 @@ class CodeHostingConfig(ParserConfig):
def __post_init__(self):
"""Initialize default values for mutable fields."""
if self.code_hosting_domains is None:
- self.code_hosting_domains = ["github.com", "gitlab.com"]
+ self.code_hosting_domains = [
+ "github.com",
+ "gitlab.com",
+ "gitcode.com",
+ "gitee.com",
+ "bitbucket.org",
+ "codeberg.org",
+ "gitea.com",
+ "atomgit.com",
+ "git.sr.ht",
+ ]
if self.github_domains is None:
self.github_domains = ["github.com", "www.github.com"]
if self.gitlab_domains is None:
diff --git a/tests/misc/test_network_guard.py b/tests/misc/test_network_guard.py
index bc049fc07..d22f23ff2 100644
--- a/tests/misc/test_network_guard.py
+++ b/tests/misc/test_network_guard.py
@@ -4,11 +4,13 @@
from __future__ import annotations
+from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import pytest
from openviking.utils.network_guard import (
+ _get_allowed_code_hosting_domains,
_is_public_ip,
_normalize_host,
_resolve_host_addresses,
@@ -18,7 +20,6 @@ from openviking.utils.network_guard import (
)
from openviking_cli.exceptions import PermissionDeniedError
-
# ── extract_remote_host ──────────────────────────────────────────────────────
@@ -179,6 +180,25 @@ class TestEnsurePublicRemoteTarget:
with pytest.raises(PermissionDeniedError, match="valid destination host"):
ensure_public_remote_target("[email protected]")
+ def test_generic_code_hosting_domains_are_allowlisted(self) -> None:
+ domains = [
+ "gitcode.example.com",
+ "gitee.example.com",
+ "bitbucket.example.com",
+ "codeberg.example.com",
+ "gitea.example.com",
+ "atomgit.example.com",
+ "sourcehut.example.com",
+ ]
+ code_config = SimpleNamespace(code_hosting_domains=domains)
+ config = SimpleNamespace(code=code_config)
+
+ with patch(
+ "openviking.utils.network_guard.get_openviking_config",
+ return_value=config,
+ ):
+ assert _get_allowed_code_hosting_domains() == set(domains)
+
# -- Rejection: localhost variants --
@pytest.mark.parametrize(
diff --git a/tests/service/test_resource_service_connector.py b/tests/service/test_resource_service_connector.py
index d0a093253..2b7ac9009 100644
--- a/tests/service/test_resource_service_connector.py
+++ b/tests/service/test_resource_service_connector.py
@@ -50,12 +50,13 @@ def connector_config(monkeypatch):
),
)
monkeypatch.setattr(
- "openviking.parse.accessors.git_accessor.get_openviking_config",
+ "openviking.utils.code_hosting_utils.get_openviking_config",
lambda: SimpleNamespace(
code=SimpleNamespace(
github_domains=["github.com", "git.example"],
gitlab_domains=[],
azure_devops_domains=[],
+ code_hosting_domains=[],
)
),
)
@@ -501,6 +502,60 @@ def test_git_route_degrades_when_disabled_or_type_not_allowed(connector_config,
assert service._should_use_connector("https://git.example/org/repo.git") is False
+ "path",
+ [
+ "[email protected]:repo.git",
+ "ssh://[email protected]/repo.git",
+ "ssh://[email protected]/repo",
+ "git://git.example.com/repo.git",
+ "git://git.example.com/repo",
+ "[email protected]:org/subgroup/repo",
+ "ssh://[email protected]/org/subgroup/repo",
+ "git://git.example.com/org/subgroup/repo",
+ ],
+)
+def test_git_connector_detection_accepts_explicit_protocol_repo(monkeypatch, path):
+ from openviking.connector.routing import detect_connector_add_type
+ from openviking.utils import code_hosting_utils
+
+ config = SimpleNamespace(
+ code=SimpleNamespace(
+ github_domains=[],
+ gitlab_domains=[],
+ azure_devops_domains=[],
+ code_hosting_domains=["git.example.com"],
+ )
+ )
+ monkeypatch.setattr(code_hosting_utils, "get_openviking_config", lambda: config)
+
+ assert detect_connector_add_type(path) == ("git", False)
+
+
+ "path",
+ [
+ "https://gitcode.com/GitHub_Trending/no/nocobase/blob/bcfdc2/examples/base/config.git",
+ "https://gitcode.com/ploc-org/CNPL/tree/master/projects/sample/config.git",
+ ],
+)
+def test_git_connector_detection_rejects_gitcode_browse_file(monkeypatch, path):
+ from openviking.connector.routing import detect_connector_add_type
+ from openviking.utils import code_hosting_utils
+
+ config = SimpleNamespace(
+ code=SimpleNamespace(
+ github_domains=[],
+ gitlab_domains=[],
+ azure_devops_domains=[],
+ code_hosting_domains=["gitcode.com"],
+ )
+ )
+ monkeypatch.setattr(code_hosting_utils, "get_openviking_config", lambda: config)
+ assert detect_connector_add_type(path) is None
+
+
def test_git_source_falls_back_for_parent_target(
connector_config,
service,
diff --git a/tests/test_code_hosting_utils.py b/tests/test_code_hosting_utils.py
index dfc823070..33d8a1ad6 100644
--- a/tests/test_code_hosting_utils.py
+++ b/tests/test_code_hosting_utils.py
@@ -22,7 +22,17 @@ def _mock_config():
"ssh.dev.azure.com",
"vs-ssh.visualstudio.com",
],
- code_hosting_domains=["github.com", "gitlab.com"],
+ code_hosting_domains=[
+ "github.com",
+ "gitlab.com",
+ "gitcode.com",
+ "gitee.com",
+ "bitbucket.org",
+ "codeberg.org",
+ "gitea.com",
+ "atomgit.com",
+ "git.sr.ht",
+ ],
)
)
@@ -48,6 +58,7 @@ sys.modules["openviking.utils.code_hosting_utils"] = _module
_spec.loader.exec_module(_module)
parse_code_hosting_url = _module.parse_code_hosting_url
+parse_git_repo_url = _module.parse_git_repo_url
is_github_url = _module.is_github_url
is_gitlab_url = _module.is_gitlab_url
is_code_hosting_url = _module.is_code_hosting_url
@@ -80,6 +91,28 @@ def test_parse_code_hosting_url_git_ssh_single_segment():
assert parse_code_hosting_url("[email protected]:repo") is None
+ "url",
+ [
+ "[email protected]:repo.git",
+ "ssh://[email protected]/repo.git",
+ "ssh://[email protected]/repo",
+ "git://git.example.com/repo.git",
+ "git://git.example.com/repo",
+ ],
+)
+def test_parse_code_hosting_url_single_segment_protocol_keeps_legacy_none(url):
+ config = _mock_config()
+ config.code.github_domains = []
+ config.code.gitlab_domains = []
+ config.code.azure_devops_domains = []
+ config.code.code_hosting_domains = ["git.example.com"]
+
+ with patch.object(_module, "get_openviking_config", return_value=config):
+ assert parse_code_hosting_url(url) is None
+
+
def test_parse_code_hosting_url_https():
assert parse_code_hosting_url("https://github.com/org/repo") == "org/repo"
@@ -281,6 +314,8 @@ def test_is_git_repo_url_https_blob():
def test_is_git_repo_url_github_tree_path_with__git_segment():
+ # A subdirectory browse URL is ambiguous with a slashed branch name, so it
+ # must stay on the web path. The _git segment must not trigger Azure rules.
assert is_git_repo_url("https://github.com/org/repo/tree/main/_git/config") is False
@@ -290,3 +325,462 @@ def test_is_git_repo_url_unknown_domain():
def test_is_git_repo_url_single_segment():
assert is_git_repo_url("https://github.com/org") is False
+
+
+ "url",
+ [
+ "[email protected]:repo.git",
+ "ssh://[email protected]/repo.git",
+ "ssh://[email protected]/repo",
+ "git://git.example.com/repo.git",
+ "git://git.example.com/repo",
+ ],
+)
+def test_is_git_repo_url_single_segment_protocol_repo(url):
+ config = _mock_config()
+ config.code.github_domains = []
+ config.code.gitlab_domains = []
+ config.code.azure_devops_domains = []
+ config.code.code_hosting_domains = ["git.example.com"]
+
+ with patch.object(_module, "get_openviking_config", return_value=config):
+ parsed = parse_git_repo_url(url)
+
+ assert parsed is not None
+ assert parsed.clone_url == url
+ assert parsed.repo_path == "repo"
+ assert parsed.route_kind == "clone"
+ assert is_git_repo_url(url) is True
+
+
+def test_is_git_repo_url_single_segment_https_repo_remains_rejected():
+ config = _mock_config()
+ config.code.github_domains = []
+ config.code.gitlab_domains = []
+ config.code.azure_devops_domains = []
+ config.code.code_hosting_domains = ["git.example.com"]
+
+ with patch.object(_module, "get_openviking_config", return_value=config):
+ assert is_git_repo_url("https://git.example.com/repo.git") is False
+
+
+ ("url", "repo_path"),
+ [
+ ("[email protected]:org/subgroup/repo", "org/subgroup/repo"),
+ ("ssh://[email protected]/org/subgroup/repo", "org/subgroup/repo"),
+ ("git://git.example.com/org/subgroup/repo", "org/subgroup/repo"),
+ ("ssh://[email protected]/org/repo/tree/main", "org/repo/tree/main"),
+ ],
+)
+def test_explicit_git_transport_preserves_nested_path_without_dotgit(url, repo_path):
+ config = _mock_config()
+ config.code.github_domains = []
+ config.code.gitlab_domains = []
+ config.code.azure_devops_domains = []
+ config.code.code_hosting_domains = ["git.example.com"]
+
+ with patch.object(_module, "get_openviking_config", return_value=config):
+ parsed = parse_git_repo_url(url)
+
+ assert parsed is not None
+ assert parsed.clone_url == url
+ assert parsed.repo_path == repo_path
+ assert parsed.route_kind == "clone"
+ assert parsed.branch is None
+ assert parsed.commit is None
+ assert is_git_repo_url(url) is True
+ assert parse_code_hosting_url(url) == repo_path
+
+
+# --- is_git_repo_url: nested groups and .git clone URLs ---
+
+
+def test_is_git_repo_url_gitcode_nested_dotgit():
+ assert is_git_repo_url("https://gitcode.com/GitHub_Trending/bl/black.git") is True
+
+
+def test_gitcode_nested_blob_file_ending_dotgit_is_not_a_repo():
+ url = "https://gitcode.com/GitHub_Trending/no/nocobase/blob/bcfdc2/examples/base/config.git"
+
+ assert parse_git_repo_url(url) is None
+ assert is_git_repo_url(url) is False
+ assert parse_code_hosting_url(url) == "GitHub_Trending/no/nocobase"
+
+
+def test_gitcode_tree_browse_file_ending_dotgit_is_not_a_repo():
+ url = "https://gitcode.com/ploc-org/CNPL/tree/master/projects/sample/config.git"
+
+ assert parse_git_repo_url(url) is None
+ assert is_git_repo_url(url) is False
+ assert parse_code_hosting_url(url) == "ploc-org/CNPL"
+
+
+def test_is_git_repo_url_gitcode_tree():
+ assert is_git_repo_url("https://gitcode.com/ploc-org/CNPL/tree/master") is True
+
+
+def test_is_git_repo_url_gitee_repo():
+ assert is_git_repo_url("https://gitee.com/mindspore/mindspore") is True
+
+
+def test_is_git_repo_url_gitee_tree():
+ assert is_git_repo_url("https://gitee.com/mindspore/mindspore/tree/master") is True
+
+
+def test_is_git_repo_url_gitee_organization_page():
+ url = "https://gitee.com/organizations/mindspore"
+
+ assert parse_git_repo_url(url) is None
+ assert is_git_repo_url(url) is False
+
+
+def test_gitee_tree_browse_file_ending_dotgit_is_not_a_repo():
+ url = "https://gitee.com/mindspore/mindspore/tree/master/config.git"
+
+ assert parse_git_repo_url(url) is None
+ assert is_git_repo_url(url) is False
+ assert parse_code_hosting_url(url) == "mindspore/mindspore"
+
+
+def test_is_git_repo_url_gitlab_subgroup_dotgit():
+ assert is_git_repo_url("https://gitlab.com/org/subgroup/repo.git") is True
+
+
+def test_parse_git_repo_url_gitlab_subgroup_named_tree():
+ url = "https://gitlab.com/org/subgroup/tree/repo.git"
+
+ parsed = parse_git_repo_url(url)
+
+ assert parsed is not None
+ assert parsed.clone_url == url
+ assert parsed.repo_path == "org/subgroup/tree/repo"
+ assert parsed.route_kind == "clone"
+ assert parsed.branch is None
+ assert parsed.commit is None
+ assert parse_code_hosting_url(url) == "org/subgroup/tree/repo"
+
+
+def test_is_git_repo_url_gitlab_subgroup_without_dotgit_rejected():
+ # Ambiguous with subgroup pages; only .git or /-/ forms disambiguate
+ assert is_git_repo_url("https://gitlab.com/org/subgroup/repo") is False
+
+
+def test_is_git_repo_url_nested_repo_named_blob_dotgit():
+ # A nested repo literally named "blob" must not be taken as a browse page
+ assert is_git_repo_url("https://gitlab.com/org/subgroup/blob.git") is True
+
+
+def test_is_git_repo_url_github_nested_dotgit_rejected():
+ # GitHub has no subgroup clone form; accepting this would make the archive
+ # fast path fetch org/repo while recording a different nested source.
+ assert is_git_repo_url("https://github.com/org/repo/not-a-repo.git") is False
+
+
+def test_is_git_repo_url_dotgit_only_segment():
+ assert is_git_repo_url("https://github.com/org/.git") is False
+
+
+# --- is_git_repo_url: GitLab "/-/" browse URLs ---
+
+
+def test_is_git_repo_url_gitlab_dash_tree():
+ assert is_git_repo_url("https://gitlab.com/gitlab-org/gitlab/-/tree/master") is True
+
+
+def test_is_git_repo_url_gitlab_dash_tree_nested():
+ assert is_git_repo_url("https://gitlab.com/org/subgroup/repo/-/tree/main") is True
+
+
+def test_is_git_repo_url_gitlab_dash_commit_sha():
+ assert (
+ is_git_repo_url(
+ "https://gitlab.com/org/repo/-/commit/1234567890abcdef1234567890abcdef12345678"
+ )
+ is True
+ )
+
+
+def test_is_git_repo_url_gitlab_dash_issues():
+ assert is_git_repo_url("https://gitlab.com/org/repo/-/issues/1") is False
+
+
+def test_is_git_repo_url_gitlab_dash_blob():
+ assert is_git_repo_url("https://gitlab.com/org/repo/-/blob/main/file.py") is False
+
+
+# --- is_git_repo_url: commit pins and tree refs ---
+
+
+def test_is_git_repo_url_github_commit_sha():
+ assert is_git_repo_url("https://github.com/org/repo/commit/abc1234") is True
+
+
+def test_is_git_repo_url_github_commit_non_sha():
+ assert is_git_repo_url("https://github.com/org/repo/commit/not-a-sha") is False
+
+
+def test_is_git_repo_url_tree_ref_with_slash_rejected_as_ambiguous():
+ assert is_git_repo_url("https://github.com/org/repo/tree/feature/foo") is False
+
+
+def test_is_git_repo_url_tree_subdirectory_rejected_as_ambiguous():
+ assert is_git_repo_url("https://github.com/org/repo/tree/main/src") is False
+
+
+def test_is_git_repo_url_gitlab_dash_tree_with_slash_rejected_as_ambiguous():
+ assert is_git_repo_url("https://gitlab.com/org/repo/-/tree/feature/foo") is False
+
+
+# --- is_git_repo_url: reserved platform pages ---
+
+
+def test_is_git_repo_url_reserved_topics():
+ assert is_git_repo_url("https://github.com/topics/python") is False
+
+
+def test_is_git_repo_url_reserved_orgs():
+ assert is_git_repo_url("https://github.com/orgs/volcengine") is False
+
+
+def test_is_git_repo_url_reserved_groups():
+ assert is_git_repo_url("https://gitlab.com/groups/gitlab-org") is False
+
+
+def test_is_git_repo_url_reserved_explore():
+ assert is_git_repo_url("https://gitee.com/explore/starred") is False
+
+
+ "url",
+ [
+ "https://gitcode.com/explore/repos",
+ "https://bitbucket.org/product/features",
+ "https://codeberg.org/explore/repos",
+ "https://gitea.com/explore/repos",
+ "https://atomgit.com/explore/repos",
+ ],
+)
+def test_is_git_repo_url_additional_platform_pages(url):
+ assert is_git_repo_url(url) is False
+
+
+def test_generic_host_does_not_inherit_platform_reserved_namespaces():
+ config = _mock_config()
+ config.code.code_hosting_domains = ["git.example.com"]
+
+ with patch.object(_module, "get_openviking_config", return_value=config):
+ assert is_git_repo_url("https://git.example.com/topics/repo") is True
+ assert is_git_repo_url("https://git.example.com/groups/repo") is True
+
+
+def test_is_git_repo_url_azure_project_page():
+ # Azure DevOps project pages are not cloneable; only the _git form is
+ assert is_git_repo_url("https://dev.azure.com/org/project") is False
+
+
+# --- is_git_repo_url: ssh/git protocols require a repo path ---
+
+
+def test_is_git_repo_url_ssh_url_without_path():
+ assert is_git_repo_url("ssh://[email protected]/") is False
+
+
+def test_is_git_repo_url_git_at_without_path():
+ assert is_git_repo_url("[email protected]:") is False
+
+
+def test_is_git_repo_url_git_at_nested_dotgit():
+ assert is_git_repo_url("[email protected]:GitHub_Trending/bl/black.git") is True
+
+
+# --- is_git_repo_url: additional default platforms ---
+
+
+def test_is_git_repo_url_bitbucket_repo():
+ assert is_git_repo_url("https://bitbucket.org/team/repo.git") is True
+
+
+def test_is_git_repo_url_bitbucket_src_browse_rejected():
+ # Bitbucket uses /src/<ref> for browsing; only repo/clone URLs are accepted
+ assert is_git_repo_url("https://bitbucket.org/team/repo/src/main/file.py") is False
+
+
+ "url",
+ [
+ "https://bitbucket.org/team/repo/src/main/config.git",
+ "https://codeberg.org/team/repo/src/branch/main/config.git",
+ "https://gitea.com/team/repo/src/branch/main/config.git",
+ ],
+)
+def test_is_git_repo_url_src_browse_file_ending_dotgit_rejected(url):
+ assert is_git_repo_url(url) is False
+
+
+def test_parse_code_hosting_url_bitbucket_src_file_ending_dotgit():
+ assert (
+ parse_code_hosting_url("https://bitbucket.org/team/repo/src/main/config.git") == "team/repo"
+ )
+
+
+def test_is_git_repo_url_codeberg_repo():
+ assert is_git_repo_url("https://codeberg.org/forgejo/forgejo") is True
+
+
+def test_is_git_repo_url_atomgit_repo():
+ assert is_git_repo_url("https://atomgit.com/openharmony/docs.git") is True
+
+
+def test_is_git_repo_url_gitea_repo():
+ assert is_git_repo_url("https://gitea.com/gitea/tea") is True
+
+
+def test_is_git_repo_url_sourcehut_repo():
+ assert is_git_repo_url("https://git.sr.ht/~sircmpwn/aerc") is True
+
+
+ ("url", "repo_path"),
+ [
+ (
+ "https://atomgit.com/easyxmen/docs/tree/master/ReleaseNotes/config.git",
+ "easyxmen/docs",
+ ),
+ (
+ "https://git.sr.ht/~sircmpwn/aerc/tree/master/item/config.git",
+ "_sircmpwn/aerc",
+ ),
+ ],
+)
+def test_tree_browse_file_ending_dotgit_rejected_for_default_platforms(url, repo_path):
+ assert parse_git_repo_url(url) is None
+ assert is_git_repo_url(url) is False
+ assert parse_code_hosting_url(url) == repo_path
+
+
+def test_generic_domain_supports_nested_clone_without_platform_route_semantics():
+ config = _mock_config()
+ config.code.code_hosting_domains = ["git.example.com"]
+
+ with patch.object(_module, "get_openviking_config", return_value=config):
+ assert is_git_repo_url("https://git.example.com/org/subgroup/repo.git") is True
+ assert is_git_repo_url("https://git.example.com/team/repo/src/main.git") is True
+ assert is_git_repo_url("https://git.example.com/org/subgroup/repo/blob/leaf.git") is True
+
+
+def test_generic_domain_keeps_nested_path_through_final_dotgit_segment():
+ config = _mock_config()
+ config.code.code_hosting_domains = ["git.example.com"]
+ url = "https://git.example.com/org/archive.git/repo.git"
+
+ with patch.object(_module, "get_openviking_config", return_value=config):
+ parsed = parse_git_repo_url(url)
+
+ assert parsed is not None
+ assert parsed.clone_url == url
+ assert parsed.repo_path == "org/archive_git/repo"
+ assert parse_code_hosting_url(url) == "org/archive_git/repo"
+
+
+def test_generic_domain_with_configured_port_supports_nested_clone():
+ config = _mock_config()
+ config.code.github_domains = []
+ config.code.gitlab_domains = []
+ config.code.azure_devops_domains = []
+ config.code.code_hosting_domains = ["git.example.com:8443"]
+ url = "https://git.example.com:8443/org/subgroup/repo.git"
+
+ with patch.object(_module, "get_openviking_config", return_value=config):
+ assert is_code_hosting_url(url) is True
+ assert is_git_repo_url(url) is True
+ assert parse_code_hosting_url(url) == "org/subgroup/repo"
+
+
+def test_parse_code_hosting_url_sourcehut_tilde_sanitized():
+ assert parse_code_hosting_url("https://git.sr.ht/~sircmpwn/aerc") == "_sircmpwn/aerc"
+
+
+# --- parse_code_hosting_url: nested groups ---
+
+
+def test_parse_code_hosting_url_gitcode_nested_dotgit():
+ assert (
+ parse_code_hosting_url("https://gitcode.com/GitHub_Trending/bl/black.git")
+ == "GitHub_Trending/bl/black"
+ )
+
+
+def test_parse_code_hosting_url_gitlab_subgroup_dotgit():
+ assert parse_code_hosting_url("https://gitlab.com/org/subgroup/repo.git") == "org/subgroup/repo"
+
+
+def test_parse_code_hosting_url_gitlab_dash_tree_nested():
+ assert (
+ parse_code_hosting_url("https://gitlab.com/org/subgroup/repo/-/tree/main")
+ == "org/subgroup/repo"
+ )
+
+
+def test_parse_code_hosting_url_git_ssh_nested_dotgit():
+ assert (
+ parse_code_hosting_url("[email protected]:GitHub_Trending/bl/black.git")
+ == "GitHub_Trending/bl/black"
+ )
+
+
+def test_parse_code_hosting_url_blob_file_named_dotgit_not_nested():
+ # org/repo/blob/main/file.git is a file browse URL, not a nested repo path
+ assert parse_code_hosting_url("https://github.com/org/repo/blob/main/file.git") == "org/repo"
+
+
+def test_parse_code_hosting_url_github_tree_unchanged():
+ assert parse_code_hosting_url("https://github.com/org/repo/tree/main") == "org/repo"
+
+
+ ("url", "clone_url", "repo_path", "branch", "commit"),
+ [
+ (
+ "https://github.com/org/repo/tree/main",
+ "https://github.com/org/repo",
+ "org/repo",
+ "main",
+ None,
+ ),
+ (
+ "https://github.com/org/repo/commit/abc1234",
+ "https://github.com/org/repo",
+ "org/repo",
+ None,
+ "abc1234",
+ ),
+ (
+ "https://gitlab.com/org/subgroup/repo/-/tree/main",
+ "https://gitlab.com/org/subgroup/repo",
+ "org/subgroup/repo",
+ "main",
+ None,
+ ),
+ (
+ "[email protected]:v3/org/project/repo",
+ "[email protected]:v3/org/project/repo",
+ "org/project/repo",
+ None,
+ None,
+ ),
+ ],
+)
+def test_parse_git_repo_url_returns_consistent_clone_metadata(
+ url, clone_url, repo_path, branch, commit
+):
+ parsed = parse_git_repo_url(url)
+
+ assert parsed is not None
+ assert parsed.clone_url == clone_url
+ assert parsed.repo_path == repo_path
+ assert parsed.branch == branch
+ assert parsed.commit == commit
+ assert is_git_repo_url(url) is True
diff --git a/tests/test_config_loader.py b/tests/test_config_loader.py
index 05ae0cc2f..d14c1ebdd 100644
--- a/tests/test_config_loader.py
+++ b/tests/test_config_loader.py
@@ -2,8 +2,11 @@
# SPDX-License-Identifier: AGPL-3.0
"""Tests for config_loader utilities."""
+import json
import logging
+import re
from logging.handlers import QueueHandler
+from pathlib import Path
import pytest
@@ -15,6 +18,7 @@ from openviking_cli.utils.config.config_loader import (
require_config,
resolve_config_path,
)
+from openviking_cli.utils.config.parser_config import CodeHostingConfig
class TestResolveConfigPath:
@@ -115,6 +119,44 @@ class TestRequireConfig:
require_config(None, "TEST_MISSING_ENV", "nonexistent_file.conf", "test")
+def test_generic_code_hosting_domains_include_supported_platforms():
+ config = CodeHostingConfig()
+
+ assert config.code_hosting_domains == [
+ "github.com",
+ "gitlab.com",
+ "gitcode.com",
+ "gitee.com",
+ "bitbucket.org",
+ "codeberg.org",
+ "gitea.com",
+ "atomgit.com",
+ "git.sr.ht",
+ ]
+
+
+def test_example_code_hosting_domains_match_runtime_defaults():
+ example_path = Path(__file__).resolve().parents[1] / "examples" / "ov.conf.example"
+ example_text = example_path.read_text(encoding="utf-8")
+ domains_match = re.search(
+ r'"code_hosting_domains"\s*:\s*(\[[^\]]*\])',
+ example_text,
+ )
+
+ assert domains_match is not None
+ assert json.loads(domains_match.group(1)) == CodeHostingConfig().code_hosting_domains
+
+
+def test_generic_code_hosting_domains_load_from_config():
+ config = CodeHostingConfig.from_dict(
+ {
+ "code_hosting_domains": ["git.generic.example.com"],
+ }
+ )
+
+ assert config.code_hosting_domains == ["git.generic.example.com"]
+
+
def test_openviking_config_rejects_unknown_nested_parser_section(monkeypatch):
monkeypatch.setenv(OPENVIKING_CONFIG_ENV, "/tmp/codex-no-config.json")
diff --git a/tests/unit/test_accessors_git.py b/tests/unit/test_accessors_git.py
index 25bb74f1c..fae625e7f 100644
--- a/tests/unit/test_accessors_git.py
+++ b/tests/unit/test_accessors_git.py
@@ -9,23 +9,20 @@ from unittest.mock import AsyncMock, patch
import pytest
from openviking.parse.accessors import GitAccessor
+from openviking.parse.parsers.directory import DirectoryParser
from openviking.utils import code_hosting_utils
-
-def _mock_config():
- return SimpleNamespace(
- code=SimpleNamespace(
- github_domains=["github.com", "www.github.com"],
- gitlab_domains=["gitlab.com", "www.gitlab.com"],
- code_hosting_domains=["github.com", "gitlab.com"],
- )
- )
-
-
[email protected](autouse=True)
-def _patch_config():
- with patch.object(code_hosting_utils, "get_openviking_config", side_effect=_mock_config):
- yield
+_GENERIC_CODE_HOSTING_DOMAINS = [
+ "github.com",
+ "gitlab.com",
+ "gitcode.com",
+ "gitee.com",
+ "bitbucket.org",
+ "codeberg.org",
+ "gitea.com",
+ "atomgit.com",
+ "git.sr.ht",
+]
def _mock_config():
@@ -38,11 +35,17 @@ def _mock_config():
"ssh.dev.azure.com",
"vs-ssh.visualstudio.com",
],
- code_hosting_domains=["github.com", "gitlab.com"],
+ code_hosting_domains=_GENERIC_CODE_HOSTING_DOMAINS,
)
)
[email protected](autouse=True)
+def _patch_config():
+ with patch.object(code_hosting_utils, "get_openviking_config", side_effect=_mock_config):
+ yield
+
+
class TestGitAccessor:
"""Tests for GitAccessor."""
@@ -116,11 +119,243 @@ class TestGitAccessor:
"""GitAccessor should handle git:// URLs."""
assert accessor.can_handle("git://github.com/volcengine/OpenViking.git") is True
- def test_normalize_repo_url_ssh_with_userinfo_and_ref(self, accessor: GitAccessor) -> None:
- """GitAccessor should normalize ssh URLs with userinfo using the shared host matcher."""
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "[email protected]:repo.git",
+ "ssh://[email protected]/repo.git",
+ "ssh://[email protected]/repo",
+ "git://git.example.com/repo.git",
+ "git://git.example.com/repo",
+ ],
+ )
+ def test_can_handle_single_segment_protocol_repo(
+ self, accessor: GitAccessor, source: str
+ ) -> None:
+ config = _mock_config()
+ config.code.github_domains = []
+ config.code.gitlab_domains = []
+ config.code.azure_devops_domains = []
+ config.code.code_hosting_domains = ["git.example.com"]
+
+ with patch.object(
+ code_hosting_utils,
+ "get_openviking_config",
+ return_value=config,
+ ):
+ assert accessor.can_handle(source) is True
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "[email protected]:org/subgroup/repo",
+ "ssh://[email protected]/org/subgroup/repo",
+ "git://git.example.com/org/subgroup/repo",
+ ],
+ )
+ def test_can_handle_nested_protocol_repo_without_dotgit(
+ self, accessor: GitAccessor, source: str
+ ) -> None:
+ config = _mock_config()
+ config.code.github_domains = []
+ config.code.gitlab_domains = []
+ config.code.azure_devops_domains = []
+ config.code.code_hosting_domains = ["git.example.com"]
+
+ with patch.object(
+ code_hosting_utils,
+ "get_openviking_config",
+ return_value=config,
+ ):
+ assert accessor.can_handle(source) is True
+ assert accessor._normalize_repo_url(source) == source
+ assert accessor._get_repo_name(source) == "org/subgroup/repo"
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "ssh://[email protected]/",
+ "git://github.com",
+ ],
+ )
+ def test_cannot_handle_git_protocol_without_repo_path(
+ self, accessor: GitAccessor, source: str
+ ) -> None:
+ assert accessor.can_handle(source) is False
+
+ def test_ssh_transport_does_not_apply_http_tree_route_rules(
+ self, accessor: GitAccessor
+ ) -> None:
+ """Explicit Git transports preserve paths that resemble HTTP browse routes."""
assert (
accessor._normalize_repo_url("ssh://[email protected]:443/volcengine/OpenViking/tree/main")
- == "ssh://[email protected]:443/volcengine/OpenViking"
+ == "ssh://[email protected]:443/volcengine/OpenViking/tree/main"
+ )
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "https://gitlab.com/org/subgroup/repo.git",
+ "https://gitlab.com/org/subgroup/repo/-/tree/main",
+ ],
+ )
+ def test_can_handle_gitlab_nested_urls(self, accessor: GitAccessor, source: str) -> None:
+ """GitAccessor should handle GitLab subgroup clone URLs and /-/ tree URLs."""
+ assert accessor.can_handle(source) is True
+
+ def test_normalize_repo_url_gitlab_dash_tree(self, accessor: GitAccessor) -> None:
+ """Normalization must cut at the GitLab /-/ separator, keeping the nested path."""
+ assert (
+ accessor._normalize_repo_url("https://gitlab.com/org/subgroup/repo/-/tree/main")
+ == "https://gitlab.com/org/subgroup/repo"
+ )
+
+ def test_normalize_repo_url_gitlab_subgroup_dotgit(self, accessor: GitAccessor) -> None:
+ """Nested .git clone URLs must not be truncated to the first two segments."""
+ assert (
+ accessor._normalize_repo_url("https://gitlab.com/org/subgroup/repo.git")
+ == "https://gitlab.com/org/subgroup/repo.git"
+ )
+
+ def test_parse_repo_source_gitlab_project_named_commit(self, accessor: GitAccessor) -> None:
+ """A project named commit must not shadow the /-/commit route marker."""
+ source = "https://gitlab.com/org/commit/-/commit/1234567"
+
+ assert accessor._parse_repo_source(source) == (
+ "https://gitlab.com/org/commit",
+ None,
+ "1234567",
+ )
+
+ def test_parse_repo_source_gitlab_project_named_tree(self, accessor: GitAccessor) -> None:
+ """A project named tree must not shadow the /-/tree route marker."""
+ source = "https://gitlab.com/org/tree/-/tree/main"
+
+ assert accessor._parse_repo_source(source) == (
+ "https://gitlab.com/org/tree",
+ "main",
+ None,
+ )
+
+ def test_parse_repo_source_gitlab_subgroup_named_tree(self, accessor: GitAccessor) -> None:
+ """A trailing .git keeps every nested namespace and does not imply a branch."""
+ source = "https://gitlab.com/org/subgroup/tree/repo.git"
+
+ assert accessor._parse_repo_source(source) == (source, None, None)
+
+ def test_gitee_tree_browse_file_ending_dotgit_is_rejected(self, accessor: GitAccessor) -> None:
+ source = "https://gitee.com/org/repo/tree/main/config.git"
+
+ assert accessor.can_handle(source) is False
+ with pytest.raises(ValueError, match="Unsupported Git repository URL"):
+ accessor._parse_repo_source(source)
+
+ def test_gitee_organization_page_is_not_handled(self, accessor: GitAccessor) -> None:
+ assert accessor.can_handle("https://gitee.com/organizations/mindspore") is False
+
+ def test_normalize_repo_url_rejects_github_nested_dotgit(self, accessor: GitAccessor) -> None:
+ with pytest.raises(ValueError, match="Unsupported Git repository URL"):
+ accessor._normalize_repo_url("https://github.com/org/repo/not-a-repo.git")
+
+ def test_normalize_repo_url_gitcode_nested_dotgit(self, accessor: GitAccessor) -> None:
+ assert (
+ accessor._normalize_repo_url("https://gitcode.com/GitHub_Trending/bl/black.git")
+ == "https://gitcode.com/GitHub_Trending/bl/black.git"
+ )
+
+ def test_gitcode_nested_blob_file_ending_dotgit_is_rejected(
+ self, accessor: GitAccessor
+ ) -> None:
+ source = (
+ "https://gitcode.com/GitHub_Trending/no/nocobase/blob/bcfdc2/examples/base/config.git"
+ )
+
+ assert accessor.can_handle(source) is False
+ with pytest.raises(ValueError, match="Unsupported Git repository URL"):
+ accessor._parse_repo_source(source)
+
+ def test_gitcode_tree_file_ending_dotgit_is_rejected(self, accessor: GitAccessor) -> None:
+ source = "https://gitcode.com/ploc-org/CNPL/tree/master/projects/sample/config.git"
+
+ assert accessor.can_handle(source) is False
+ with pytest.raises(ValueError, match="Unsupported Git repository URL"):
+ accessor._parse_repo_source(source)
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "https://atomgit.com/easyxmen/docs/tree/master/ReleaseNotes/config.git",
+ "https://git.sr.ht/~sircmpwn/aerc/tree/master/item/config.git",
+ ],
+ )
+ def test_default_platform_tree_file_ending_dotgit_is_rejected(
+ self,
+ accessor: GitAccessor,
+ source: str,
+ ) -> None:
+ assert accessor.can_handle(source) is False
+ with pytest.raises(ValueError, match="Unsupported Git repository URL"):
+ accessor._parse_repo_source(source)
+
+ def test_normalize_repo_url_uses_final_dotgit_segment(self, accessor: GitAccessor) -> None:
+ config = _mock_config()
+ config.code.github_domains = []
+ config.code.gitlab_domains = []
+ config.code.azure_devops_domains = []
+ config.code.code_hosting_domains = ["git.example.com"]
+ source = "https://git.example.com/org/archive.git/repo.git"
+
+ with patch.object(
+ code_hosting_utils,
+ "get_openviking_config",
+ return_value=config,
+ ):
+ assert accessor._normalize_repo_url(source) == source
+ assert accessor._parse_repo_source(source) == (source, None, None)
+
+ @pytest.mark.parametrize(
+ ("source", "expected"),
+ [
+ ("https://gitlab.com/org/repo.git", True),
+ ("https://gitlab.com/org/subgroup/repo.git", False),
+ ],
+ )
+ def test_can_use_gitlab_zip(self, accessor: GitAccessor, source: str, expected: bool) -> None:
+ assert accessor._can_use_gitlab_zip(source) is expected
+
+ async def test_nested_gitlab_url_skips_zip_fast_path(
+ self, accessor: GitAccessor, tmp_path: Path
+ ) -> None:
+ source = "https://gitlab.com/org/subgroup/repo.git"
+ with (
+ patch(
+ "openviking.parse.accessors.git_accessor.tempfile.mkdtemp",
+ return_value=str(tmp_path),
+ ),
+ patch.object(
+ accessor,
+ "_gitlab_zip_download",
+ new_callable=AsyncMock,
+ ) as zip_download,
+ patch.object(
+ accessor,
+ "_git_clone",
+ new_callable=AsyncMock,
+ return_value="org/subgroup/repo",
+ ) as git_clone,
+ ):
+ await accessor.access(source)
+
+ zip_download.assert_not_awaited()
+ git_clone.assert_awaited_once()
+ assert git_clone.await_args.args[0] == source
+
+ def test_normalize_repo_url_github_commit_page(self, accessor: GitAccessor) -> None:
+ """Commit-pin URLs normalize to the bare repo; the ref is extracted separately."""
+ assert (
+ accessor._normalize_repo_url("https://github.com/org/repo/commit/abc1234")
+ == "https://github.com/org/repo"
)
@pytest.mark.parametrize(
@@ -163,6 +398,31 @@ class TestGitAccessor:
assert "--no-recurse-submodules" in clone_args
assert "--recursive" not in clone_args
+ @pytest.mark.parametrize(
+ ("source", "repo_name"),
+ [
+ ("https://gitcode.com/org/repo.git", "org/repo"),
+ ("https://gitee.com/org/repo.git", "org/repo"),
+ ("https://bitbucket.org/org/repo.git", "org/repo"),
+ ("https://codeberg.org/org/repo.git", "org/repo"),
+ ("https://gitea.com/org/repo.git", "org/repo"),
+ ("https://atomgit.com/org/repo.git", "org/repo"),
+ ("https://git.sr.ht/~user/repo", "_user/repo"),
+ ],
+ )
+ async def test_generic_code_hosts_are_marked_for_code_repository_parser(
+ self,
+ accessor: GitAccessor,
+ tmp_path: Path,
+ source: str,
+ repo_name: str,
+ ) -> None:
+ with patch.object(accessor, "_run_git", new_callable=AsyncMock):
+ assert await accessor._git_clone(source, str(tmp_path)) == repo_name
+
+ assert (tmp_path / ".git_source_repo").read_text(encoding="utf-8") == source
+ assert await DirectoryParser._is_git_repository(tmp_path) is True
+
async def test_github_archive_encodes_fragment_in_ref(
self, accessor: GitAccessor, tmp_path: Path
) -> None: