coderg / git_agent.py
prashantmatlani's picture
updated agentic functions
f54201d
Raw
History Blame Contribute Delete
3.75 kB
"""
# ./git_agent.py
# The Courier - Features the fixed parameter initialization logic, calls GitHub API to provision new repos under CoderG's dedicated account, and completely clears the transient temp_repo folder after pushing.
"""
import os
import shutil
import requests
from git import Repo
from agent_logging import log_agent_action
def manage_github_repo(repo_name, commit_message, files_to_add):
"""Clones, creates missing repos, pushes files, and forces local directory purge."""
token = os.getenv("GITHUB_TOKEN")
username = os.getenv("GITHUB_USERNAME")
if not token or not username:
log_agent_action("GIT_ERROR", "Missing GITHUB_TOKEN or GITHUB_USERNAME in environment.")
return "GIT ERROR: Missing authentication credentials."
# 1. Check/Create Repository on GitHub via API
api_url = "https://api.github.com/user/repos"
check_url = f"https://api.github.com/repos/{username}/{repo_name}"
headers = {"Authorization": f"token {token}", "Accept": "application/vnd.github.v3+json"}
try:
response = requests.get(check_url, headers=headers)
if response.status_code == 404:
log_agent_action("GIT_PROVISION", f"Repo '{repo_name}' not found. Initializing on GitHub...")
create_res = requests.post(api_url, json={"name": repo_name, "private": False}, headers=headers)
if create_res.status_code != 201:
raise Exception(f"GitHub API creation failed: {create_res.text}")
log_agent_action("GIT_PROVISION", f"Successfully created remote repo: {repo_name}")
except Exception as api_err:
log_agent_action("GIT_ERROR", f"API Verification Phase failed: {str(api_err)}")
return f"GIT ERROR: {str(api_err)}"
# 2. Local Git Actions
repo_url = f"https://{username}:{token}@github.com/{username}/{repo_name}.git"
local_path = os.path.join(os.getcwd(), "temp_repo")
try:
if not os.path.exists(local_path):
repo = Repo.clone_from(repo_url, local_path)
else:
repo = Repo(local_path)
# Move files from outputs to temp_repo safely
files_actually_added = 0
for file in files_to_add:
src = os.path.join("outputs", file)
dst = os.path.join(local_path, file)
if os.path.exists(src):
shutil.copy2(src, dst)
repo.index.add([file])
files_actually_added += 1
else:
log_agent_action("GIT_WARN", f"Staged file item '{file}' not found in outputs/ directory. Skipping.")
if files_actually_added == 0:
status_msg = "NOTICE: Commit aborted. None of the listed staged files exist in local storage."
return status_msg
if repo.is_dirty():
repo.index.commit(commit_message)
origin = repo.remote(name='origin')
origin.push()
log_agent_action("GIT_PUSH", f"Pushed {len(files_to_add)} files to {repo_name}")
status_msg = f"Success: Repository {repo_name} is live/updated at {repo_url}"
else:
log_agent_action("GIT_NOTICE", "No modifications detected; push aborted.")
status_msg = "NOTICE: No changes detected to commit."
except Exception as git_err:
log_agent_action("GIT_ERROR", f"Local operations failed: {str(git_err)}")
status_msg = f"GIT ERROR: {str(git_err)}"
finally:
# 3. Dynamic Cleanup Execution
if os.path.exists(local_path):
shutil.rmtree(local_path, ignore_errors=True)
log_agent_action("CLEANUP", "Transient directory 'temp_repo' purged successfully.")
return status_msg