tsest_rep/gitea_api.py

166 lines
7.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import requests
import os
from dotenv import load_dotenv
# Загружаем переменные окружения из файла .env
load_dotenv()
class GiteaAPI:
def __init__(self):
self.base_url = "https://git.vyatsu.ru/api/v1"
self.token = os.getenv('GITEA_TOKEN')
if not self.token:
print("❌ Ошибка: GITEA_TOKEN не найден в переменных окружения")
print(" Убедитесь, что файл .env существует и содержит GITEA_TOKEN=your_token")
self.headers = None
return
self.headers = {
"Authorization": f"token {self.token}",
"Content-Type": "application/json"
}
print("✅ Gitea API клиент инициализирован")
def get_user_info(self):
"""Получение информации о текущем пользователе"""
if not self.headers:
return None
print("\n👤 Получаем информацию о пользователе...")
try:
response = requests.get(
f"{self.base_url}/user",
headers=self.headers,
timeout=10
)
response.raise_for_status()
user_data = response.json()
print("✅ Информация о пользователе получена:")
print(f" • ID: {user_data.get('id')}")
print(f" • Логин: {user_data.get('login')}")
print(f" • Имя: {user_data.get('full_name', 'Не указано')}")
print(f" • Email: {user_data.get('email', 'Не указан')}")
print(f" • Админ: {'Да' if user_data.get('is_admin') else 'Нет'}")
return user_data
except requests.RequestException as e:
print(f"❌ Ошибка при получении информации о пользователе: {e}")
return None
def list_user_repos(self):
"""Получение списка репозиториев пользователя"""
if not self.headers:
return None
print("\n📚 Получаем список репозиториев...")
try:
response = requests.get(
f"{self.base_url}/user/repos",
headers=self.headers,
timeout=10
)
response.raise_for_status()
repos = response.json()
print(f"✅ Найдено репозиториев: {len(repos)}")
for i, repo in enumerate(repos[:5], 1): # Показываем первые 5
print(f" {i}. {repo['name']}")
print(f" Описание: {repo.get('description', 'Нет описания')}")
print(f" URL: {repo.get('html_url')}")
print(f" Приватный: {'Да' if repo.get('private') else 'Нет'}")
print()
if len(repos) > 5:
print(f" ... и еще {len(repos) - 5} репозиториев")
return repos
except requests.RequestException as e:
print(f"❌ Ошибка при получении списка репозиториев: {e}")
return None
def create_repository(self, repo_name, description=""):
"""Создание нового репозитория"""
if not self.headers:
return None
print(f"\n🆕 Создаем репозиторий '{repo_name}'...")
data = {
"name": repo_name,
"description": description,
"auto_init": True, # Создать README автоматически
"private": False, # Публичный репозиторий
"readme": "Default" # Использовать README по умолчанию
}
try:
response = requests.post(
f"{self.base_url}/user/repos",
headers=self.headers,
json=data,
timeout=10
)
if response.status_code == 201:
repo_data = response.json()
print(f"✅ Репозиторий '{repo_name}' успешно создан!")
print(f" URL: {repo_data.get('html_url')}")
print(f" SSH: {repo_data.get('ssh_url')}")
return repo_data
else:
print(f"❌ Ошибка при создании репозитория: {response.status_code}")
error_detail = response.json()
print(f" Сообщение: {error_detail.get('message', 'Неизвестная ошибка')}")
return None
except requests.RequestException as e:
print(f"❌ Ошибка при создании репозитория: {e}")
return None
def main():
# Проверяем наличие токена
if not os.getenv('GITEA_TOKEN'):
print("❌ Ошибка: GITEA_TOKEN не найден в переменных окружения")
print("\n📝 Инструкция по настройке:")
print("1. Создайте файл .env в корне проекта")
print("2. Добавьте в него строку: GITEA_TOKEN=your_token_here")
print("3. Замените your_token_here на реальный токен из Gitea")
print("4. Убедитесь, что .env добавлен в .gitignore")
return
# Создаем экземпляр API клиента
gitea = GiteaAPI()
# Получаем информацию о пользователе
user_info = gitea.get_user_info()
if not user_info:
return
# Получаем список репозиториев
repos = gitea.list_user_repos()
# Создаем репозиторий для лабораторной работы
new_repo_name = f"network-programming-lab3-{user_info.get('login')}"
new_repo_description = "Третья лабораторная работа по сетевым соединениям в Python"
print("\n" + "="*50)
create_repo = input("Создать новый репозиторий для лабораторной работы? (y/n): ")
if create_repo.lower() == 'y':
new_repo = gitea.create_repository(new_repo_name, new_repo_description)
if new_repo:
print(f"\n🎉 Репозиторий для лабораторной работы создан!")
print(f" Вы можете перейти по ссылке: {new_repo.get('html_url')}")
else:
print("\n⚠️ Не удалось создать репозиторий. Возможно, он уже существует.")
else:
print("Создание репозитория пропущено.")
if __name__ == "__main__":
main()