"""Git-based repository identity detection.""" import subprocess from pathlib import Path def detect_project_identity(cwd: Path | None = None) -> str: """Detect project identity. Priority: git remote URL -> git folder name -> cwd name.""" cwd = cwd or Path.cwd() # 1. Try git remote URL remote = _get_git_remote(cwd) if remote: return _normalize_remote(remote) # 2. Try git root folder name git_root = _get_git_root(cwd) if git_root: return git_root.name # 3. Fall back to current directory name return cwd.resolve().name def _get_git_remote(cwd: Path) -> str | None: """Get the origin remote URL, or None.""" try: result = subprocess.run( ["git", "remote", "get-url", "origin"], cwd=str(cwd), capture_output=True, text=True, timeout=5, ) if result.returncode == 0: return result.stdout.strip() except (FileNotFoundError, subprocess.TimeoutExpired): pass return None def _get_git_root(cwd: Path) -> Path | None: """Get the git repository root directory, or None.""" try: result = subprocess.run( ["git", "rev-parse", "--show-toplevel"], cwd=str(cwd), capture_output=True, text=True, timeout=5, ) if result.returncode == 0: return Path(result.stdout.strip()) except (FileNotFoundError, subprocess.TimeoutExpired): pass return None def _normalize_remote(url: str) -> str: """Extract project name from a git remote URL. Handles: git@github.com:user/project.git -> project https://github.com/user/project.git -> project https://github.com/user/project -> project """ # Strip trailing .git url = url.rstrip("/") if url.endswith(".git"): url = url[:-4] # Get the last path segment as the project name return url.split("/")[-1].split(":")[-1]