Files
AgentScript/agent/backend/app/tools/git_tools.py
T
HenryandClaude Code 26e13ff032 feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。
排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。

Co-Authored-By: Claude Code <[email protected]>
2026-11-13 13:48:41 +08:00

164 lines
6.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Git 操作工具
============
【功能说明】
封装本地 Git 的常用写操作:状态查看、diff、建任务分支、提交。
对应决策点 12/13「本地 Git 管理 + 真实分支语义」。
【技术选型理由】
1. 决策点 12 已锁定「本地 Git(无远程)」:改动可回滚、可审计、可并发隔离;
2. 任务分支策略:每个任务自动建 `agent/task_<id>` 分支,
改动隔离在任务分支上,master 不受污染(企业级标准做法);
3. 仍走 subprocess list 传参,防注入(与 GitReadService 同款)。
【实现思路】
- ensure_task_branch:存在则切、不存在则建并切;
- commit_changes:add + commit(不 push,无远程);
- get_diff:工作区相对 HEAD 的 diff,供 Agent/人查看改动。
【潜在风险与应对】
风险1:工作区有未提交改动时切分支被拒。
应对:先自动 stash 或 commit 当前改动(决策:选 commit 留痕)。
风险2:git user.name/email 未配置导致 commit 失败。
应对:首次提交前自动设置仓库级 user(agent-bot)。
风险3:误提交大文件/敏感文件。
应对:.gitignore 已排除 .env 等;审计日志记录每次 commit 内容摘要。
"""
from __future__ import annotations
import logging
import subprocess
from pathlib import Path
from typing import Any
from app.tools.audit import log_action
from app.tools.path_guard import ensure_under_root
from app.tools.proc_flags import hidden_popen_kwargs
logger = logging.getLogger("agent.tools.git")
class GitToolError(RuntimeError):
"""Git 工具异常(中文可读)"""
def __init__(self, message: str, *, error_type: str = "GitToolError") -> None:
super().__init__(message)
self.error_type = error_type
def _git(repo: Path, args: list[str], timeout: int = 30) -> str:
"""在指定仓库执行 git 命令,返回 stdout。"""
try:
completed = subprocess.run(
["git", *args],
cwd=str(repo),
capture_output=True,
text=True,
timeout=timeout,
shell=False,
encoding="utf-8",
errors="replace",
**hidden_popen_kwargs(),
)
except FileNotFoundError as exc:
raise GitToolError("未检测到 git 命令", error_type="GitNotFound") from exc
except subprocess.TimeoutExpired as exc:
raise GitToolError(f"git 命令超时:git {' '.join(args)}", error_type="Timeout") from exc
if completed.returncode != 0:
raise GitToolError(
f"git {' '.join(args)} 失败(退出码 {completed.returncode}):{(completed.stderr or '')[:500]}",
error_type="GitCommandFailed",
)
return completed.stdout or ""
def ensure_task_branch(repo_path: str | Path, task_id: str) -> dict[str, Any]:
"""
确保当前仓库位于任务分支上(存在则切、不存在则建并切)。
【分支命名】agent/task_<task_id>,隔离任务改动。
"""
repo = ensure_under_root(Path(repo_path), action="Git 操作")
branch = f"agent/task_{task_id}"
# 确保 user 配置存在(否则 commit 会失败)
try:
_git(repo, ["config", "user.email"], timeout=10)
except GitToolError:
_git(repo, ["config", "user.email", "agent-bot@local"], timeout=10)
_git(repo, ["config", "user.name", "agent-bot"], timeout=10)
try:
_git(repo, ["rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], timeout=10)
# 分支已存在 → 切换
_git(repo, ["checkout", branch], timeout=15)
action = "switched"
except GitToolError:
# 分支不存在 → 创建并切换(若工作区脏,先建分支自带改动)
try:
_git(repo, ["checkout", "-b", branch], timeout=15)
action = "created"
except GitToolError as exc:
raise GitToolError(
f"创建任务分支失败:{exc}", error_type="BranchCreateFailed"
) from exc
log_action(
action="git_branch",
target=str(repo),
result="success",
details={"branch": branch, "action": action, "task_id": task_id},
)
return {"repo": str(repo), "branch": branch, "action": action}
def commit_changes(repo_path: str | Path, message: str, task_id: str = "") -> dict[str, Any]:
"""
提交当前工作区改动(add + commit,不 push——决策点 12 无远程)。
【返回】{commit_hash, branch, files_changed}
"""
repo = ensure_under_root(Path(repo_path), action="Git 提交")
# add 全部改动(.gitignore 自动排除敏感文件)
_git(repo, ["add", "-A"], timeout=30)
# 若无可提交内容,返回空
status = _git(repo, ["status", "--porcelain"], timeout=15)
if not status.strip():
logger.info("无可提交内容:%s", repo)
return {"commit_hash": None, "branch": "", "files_changed": 0}
_git(repo, ["commit", "-m", message], timeout=30)
commit_hash = _git(repo, ["rev-parse", "--short", "HEAD"], timeout=10).strip()
branch = _git(repo, ["rev-parse", "--abbrev-ref", "HEAD"], timeout=10).strip()
files_changed = len([l for l in status.splitlines() if l.strip()])
log_action(
action="git_commit",
target=str(repo),
result="success",
details={
"commit": commit_hash,
"branch": branch,
"files_changed": files_changed,
"message": message[:200],
"task_id": task_id,
},
)
return {
"commit_hash": commit_hash,
"branch": branch,
"files_changed": files_changed,
}
def get_diff(repo_path: str | Path) -> dict[str, Any]:
"""获取工作区相对 HEAD 的 diff(供 Agent/人查看改动)。"""
repo = ensure_under_root(Path(repo_path), action="Git diff")
diff = _git(repo, ["diff", "HEAD"], timeout=20)
return {"repo": str(repo), "diff": diff[:5000], "truncated": len(diff) > 5000}