ai-demo/git_mcp_server/git_commit_tool.py

112 lines
3.5 KiB
Python

"""Git 提交工具"""
import subprocess
import logging
from typing import Dict, Any
from base import BaseTool, ToolResult
logger = logging.getLogger(__name__)
class GitCommitTool(BaseTool):
"""提交 Git 更改"""
@property
def parameters_schema(self) -> Dict[str, Any]:
return {
"type": "object",
"properties": {
"repo_path": {
"type": "string",
"description": "Git 仓库路径"
},
"message": {
"type": "string",
"description": "提交信息",
"default": "Auto commit"
},
"timeout": {
"type": "integer",
"description": "超时时间(秒)",
"default": 30
}
},
"required": ["repo_path"]
}
def execute(self,
repo_path: str,
message: str = "Auto commit",
timeout: int = 30,
**kwargs) -> ToolResult:
"""
提交更改
Args:
repo_path: 仓库路径
message: 提交信息
timeout: 超时时间(秒)
Returns:
ToolResult: 包含提交结果的工具返回对象
"""
# 参数验证
if not repo_path or not repo_path.strip():
error_msg = "仓库路径不能为空"
logger.error(error_msg)
raise ValueError(error_msg)
if not message or not message.strip():
error_msg = "提交信息不能为空"
logger.error(error_msg)
raise ValueError(error_msg)
try:
# 执行 git commit
commit_cmd = ["git", "commit", "-m", message]
result = subprocess.run(
commit_cmd,
capture_output=True,
encoding='utf-8',
cwd=repo_path,
timeout=timeout
)
if result.returncode != 0:
if "nothing to commit" in result.stderr or "nothing to commit" in result.stdout:
logger.warning("没有需要提交的内容")
return ToolResult(
success=True,
data={
"repo_path": repo_path,
"has_changes": False
},
message="没有需要提交的内容"
)
error_msg = f"git commit 失败: {result.stderr}"
logger.error(error_msg)
raise RuntimeError(error_msg)
logger.info(f"代码已提交: {message}")
return ToolResult(
success=True,
data={
"repo_path": repo_path,
"message": message,
"has_changes": True
},
message=f"代码已提交: {message}"
)
except subprocess.TimeoutExpired:
error_msg = f"git commit 超时({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 commit 执行异常: {str(e)}"
logger.error(error_msg)
raise RuntimeError(error_msg)