""" Git 读取服务 ============ 【功能说明】 封装对本地 Git 仓库的只读操作:读取分支列表、校验分支是否存在、 读取仓库当前状态摘要。供项目管理 API 展示「前端/后端仓库分支」下拉框使用。 【技术选型理由】 1. 决策点 12/13 已锁定「本地 Git 管理 + 真实分支语义」——分支必须来自 真实 git 仓库,不能是自由文本标签,所以用 subprocess 调本机 git CLI。 2. 不用 GitPython / pygit2:多一层原生依赖与编译风险,subprocess 足够 且行为与你在 PyCharm/终端里看到的完全一致,便于教学对照。 3. 只做只读操作(分支列表/校验):写操作(checkout/commit)属于 代码修改链路(M4/M5),届时通过白名单执行器统一收口,本模块不越权。 【实现思路】 - 所有命令用 list 参数传参(不经 shell 字符串拼接),杜绝命令注入; - 强制 subprocess 工作目录为传入的仓库路径,不信任环境变量里的 cwd; - 统一超时与输出截断,避免 git 卡死拖垮 API。 【潜在风险与应对】 风险1:目标路径不是 git 仓库(用户填错路径)。 应对:捕获 git 返回码非 0,转成结构化「不是 Git 仓库」业务错误, 绝不让 API 500。 风险2:git 命令不存在(未安装)。 应对:捕获 FileNotFoundError,返回「未检测到 git 命令,请先安装」。 风险3:仓库损坏 / 文件锁冲突导致 git 长时间阻塞。 应对:强制 timeout=15s,超时返回明确提示,不无限等待。 """ from __future__ import annotations import subprocess from pathlib import Path class GitError(RuntimeError): """Git 操作失败的统一业务异常(带中文可读信息)""" def __init__(self, message: str, *, error_type: str = "GitError") -> None: super().__init__(message) self.error_type = error_type class GitReadService: """Git 只读服务(一期:分支列表与校验)""" def __init__(self, timeout_seconds: int = 15) -> None: self._timeout = timeout_seconds def _run_git(self, repo_path: Path, args: list[str]) -> str: """ 在指定仓库目录执行 git 子命令,返回 stdout 文本。 【安全要点】args 用 list 传参,绝不拼接 shell 字符串,防命令注入。 """ if not Path(repo_path).exists(): raise GitError( f"代码路径不存在:{repo_path}", error_type="PathNotFound" ) try: completed = subprocess.run( ["git", *args], cwd=str(repo_path), capture_output=True, text=True, timeout=self._timeout, shell=False, encoding="utf-8", errors="replace", ) except FileNotFoundError as exc: raise GitError( "未检测到 git 命令,请先安装 Git 并加入 PATH", error_type="GitNotFound" ) from exc except subprocess.TimeoutExpired as exc: raise GitError( f"git 命令执行超时(>{self._timeout}秒):git {' '.join(args)}", error_type="GitTimeout", ) from exc if completed.returncode != 0: stderr = (completed.stderr or "").strip() raise GitError( f"git 命令执行失败(退出码 {completed.returncode}):{stderr[:500]}", error_type="GitCommandFailed", ) return completed.stdout or "" def is_git_repo(self, repo_path: Path) -> bool: """判断指定路径是否是 git 仓库(含子目录)。""" try: out = self._run_git(repo_path, ["rev-parse", "--is-inside-work-tree"]) return out.strip().lower() == "true" except GitError: return False def list_branches(self, repo_path: Path) -> list[str]: """ 列出仓库全部本地分支名。 【返回】分支名列表(不含星号前缀),按字母序去重。 """ out = self._run_git(repo_path, ["branch", "--format=%(refname:short)"]) branches = [line.strip() for line in out.splitlines() if line.strip()] return sorted(set(branches)) def branch_exists(self, repo_path: Path, branch_name: str) -> bool: """校验指定分支是否存在(供前端下拉框与校验使用)。""" try: self._run_git( repo_path, ["rev-parse", "--verify", "--quiet", f"refs/heads/{branch_name}"], ) return True except GitError: return False def current_branch(self, repo_path: Path) -> str: """读取仓库当前所在分支名(HEAD 指向)。""" out = self._run_git(repo_path, ["rev-parse", "--abbrev-ref", "HEAD"]) return out.strip() or "HEAD"