initial commit heh
This commit is contained in:
78 files changed
+11181
No files matched your search
@@ -0,0 +1,33 @@
|
||||
"""Gitea extension package for HomeAgent."""
|
||||
|
||||
from extensions.gitea.tools import (
|
||||
gitea_add_issue_comment,
|
||||
gitea_create_branch,
|
||||
gitea_create_issue,
|
||||
gitea_create_pull_request,
|
||||
gitea_get_file_or_dir,
|
||||
gitea_get_issue,
|
||||
gitea_get_repo,
|
||||
gitea_list_branches,
|
||||
gitea_list_issues,
|
||||
gitea_list_pull_requests,
|
||||
gitea_list_repos,
|
||||
gitea_save_file,
|
||||
gitea_search_repos,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"gitea_list_repos",
|
||||
"gitea_search_repos",
|
||||
"gitea_get_repo",
|
||||
"gitea_get_file_or_dir",
|
||||
"gitea_save_file",
|
||||
"gitea_list_branches",
|
||||
"gitea_create_branch",
|
||||
"gitea_list_issues",
|
||||
"gitea_get_issue",
|
||||
"gitea_create_issue",
|
||||
"gitea_add_issue_comment",
|
||||
"gitea_list_pull_requests",
|
||||
"gitea_create_pull_request",
|
||||
]
|
||||
@@ -0,0 +1,237 @@
|
||||
"""Asynchronous Gitea / Forgejo REST API v1 Client."""
|
||||
|
||||
import base64
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
import httpx
|
||||
|
||||
from homeagent.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class GiteaClient:
|
||||
"""Async Client for Gitea / Forgejo REST API v1."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: Optional[str] = None,
|
||||
token: Optional[str] = None,
|
||||
) -> None:
|
||||
settings = get_settings()
|
||||
raw_url = (base_url or settings.GITEA_URL or "https://git.timka.su").rstrip("/")
|
||||
if not raw_url.endswith("/api/v1"):
|
||||
self.api_url = f"{raw_url}/api/v1"
|
||||
else:
|
||||
self.api_url = raw_url
|
||||
self.web_url = raw_url.replace("/api/v1", "")
|
||||
|
||||
self.token = (
|
||||
token
|
||||
or (settings.GITEA_TOKEN.get_secret_value() if settings.GITEA_TOKEN else "")
|
||||
)
|
||||
|
||||
def is_configured(self) -> bool:
|
||||
return bool(self.token)
|
||||
|
||||
def _get_headers(self) -> dict[str, str]:
|
||||
headers = {
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
if self.token:
|
||||
headers["Authorization"] = f"token {self.token}"
|
||||
return headers
|
||||
|
||||
async def _request(
|
||||
self,
|
||||
method: str,
|
||||
endpoint: str,
|
||||
params: Optional[dict[str, Any]] = None,
|
||||
json_data: Optional[dict[str, Any]] = None,
|
||||
) -> Any:
|
||||
url = f"{self.api_url}/{endpoint.lstrip('/')}"
|
||||
headers = self._get_headers()
|
||||
|
||||
async with httpx.AsyncClient(timeout=25.0) as client:
|
||||
response = await client.request(
|
||||
method=method,
|
||||
url=url,
|
||||
headers=headers,
|
||||
params=params,
|
||||
json=json_data,
|
||||
)
|
||||
|
||||
if response.status_code == 204 or not response.content:
|
||||
return None
|
||||
|
||||
if response.is_error:
|
||||
error_body = response.text
|
||||
logger.error("Gitea API error %d on %s: %s", response.status_code, url, error_body)
|
||||
raise RuntimeError(f"Gitea API error ({response.status_code}): {error_body}")
|
||||
|
||||
return response.json()
|
||||
|
||||
async def get_current_user(self) -> dict[str, Any]:
|
||||
"""Get profile of authenticated user."""
|
||||
return await self._request("GET", "user")
|
||||
|
||||
async def list_user_repos(self, limit: int = 30) -> list[dict[str, Any]]:
|
||||
"""List repositories accessible to the authenticated user."""
|
||||
return await self._request("GET", "user/repos", params={"limit": limit})
|
||||
|
||||
async def search_repos(self, query: str, limit: int = 15) -> list[dict[str, Any]]:
|
||||
"""Search repositories by keyword."""
|
||||
data = await self._request("GET", "repos/search", params={"q": query, "limit": limit})
|
||||
return data.get("data", []) if isinstance(data, dict) else data
|
||||
|
||||
async def get_repo(self, owner: str, repo: str) -> dict[str, Any]:
|
||||
"""Get repository details."""
|
||||
return await self._request("GET", f"repos/{owner}/{repo}")
|
||||
|
||||
async def get_contents(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
filepath: str = "",
|
||||
ref: Optional[str] = None,
|
||||
) -> Any:
|
||||
"""Get contents of a file or directory in a repository."""
|
||||
params = {}
|
||||
if ref:
|
||||
params["ref"] = ref
|
||||
endpoint = f"repos/{owner}/{repo}/contents/{filepath.lstrip('/')}"
|
||||
return await self._request("GET", endpoint, params=params)
|
||||
|
||||
async def create_or_update_file(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
filepath: str,
|
||||
content: str,
|
||||
commit_message: str,
|
||||
branch: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Create or update file in repository (Vibecoding)."""
|
||||
clean_path = filepath.lstrip("/")
|
||||
b64_content = base64.b64encode(content.encode("utf-8")).decode("utf-8")
|
||||
|
||||
# Check if file exists to get SHA for update
|
||||
existing_sha = None
|
||||
try:
|
||||
existing = await self.get_contents(owner, repo, clean_path, ref=branch)
|
||||
if isinstance(existing, dict) and "sha" in existing:
|
||||
existing_sha = existing["sha"]
|
||||
except Exception:
|
||||
# File does not exist yet
|
||||
pass
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"content": b64_content,
|
||||
"message": commit_message,
|
||||
}
|
||||
if branch:
|
||||
payload["branch"] = branch
|
||||
|
||||
if existing_sha:
|
||||
# Update existing file
|
||||
payload["sha"] = existing_sha
|
||||
return await self._request("PUT", f"repos/{owner}/{repo}/contents/{clean_path}", json_data=payload)
|
||||
else:
|
||||
# Create new file
|
||||
return await self._request("POST", f"repos/{owner}/{repo}/contents/{clean_path}", json_data=payload)
|
||||
|
||||
async def list_branches(self, owner: str, repo: str) -> list[dict[str, Any]]:
|
||||
"""List branches in repository."""
|
||||
return await self._request("GET", f"repos/{owner}/{repo}/branches")
|
||||
|
||||
async def create_branch(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
new_branch: str,
|
||||
old_ref: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Create a new branch from an existing ref/branch."""
|
||||
payload: dict[str, Any] = {"new_branch_name": new_branch}
|
||||
if old_ref:
|
||||
payload["old_ref_name"] = old_ref
|
||||
return await self._request("POST", f"repos/{owner}/{repo}/branches", json_data=payload)
|
||||
|
||||
async def list_issues(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
state: str = "open",
|
||||
limit: int = 20,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""List issues for a repository."""
|
||||
return await self._request(
|
||||
"GET",
|
||||
f"repos/{owner}/{repo}/issues",
|
||||
params={"state": state, "limit": limit},
|
||||
)
|
||||
|
||||
async def get_issue(self, owner: str, repo: str, index: int) -> dict[str, Any]:
|
||||
"""Get issue details by index."""
|
||||
return await self._request("GET", f"repos/{owner}/{repo}/issues/{index}")
|
||||
|
||||
async def create_issue(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
title: str,
|
||||
body: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""Create a new issue."""
|
||||
return await self._request(
|
||||
"POST",
|
||||
f"repos/{owner}/{repo}/issues",
|
||||
json_data={"title": title, "body": body},
|
||||
)
|
||||
|
||||
async def add_issue_comment(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
index: int,
|
||||
comment: str,
|
||||
) -> dict[str, Any]:
|
||||
"""Add a comment to an issue or pull request."""
|
||||
return await self._request(
|
||||
"POST",
|
||||
f"repos/{owner}/{repo}/issues/{index}/comments",
|
||||
json_data={"body": comment},
|
||||
)
|
||||
|
||||
async def list_pull_requests(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
state: str = "open",
|
||||
limit: int = 20,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""List pull requests for a repository."""
|
||||
return await self._request(
|
||||
"GET",
|
||||
f"repos/{owner}/{repo}/pulls",
|
||||
params={"state": state, "limit": limit},
|
||||
)
|
||||
|
||||
async def create_pull_request(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
title: str,
|
||||
head: str,
|
||||
base: str = "main",
|
||||
body: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""Create a new pull request."""
|
||||
payload = {
|
||||
"title": title,
|
||||
"head": head,
|
||||
"base": base,
|
||||
"body": body,
|
||||
}
|
||||
return await self._request("POST", f"repos/{owner}/{repo}/pulls", json_data=payload)
|
||||
@@ -0,0 +1,580 @@
|
||||
"""Gitea tools exposed to HomeAgent and Gemini for repository interaction and vibecoding."""
|
||||
|
||||
import base64
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from extensions.gitea.client import GiteaClient
|
||||
from homeagent.config import get_settings
|
||||
from homeagent.tools.base import tool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_client: Optional[GiteaClient] = None
|
||||
|
||||
|
||||
def get_gitea_client() -> GiteaClient:
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = GiteaClient()
|
||||
return _client
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_list_repos",
|
||||
description="Получить список доступных репозиториев текущего пользователя в Gitea (git.timka.su).",
|
||||
)
|
||||
async def gitea_list_repos(limit: int = 30) -> str:
|
||||
"""Список репозиториев в Gitea.
|
||||
|
||||
Args:
|
||||
limit: Максимальное количество репозиториев (по умолчанию 30)
|
||||
"""
|
||||
settings = get_settings()
|
||||
if not settings.GITEA_ENABLED:
|
||||
return "Интеграция с Gitea отключена в настройках (GITEA_ENABLED=False)."
|
||||
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return f"Gitea не настроена. Укажите GITEA_TOKEN в файле .env (инстанс: {client.web_url})"
|
||||
|
||||
try:
|
||||
repos = await client.list_user_repos(limit=limit)
|
||||
if not repos:
|
||||
return "Репозитории не найдены."
|
||||
|
||||
lines = [f"Доступные репозитории в Gitea ({len(repos)}):"]
|
||||
for repo in repos:
|
||||
full_name = repo.get("full_name") or repo.get("name", "")
|
||||
html_url = repo.get("html_url", "")
|
||||
desc = repo.get("description") or "Без описания"
|
||||
default_branch = repo.get("default_branch", "main")
|
||||
is_private = "🔒 Приватный" if repo.get("private") else "🌐 Публичный"
|
||||
stars = repo.get("stars_count", 0)
|
||||
open_issues = repo.get("open_issues_count", 0)
|
||||
|
||||
lines.append(
|
||||
f"- **[{full_name}]({html_url})** ({is_private})\n"
|
||||
f" {desc} (Ветка: `{default_branch}`, Issues: {open_issues}, Stars: {stars})"
|
||||
)
|
||||
|
||||
return "\n".join(lines)
|
||||
except Exception as e:
|
||||
return f"Ошибка получения репозиториев Gitea: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_search_repos",
|
||||
description="Поиск репозиториев в Gitea по ключевому слову или названию.",
|
||||
)
|
||||
async def gitea_search_repos(query: str, limit: int = 15) -> str:
|
||||
"""Поиск репозиториев в Gitea.
|
||||
|
||||
Args:
|
||||
query: Поисковый запрос (например: 'bot', 'infra', 'agent')
|
||||
limit: Максимальное количество результатов
|
||||
"""
|
||||
settings = get_settings()
|
||||
if not settings.GITEA_ENABLED:
|
||||
return "Интеграция с Gitea отключена."
|
||||
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return f"Gitea не настроена. Укажите GITEA_TOKEN в файле .env"
|
||||
|
||||
try:
|
||||
repos = await client.search_repos(query=query, limit=limit)
|
||||
if not repos:
|
||||
return f"По запросу '{query}' репозитории не найдены."
|
||||
|
||||
lines = [f"Результаты поиска репозиториев по '{query}' ({len(repos)}):"]
|
||||
for repo in repos:
|
||||
full_name = repo.get("full_name") or repo.get("name", "")
|
||||
html_url = repo.get("html_url", "")
|
||||
desc = repo.get("description") or "Без описания"
|
||||
lines.append(f"- **[{full_name}]({html_url})**: {desc}")
|
||||
|
||||
return "\n".join(lines)
|
||||
except Exception as e:
|
||||
return f"Ошибка поиска репозиториев: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_get_repo",
|
||||
description="Получить подробную информацию о конкретном репозитории в Gitea.",
|
||||
)
|
||||
async def gitea_get_repo(owner: str, repo: str) -> str:
|
||||
"""Детальная информация о репозитории.
|
||||
|
||||
Args:
|
||||
owner: Владелец репозитория (пользователь или организация)
|
||||
repo: Имя репозитория
|
||||
"""
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return "Gitea не настроена в .env"
|
||||
|
||||
try:
|
||||
data = await client.get_repo(owner, repo)
|
||||
full_name = data.get("full_name", f"{owner}/{repo}")
|
||||
html_url = data.get("html_url", "")
|
||||
clone_ssh = data.get("ssh_url", "")
|
||||
clone_http = data.get("clone_url", "")
|
||||
desc = data.get("description") or "Без описания"
|
||||
default_branch = data.get("default_branch", "main")
|
||||
is_private = "🔒 Приватный" if data.get("private") else "🌐 Публичный"
|
||||
stars = data.get("stars_count", 0)
|
||||
forks = data.get("forks_count", 0)
|
||||
open_issues = data.get("open_issues_count", 0)
|
||||
open_prs = data.get("open_pr_counter", 0)
|
||||
|
||||
details = [
|
||||
f"**Репозиторий [{full_name}]({html_url})** ({is_private})",
|
||||
f"- **Описание**: {desc}",
|
||||
f"- **Основная ветка**: `{default_branch}`",
|
||||
f"- **Статистика**: Stars: {stars}, Forks: {forks}, Открытых Issues: {open_issues}, PRs: {open_prs}",
|
||||
f"- **Клонирование**: HTTPS: `{clone_http}` | SSH: `{clone_ssh}`",
|
||||
]
|
||||
return "\n".join(details)
|
||||
except Exception as e:
|
||||
return f"Ошибка получения репозитория {owner}/{repo}: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_get_file_or_dir",
|
||||
description="Просмотреть содержимое файла или структуру папки/директории в репозитории Gitea.",
|
||||
)
|
||||
async def gitea_get_file_or_dir(
|
||||
owner: str,
|
||||
repo: str,
|
||||
path: str = "",
|
||||
branch: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Просмотр файлов и директорий репозитория.
|
||||
|
||||
Args:
|
||||
owner: Владелец репозитория
|
||||
repo: Имя репозитория
|
||||
path: Путь к файлу или папке (пустая строка для корневой папки)
|
||||
branch: Ветка, тэг или коммит (опционально, по умолчанию основная ветка)
|
||||
"""
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return "Gitea не настроена в .env"
|
||||
|
||||
try:
|
||||
data = await client.get_contents(owner, repo, filepath=path, ref=branch)
|
||||
|
||||
# If data is a list -> it's a directory
|
||||
if isinstance(data, list):
|
||||
dir_label = path.strip("/") if path.strip("/") else "/"
|
||||
lines = [f"Содержимое директории `{dir_label}` в `{owner}/{repo}` (ветка: {branch or 'default'}):"]
|
||||
|
||||
# Sort: directories first, then files
|
||||
sorted_items = sorted(
|
||||
data,
|
||||
key=lambda x: (0 if x.get("type") in ("dir", "submodule") else 1, x.get("name", "").lower()),
|
||||
)
|
||||
|
||||
for item in sorted_items:
|
||||
item_name = item.get("name", "")
|
||||
item_type = item.get("type", "file")
|
||||
item_size = item.get("size", 0)
|
||||
|
||||
if item_type == "dir":
|
||||
lines.append(f"- 📁 **{item_name}/**")
|
||||
elif item_type == "submodule":
|
||||
lines.append(f"- 📦 **{item_name}** (submodule)")
|
||||
else:
|
||||
size_kb = f"{item_size / 1024:.1f} KB" if item_size > 1024 else f"{item_size} B"
|
||||
lines.append(f"- 📄 `{item_name}` ({size_kb})")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
# If data is a dict -> single file
|
||||
if isinstance(data, dict):
|
||||
file_name = data.get("name", path)
|
||||
file_size = data.get("size", 0)
|
||||
encoding = data.get("encoding", "")
|
||||
raw_content = data.get("content", "")
|
||||
|
||||
if encoding == "base64" and raw_content:
|
||||
try:
|
||||
decoded = base64.b64decode(raw_content).decode("utf-8", errors="replace")
|
||||
except Exception:
|
||||
decoded = "[Не удалось декодировать бинарное содержимое в UTF-8]"
|
||||
else:
|
||||
decoded = raw_content or "[Пустой файл]"
|
||||
|
||||
max_preview = 12000
|
||||
truncated = False
|
||||
if len(decoded) > max_preview:
|
||||
decoded = decoded[:max_preview]
|
||||
truncated = True
|
||||
|
||||
ext = file_name.split(".")[-1] if "." in file_name else ""
|
||||
res = [
|
||||
f"**Файл `{path}`** в `{owner}/{repo}` ({file_size} B, ветка: {branch or 'default'}):",
|
||||
f"```{ext}\n{decoded}\n```",
|
||||
]
|
||||
if truncated:
|
||||
res.append(f"\n_... [Содержимое обрезано, показаны первые {max_preview} символов]_")
|
||||
|
||||
return "\n".join(res)
|
||||
|
||||
return f"Не удалось получить содержимое пути '{path}'."
|
||||
except Exception as e:
|
||||
return f"Ошибка чтения '{path}' в {owner}/{repo}: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_save_file",
|
||||
description="Создать новый файл или обновить существующий файл в репозитории Gitea с коммитом (вайбкодинг).",
|
||||
)
|
||||
async def gitea_save_file(
|
||||
owner: str,
|
||||
repo: str,
|
||||
filepath: str,
|
||||
content: str,
|
||||
commit_message: str,
|
||||
branch: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Создание или обновление файла в Gitea.
|
||||
|
||||
Args:
|
||||
owner: Владелец репозитория
|
||||
repo: Имя репозитория
|
||||
filepath: Путь к файлу (например, 'src/main.py' или 'README.md')
|
||||
content: Полный текст файла для записи
|
||||
commit_message: Сообщение коммита (например: 'feat: add metrics endpoint')
|
||||
branch: Ветка для коммита (опционально, по умолчанию default ветка репозитория)
|
||||
"""
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return "Gitea не настроена в .env"
|
||||
|
||||
try:
|
||||
clean_path = filepath.strip("/")
|
||||
res = await client.create_or_update_file(
|
||||
owner=owner,
|
||||
repo=repo,
|
||||
filepath=clean_path,
|
||||
content=content,
|
||||
commit_message=commit_message,
|
||||
branch=branch,
|
||||
)
|
||||
|
||||
commit_sha = (res.get("commit") or {}).get("sha", "")
|
||||
sha_str = f" (SHA: `{commit_sha[:8]}`)" if commit_sha else ""
|
||||
branch_str = f" в ветку `{branch}`" if branch else ""
|
||||
web_link = f"{client.web_url}/{owner}/{repo}/src/branch/{branch or 'main'}/{clean_path}"
|
||||
|
||||
return (
|
||||
f"✅ Файл `[{clean_path}]({web_link})` успешно сохранен в репозитории "
|
||||
f"**{owner}/{repo}**{branch_str}{sha_str}.\n"
|
||||
f"Коммит: _{commit_message}_"
|
||||
)
|
||||
except Exception as e:
|
||||
return f"Ошибка сохранения файла '{filepath}': {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_list_branches",
|
||||
description="Получить список всех веток в репозитории Gitea.",
|
||||
)
|
||||
async def gitea_list_branches(owner: str, repo: str) -> str:
|
||||
"""Список веток в репозитории.
|
||||
|
||||
Args:
|
||||
owner: Владелец репозитория
|
||||
repo: Имя репозитория
|
||||
"""
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return "Gitea не настроена в .env"
|
||||
|
||||
try:
|
||||
branches = await client.list_branches(owner, repo)
|
||||
if not branches:
|
||||
return f"Ветки в репозитории {owner}/{repo} не найдены."
|
||||
|
||||
lines = [f"Ветки в репозитории {owner}/{repo} ({len(branches)}):"]
|
||||
for b in branches:
|
||||
name = b.get("name", "")
|
||||
commit = b.get("commit", {})
|
||||
sha = commit.get("id", "")[:7]
|
||||
msg = (commit.get("message") or "").strip().split("\n")[0]
|
||||
lines.append(f"- 🌿 `{name}` (последний коммит: `{sha}`: {msg})")
|
||||
|
||||
return "\n".join(lines)
|
||||
except Exception as e:
|
||||
return f"Ошибка получения веток: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_create_branch",
|
||||
description="Создать новую ветку в репозитории Gitea от существующей ветки или коммита.",
|
||||
)
|
||||
async def gitea_create_branch(
|
||||
owner: str,
|
||||
repo: str,
|
||||
new_branch: str,
|
||||
base_branch: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Создание новой ветки.
|
||||
|
||||
Args:
|
||||
owner: Владелец репозитория
|
||||
repo: Имя репозитория
|
||||
new_branch: Название новой ветки (например, 'feature/telegram-bot')
|
||||
base_branch: Базовая ветка или реф (опционально, по умолчанию main/master)
|
||||
"""
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return "Gitea не настроена в .env"
|
||||
|
||||
try:
|
||||
res = await client.create_branch(
|
||||
owner=owner,
|
||||
repo=repo,
|
||||
new_branch=new_branch,
|
||||
old_ref=base_branch,
|
||||
)
|
||||
created_name = res.get("name", new_branch)
|
||||
base_info = f" от `{base_branch}`" if base_branch else ""
|
||||
return f"✅ Ветка `🌿 {created_name}` успешно создана в репозитории **{owner}/{repo}**{base_info}."
|
||||
except Exception as e:
|
||||
return f"Ошибка создания ветки '{new_branch}': {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_list_issues",
|
||||
description="Получить список задач (issues) в репозитории Gitea с фильтром по статусу (open / closed).",
|
||||
)
|
||||
async def gitea_list_issues(
|
||||
owner: str,
|
||||
repo: str,
|
||||
state: str = "open",
|
||||
limit: int = 20,
|
||||
) -> str:
|
||||
"""Список задач (issues) репозитория.
|
||||
|
||||
Args:
|
||||
owner: Владелец репозитория
|
||||
repo: Имя репозитория
|
||||
state: Статус задач ('open', 'closed', 'all')
|
||||
limit: Максимальное количество задач
|
||||
"""
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return "Gitea не настроена в .env"
|
||||
|
||||
try:
|
||||
issues = await client.list_issues(owner, repo, state=state, limit=limit)
|
||||
if not issues:
|
||||
return f"Задачи со статусом '{state}' в репозитории {owner}/{repo} не найдены."
|
||||
|
||||
lines = [f"Задачи ({state}) в {owner}/{repo} ({len(issues)}):"]
|
||||
for issue in issues:
|
||||
is_pr = bool(issue.get("pull_request"))
|
||||
prefix = "🔀 PR" if is_pr else "📌 Issue"
|
||||
index = issue.get("number") or issue.get("index", 0)
|
||||
title = issue.get("title", "")
|
||||
html_url = issue.get("html_url", "")
|
||||
user = (issue.get("user") or {}).get("login", "Unknown")
|
||||
comments = issue.get("comments", 0)
|
||||
|
||||
lines.append(f"- {prefix} **[#{index}]({html_url})**: {title} [Автор: {user}, Комментов: {comments}]")
|
||||
|
||||
return "\n".join(lines)
|
||||
except Exception as e:
|
||||
return f"Ошибка получения задач: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_get_issue",
|
||||
description="Получить детальную информацию о конкретной задаче (issue) в Gitea по её номеру.",
|
||||
)
|
||||
async def gitea_get_issue(owner: str, repo: str, index: int) -> str:
|
||||
"""Детали задачи (issue) в Gitea.
|
||||
|
||||
Args:
|
||||
owner: Владелец репозитория
|
||||
repo: Имя репозитория
|
||||
index: Номер задачи (#)
|
||||
"""
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return "Gitea не настроена в .env"
|
||||
|
||||
try:
|
||||
issue = await client.get_issue(owner, repo, index)
|
||||
title = issue.get("title", "")
|
||||
html_url = issue.get("html_url", "")
|
||||
state = issue.get("state", "open")
|
||||
body = issue.get("body") or "Нет описания"
|
||||
user = (issue.get("user") or {}).get("login", "Unknown")
|
||||
created_at = issue.get("created_at", "")[:10]
|
||||
assignee = (issue.get("assignee") or {}).get("login", "Не назначен")
|
||||
|
||||
details = [
|
||||
f"**Задача [#{index}]({html_url})**: {title}",
|
||||
f"- **Статус**: {state.upper()}",
|
||||
f"- **Автор**: {user}",
|
||||
f"- **Исполнитель**: {assignee}",
|
||||
f"- **Дата создания**: {created_at}",
|
||||
f"- **Описание**:\n{body}",
|
||||
]
|
||||
return "\n".join(details)
|
||||
except Exception as e:
|
||||
return f"Ошибка получения задачи #{index}: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_create_issue",
|
||||
description="Создать новую задачу (issue) в репозитории Gitea.",
|
||||
)
|
||||
async def gitea_create_issue(
|
||||
owner: str,
|
||||
repo: str,
|
||||
title: str,
|
||||
body: str = "",
|
||||
) -> str:
|
||||
"""Создание новой задачи в Gitea.
|
||||
|
||||
Args:
|
||||
owner: Владелец репозитория
|
||||
repo: Имя репозитория
|
||||
title: Название задачи
|
||||
body: Описание задачи в Markdown
|
||||
"""
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return "Gitea не настроена в .env"
|
||||
|
||||
try:
|
||||
issue = await client.create_issue(owner, repo, title=title, body=body)
|
||||
index = issue.get("number") or issue.get("index", 0)
|
||||
html_url = issue.get("html_url", "")
|
||||
return f"✅ Задача **[#{index}]({html_url})** '{title}' успешно создана в репозитории **{owner}/{repo}**!"
|
||||
except Exception as e:
|
||||
return f"Ошибка создания задачи: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_add_issue_comment",
|
||||
description="Добавить комментарий к задаче (issue) или pull request в Gitea.",
|
||||
)
|
||||
async def gitea_add_issue_comment(
|
||||
owner: str,
|
||||
repo: str,
|
||||
index: int,
|
||||
comment: str,
|
||||
) -> str:
|
||||
"""Добавить комментарий к задаче или PR.
|
||||
|
||||
Args:
|
||||
owner: Владелец репозитория
|
||||
repo: Имя репозитория
|
||||
index: Номер задачи или PR
|
||||
comment: Текст комментария в Markdown
|
||||
"""
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return "Gitea не настроена в .env"
|
||||
|
||||
try:
|
||||
res = await client.add_issue_comment(owner, repo, index=index, comment=comment)
|
||||
html_url = res.get("html_url", "")
|
||||
url_str = f" ([Ссылка]({html_url}))" if html_url else ""
|
||||
return f"✅ Комментарий к задаче/PR #{index} в **{owner}/{repo}** успешно добавлен{url_str}."
|
||||
except Exception as e:
|
||||
return f"Ошибка добавления комментария к #{index}: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_list_pull_requests",
|
||||
description="Получить список Pull Requests в репозитории Gitea.",
|
||||
)
|
||||
async def gitea_list_pull_requests(
|
||||
owner: str,
|
||||
repo: str,
|
||||
state: str = "open",
|
||||
limit: int = 20,
|
||||
) -> str:
|
||||
"""Список Pull Requests в репозитории.
|
||||
|
||||
Args:
|
||||
owner: Владелец репозитория
|
||||
repo: Имя репозитория
|
||||
state: Статус PR ('open', 'closed', 'all')
|
||||
limit: Максимальное количество PR
|
||||
"""
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return "Gitea не настроена в .env"
|
||||
|
||||
try:
|
||||
prs = await client.list_pull_requests(owner, repo, state=state, limit=limit)
|
||||
if not prs:
|
||||
return f"Pull Requests со статусом '{state}' в репозитории {owner}/{repo} не найдены."
|
||||
|
||||
lines = [f"Pull Requests ({state}) в {owner}/{repo} ({len(prs)}):"]
|
||||
for pr in prs:
|
||||
index = pr.get("number") or pr.get("index", 0)
|
||||
title = pr.get("title", "")
|
||||
html_url = pr.get("html_url", "")
|
||||
head = (pr.get("head") or {}).get("label") or (pr.get("head") or {}).get("ref", "?")
|
||||
base = (pr.get("base") or {}).get("label") or (pr.get("base") or {}).get("ref", "?")
|
||||
user = (pr.get("user") or {}).get("login", "Unknown")
|
||||
|
||||
lines.append(f"- 🔀 **[#{index}]({html_url})**: {title} [`{head}` → `{base}`, Автор: {user}]")
|
||||
|
||||
return "\n".join(lines)
|
||||
except Exception as e:
|
||||
return f"Ошибка получения Pull Requests: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="gitea_create_pull_request",
|
||||
description="Создать новый Pull Request в репозитории Gitea.",
|
||||
)
|
||||
async def gitea_create_pull_request(
|
||||
owner: str,
|
||||
repo: str,
|
||||
title: str,
|
||||
head_branch: str,
|
||||
base_branch: str = "main",
|
||||
body: str = "",
|
||||
) -> str:
|
||||
"""Создание Pull Request.
|
||||
|
||||
Args:
|
||||
owner: Владелец репозитория
|
||||
repo: Имя репозитория
|
||||
title: Название Pull Request
|
||||
head_branch: Ветка с вашими изменениями (source branch)
|
||||
base_branch: Ветка, в которую нужно влить изменения (target branch, по умолчанию 'main')
|
||||
body: Описание Pull Request
|
||||
"""
|
||||
client = get_gitea_client()
|
||||
if not client.is_configured():
|
||||
return "Gitea не настроена в .env"
|
||||
|
||||
try:
|
||||
pr = await client.create_pull_request(
|
||||
owner=owner,
|
||||
repo=repo,
|
||||
title=title,
|
||||
head=head_branch,
|
||||
base=base_branch,
|
||||
body=body,
|
||||
)
|
||||
index = pr.get("number") or pr.get("index", 0)
|
||||
html_url = pr.get("html_url", "")
|
||||
return (
|
||||
f"✅ Pull Request **[#{index}]({html_url})** '{title}' успешно создан в репозитории **{owner}/{repo}**!\n"
|
||||
f"Ветка: `{head_branch}` → `{base_branch}`"
|
||||
)
|
||||
except Exception as e:
|
||||
return f"Ошибка создания Pull Request: {type(e).__name__}: {str(e)}"
|
||||
Reference in new issue
Block a user