#!/usr/bin/env python3 """Автоматизация git bisect с внешней тестовой командой.""" from __future__ import annotations import argparse import os import shlex import shutil import subprocess from pathlib import Path 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 git_path(repo: Path, name: str) -> Path: result = git(repo, "rev-parse", "--git-path", name) path = Path(result.stdout.strip()) if not path.is_absolute(): path = repo / path return path def main() -> int: parser = argparse.ArgumentParser(description="Запустить git bisect") parser.add_argument("--repo", default=".", help="Путь к репозиторию") parser.add_argument("--good", required=True, help="Хороший коммит или тег") parser.add_argument("--bad", default="HEAD", help="Плохой коммит") parser.add_argument("--command", required=True, help="Команда теста в кавычках") parser.add_argument("--run", action="store_true", help="Выполнить поиск") parser.add_argument("--keep", action="store_true", help="Не делать bisect reset") 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 if git(repo, "status", "--porcelain").stdout.strip(): print("Рабочее дерево не чистое. Закоммитьте или спрячьте изменения.") return 2 if git_path(repo, "BISECT_LOG").exists(): print("Bisect уже запущен. Завершите его командой git bisect reset.") return 2 for name, ref in (("good", args.good), ("bad", args.bad)): if git(repo, "rev-parse", "--verify", f"{ref}^{{commit}}").returncode != 0: print(f"Не найден коммит {name}: {ref}") return 2 if git(repo, "merge-base", "--is-ancestor", args.good, args.bad).returncode != 0: print("Хороший коммит не является предком плохого.") return 2 try: test_command = shlex.split(args.command, posix=(os.name != "nt")) except ValueError as error: print(f"Не удалось разобрать команду: {error}") return 2 if not test_command: print("Пустая тестовая команда.") return 2 print(f"Репозиторий: {repo}") print(f"Хороший: {args.good}") print(f"Плохой: {args.bad}") print(f"Тест: {shlex.join(test_command)}") print() if not args.run: print("Будет выполнено: git bisect start, bisect bad, bisect good, bisect run ...") print("Это предпросмотр. Для запуска добавьте --run.") return 0 steps = [ ["git", "-C", str(repo), "bisect", "start"], ["git", "-C", str(repo), "bisect", "bad", args.bad], ["git", "-C", str(repo), "bisect", "good", args.good], ] for step in steps: if subprocess.run(step).returncode != 0: print(f"Команда не выполнена: {' '.join(step)}") subprocess.run(["git", "-C", str(repo), "bisect", "reset"]) return 1 result = subprocess.run( ["git", "-C", str(repo), "bisect", "run", *test_command] ) if not args.keep: reset = subprocess.run(["git", "-C", str(repo), "bisect", "reset"]) if reset.returncode != 0: print("Не удалось выполнить git bisect reset. Проверьте состояние вручную.") else: print("Состояние bisect сохранено. Для выхода выполните git bisect reset.") if result.returncode == 0: print("Поиск завершён. Первый плохой коммит показан выше.") else: print("Git bisect завершился с ошибкой. Проверьте вывод теста.") return result.returncode if __name__ == "__main__": raise SystemExit(main())