s-gitkit 0.1.0__tar.gz
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.
- s_gitkit-0.1.0/.gitignore +52 -0
- s_gitkit-0.1.0/.gitlab-ci.yml +32 -0
- s_gitkit-0.1.0/AGENTS.md +57 -0
- s_gitkit-0.1.0/CHANGELOG.md +22 -0
- s_gitkit-0.1.0/DETAILS.txt +43 -0
- s_gitkit-0.1.0/LICENSE +21 -0
- s_gitkit-0.1.0/PKG-INFO +96 -0
- s_gitkit-0.1.0/README.md +80 -0
- s_gitkit-0.1.0/gitkit/__init__.py +35 -0
- s_gitkit-0.1.0/gitkit/errors.py +10 -0
- s_gitkit-0.1.0/gitkit/factory.py +153 -0
- s_gitkit-0.1.0/gitkit/github_provider.py +144 -0
- s_gitkit-0.1.0/gitkit/gitlab_provider.py +122 -0
- s_gitkit-0.1.0/gitkit/types.py +53 -0
- s_gitkit-0.1.0/pyproject.toml +38 -0
- s_gitkit-0.1.0/tests/__init__.py +1 -0
- s_gitkit-0.1.0/tests/test_factory.py +149 -0
- s_gitkit-0.1.0/tests/test_providers.py +179 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
*.so
|
|
6
|
+
.Python
|
|
7
|
+
build/
|
|
8
|
+
develop-eggs/
|
|
9
|
+
dist/
|
|
10
|
+
downloads/
|
|
11
|
+
eggs/
|
|
12
|
+
.eggs/
|
|
13
|
+
lib/
|
|
14
|
+
lib64/
|
|
15
|
+
parts/
|
|
16
|
+
sdist/
|
|
17
|
+
var/
|
|
18
|
+
wheels/
|
|
19
|
+
pip-wheel-metadata/
|
|
20
|
+
share/python-wheels/
|
|
21
|
+
*.egg-info/
|
|
22
|
+
.installed.cfg
|
|
23
|
+
*.egg
|
|
24
|
+
MANIFEST
|
|
25
|
+
|
|
26
|
+
# Virtual environments
|
|
27
|
+
.venv
|
|
28
|
+
venv/
|
|
29
|
+
ENV/
|
|
30
|
+
env/
|
|
31
|
+
|
|
32
|
+
# IDE
|
|
33
|
+
.vscode/
|
|
34
|
+
.idea/
|
|
35
|
+
*.swp
|
|
36
|
+
*.swo
|
|
37
|
+
*~
|
|
38
|
+
.DS_Store
|
|
39
|
+
|
|
40
|
+
# Testing
|
|
41
|
+
.pytest_cache/
|
|
42
|
+
.coverage
|
|
43
|
+
htmlcov/
|
|
44
|
+
.tox/
|
|
45
|
+
.hypothesis/
|
|
46
|
+
*.cover
|
|
47
|
+
|
|
48
|
+
# Ruff
|
|
49
|
+
.ruff_cache/
|
|
50
|
+
|
|
51
|
+
# Lock files (optional, uncomment if you want to commit them)
|
|
52
|
+
# uv.lock
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
stages:
|
|
2
|
+
- test
|
|
3
|
+
- publish
|
|
4
|
+
|
|
5
|
+
variables:
|
|
6
|
+
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
|
|
7
|
+
|
|
8
|
+
cache:
|
|
9
|
+
paths:
|
|
10
|
+
- .cache/pip
|
|
11
|
+
- .venv/
|
|
12
|
+
|
|
13
|
+
before_script:
|
|
14
|
+
- python -m pip install --upgrade pip
|
|
15
|
+
- python -m pip install uv
|
|
16
|
+
- uv sync --extra dev
|
|
17
|
+
|
|
18
|
+
test:
|
|
19
|
+
stage: test
|
|
20
|
+
image: python:3.11
|
|
21
|
+
script:
|
|
22
|
+
- uv run pytest -q --cov=gitkit --cov-report=term-missing
|
|
23
|
+
- uv run ruff check gitkit
|
|
24
|
+
|
|
25
|
+
publish:
|
|
26
|
+
stage: publish
|
|
27
|
+
image: python:3.11
|
|
28
|
+
only:
|
|
29
|
+
- tags
|
|
30
|
+
script:
|
|
31
|
+
- uv build
|
|
32
|
+
- uv publish
|
s_gitkit-0.1.0/AGENTS.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Агенты и разработка s-gitkit
|
|
2
|
+
|
|
3
|
+
## Архитектура
|
|
4
|
+
|
|
5
|
+
gitkit — это миниатюрный, самостоятельный кит (зависит только от httpx, stamina и stdlib).
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
gitkit
|
|
9
|
+
├── types.py — GitRepoRef, GitTreeEntry, GitProvider Protocol
|
|
10
|
+
├── errors.py — GitProviderError, UnsupportedGitHostError
|
|
11
|
+
├── github_provider.py — GitHubProvider (github.com + GHE)
|
|
12
|
+
├── gitlab_provider.py — GitLabProvider (gitlab.com + self-hosted)
|
|
13
|
+
├── factory.py — GitProviderFactory + parse/detect функции
|
|
14
|
+
└── __init__.py — public API
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Разработка
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
# Установка зависимостей
|
|
21
|
+
uv sync --extra dev
|
|
22
|
+
|
|
23
|
+
# Тесты
|
|
24
|
+
uv run pytest tests/ -q
|
|
25
|
+
|
|
26
|
+
# Линтинг
|
|
27
|
+
uv run ruff check gitkit
|
|
28
|
+
uv run ruff format gitkit
|
|
29
|
+
|
|
30
|
+
# Построение
|
|
31
|
+
uv build
|
|
32
|
+
|
|
33
|
+
# Публикация
|
|
34
|
+
uv publish
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Дизайн
|
|
38
|
+
|
|
39
|
+
- **Protocol-based** — `GitProvider` — это Protocol, не abstract base class. Новый провайдер просто реализует интерфейс.
|
|
40
|
+
- **Retry-встроен** — Все API-запросы используют tenacity с exponential backoff (3 попытки).
|
|
41
|
+
- **No coupling** — Не зависит от librarykit (хотя librarykit может использовать gitkit).
|
|
42
|
+
- **Read-only** — Интерфейс только для чтения (list_tags, resolve_tag, fetch_file, fetch_tree, clone_url).
|
|
43
|
+
|
|
44
|
+
## Изменение версии
|
|
45
|
+
|
|
46
|
+
В `pyproject.toml` обновить версию (patching 0.1.x, не минорные скачки на ранней стадии).
|
|
47
|
+
|
|
48
|
+
## Когда добавлять новых провайдеров
|
|
49
|
+
|
|
50
|
+
Если нужна поддержка новой платформы (напр. Gitea, Forgejo):
|
|
51
|
+
|
|
52
|
+
1. Создать `gitkit/gitea_provider.py` (реализует `GitProvider` Protocol)
|
|
53
|
+
2. Добавить логику в `factory.detect_provider()`
|
|
54
|
+
3. Добавить тесты в `tests/test_providers.py`
|
|
55
|
+
4. Обновить `README.md` с примером
|
|
56
|
+
|
|
57
|
+
Дизайн Protocol гарантирует, что новый провайдер автоматически работает везде, где использован `GitProvider`.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# CHANGELOG
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
## [0.1.0] — 2026-07-07
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Initial release
|
|
10
|
+
- `GitProvider` Protocol — read-only интерфейс для git-хостингов
|
|
11
|
+
- `GitHubProvider` — реализация для GitHub (github.com и GitHub Enterprise)
|
|
12
|
+
- `GitLabProvider` — реализация для GitLab (gitlab.com и self-hosted)
|
|
13
|
+
- `GitProviderFactory` — фабрика с автоматическим выбором провайдера
|
|
14
|
+
- URL парсинг (https и scp-like форматы)
|
|
15
|
+
- Retry-политика с exponential backoff
|
|
16
|
+
- Полная асинхронная поддержка
|
|
17
|
+
|
|
18
|
+
### Supported Platforms
|
|
19
|
+
|
|
20
|
+
- Python 3.11+
|
|
21
|
+
- GitHub (github.com, GitHub Enterprise)
|
|
22
|
+
- GitLab (gitlab.com, self-hosted)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# s-gitkit: git-хостинг абстракция (GitHub/GitLab read-layer)
|
|
2
|
+
|
|
3
|
+
## Структура
|
|
4
|
+
|
|
5
|
+
gitkit/ — основной пакет
|
|
6
|
+
├── __init__.py — public API (GitProvider, GitRepoRef, GitTreeEntry, GitHubProvider, GitLabProvider, GitProviderFactory)
|
|
7
|
+
├── types.py — Protocol GitProvider и data-классы GitRepoRef, GitTreeEntry
|
|
8
|
+
├── errors.py — GitProviderError, UnsupportedGitHostError
|
|
9
|
+
├── github_provider.py — GitHubProvider (github.com, GitHub Enterprise)
|
|
10
|
+
├── gitlab_provider.py — GitLabProvider (gitlab.com, self-hosted)
|
|
11
|
+
└── factory.py — GitProviderFactory + parse_repo_ref, detect_provider
|
|
12
|
+
|
|
13
|
+
tests/ — 25 тестов
|
|
14
|
+
├── test_factory.py — парсинг URL, выбор провайдера
|
|
15
|
+
└── test_providers.py — GitHub и GitLab провайдеры (мокированные HTTP)
|
|
16
|
+
|
|
17
|
+
Документация:
|
|
18
|
+
- README.md — установка, quick start, примеры self-hosted
|
|
19
|
+
- CHANGELOG.md — история версий
|
|
20
|
+
- AGENTS.md — архитектура, разработка
|
|
21
|
+
- LICENSE — MIT
|
|
22
|
+
- pyproject.toml — конфиг проекта
|
|
23
|
+
- .gitlab-ci.yml — CI/CD
|
|
24
|
+
- .gitignore — исключения Git
|
|
25
|
+
|
|
26
|
+
## Ключевые характеристики
|
|
27
|
+
|
|
28
|
+
✓ Никаких зависимостей от skills_hub_backend — полностью самостоятельный
|
|
29
|
+
✓ Легковесные зависимости: только httpx, stamina (и stdlib)
|
|
30
|
+
✓ Protocol-based design — легко добавлять новых провайдеров (Gitea, Forgejo и т.д.)
|
|
31
|
+
✓ Встроенная retry-политика (tenacity, 3 попытки, exponential backoff)
|
|
32
|
+
✓ Поддержка всех форм git URL (https, scp-like)
|
|
33
|
+
✓ Self-hosted GitLab + GitHub Enterprise готовы к работе
|
|
34
|
+
✓ 100% асинхронный код (async/await)
|
|
35
|
+
✓ Fully type-hinted (py311+)
|
|
36
|
+
|
|
37
|
+
## Проверки выполнены
|
|
38
|
+
|
|
39
|
+
✓ Import OK: python -c 'import gitkit; print(gitkit.__version__)'
|
|
40
|
+
✓ 0 импортов skills_hub_backend
|
|
41
|
+
✓ 0 утечек личной информации (_storage, C:, @gmail, Slug, навык)
|
|
42
|
+
✓ 25 тестов прошли успешно
|
|
43
|
+
✓ Структура соответствует эталону librarykit
|
s_gitkit-0.1.0/LICENSE
ADDED
|
@@ -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.
|
s_gitkit-0.1.0/PKG-INFO
ADDED
|
@@ -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.
|
s_gitkit-0.1.0/README.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# gitkit
|
|
2
|
+
|
|
3
|
+
**Git-хостинг абстракция: GitHub/GitLab read-layer.**
|
|
4
|
+
|
|
5
|
+
Единая интерфейс для работы с произвольными git-репозиториями на GitHub, GitLab и self-hosted GitLab инстансах. Provider pattern позволяет добавить новых провайдеров.
|
|
6
|
+
|
|
7
|
+
## Возможности
|
|
8
|
+
|
|
9
|
+
- **GitProvider Protocol** — read-only операции (list_tags, resolve_tag, fetch_file, fetch_tree, clone_url)
|
|
10
|
+
- **GitHubProvider** — поддержка github.com и GitHub Enterprise
|
|
11
|
+
- **GitLabProvider** — поддержка gitlab.com и self-hosted GitLab
|
|
12
|
+
- **GitProviderFactory** — автоматический выбор провайдера по URL
|
|
13
|
+
- **Парсинг URL** — поддержка https и scp-like git URL-ов
|
|
14
|
+
- **Retry-политика** — автоматический retry с exponential backoff (3 попытки)
|
|
15
|
+
|
|
16
|
+
## Установка
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
uv add s-gitkit
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Имя пакета для импорта — `gitkit`.
|
|
23
|
+
|
|
24
|
+
## Быстрый старт
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import gitkit
|
|
28
|
+
|
|
29
|
+
# Автоматический выбор провайдера по URL
|
|
30
|
+
factory = gitkit.GitProviderFactory()
|
|
31
|
+
provider, repo = factory.create(
|
|
32
|
+
"https://github.com/owner/repo.git",
|
|
33
|
+
token="ghp_xxx" # опционально
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
# Работа с репозиторием
|
|
37
|
+
tags = await provider.list_tags(repo=repo)
|
|
38
|
+
sha = await provider.resolve_tag(repo=repo, tag="v1.0.0")
|
|
39
|
+
content = await provider.fetch_file(repo=repo, ref="main", path="README.md")
|
|
40
|
+
tree = await provider.fetch_tree(repo=repo, ref="main")
|
|
41
|
+
|
|
42
|
+
# Clone URL
|
|
43
|
+
clone = provider.clone_url(repo=repo)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Self-hosted GitLab
|
|
47
|
+
|
|
48
|
+
Для поддержки self-hosted GitLab инстансов передайте хосты при создании фабрики:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
factory = gitkit.GitProviderFactory(
|
|
52
|
+
self_hosted_hosts=["git.example.com", "gitlab.company.org"]
|
|
53
|
+
)
|
|
54
|
+
provider, repo = factory.create(
|
|
55
|
+
"https://git.example.com/group/project.git",
|
|
56
|
+
token="glpat_xxx"
|
|
57
|
+
)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## GitHub Enterprise
|
|
61
|
+
|
|
62
|
+
Для GitHub Enterprise используйте `github_base_url`:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
factory = gitkit.GitProviderFactory(
|
|
66
|
+
github_base_url="https://github.enterprise.com/api/v3"
|
|
67
|
+
)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Разработка
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
uv sync --extra dev
|
|
74
|
+
uv run pytest -q
|
|
75
|
+
uv run ruff check gitkit
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Лицензия
|
|
79
|
+
|
|
80
|
+
MIT © 2026 Dmitry.
|
|
@@ -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
|
+
]
|
|
@@ -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-хост)."""
|
|
@@ -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"
|
|
@@ -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,38 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "s-gitkit"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Git-хостинг абстракция: GitHub/GitLab read-layer (provider pattern для любых репозиториев + фабрика)"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = { text = "MIT" }
|
|
7
|
+
requires-python = ">=3.11"
|
|
8
|
+
authors = [{ name = "Dmitry" }]
|
|
9
|
+
# Core dependencies: только httpx (для git API) + retry-слой (stamina).
|
|
10
|
+
# Всё остальное — stdlib. Никаких зависимостей от librarykit (обратное направление возможно).
|
|
11
|
+
dependencies = [
|
|
12
|
+
"httpx>=0.27",
|
|
13
|
+
"stamina>=24.3",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
dev = ["pytest>=8", "pytest-asyncio>=0.24", "respx>=0.21"]
|
|
18
|
+
|
|
19
|
+
[build-system]
|
|
20
|
+
requires = ["hatchling"]
|
|
21
|
+
build-backend = "hatchling.build"
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["gitkit"]
|
|
25
|
+
|
|
26
|
+
[tool.ruff]
|
|
27
|
+
line-length = 100
|
|
28
|
+
target-version = "py311"
|
|
29
|
+
src = ["."]
|
|
30
|
+
|
|
31
|
+
[tool.ruff.lint]
|
|
32
|
+
select = ["E", "F", "I", "B", "UP", "N", "SIM", "RUF"]
|
|
33
|
+
ignore = ["RUF002", "RUF003", "RUF022"]
|
|
34
|
+
|
|
35
|
+
[tool.pytest.ini_options]
|
|
36
|
+
asyncio_mode = "auto"
|
|
37
|
+
testpaths = ["tests"]
|
|
38
|
+
pythonpath = ["."]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Tests for gitkit."""
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Tests for URL parsing and provider factory."""
|
|
2
|
+
import pytest
|
|
3
|
+
|
|
4
|
+
from gitkit import (
|
|
5
|
+
GitProviderError,
|
|
6
|
+
GitProviderFactory,
|
|
7
|
+
GitHubProvider,
|
|
8
|
+
GitLabProvider,
|
|
9
|
+
UnsupportedGitHostError,
|
|
10
|
+
parse_repo_ref,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TestParseRepoRef:
|
|
15
|
+
"""Test URL parsing."""
|
|
16
|
+
|
|
17
|
+
def test_parse_https_github(self):
|
|
18
|
+
"""Parse HTTPS GitHub URL."""
|
|
19
|
+
ref = parse_repo_ref("https://github.com/owner/repo.git")
|
|
20
|
+
assert ref.host == "github.com"
|
|
21
|
+
assert ref.owner == "owner"
|
|
22
|
+
assert ref.name == "repo"
|
|
23
|
+
|
|
24
|
+
def test_parse_https_gitlab_subgroup(self):
|
|
25
|
+
"""Parse GitLab URL with subgroups."""
|
|
26
|
+
ref = parse_repo_ref("https://gitlab.com/group/subgroup/project.git")
|
|
27
|
+
assert ref.host == "gitlab.com"
|
|
28
|
+
assert ref.owner == "group/subgroup"
|
|
29
|
+
assert ref.name == "project"
|
|
30
|
+
|
|
31
|
+
def test_parse_scp_github(self):
|
|
32
|
+
"""Parse SCP-style GitHub URL."""
|
|
33
|
+
ref = parse_repo_ref("git@github.com:owner/repo.git")
|
|
34
|
+
assert ref.host == "github.com"
|
|
35
|
+
assert ref.owner == "owner"
|
|
36
|
+
assert ref.name == "repo"
|
|
37
|
+
|
|
38
|
+
def test_parse_scp_gitlab(self):
|
|
39
|
+
"""Parse SCP-style GitLab URL."""
|
|
40
|
+
ref = parse_repo_ref("git@gitlab.com:group/project.git")
|
|
41
|
+
assert ref.host == "gitlab.com"
|
|
42
|
+
assert ref.owner == "group"
|
|
43
|
+
assert ref.name == "project"
|
|
44
|
+
|
|
45
|
+
def test_parse_https_no_git_suffix(self):
|
|
46
|
+
"""Parse HTTPS URL without .git suffix."""
|
|
47
|
+
ref = parse_repo_ref("https://github.com/owner/repo")
|
|
48
|
+
assert ref.host == "github.com"
|
|
49
|
+
assert ref.owner == "owner"
|
|
50
|
+
assert ref.name == "repo"
|
|
51
|
+
|
|
52
|
+
def test_parse_empty_url(self):
|
|
53
|
+
"""Raise error on empty URL."""
|
|
54
|
+
with pytest.raises(GitProviderError, match="Пустой repo URL"):
|
|
55
|
+
parse_repo_ref("")
|
|
56
|
+
|
|
57
|
+
def test_parse_invalid_url(self):
|
|
58
|
+
"""Raise error on invalid URL format."""
|
|
59
|
+
with pytest.raises(GitProviderError, match="Не удалось распарсить"):
|
|
60
|
+
parse_repo_ref("not-a-valid-url!@#$")
|
|
61
|
+
|
|
62
|
+
def test_parse_missing_owner(self):
|
|
63
|
+
"""Raise error when URL has insufficient segments."""
|
|
64
|
+
with pytest.raises(GitProviderError, match="owner и name"):
|
|
65
|
+
parse_repo_ref("https://github.com/")
|
|
66
|
+
|
|
67
|
+
def test_parse_case_insensitive_host(self):
|
|
68
|
+
"""Host should be lowercase."""
|
|
69
|
+
ref = parse_repo_ref("https://GitHub.Com/owner/repo")
|
|
70
|
+
assert ref.host == "github.com"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class TestDetectProvider:
|
|
74
|
+
"""Test provider detection."""
|
|
75
|
+
|
|
76
|
+
def test_github_provider_for_github_com(self):
|
|
77
|
+
"""Detect GitHub provider for github.com."""
|
|
78
|
+
from gitkit.factory import detect_provider
|
|
79
|
+
|
|
80
|
+
provider, ref = detect_provider("https://github.com/owner/repo")
|
|
81
|
+
assert isinstance(provider, GitHubProvider)
|
|
82
|
+
assert ref.host == "github.com"
|
|
83
|
+
|
|
84
|
+
def test_gitlab_provider_for_gitlab_com(self):
|
|
85
|
+
"""Detect GitLab provider for gitlab.com."""
|
|
86
|
+
from gitkit.factory import detect_provider
|
|
87
|
+
|
|
88
|
+
provider, ref = detect_provider("https://gitlab.com/group/project")
|
|
89
|
+
assert isinstance(provider, GitLabProvider)
|
|
90
|
+
assert ref.host == "gitlab.com"
|
|
91
|
+
|
|
92
|
+
def test_unsupported_host(self):
|
|
93
|
+
"""Raise error for unsupported host."""
|
|
94
|
+
from gitkit.factory import detect_provider
|
|
95
|
+
|
|
96
|
+
with pytest.raises(UnsupportedGitHostError, match="Неподдерживаемый"):
|
|
97
|
+
detect_provider("https://gitea.example.com/owner/repo")
|
|
98
|
+
|
|
99
|
+
def test_self_hosted_gitlab(self):
|
|
100
|
+
"""Detect GitLab provider for self-hosted instance."""
|
|
101
|
+
from gitkit.factory import detect_provider
|
|
102
|
+
|
|
103
|
+
provider, ref = detect_provider(
|
|
104
|
+
"https://git.example.com/group/project",
|
|
105
|
+
self_hosted_hosts=["git.example.com"],
|
|
106
|
+
)
|
|
107
|
+
assert isinstance(provider, GitLabProvider)
|
|
108
|
+
assert ref.host == "git.example.com"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class TestGitProviderFactory:
|
|
112
|
+
"""Test factory class."""
|
|
113
|
+
|
|
114
|
+
def test_factory_parse(self):
|
|
115
|
+
"""Factory can parse URLs."""
|
|
116
|
+
factory = GitProviderFactory()
|
|
117
|
+
ref = factory.parse("https://github.com/owner/repo")
|
|
118
|
+
assert ref.host == "github.com"
|
|
119
|
+
assert ref.owner == "owner"
|
|
120
|
+
assert ref.name == "repo"
|
|
121
|
+
|
|
122
|
+
def test_factory_create_github(self):
|
|
123
|
+
"""Factory creates GitHub provider."""
|
|
124
|
+
factory = GitProviderFactory()
|
|
125
|
+
provider, ref = factory.create("https://github.com/owner/repo")
|
|
126
|
+
assert isinstance(provider, GitHubProvider)
|
|
127
|
+
assert ref.host == "github.com"
|
|
128
|
+
|
|
129
|
+
def test_factory_create_gitlab(self):
|
|
130
|
+
"""Factory creates GitLab provider."""
|
|
131
|
+
factory = GitProviderFactory()
|
|
132
|
+
provider, ref = factory.create("https://gitlab.com/group/project")
|
|
133
|
+
assert isinstance(provider, GitLabProvider)
|
|
134
|
+
assert ref.host == "gitlab.com"
|
|
135
|
+
|
|
136
|
+
def test_factory_with_self_hosted(self):
|
|
137
|
+
"""Factory with self-hosted GitLab configuration."""
|
|
138
|
+
factory = GitProviderFactory(self_hosted_hosts=["git.example.com"])
|
|
139
|
+
provider, ref = factory.create("https://git.example.com/group/project")
|
|
140
|
+
assert isinstance(provider, GitLabProvider)
|
|
141
|
+
assert ref.host == "git.example.com"
|
|
142
|
+
|
|
143
|
+
def test_factory_with_custom_github_url(self):
|
|
144
|
+
"""Factory with custom GitHub base URL."""
|
|
145
|
+
factory = GitProviderFactory(
|
|
146
|
+
github_base_url="https://github.enterprise.com/api/v3"
|
|
147
|
+
)
|
|
148
|
+
provider, ref = factory.create("https://github.com/owner/repo")
|
|
149
|
+
assert isinstance(provider, GitHubProvider)
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Tests for GitHub and GitLab providers."""
|
|
2
|
+
import pytest
|
|
3
|
+
import respx
|
|
4
|
+
import httpx
|
|
5
|
+
|
|
6
|
+
from gitkit import GitHubProvider, GitLabProvider, GitRepoRef
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TestGitHubProvider:
|
|
10
|
+
"""Tests for GitHubProvider."""
|
|
11
|
+
|
|
12
|
+
@pytest.mark.asyncio
|
|
13
|
+
async def test_list_tags(self):
|
|
14
|
+
"""Test listing tags from GitHub."""
|
|
15
|
+
provider = GitHubProvider()
|
|
16
|
+
repo = GitRepoRef(
|
|
17
|
+
raw_url="https://github.com/owner/repo",
|
|
18
|
+
host="github.com",
|
|
19
|
+
owner="owner",
|
|
20
|
+
name="repo",
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
with respx.mock:
|
|
24
|
+
respx.get(
|
|
25
|
+
"https://api.github.com/repos/owner/repo/tags?per_page=100"
|
|
26
|
+
).mock(
|
|
27
|
+
return_value=httpx.Response(
|
|
28
|
+
200,
|
|
29
|
+
json=[
|
|
30
|
+
{"name": "v1.0.0"},
|
|
31
|
+
{"name": "v0.9.0"},
|
|
32
|
+
],
|
|
33
|
+
)
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
tags = await provider.list_tags(repo=repo)
|
|
37
|
+
assert tags == ["v1.0.0", "v0.9.0"]
|
|
38
|
+
|
|
39
|
+
await provider.close()
|
|
40
|
+
|
|
41
|
+
@pytest.mark.asyncio
|
|
42
|
+
async def test_resolve_tag(self):
|
|
43
|
+
"""Test resolving tag to commit SHA."""
|
|
44
|
+
provider = GitHubProvider()
|
|
45
|
+
repo = GitRepoRef(
|
|
46
|
+
raw_url="https://github.com/owner/repo",
|
|
47
|
+
host="github.com",
|
|
48
|
+
owner="owner",
|
|
49
|
+
name="repo",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
with respx.mock:
|
|
53
|
+
respx.get(
|
|
54
|
+
"https://api.github.com/repos/owner/repo/git/ref/tags/v1.0.0"
|
|
55
|
+
).mock(
|
|
56
|
+
return_value=httpx.Response(
|
|
57
|
+
200,
|
|
58
|
+
json={
|
|
59
|
+
"object": {
|
|
60
|
+
"type": "commit",
|
|
61
|
+
"sha": "abc123def456",
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
sha = await provider.resolve_tag(repo=repo, tag="v1.0.0")
|
|
68
|
+
assert sha == "abc123def456"
|
|
69
|
+
|
|
70
|
+
await provider.close()
|
|
71
|
+
|
|
72
|
+
@pytest.mark.asyncio
|
|
73
|
+
async def test_clone_url(self):
|
|
74
|
+
"""Test clone URL generation."""
|
|
75
|
+
provider = GitHubProvider()
|
|
76
|
+
repo = GitRepoRef(
|
|
77
|
+
raw_url="https://github.com/owner/repo",
|
|
78
|
+
host="github.com",
|
|
79
|
+
owner="owner",
|
|
80
|
+
name="repo",
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
url = provider.clone_url(repo=repo)
|
|
84
|
+
assert url == "https://github.com/owner/repo.git"
|
|
85
|
+
|
|
86
|
+
await provider.close()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class TestGitLabProvider:
|
|
90
|
+
"""Tests for GitLabProvider."""
|
|
91
|
+
|
|
92
|
+
@pytest.mark.asyncio
|
|
93
|
+
async def test_list_tags(self):
|
|
94
|
+
"""Test listing tags from GitLab."""
|
|
95
|
+
provider = GitLabProvider()
|
|
96
|
+
repo = GitRepoRef(
|
|
97
|
+
raw_url="https://gitlab.com/group/project",
|
|
98
|
+
host="gitlab.com",
|
|
99
|
+
owner="group",
|
|
100
|
+
name="project",
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
with respx.mock:
|
|
104
|
+
respx.get(
|
|
105
|
+
"https://gitlab.com/api/v4/projects/group%2Fproject/repository/tags?per_page=100"
|
|
106
|
+
).mock(
|
|
107
|
+
return_value=httpx.Response(
|
|
108
|
+
200,
|
|
109
|
+
json=[
|
|
110
|
+
{"name": "v1.0.0"},
|
|
111
|
+
{"name": "v0.9.0"},
|
|
112
|
+
],
|
|
113
|
+
)
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
tags = await provider.list_tags(repo=repo)
|
|
117
|
+
assert tags == ["v1.0.0", "v0.9.0"]
|
|
118
|
+
|
|
119
|
+
await provider.close()
|
|
120
|
+
|
|
121
|
+
@pytest.mark.asyncio
|
|
122
|
+
async def test_resolve_tag(self):
|
|
123
|
+
"""Test resolving tag to commit SHA."""
|
|
124
|
+
provider = GitLabProvider()
|
|
125
|
+
repo = GitRepoRef(
|
|
126
|
+
raw_url="https://gitlab.com/group/project",
|
|
127
|
+
host="gitlab.com",
|
|
128
|
+
owner="group",
|
|
129
|
+
name="project",
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
with respx.mock:
|
|
133
|
+
respx.get(
|
|
134
|
+
"https://gitlab.com/api/v4/projects/group%2Fproject/repository/commits/v1.0.0"
|
|
135
|
+
).mock(
|
|
136
|
+
return_value=httpx.Response(
|
|
137
|
+
200,
|
|
138
|
+
json={"id": "abc123def456"},
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
sha = await provider.resolve_tag(repo=repo, tag="v1.0.0")
|
|
143
|
+
assert sha == "abc123def456"
|
|
144
|
+
|
|
145
|
+
await provider.close()
|
|
146
|
+
|
|
147
|
+
@pytest.mark.asyncio
|
|
148
|
+
async def test_clone_url(self):
|
|
149
|
+
"""Test clone URL generation."""
|
|
150
|
+
provider = GitLabProvider()
|
|
151
|
+
repo = GitRepoRef(
|
|
152
|
+
raw_url="https://gitlab.com/group/project",
|
|
153
|
+
host="gitlab.com",
|
|
154
|
+
owner="group",
|
|
155
|
+
name="project",
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
url = provider.clone_url(repo=repo)
|
|
159
|
+
assert url == "https://gitlab.com/group/project.git"
|
|
160
|
+
|
|
161
|
+
await provider.close()
|
|
162
|
+
|
|
163
|
+
@pytest.mark.asyncio
|
|
164
|
+
async def test_self_hosted(self):
|
|
165
|
+
"""Test self-hosted GitLab provider."""
|
|
166
|
+
provider = GitLabProvider(
|
|
167
|
+
host="git.example.com", base_url="https://git.example.com"
|
|
168
|
+
)
|
|
169
|
+
repo = GitRepoRef(
|
|
170
|
+
raw_url="https://git.example.com/group/project",
|
|
171
|
+
host="git.example.com",
|
|
172
|
+
owner="group",
|
|
173
|
+
name="project",
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
url = provider.clone_url(repo=repo)
|
|
177
|
+
assert url == "https://git.example.com/group/project.git"
|
|
178
|
+
|
|
179
|
+
await provider.close()
|