Files
2026-11-07 22:34:12 +03:00

581 lines
23 KiB
Python

"""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)}"