ai-demo/app/tools/git/git_add_tool.py

81 lines
2.2 KiB
Python

"""Git 添加文件工具"""
import subprocess
import logging
from typing import Dict, Any
from app.tools.base import BaseTool, ToolResult
from app.tools.registry import ToolRegistry
logger = logging.getLogger(__name__)
@ToolRegistry.register
class GitAddTool(BaseTool):
"""添加文件到 Git 暂存区"""
@property
def parameters_schema(self) -> Dict[str, Any]:
return {
"type": "object",
"properties": {
"repo_path": {
"type": "string",
"description": "Git 仓库路径"
},
"file_path": {
"type": "string",
"description": "要添加的文件或目录路径"
}
},
"required": ["repo_path", "file_path"]
}
def execute(self,
repo_path: str,
file_path: str,
**kwargs) -> ToolResult:
"""
添加文件到暂存区
Args:
repo_path: 仓库路径
file_path: 文件或目录路径
Returns:
ToolResult: 包含添加结果的工具返回对象
"""
# 参数验证
if not repo_path or not repo_path.strip():
error_msg = "仓库路径不能为空"
logger.error(error_msg)
raise ValueError(error_msg)
if not file_path or not file_path.strip():
error_msg = "文件路径不能为空"
logger.error(error_msg)
raise ValueError(error_msg)
# 执行 git add
add_cmd = ["git", "add", file_path]
result = subprocess.run(
add_cmd,
capture_output=True,
encoding='utf-8',
cwd=repo_path
)
if result.returncode != 0:
error_msg = f"git add 失败: {result.stderr}"
logger.error(error_msg)
raise RuntimeError(error_msg)
logger.info(f"文件已添加到暂存区: {file_path}")
return ToolResult(
success=True,
data={
"file_path": file_path,
"repo_path": repo_path
},
message=f"文件已添加到暂存区: {file_path}"
)