#!/usr/bin/env python3 """Установка простых git-хуков в репозиторий.""" from __future__ import annotations import argparse import shutil import subprocess from datetime import datetime from pathlib import Path HOOKS = { "pre-commit": """#!/usr/bin/env bash set -euo pipefail if [[ -f .pre-commit-config.yaml ]] && command -v pre-commit >/dev/null 2>&1; then exec pre-commit run --hook-stage pre-commit fi if git diff --cached --check; then exit 0 fi echo "Whitespace errors found. Fix them before committing." >&2 exit 1 """, "commit-msg": """#!/usr/bin/env bash set -euo pipefail message_file="${1:?message file required}" first_line="$(head -n 1 "$message_file")" if [[ -z "$first_line" ]]; then echo "Commit message is empty." >&2 exit 1 fi if [[ "${#first_line}" -gt 72 ]]; then echo "Commit subject is longer than 72 characters." >&2 exit 1 fi if grep -n '[[:blank:]]$' "$message_file" >/dev/null 2>&1; then echo "Commit message has trailing whitespace." >&2 exit 1 fi """, "pre-push": """#!/usr/bin/env bash set -euo pipefail if [[ -f .pre-commit-config.yaml ]] && command -v pre-commit >/dev/null 2>&1; then exec pre-commit run --hook-stage pre-push fi exit 0 """, } def git(repo: Path, *args: str) -> subprocess.CompletedProcess[str]: return subprocess.run( ["git", "-C", str(repo), *args], capture_output=True, text=True, encoding="utf-8", errors="replace", ) def main() -> int: parser = argparse.ArgumentParser(description="Установить git-хуки") parser.add_argument("--repo", default=".", help="Путь к репозиторию") parser.add_argument( "--hook", action="append", choices=sorted(HOOKS), help="Какой хук установить, можно указать несколько раз", ) parser.add_argument("--apply", action="store_true", help="Записать хуки") parser.add_argument("--force", action="store_true", help="Заменить существующие хуки") args = parser.parse_args() if not shutil.which("git"): print("Не найден git.") return 2 repo = Path(args.repo).expanduser().resolve() if not repo.is_dir(): print(f"Папка не найдена: {repo}") return 2 if git(repo, "rev-parse", "--is-inside-work-tree").returncode != 0: print(f"Это не git-репозиторий: {repo}") return 2 hooks_path = git(repo, "config", "--get", "core.hooksPath").stdout.strip() if hooks_path: print("В репозитории задан core.hooksPath. Установите хуки в этот каталог вручную.") print(f"core.hooksPath = {hooks_path}") return 2 result = git(repo, "rev-parse", "--git-path", "hooks") hooks_dir = Path(result.stdout.strip()) if not hooks_dir.is_absolute(): hooks_dir = repo / hooks_dir selected = args.hook or sorted(HOOKS) print(f"Репозиторий: {repo}") print(f"Каталог хуков: {hooks_dir}") print(f"Хуки: {', '.join(selected)}") print() planned = [] for name in selected: target = hooks_dir / name if target.exists() and not args.force: print(f"Пропуск {name}: файл уже существует. Добавьте --force для замены.") continue planned.append((name, target)) if not planned: print("Нечего устанавливать.") return 0 if not args.apply: for name, target in planned: print(f"Будет создан: {target}") print("Это предпросмотр. Для установки добавьте --apply.") return 0 hooks_dir.mkdir(parents=True, exist_ok=True) stamp = datetime.now().strftime("%Y%m%d-%H%M%S") for name, target in planned: if target.exists(): backup = target.with_name(f"{name}.bak.{stamp}") shutil.copy2(target, backup) print(f"Резервная копия: {backup}") target.write_text(HOOKS[name], encoding="utf-8") target.chmod(0o755) print(f"Установлен: {target}") print("Готово. Проверьте хуки на тестовом коммите.") return 0 if __name__ == "__main__": raise SystemExit(main())