Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions src/repo2rlenv/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from __future__ import annotations

from enum import StrEnum
from urllib.parse import urlparse


class Capability(StrEnum):
Expand Down Expand Up @@ -50,17 +51,29 @@ class SourceKind(StrEnum):
}


def _remote_host(url: str) -> str:
"""Return the lowercased hostname from a scheme or SCP-style git URL."""
if "://" in url:
return (urlparse(url).hostname or "").lower()
if url.startswith("git@"):
host, sep, _rest = url[len("git@") :].partition(":")
if sep:
return host.lower()
return ""


def detect_source_kind(url: str) -> SourceKind:
"""Classify a (normalized) repo URL into a source kind.

`RepoSpec.normalize_url` canonicalizes local paths to ``file://`` and
leaves github/gitlab URLs intact, so detection is a simple prefix/host
check. A bare ``owner/name`` has already been expanded to a github URL.
leaves github/gitlab URLs intact, so detection inspects the scheme/host
rather than matching hostnames as arbitrary substrings. A bare
``owner/name`` has already been expanded to a github URL.
"""
u = url.strip()
if u.startswith("file://"):
if u.lower().startswith("file://"):
return SourceKind.LOCAL
if "gitlab.com" in u or u.startswith("git@gitlab.com"):
if _remote_host(u) == "gitlab.com":
return SourceKind.GITLAB
return SourceKind.GITHUB

Expand Down
16 changes: 16 additions & 0 deletions tests/test_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,25 @@ def test_issues_capability_present_on_remotes_only():
def test_detect_source_kind():
assert detect_source_kind("https://github.com/a/b") == SourceKind.GITHUB
assert detect_source_kind("https://gitlab.com/a/b") == SourceKind.GITLAB
assert detect_source_kind("https://GITLAB.COM/a/b") == SourceKind.GITLAB
assert detect_source_kind("git@gitlab.com:a/b") == SourceKind.GITLAB
assert detect_source_kind("ssh://git@gitlab.com/a/b") == SourceKind.GITLAB
assert detect_source_kind("file:///tmp/a") == SourceKind.LOCAL


@pytest.mark.parametrize(
"url",
[
"https://github.com/myorg/gitlab.com-mirror",
"git@github.com:myorg/gitlab.com-mirror",
"https://mygitlab.com/org/repo",
"git@gitlab.com.example.org:org/repo",
],
)
def test_detect_source_kind_ignores_non_gitlab_hosts_containing_gitlab_substring(url):
assert detect_source_kind(url) == SourceKind.GITHUB


def _allowed(name: str, kind: SourceKind) -> bool:
req = getattr(PIPELINES[name], "required_capabilities", frozenset())
return req <= capabilities_for(kind)
Expand Down