s-gitkit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gitkit/__init__.py +35 -0
- gitkit/errors.py +10 -0
- gitkit/factory.py +153 -0
- gitkit/github_provider.py +144 -0
- gitkit/gitlab_provider.py +122 -0
- gitkit/types.py +53 -0
- s_gitkit-0.1.0.dist-info/METADATA +96 -0
- s_gitkit-0.1.0.dist-info/RECORD +10 -0
- s_gitkit-0.1.0.dist-info/WHEEL +4 -0
- s_gitkit-0.1.0.dist-info/licenses/LICENSE +21 -0
gitkit/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Git-хостинг абстракция: GitHub/GitLab read-layer.
|
|
2
|
+
|
|
3
|
+
Единая абстракция над git-хостингами (GitHub, GitLab, self-hosted GitLab):
|
|
4
|
+
- GitProvider Protocol (read-only: list_tags, resolve_tag, fetch_file, fetch_tree, clone_url)
|
|
5
|
+
- GitRepoRef (распарсенная ссылка на репо: host/owner/name)
|
|
6
|
+
- GitHubProvider, GitLabProvider (конкретные реализации)
|
|
7
|
+
- GitProviderFactory (фабрика с поддержкой self-hosted)
|
|
8
|
+
- Набор исключений (GitProviderError, UnsupportedGitHostError)
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from gitkit.errors import GitProviderError, UnsupportedGitHostError
|
|
13
|
+
from gitkit.factory import GitProviderFactory, detect_provider, parse_repo_ref
|
|
14
|
+
from gitkit.github_provider import GitHubProvider
|
|
15
|
+
from gitkit.gitlab_provider import GitLabProvider
|
|
16
|
+
from gitkit.types import GitProvider, GitRepoRef, GitTreeEntry
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
# Типы и интерфейсы
|
|
22
|
+
"GitRepoRef",
|
|
23
|
+
"GitTreeEntry",
|
|
24
|
+
"GitProvider",
|
|
25
|
+
# Исключения
|
|
26
|
+
"GitProviderError",
|
|
27
|
+
"UnsupportedGitHostError",
|
|
28
|
+
# Провайдеры
|
|
29
|
+
"GitHubProvider",
|
|
30
|
+
"GitLabProvider",
|
|
31
|
+
# Фабрика
|
|
32
|
+
"GitProviderFactory",
|
|
33
|
+
"parse_repo_ref",
|
|
34
|
+
"detect_provider",
|
|
35
|
+
]
|
gitkit/errors.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Исключения git-провайдеров."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class GitProviderError(RuntimeError):
|
|
6
|
+
"""Базовая ошибка провайдера (сетевые/API-сбои уровня абстракции)."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class UnsupportedGitHostError(GitProviderError):
|
|
10
|
+
"""Host не поддерживается (не github.com / не известный GitLab-хост)."""
|
gitkit/factory.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Парсинг repo URL + выбор провайдера по host.
|
|
2
|
+
|
|
3
|
+
`parse_repo_ref` понимает обе формы git-URL:
|
|
4
|
+
- https://host/owner/.../name(.git)
|
|
5
|
+
- scp-like: git@host:owner/.../name(.git)
|
|
6
|
+
|
|
7
|
+
`detect_provider` выбирает GitHubProvider (github.com) или GitLabProvider
|
|
8
|
+
(gitlab.com + переданные self_hosted_hosts).
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
import urllib.parse
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from gitkit.errors import GitProviderError, UnsupportedGitHostError
|
|
18
|
+
from gitkit.github_provider import GitHubProvider
|
|
19
|
+
from gitkit.gitlab_provider import GitLabProvider
|
|
20
|
+
from gitkit.types import GitProvider, GitRepoRef
|
|
21
|
+
|
|
22
|
+
_GITHUB_HOST = "github.com"
|
|
23
|
+
_GITLAB_HOST = "gitlab.com"
|
|
24
|
+
|
|
25
|
+
# git@host:owner/.../name(.git)
|
|
26
|
+
_SCP_RE = re.compile(r"^(?:[\w.+-]+@)?(?P<host>[\w.-]+):(?P<path>.+)$")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def parse_repo_ref(repo_url: str) -> GitRepoRef:
|
|
30
|
+
"""Распарсить http(s) или scp-like git URL в GitRepoRef.
|
|
31
|
+
|
|
32
|
+
`owner` сохраняет промежуточные подгруппы (для GitLab), `name` — последний
|
|
33
|
+
сегмент пути без суффикса `.git`.
|
|
34
|
+
"""
|
|
35
|
+
raw = repo_url.strip()
|
|
36
|
+
if not raw:
|
|
37
|
+
raise GitProviderError("Пустой repo URL")
|
|
38
|
+
|
|
39
|
+
host: str
|
|
40
|
+
path: str
|
|
41
|
+
|
|
42
|
+
if raw.startswith(("http://", "https://", "git://", "ssh://")):
|
|
43
|
+
parsed = urllib.parse.urlparse(raw)
|
|
44
|
+
host = (parsed.hostname or "").lower()
|
|
45
|
+
path = parsed.path
|
|
46
|
+
else:
|
|
47
|
+
scp = _SCP_RE.match(raw)
|
|
48
|
+
if not scp:
|
|
49
|
+
raise GitProviderError(f"Не удалось распарсить repo URL: {repo_url!r}")
|
|
50
|
+
host = scp.group("host").lower()
|
|
51
|
+
path = scp.group("path")
|
|
52
|
+
|
|
53
|
+
if not host:
|
|
54
|
+
raise GitProviderError(f"В URL не найден host: {repo_url!r}")
|
|
55
|
+
|
|
56
|
+
segments = [s for s in path.strip("/").split("/") if s]
|
|
57
|
+
if len(segments) < 2:
|
|
58
|
+
raise GitProviderError(
|
|
59
|
+
f"URL должен содержать owner и name: {repo_url!r}"
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
name = segments[-1]
|
|
63
|
+
if name.endswith(".git"):
|
|
64
|
+
name = name[: -len(".git")]
|
|
65
|
+
owner = "/".join(segments[:-1])
|
|
66
|
+
if not name:
|
|
67
|
+
raise GitProviderError(f"Пустое имя репозитория: {repo_url!r}")
|
|
68
|
+
|
|
69
|
+
return GitRepoRef(raw_url=raw, host=host, owner=owner, name=name)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
_GITHUB_API_BASE = "https://api.github.com"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def detect_provider(
|
|
76
|
+
repo_url: str,
|
|
77
|
+
*,
|
|
78
|
+
token: str | None = None,
|
|
79
|
+
http_client: httpx.AsyncClient | None = None,
|
|
80
|
+
self_hosted_hosts: list[str] | None = None,
|
|
81
|
+
github_base_url: str = _GITHUB_API_BASE,
|
|
82
|
+
) -> tuple[GitProvider, GitRepoRef]:
|
|
83
|
+
"""Выбрать провайдер по host распарсенного URL.
|
|
84
|
+
|
|
85
|
+
- github.com → GitHubProvider (с заданным ``github_base_url`` — для GHE)
|
|
86
|
+
- gitlab.com и любой host из self_hosted_hosts → GitLabProvider
|
|
87
|
+
- иначе → UnsupportedGitHostError
|
|
88
|
+
"""
|
|
89
|
+
repo = parse_repo_ref(repo_url)
|
|
90
|
+
host = repo.host.lower()
|
|
91
|
+
gitlab_hosts = {_GITLAB_HOST, *(h.lower() for h in (self_hosted_hosts or []))}
|
|
92
|
+
|
|
93
|
+
provider: GitProvider
|
|
94
|
+
if host == _GITHUB_HOST:
|
|
95
|
+
provider = GitHubProvider(
|
|
96
|
+
host=host,
|
|
97
|
+
base_url=github_base_url,
|
|
98
|
+
token=token,
|
|
99
|
+
http_client=http_client,
|
|
100
|
+
)
|
|
101
|
+
elif host in gitlab_hosts:
|
|
102
|
+
provider = GitLabProvider(
|
|
103
|
+
host=host,
|
|
104
|
+
base_url=f"https://{host}",
|
|
105
|
+
token=token,
|
|
106
|
+
http_client=http_client,
|
|
107
|
+
)
|
|
108
|
+
else:
|
|
109
|
+
raise UnsupportedGitHostError(
|
|
110
|
+
f"Неподдерживаемый git-host: {host!r} "
|
|
111
|
+
"(ожидается github.com, gitlab.com или self-hosted GitLab из конфига)"
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
return provider, repo
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class GitProviderFactory:
|
|
118
|
+
"""Конфиг-связанная фабрика провайдеров.
|
|
119
|
+
|
|
120
|
+
Держит настройки окружения (self-hosted GitLab-хосты, GitHub base_url) и
|
|
121
|
+
отдаёт ``detect_provider`` уже с ними. Токен передаётся per-call.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
def __init__(
|
|
125
|
+
self,
|
|
126
|
+
*,
|
|
127
|
+
self_hosted_hosts: list[str] | None = None,
|
|
128
|
+
github_base_url: str = _GITHUB_API_BASE,
|
|
129
|
+
) -> None:
|
|
130
|
+
self._self_hosted_hosts = list(self_hosted_hosts or [])
|
|
131
|
+
self._github_base_url = github_base_url
|
|
132
|
+
|
|
133
|
+
def parse(self, repo_url: str) -> GitRepoRef:
|
|
134
|
+
"""Распарсить URL в ``GitRepoRef`` без конструирования провайдера.
|
|
135
|
+
|
|
136
|
+
Нужно, чтобы резолвер выбрал токен по host ДО создания провайдера.
|
|
137
|
+
"""
|
|
138
|
+
return parse_repo_ref(repo_url)
|
|
139
|
+
|
|
140
|
+
def create(
|
|
141
|
+
self,
|
|
142
|
+
repo_url: str,
|
|
143
|
+
*,
|
|
144
|
+
token: str | None = None,
|
|
145
|
+
http_client: httpx.AsyncClient | None = None,
|
|
146
|
+
) -> tuple[GitProvider, GitRepoRef]:
|
|
147
|
+
return detect_provider(
|
|
148
|
+
repo_url,
|
|
149
|
+
token=token,
|
|
150
|
+
http_client=http_client,
|
|
151
|
+
self_hosted_hosts=self._self_hosted_hosts,
|
|
152
|
+
github_base_url=self._github_base_url,
|
|
153
|
+
)
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""GitHubProvider — read-слой над GitHub REST API (api.github.com).
|
|
2
|
+
|
|
3
|
+
Реализует `GitProvider` для произвольного репозитория github.com.
|
|
4
|
+
Auth опционален: с токеном — `Authorization: Bearer <token>`, без — аноним
|
|
5
|
+
(подходит для публичных репо, но с rate-limit'ом).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import urllib.parse
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
from tenacity import (
|
|
14
|
+
AsyncRetrying,
|
|
15
|
+
retry_if_exception_type,
|
|
16
|
+
stop_after_attempt,
|
|
17
|
+
wait_exponential,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
from gitkit.errors import GitProviderError
|
|
21
|
+
from gitkit.types import GitRepoRef, GitTreeEntry
|
|
22
|
+
|
|
23
|
+
_API_VERSION = "2022-11-28"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _retry() -> AsyncRetrying:
|
|
27
|
+
return AsyncRetrying(
|
|
28
|
+
stop=stop_after_attempt(3),
|
|
29
|
+
wait=wait_exponential(multiplier=1, min=1, max=8),
|
|
30
|
+
retry=retry_if_exception_type(httpx.TransportError),
|
|
31
|
+
reraise=True,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _headers(token: str | None) -> dict[str, str]:
|
|
36
|
+
headers = {
|
|
37
|
+
"Accept": "application/vnd.github+json",
|
|
38
|
+
"X-GitHub-Api-Version": _API_VERSION,
|
|
39
|
+
}
|
|
40
|
+
if token:
|
|
41
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
42
|
+
return headers
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class GitHubProvider:
|
|
46
|
+
"""Read-only провайдер для github.com."""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
*,
|
|
51
|
+
host: str = "github.com",
|
|
52
|
+
base_url: str = "https://api.github.com",
|
|
53
|
+
token: str | None = None,
|
|
54
|
+
http_client: httpx.AsyncClient | None = None,
|
|
55
|
+
) -> None:
|
|
56
|
+
self.host = host
|
|
57
|
+
self._base_url = base_url.rstrip("/")
|
|
58
|
+
self._token = token
|
|
59
|
+
self._owns_client = http_client is None
|
|
60
|
+
self._client = http_client or httpx.AsyncClient(
|
|
61
|
+
timeout=30.0, headers=_headers(token)
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
async def close(self) -> None:
|
|
65
|
+
if self._owns_client and self._client is not None:
|
|
66
|
+
await self._client.aclose()
|
|
67
|
+
|
|
68
|
+
def _repo_base(self, repo: GitRepoRef) -> str:
|
|
69
|
+
return f"{self._base_url}/repos/{repo.owner}/{repo.name}"
|
|
70
|
+
|
|
71
|
+
async def _get(
|
|
72
|
+
self, url: str, *, headers: dict[str, str] | None = None
|
|
73
|
+
) -> httpx.Response:
|
|
74
|
+
resp: httpx.Response | None = None
|
|
75
|
+
async for attempt in _retry():
|
|
76
|
+
with attempt:
|
|
77
|
+
resp = await self._client.get(url, headers=headers)
|
|
78
|
+
assert resp is not None # _retry reraises; resp set on success
|
|
79
|
+
return resp
|
|
80
|
+
|
|
81
|
+
async def list_tags(self, *, repo: GitRepoRef) -> list[str]:
|
|
82
|
+
url = f"{self._repo_base(repo)}/tags?per_page=100"
|
|
83
|
+
resp = await self._get(url)
|
|
84
|
+
resp.raise_for_status()
|
|
85
|
+
return [t["name"] for t in resp.json()]
|
|
86
|
+
|
|
87
|
+
async def resolve_tag(self, *, repo: GitRepoRef, tag: str) -> str:
|
|
88
|
+
encoded_tag = urllib.parse.quote(tag, safe="")
|
|
89
|
+
url = f"{self._repo_base(repo)}/git/ref/tags/{encoded_tag}"
|
|
90
|
+
resp = await self._get(url)
|
|
91
|
+
if resp.status_code == 404:
|
|
92
|
+
# Аннотированный тег или прямой коммит/ветка — fallback на /commits.
|
|
93
|
+
commits_url = f"{self._repo_base(repo)}/commits/{encoded_tag}"
|
|
94
|
+
resp = await self._get(commits_url)
|
|
95
|
+
resp.raise_for_status()
|
|
96
|
+
return resp.json()["sha"]
|
|
97
|
+
resp.raise_for_status()
|
|
98
|
+
data = resp.json()
|
|
99
|
+
obj = data["object"]
|
|
100
|
+
if obj.get("type") == "tag":
|
|
101
|
+
# Аннотированный тег → разыменовать tag-object до коммита.
|
|
102
|
+
tag_resp = await self._get(obj["url"])
|
|
103
|
+
tag_resp.raise_for_status()
|
|
104
|
+
return tag_resp.json()["object"]["sha"]
|
|
105
|
+
return obj["sha"]
|
|
106
|
+
|
|
107
|
+
async def fetch_file(self, *, repo: GitRepoRef, ref: str, path: str) -> bytes:
|
|
108
|
+
encoded_path = urllib.parse.quote(path.lstrip("/"), safe="/")
|
|
109
|
+
encoded_ref = urllib.parse.quote(ref, safe="")
|
|
110
|
+
url = f"{self._repo_base(repo)}/contents/{encoded_path}?ref={encoded_ref}"
|
|
111
|
+
# Accept: raw → тело ответа = сырое содержимое файла.
|
|
112
|
+
resp = await self._get(url, headers={"Accept": "application/vnd.github.raw"})
|
|
113
|
+
resp.raise_for_status()
|
|
114
|
+
ctype = resp.headers.get("content-type", "")
|
|
115
|
+
if "application/json" in ctype:
|
|
116
|
+
# Сервер вернул JSON-метаданные (raw не применился) → decode base64.
|
|
117
|
+
data = resp.json()
|
|
118
|
+
if data.get("encoding") == "base64":
|
|
119
|
+
return base64.b64decode(data["content"])
|
|
120
|
+
raise GitProviderError(
|
|
121
|
+
f"Неожиданный формат contents-ответа для {path!r}"
|
|
122
|
+
)
|
|
123
|
+
return resp.content
|
|
124
|
+
|
|
125
|
+
async def fetch_tree(self, *, repo: GitRepoRef, ref: str) -> list[GitTreeEntry]:
|
|
126
|
+
encoded_ref = urllib.parse.quote(ref, safe="")
|
|
127
|
+
url = f"{self._repo_base(repo)}/git/trees/{encoded_ref}?recursive=1"
|
|
128
|
+
resp = await self._get(url)
|
|
129
|
+
resp.raise_for_status()
|
|
130
|
+
data = resp.json()
|
|
131
|
+
entries: list[GitTreeEntry] = []
|
|
132
|
+
for node in data.get("tree", []):
|
|
133
|
+
node_type = "tree" if node.get("type") == "tree" else "blob"
|
|
134
|
+
entries.append(
|
|
135
|
+
GitTreeEntry(
|
|
136
|
+
path=node["path"],
|
|
137
|
+
type=node_type,
|
|
138
|
+
size=node.get("size"),
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
return entries
|
|
142
|
+
|
|
143
|
+
def clone_url(self, *, repo: GitRepoRef) -> str:
|
|
144
|
+
return f"https://{self.host}/{repo.owner}/{repo.name}.git"
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""GitLabProvider — read-слой над GitLab REST API v4.
|
|
2
|
+
|
|
3
|
+
Реализует `GitProvider` для произвольного репозитория на gitlab.com или на
|
|
4
|
+
self-hosted GitLab. Project id = url-encoded `"{owner}/{name}"` (owner может
|
|
5
|
+
содержать подгруппы). Auth — header `PRIVATE-TOKEN` (как для gitlab.com).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import urllib.parse
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
from tenacity import (
|
|
13
|
+
AsyncRetrying,
|
|
14
|
+
retry_if_exception_type,
|
|
15
|
+
stop_after_attempt,
|
|
16
|
+
wait_exponential,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from gitkit.types import GitRepoRef, GitTreeEntry
|
|
20
|
+
|
|
21
|
+
_TREE_MAX_PAGES = 100 # защита от бесконечного цикла пагинации
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _retry() -> AsyncRetrying:
|
|
25
|
+
return AsyncRetrying(
|
|
26
|
+
stop=stop_after_attempt(3),
|
|
27
|
+
wait=wait_exponential(multiplier=1, min=1, max=8),
|
|
28
|
+
retry=retry_if_exception_type(httpx.TransportError),
|
|
29
|
+
reraise=True,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class GitLabProvider:
|
|
34
|
+
"""Read-only провайдер для gitlab.com / self-hosted GitLab."""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
*,
|
|
39
|
+
host: str = "gitlab.com",
|
|
40
|
+
base_url: str = "https://gitlab.com",
|
|
41
|
+
token: str | None = None,
|
|
42
|
+
http_client: httpx.AsyncClient | None = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
self.host = host
|
|
45
|
+
self._base_url = base_url.rstrip("/")
|
|
46
|
+
self._token = token
|
|
47
|
+
self._owns_client = http_client is None
|
|
48
|
+
headers = {"PRIVATE-TOKEN": token} if token else {}
|
|
49
|
+
self._client = http_client or httpx.AsyncClient(
|
|
50
|
+
timeout=30.0, headers=headers
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
async def close(self) -> None:
|
|
54
|
+
if self._owns_client and self._client is not None:
|
|
55
|
+
await self._client.aclose()
|
|
56
|
+
|
|
57
|
+
def _project_id(self, repo: GitRepoRef) -> str:
|
|
58
|
+
return urllib.parse.quote(f"{repo.owner}/{repo.name}", safe="")
|
|
59
|
+
|
|
60
|
+
def _project_base(self, repo: GitRepoRef) -> str:
|
|
61
|
+
return f"{self._base_url}/api/v4/projects/{self._project_id(repo)}"
|
|
62
|
+
|
|
63
|
+
async def _get(self, url: str) -> httpx.Response:
|
|
64
|
+
resp: httpx.Response | None = None
|
|
65
|
+
async for attempt in _retry():
|
|
66
|
+
with attempt:
|
|
67
|
+
resp = await self._client.get(url)
|
|
68
|
+
assert resp is not None # _retry reraises; resp set on success
|
|
69
|
+
return resp
|
|
70
|
+
|
|
71
|
+
async def list_tags(self, *, repo: GitRepoRef) -> list[str]:
|
|
72
|
+
url = f"{self._project_base(repo)}/repository/tags?per_page=100"
|
|
73
|
+
resp = await self._get(url)
|
|
74
|
+
resp.raise_for_status()
|
|
75
|
+
return [t["name"] for t in resp.json()]
|
|
76
|
+
|
|
77
|
+
async def resolve_tag(self, *, repo: GitRepoRef, tag: str) -> str:
|
|
78
|
+
encoded_tag = urllib.parse.quote(tag, safe="")
|
|
79
|
+
url = f"{self._project_base(repo)}/repository/commits/{encoded_tag}"
|
|
80
|
+
resp = await self._get(url)
|
|
81
|
+
resp.raise_for_status()
|
|
82
|
+
return resp.json()["id"]
|
|
83
|
+
|
|
84
|
+
async def fetch_file(self, *, repo: GitRepoRef, ref: str, path: str) -> bytes:
|
|
85
|
+
encoded_path = urllib.parse.quote(path.lstrip("/"), safe="")
|
|
86
|
+
encoded_ref = urllib.parse.quote(ref, safe="")
|
|
87
|
+
url = (
|
|
88
|
+
f"{self._project_base(repo)}/repository/files/"
|
|
89
|
+
f"{encoded_path}/raw?ref={encoded_ref}"
|
|
90
|
+
)
|
|
91
|
+
resp = await self._get(url)
|
|
92
|
+
resp.raise_for_status()
|
|
93
|
+
return resp.content
|
|
94
|
+
|
|
95
|
+
async def fetch_tree(self, *, repo: GitRepoRef, ref: str) -> list[GitTreeEntry]:
|
|
96
|
+
entries: list[GitTreeEntry] = []
|
|
97
|
+
page = 1
|
|
98
|
+
while page <= _TREE_MAX_PAGES:
|
|
99
|
+
encoded_ref = urllib.parse.quote(ref, safe="")
|
|
100
|
+
url = (
|
|
101
|
+
f"{self._project_base(repo)}/repository/tree"
|
|
102
|
+
f"?recursive=true&per_page=100&ref={encoded_ref}&page={page}"
|
|
103
|
+
)
|
|
104
|
+
resp = await self._get(url)
|
|
105
|
+
resp.raise_for_status()
|
|
106
|
+
for node in resp.json():
|
|
107
|
+
node_type = "tree" if node.get("type") == "tree" else "blob"
|
|
108
|
+
entries.append(
|
|
109
|
+
GitTreeEntry(
|
|
110
|
+
path=node["path"],
|
|
111
|
+
type=node_type,
|
|
112
|
+
size=None, # GitLab tree API не отдаёт размер
|
|
113
|
+
)
|
|
114
|
+
)
|
|
115
|
+
next_page = resp.headers.get("x-next-page", "")
|
|
116
|
+
if not next_page:
|
|
117
|
+
break
|
|
118
|
+
page = int(next_page)
|
|
119
|
+
return entries
|
|
120
|
+
|
|
121
|
+
def clone_url(self, *, repo: GitRepoRef) -> str:
|
|
122
|
+
return f"{self._base_url}/{repo.owner}/{repo.name}.git"
|
gitkit/types.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Типы и Protocol для git-провайдеров."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class GitRepoRef:
|
|
10
|
+
"""Ссылка на внешний git-репозиторий, распарсенная из URL.
|
|
11
|
+
|
|
12
|
+
`owner` для GitLab может содержать подгруппы (`group/subgroup`).
|
|
13
|
+
`raw_url` сохраняет исходный URL как был передан (для логов/трейсинга).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
raw_url: str
|
|
17
|
+
host: str
|
|
18
|
+
owner: str
|
|
19
|
+
name: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class GitTreeEntry:
|
|
24
|
+
"""Запись дерева репозитория для указанного ref."""
|
|
25
|
+
|
|
26
|
+
path: str
|
|
27
|
+
type: str # "blob" | "tree"
|
|
28
|
+
size: int | None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class GitProvider(Protocol):
|
|
32
|
+
"""Read-only абстракция над git-хостингом (GitHub / GitLab).
|
|
33
|
+
|
|
34
|
+
Интерфейс провайдера для работы с произвольным внешним репозиторием.
|
|
35
|
+
Поддерживает list_tags, resolve_tag, fetch_file, fetch_tree и clone_url.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
host: str
|
|
39
|
+
|
|
40
|
+
async def list_tags(self, *, repo: GitRepoRef) -> list[str]:
|
|
41
|
+
"""Возвращает имена тегов репозитория (newest first, как отдаёт API)."""
|
|
42
|
+
|
|
43
|
+
async def resolve_tag(self, *, repo: GitRepoRef, tag: str) -> str:
|
|
44
|
+
"""Возвращает commit SHA, на который указывает тег."""
|
|
45
|
+
|
|
46
|
+
async def fetch_file(self, *, repo: GitRepoRef, ref: str, path: str) -> bytes:
|
|
47
|
+
"""Возвращает сырое содержимое файла по ref."""
|
|
48
|
+
|
|
49
|
+
async def fetch_tree(self, *, repo: GitRepoRef, ref: str) -> list[GitTreeEntry]:
|
|
50
|
+
"""Возвращает рекурсивное дерево файлов/каталогов для ref."""
|
|
51
|
+
|
|
52
|
+
def clone_url(self, *, repo: GitRepoRef) -> str:
|
|
53
|
+
"""Детерминированный https clone URL (с суффиксом .git)."""
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: s-gitkit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Git-хостинг абстракция: GitHub/GitLab read-layer (provider pattern для любых репозиториев + фабрика)
|
|
5
|
+
Author: Dmitry
|
|
6
|
+
License: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Requires-Dist: httpx>=0.27
|
|
10
|
+
Requires-Dist: stamina>=24.3
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
13
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
14
|
+
Requires-Dist: respx>=0.21; extra == 'dev'
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# gitkit
|
|
18
|
+
|
|
19
|
+
**Git-хостинг абстракция: GitHub/GitLab read-layer.**
|
|
20
|
+
|
|
21
|
+
Единая интерфейс для работы с произвольными git-репозиториями на GitHub, GitLab и self-hosted GitLab инстансах. Provider pattern позволяет добавить новых провайдеров.
|
|
22
|
+
|
|
23
|
+
## Возможности
|
|
24
|
+
|
|
25
|
+
- **GitProvider Protocol** — read-only операции (list_tags, resolve_tag, fetch_file, fetch_tree, clone_url)
|
|
26
|
+
- **GitHubProvider** — поддержка github.com и GitHub Enterprise
|
|
27
|
+
- **GitLabProvider** — поддержка gitlab.com и self-hosted GitLab
|
|
28
|
+
- **GitProviderFactory** — автоматический выбор провайдера по URL
|
|
29
|
+
- **Парсинг URL** — поддержка https и scp-like git URL-ов
|
|
30
|
+
- **Retry-политика** — автоматический retry с exponential backoff (3 попытки)
|
|
31
|
+
|
|
32
|
+
## Установка
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
uv add s-gitkit
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Имя пакета для импорта — `gitkit`.
|
|
39
|
+
|
|
40
|
+
## Быстрый старт
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
import gitkit
|
|
44
|
+
|
|
45
|
+
# Автоматический выбор провайдера по URL
|
|
46
|
+
factory = gitkit.GitProviderFactory()
|
|
47
|
+
provider, repo = factory.create(
|
|
48
|
+
"https://github.com/owner/repo.git",
|
|
49
|
+
token="ghp_xxx" # опционально
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# Работа с репозиторием
|
|
53
|
+
tags = await provider.list_tags(repo=repo)
|
|
54
|
+
sha = await provider.resolve_tag(repo=repo, tag="v1.0.0")
|
|
55
|
+
content = await provider.fetch_file(repo=repo, ref="main", path="README.md")
|
|
56
|
+
tree = await provider.fetch_tree(repo=repo, ref="main")
|
|
57
|
+
|
|
58
|
+
# Clone URL
|
|
59
|
+
clone = provider.clone_url(repo=repo)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Self-hosted GitLab
|
|
63
|
+
|
|
64
|
+
Для поддержки self-hosted GitLab инстансов передайте хосты при создании фабрики:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
factory = gitkit.GitProviderFactory(
|
|
68
|
+
self_hosted_hosts=["git.example.com", "gitlab.company.org"]
|
|
69
|
+
)
|
|
70
|
+
provider, repo = factory.create(
|
|
71
|
+
"https://git.example.com/group/project.git",
|
|
72
|
+
token="glpat_xxx"
|
|
73
|
+
)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## GitHub Enterprise
|
|
77
|
+
|
|
78
|
+
Для GitHub Enterprise используйте `github_base_url`:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
factory = gitkit.GitProviderFactory(
|
|
82
|
+
github_base_url="https://github.enterprise.com/api/v3"
|
|
83
|
+
)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Разработка
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
uv sync --extra dev
|
|
90
|
+
uv run pytest -q
|
|
91
|
+
uv run ruff check gitkit
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Лицензия
|
|
95
|
+
|
|
96
|
+
MIT © 2026 Dmitry.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
gitkit/__init__.py,sha256=v9ZbK15N6QwcJth5hs7xsqypim7qWzelsac9_OD5mLY,1311
|
|
2
|
+
gitkit/errors.py,sha256=P1gz1BOpDdZIYxkCkW3HHQvod8QR-wJ_q2TsDNREYLE,415
|
|
3
|
+
gitkit/factory.py,sha256=YgjkGdJGoI7MteGSkcW72N93Zv-Jse7vvq-aUM7DTuA,5110
|
|
4
|
+
gitkit/github_provider.py,sha256=WnpnOMNeG0jGqI3pEkHQRwUtLZSdsDkVL5aWTUylBSg,5479
|
|
5
|
+
gitkit/gitlab_provider.py,sha256=GbGpyYmEsQuYK9UlAfzNktzQFpErLX2HTjCr348Xbvg,4462
|
|
6
|
+
gitkit/types.py,sha256=VaNKNUP5X6q3ChwmilefWec-z3EkTTP5rwL3wT3UmVc,2066
|
|
7
|
+
s_gitkit-0.1.0.dist-info/METADATA,sha256=V5sNm2dzTfA2ntNKxwRPs-x0CI0F2NVHP1gaUP73JQI,2922
|
|
8
|
+
s_gitkit-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
9
|
+
s_gitkit-0.1.0.dist-info/licenses/LICENSE,sha256=j9GKJmUNdQuKRUbKhbpv0uyMaL99xsxE6L2TDtXuaZ4,1063
|
|
10
|
+
s_gitkit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dmitry
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|