""" Example Usage of Allegro-Primus Gitea Integration Demonstrates all major features of the integration. """ import os from dotenv import load_dotenv # Load environment variables load_dotenv() from gitea_client import GiteaClient, IssueState, IssuePriority from repo_manager import RepoManager, GitConfig from work_scheduler import WorkScheduler, WorkTask, TaskStatus def example_1_basic_api_usage(): """Example 1: Basic Gitea API client usage.""" print("\n=== Example 1: Basic API Usage ===\n") # Initialize client (uses env vars GITEA_URL and GITEA_TOKEN) client = GiteaClient() # Get authenticated user info user = client.get_user() print(f"Authenticated as: {user.get('login')} ({user.get('email')})") # List accessible repositories repos = client.get_repos(limit=10) print(f"\nFound {len(repos)} accessible repositories:") for repo in repos: print(f" - {repo['full_name']} ({repo['description'] or 'No description'})") return client, repos def example_2_issue_management(client: GiteaClient, owner: str, repo: str): """Example 2: Issue management operations.""" print("\n=== Example 2: Issue Management ===\n") # List open issues issues = client.list_issues(owner, repo, state=IssueState.OPEN, limit=10) print(f"Found {len(issues)} open issues:") for issue in issues[:5]: priority = issue.priority or "No priority" print(f" #{issue.number}: {issue.title[:50]}... [Priority: {priority}]") # Get priority issues (P0, P1) priority_issues = client.get_priority_issues(owner, repo, priorities=["P0", "P1"]) print(f"\nFound {len(priority_issues)} P0/P1 priority issues") # Example: Create an issue (commented out to avoid creating test issues) # new_issue = client.create_issue( # owner=owner, # repo=repo, # title="Test Issue from Allegro-Primus", # body="This is a test issue created via the Gitea API integration.", # labels=["P2", "automation"] # ) # print(f"\nCreated issue #{new_issue.number}") # Example: Add comment to an issue if issues: first_issue = issues[0] # client.add_issue_comment( # owner, repo, first_issue.number, # "šŸ¤– This is an automated comment from Allegro-Primus." # ) print(f"\nWould add comment to issue #{first_issue.number}") return issues def example_3_pr_management(client: GiteaClient, owner: str, repo: str): """Example 3: Pull request operations.""" print("\n=== Example 3: PR Management ===\n") # List open PRs prs = client.list_pull_requests(owner, repo, state="open", limit=10) print(f"Found {len(prs)} open pull requests:") for pr in prs[:5]: merge_status = "mergeable" if pr.mergeable else "not mergeable" print(f" #{pr.number}: {pr.title[:50]}... [{merge_status}]") # Example: Check if PR is mergeable if prs: first_pr = prs[0] is_mergeable = client.is_pr_mergeable(owner, repo, first_pr.number) print(f"\nPR #{first_pr.number} mergeable: {is_mergeable}") # Example: Merge a PR (commented out for safety) # if is_mergeable: # result = client.merge_pull_request( # owner, repo, first_pr.number, # merge_method="squash", # delete_branch=True # ) # print(f"Merged PR: {result}") return prs def example_4_repo_operations(owner: str, repo: str): """Example 4: Repository operations.""" print("\n=== Example 4: Repository Operations ===\n") # Initialize repo manager manager = RepoManager( base_path="./repos", git_config=GitConfig( name="Allegro-Primus", email="ap@allegro-primus.local" ) ) # Ensure repository exists locally print(f"Ensuring repository {owner}/{repo} is cloned...") repo_path = manager.ensure_repo(owner, repo) print(f"Repository ready at: {repo_path}") # Get repository status status = manager.get_status(owner, repo) print(f"\nRepository Status:") print(f" Branch: {status['branch']}") print(f" Has uncommitted changes: {status['has_uncommitted_changes']}") print(f" Last commit: {status['last_commit_hash'][:8]} - {status['last_commit_message'][:40]}") # List branches branches = manager.list_branches(owner, repo) print(f"\nBranches ({len(branches)}):") for branch in branches[:10]: print(f" - {branch}") # Example: Create a work branch # branch_name = manager.create_work_branch(owner, repo, 42, "fix-bug") # print(f"\nCreated branch: {branch_name}") return manager def example_5_work_scheduling(owner: str, repo: str): """Example 5: Work scheduling and task management.""" print("\n=== Example 5: Work Scheduling ===\n") # Initialize scheduler scheduler = WorkScheduler() # Fetch and prioritize pending tasks pending = scheduler.get_pending_tasks(owner, repo) print(f"Found {len(pending)} pending priority tasks:") for task in pending[:5]: print(f" #{task.issue.number}: {task.issue.title[:40]}... " f"(score: {task.priority_score:.1f})") # Example: Create a work cycle cycle = scheduler.create_work_cycle(owner, repo, cycle_name="demo-cycle") print(f"\nCreated work cycle: {cycle.cycle_id}") print(f"Tasks in cycle: {len(cycle.tasks)}") # Example: Define a task processor def demo_processor(task: WorkTask) -> bool: """Demo task processor - simulates work.""" print(f" Processing task #{task.issue.number}: {task.issue.title}") # Your actual work logic here return True # Example: Run a work cycle with processor # completed = scheduler.run_work_cycle(owner, repo, task_processor=demo_processor) # print(f"Completed cycle with {completed.completed_tasks} tasks done") # Get cycle history history = scheduler.get_cycle_history() print(f"\nCycle history ({len(history)} cycles):") for h in history[:5]: print(f" - {h['cycle_id']}: {h['status']} ({h['completed_tasks']} tasks)") return scheduler def example_6_complete_workflow(): """Example 6: Complete autonomous workflow.""" print("\n=== Example 6: Complete Autonomous Workflow ===\n") owner = "your-org" repo = "your-repo" # Initialize all components client = GiteaClient() scheduler = WorkScheduler() # Define comprehensive task processor def autonomous_processor(task: WorkTask) -> bool: """Autonomous task processor that handles issues end-to-end.""" print(f"\nšŸ¤– Processing issue #{task.issue.number}: {task.issue.title}") try: # Step 1: Clone repo and create branch manager = RepoManager() manager.ensure_repo(task.owner, task.repo) # Step 2: Analyze issue and determine action issue_body = task.issue.body print(f" Analyzing: {issue_body[:100]}...") # Step 3: Make changes (this is where your AI logic goes) # - Read relevant files # - Generate fixes # - Apply changes # Step 4: Commit and push # manager.commit_and_push( # task.owner, task.repo, task.branch_name, # f"Fix: {task.issue.title} (closes #{task.issue.number})" # ) # Step 5: Create PR # pr = manager.open_pull_request( # task.owner, task.repo, # title=f"Fix: {task.issue.title}", # head_branch=task.branch_name, # body=f"Closes #{task.issue.number}\n\n{task.issue.body}" # ) # Step 6: Update issue client.add_issue_comment( task.owner, task.repo, task.issue.number, f"āœ… Automated fix submitted in PR #{pr.number}" ) return True except Exception as e: print(f" āŒ Error: {e}") return False # Register the processor and run # scheduler.run_work_cycle(owner, repo, task_processor=autonomous_processor) print("Workflow example defined. Uncomment to run with real credentials.") return client, scheduler def main(): """Run all examples.""" print("=" * 60) print("Allegro-Primus Gitea Integration - Example Usage") print("=" * 60) # Check environment if not os.getenv("GITEA_URL") or not os.getenv("GITEA_TOKEN"): print("\nāš ļø Warning: GITEA_URL and GITEA_TOKEN not set in environment!") print("Please set these variables or create a .env file.") return try: # Run examples client, repos = example_1_basic_api_usage() if repos: # Use first available repo for remaining examples first_repo = repos[0] owner = first_repo['owner']['login'] repo = first_repo['name'] example_2_issue_management(client, owner, repo) example_3_pr_management(client, owner, repo) example_4_repo_operations(owner, repo) example_5_work_scheduling(owner, repo) example_6_complete_workflow() print("\n" + "=" * 60) print("All examples completed successfully!") print("=" * 60) except Exception as e: print(f"\nāŒ Error running examples: {e}") import traceback traceback.print_exc() if __name__ == "__main__": main()