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