99 lines
3.0 KiB
Python
99 lines
3.0 KiB
Python
"""Git 添加文件工具"""
|
|
import subprocess
|
|
import logging
|
|
from typing import Dict, Any
|
|
|
|
from base import BaseTool, ToolResult
|
|
logger = logging.getLogger(__name__)
|
|
|
|
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": "要添加的文件或目录路径"
|
|
},
|
|
"timeout": {
|
|
"type": "integer",
|
|
"description": "超时时间(秒)",
|
|
"default": 30
|
|
}
|
|
},
|
|
"required": ["repo_path", "file_path"]
|
|
}
|
|
|
|
def execute(self,
|
|
repo_path: str,
|
|
file_path: str,
|
|
timeout: int = 30,
|
|
**kwargs) -> ToolResult:
|
|
"""
|
|
添加文件到暂存区
|
|
|
|
Args:
|
|
repo_path: 仓库路径
|
|
file_path: 文件或目录路径
|
|
timeout: 超时时间(秒)
|
|
|
|
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)
|
|
|
|
try:
|
|
# 执行 git add
|
|
add_cmd = ["git", "add", file_path]
|
|
result = subprocess.run(
|
|
add_cmd,
|
|
capture_output=True,
|
|
encoding='utf-8',
|
|
cwd=repo_path,
|
|
timeout=timeout
|
|
)
|
|
|
|
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}"
|
|
)
|
|
except subprocess.TimeoutExpired:
|
|
error_msg = f"git add 超时({timeout}秒)"
|
|
logger.error(error_msg)
|
|
raise RuntimeError(error_msg)
|
|
except FileNotFoundError:
|
|
error_msg = "未找到 git 命令,请确认已安装 git"
|
|
logger.error(error_msg)
|
|
raise RuntimeError(error_msg)
|
|
except Exception as e:
|
|
error_msg = f"git add 执行异常: {str(e)}"
|
|
logger.error(error_msg)
|
|
raise RuntimeError(error_msg)
|