Установить git-хуки проекта
Ставит проверки pre-commit, commit-msg и pre-push с резервной копией старых хуков.
Что делает скрипт
Скрипт устанавливает небольшие bash-хуки в каталог hooks текущего репозитория. Существующие файлы не затираются без --force, а перед заменой сохраняется копия с датой. По умолчанию показывается план, запись выполняется с --apply.
- С --apply файлы в .git/hooks будут созданы или заменены с резервной копией.
Быстрый старт
python install_hooks.py --repo . --apply
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python install_hooks.py --repo .python install_hooks.py --repo . --hook pre-commit --hook commit-msg --apply
Что понадобится
sudo apt install git
brew install git
sudo apt install python3
brew install python
sudo apt install bash
brew install bash
python3 -m pip install pre-commit
python3 -m pip install pre-commit
install_hooks.py
#!/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())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.