import os import logging from pathlib import Path from dataclasses import dataclass, field from typing import Optional logger = logging.getLogger(__name__) @dataclass class GitRepoInfo: url: str local_path: Path branch: str = "main" language: str = "" framework: str = "" files: list[str] = field(default_factory=list) class GitOps: def __init__(self, work_dir: Path): self.work_dir = Path(work_dir) self.work_dir.mkdir(parents=True, exist_ok=True) def clone_or_pull(self, repo_url: str, branch: str = "main") -> GitRepoInfo: repo_name = self._extract_repo_name(repo_url) local_path = self.work_dir / repo_name try: import git except ImportError: raise ImportError("请安装 gitpython: pip install gitpython") if local_path.exists(): logger.info(f"仓库已存在,执行 git pull: {local_path}") repo = git.Repo(local_path) origin = repo.remotes.origin origin.fetch() repo.git.checkout(branch) origin.pull(branch) else: logger.info(f"克隆仓库: {repo_url} -> {local_path}") git.Repo.clone_from(repo_url, local_path, branch=branch, depth=50) info = self._analyze_repo(local_path) info.url = repo_url info.branch = branch return info def _extract_repo_name(self, repo_url: str) -> str: name = repo_url.rstrip("/").split("/")[-1] if name.endswith(".git"): name = name[:-4] return name def _analyze_repo(self, local_path: Path) -> GitRepoInfo: info = GitRepoInfo(url="", local_path=local_path, branch="main") info.files = self._collect_source_files(local_path) info.language = self._detect_language(info.files) info.framework = self._detect_framework(local_path, info.language) return info def _collect_source_files(self, root: Path) -> list[str]: ignore_dirs = { "node_modules", "__pycache__", ".git", "dist", "build", "vendor", ".venv", "venv", "env", ".tox", ".eggs", "*.egg-info", ".pytest_cache", ".mypy_cache", ".ruff_cache", } source_extensions = { ".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".java", } files = [] for f in root.rglob("*"): if f.is_file() and f.suffix in source_extensions: parts = f.relative_to(root).parts if not any(ig in parts for ig in ignore_dirs): files.append(str(f.relative_to(root))) return files def _detect_language(self, files: list[str]) -> str: ext_counts = {} for f in files: ext = Path(f).suffix ext_counts[ext] = ext_counts.get(ext, 0) + 1 if not ext_counts: return "unknown" dominant = max(ext_counts, key=ext_counts.get) lang_map = { ".py": "python", ".ts": "typescript", ".tsx": "typescript", ".js": "javascript", ".jsx": "javascript", ".go": "go", ".java": "java", } return lang_map.get(dominant, "unknown") def _detect_framework(self, root: Path, language: str) -> str: indicators = { ("requirements.txt", "fastapi"): "FastAPI", ("requirements.txt", "flask"): "Flask", ("requirements.txt", "django"): "Django", ("pyproject.toml", "pytest"): "Pytest", ("package.json", "vue"): "Vue", ("package.json", "react"): "React", ("package.json", "next"): "Next.js", ("go.mod", ""): "Go", ("pom.xml", ""): "Spring Boot", } for (filename, keyword), framework in indicators.items(): indicator_file = root / filename if indicator_file.exists(): if keyword: content = indicator_file.read_text(errors="ignore") if keyword.lower() in content.lower(): return framework else: return framework return "unknown" def get_diff(self, repo_path: Path, against: str = "HEAD~1") -> list[str]: try: import git except ImportError: raise ImportError("请安装 gitpython: pip install gitpython") repo = git.Repo(repo_path) try: diff = repo.git.diff("--name-only", against) return [f for f in diff.split("\n") if f] except git.GitCommandError: return [] def get_file_content(self, repo_path: Path, file_path: str) -> str: full_path = repo_path / file_path if full_path.exists(): return full_path.read_text(encoding="utf-8", errors="ignore") return ""