"""# Aider Gitea. A code automation tool that integrates Gitea with Aider to automatically solve issues. This program monitors your [Gitea](https://about.gitea.com/) repository for issues with the 'aider' label. When such an issue is found, it: 1. Creates a new branch. 2. Invokes [Aider](https://aider.chat/) to solve the issue using a Large-Language Model. 3. Runs tests and code quality checks. 4. Creates a pull request with the solution. ## Example Usage ### Command Line ```bash # Run with default settings python -m aider_gitea # Specify custom repository and owner python -m aider_gitea --owner myorg --repo myproject ``` """ import argparse import logging import re import subprocess import sys import tempfile import time from pathlib import Path import requests from . import secrets from ._version import __version__ # noqa: F401 from .seen_issues_db import SeenIssuesDB logger = logging.getLogger(__name__) def generate_branch_name(issue_number: str, issue_title: str) -> str: """ Create a branch name by sanitizing the issue title. Non-alphanumeric characters (except spaces) are removed, the text is lowercased, and spaces are replaced with dashes. """ sanitized = re.sub(r'[^0-9a-zA-Z ]+', '', issue_title) parts = ['issue', str(issue_number), *sanitized.lower().split()] return '-'.join(parts) def bash_cmd(*commands: str) -> str: commands = ('set -e', *commands) return 'bash -c "' + ';'.join(commands) + '"' AIDER_TEST = bash_cmd( 'virtualenv venv', 'source venv/bin/activate', 'pip install -e .', 'pytest test', ) RUFF_FORMAT_AND_AUTO_FIX = bash_cmd( 'ruff format', 'ruff check --fix --ignore RUF022 --ignore PGH004', 'ruff format', 'ruff check --fix --ignore RUF022 --ignore PGH004', ) AIDER_LINT = bash_cmd( RUFF_FORMAT_AND_AUTO_FIX, 'ruff format', 'ruff check --ignore RUF022 --ignore PGH004', ) LLM_MESSAGE_FORMAT = """ {issue} # Solution Details For code tasks: 1. Create a plan for how to solve the issue. 2. Write unit tests that proves that your solution works. 3. Then, solve the issue by writing the required code. """ def create_aider_command(issue: str) -> list[str]: return [ 'aider', '--chat-language', 'english', '--test-cmd', AIDER_TEST, '--lint-cmd', AIDER_LINT, '--auto-test', '--no-auto-lint', '--api-key', secrets.llm_api_key(), '--read', 'CONVENTIONS.md', '--message', LLM_MESSAGE_FORMAT.format(issue=issue), '--yes-always', '--architect', ] def push_changes( cwd: Path, branch_name: str, issue_number: str, issue_title: str, issue_description: str, base_branch: str, ) -> bool: # Check if there are any commits on the branch before pushing if not has_commits_on_branch(cwd, base_branch, branch_name): logger.info(f'No commits made on branch {branch_name}, skipping push') return False cmd = [ 'git', 'push', 'origin', f'HEAD:refs/for/{base_branch}', '-o', f'topic={branch_name}', '-o', f'title={issue_title}', '-o', f'description=This pull request resolves #{issue_number}', ] run_cmd(cmd, cwd) return True def has_commits_on_branch(cwd: Path, base_branch: str, current_branch: str) -> bool: """Check if there are any commits on the current branch that aren't in the base branch.""" try: result = subprocess.run( ['git', 'log', f'{base_branch}..{current_branch}', '--oneline'], check=True, cwd=cwd, capture_output=True, text=True, ) return bool(result.stdout.strip()) except subprocess.CalledProcessError: logger.exception(f'Failed to check commits on branch {current_branch}') return False def run_cmd(cmd: list[str], cwd: Path | None = None, check=True) -> bool: """Returns true if the command succeeded.""" result = subprocess.run(cmd, check=check, cwd=cwd) return result.returncode == 0 def solve_issue_in_repository( args, tmpdirname: Path, branch_name: str, issue_title: str, issue_description: str, issue_number: str, ) -> bool: repo_url = f'{args.gitea_url}:{args.owner}/{args.repo}.git'.replace( 'https://', 'git@', ) # Setup repository run_cmd(['git', 'clone', repo_url, tmpdirname]) run_cmd(['bash', '-c', AIDER_TEST], tmpdirname) run_cmd(['git', 'checkout', args.base_branch], tmpdirname) run_cmd(['git', 'checkout', '-b', branch_name], tmpdirname) # Run aider succeeded = run_cmd( create_aider_command(f'# {issue_title}\n{issue_description}'), tmpdirname, check=False, ) if not succeeded: logger.error('Aider invocation failed for issue #%s', issue_number) return False # Auto-fix standard code quality stuff run_cmd(['bash', '-c', RUFF_FORMAT_AND_AUTO_FIX], tmpdirname, check=False) run_cmd(['git', 'add', '.'], tmpdirname) run_cmd(['git', 'commit', '-m', 'Ruff'], tmpdirname, check=False) # Push changes return push_changes( tmpdirname, branch_name, issue_number, issue_title, issue_description, args.base_branch, ) def handle_issues(args, client, seen_issues_db): """Process all open issues with the 'aider' label.""" try: issues = client.get_issues(args.owner, args.repo) except Exception: logger.exception('Failed to retrieve issues') sys.exit(1) if not issues: logger.info('No issues found.') return for issue in issues: issue_number = issue.get('number') issue_description = issue.get('body', '') title = issue.get('title', f'Issue {issue_number}') issue_text = f'{title}\n{issue_description}' if seen_issues_db.has_seen(issue_text): logger.info(f'Skipping already processed issue #{issue_number}: {title}') continue branch_name = generate_branch_name(issue_number, title) with tempfile.TemporaryDirectory() as tmpdirname: solved = solve_issue_in_repository( args, Path(tmpdirname), branch_name, title, issue_description, issue_number, ) if solved: seen_issues_db.mark_as_seen(issue_text)