zenex-ai-project / agent /tools /git_tool.py
shashankmacherla's picture
Upload full llm_project
6d5c79f verified
Raw History Blame Contribute Delete
3.48 kB
"""Git tool — init, add, commit, status, diff for generated projects."""
from __future__ import annotations
import logging
import subprocess
from pathlib import Path
from typing import Any
from agent.tools.base import BaseTool
LOGGER = logging.getLogger(__name__)
class GitTool(BaseTool):
"""Lightweight git wrapper for agent-managed project repositories.
Only performs local git operations — no push/pull/remote access.
"""
name = "git"
description = "Run git operations (init, add, commit, status, diff, log)."
def __init__(self, timeout: int = 30) -> None:
self._timeout = timeout
def run(self, args: dict[str, Any]) -> dict[str, Any]:
op = args.get("op", "status")
repo_dir = args.get("repo_dir", ".")
ops = {
"init": self._init,
"add": self._add,
"commit": self._commit,
"status": self._status,
"diff": self._diff,
"log": self._log,
}
if op not in ops:
return self._fail(f"Unknown git op '{op}'. Available: {list(ops.keys())}")
return ops[op](args, Path(repo_dir))
# ------------------------------------------------------------------
def _init(self, args: dict, repo: Path) -> dict:
repo.mkdir(parents=True, exist_ok=True)
r = self._git(["init"], cwd=repo)
if r["success"]:
# Set safe defaults for a new repo
self._git(["config", "user.email", "zenex-agent@local"], cwd=repo)
self._git(["config", "user.name", "Zenex Agent"], cwd=repo)
return r
def _add(self, args: dict, repo: Path) -> dict:
paths = args.get("paths", ["."])
if isinstance(paths, str):
paths = [paths]
return self._git(["add"] + paths, cwd=repo)
def _commit(self, args: dict, repo: Path) -> dict:
message = args.get("message", "agent: automated commit")
# Stage everything if nothing staged
self._git(["add", "-A"], cwd=repo)
return self._git(["commit", "-m", message, "--allow-empty"], cwd=repo)
def _status(self, args: dict, repo: Path) -> dict:
return self._git(["status", "--short"], cwd=repo)
def _diff(self, args: dict, repo: Path) -> dict:
ref = args.get("ref", "HEAD")
return self._git(["diff", ref], cwd=repo)
def _log(self, args: dict, repo: Path) -> dict:
n = args.get("n", 10)
return self._git(["log", f"-{n}", "--oneline"], cwd=repo)
# ------------------------------------------------------------------
def _git(self, cmd: list[str], cwd: Path) -> dict:
try:
proc = subprocess.run(
["git"] + cmd,
cwd=cwd,
capture_output=True,
text=True,
timeout=self._timeout,
)
return {
"success": proc.returncode == 0,
"stdout": proc.stdout.strip(),
"stderr": proc.stderr.strip(),
"exit_code": proc.returncode,
"error": proc.stderr.strip() if proc.returncode != 0 else "",
}
except subprocess.TimeoutExpired:
return self._fail(f"git {cmd[0]} timed out after {self._timeout}s")
except FileNotFoundError:
return self._fail("git executable not found. Please install git.")
except Exception as exc:
return self._fail(str(exc))