#!/usr/bin/env python3 """Клонирование репозитория с проверкой папки назначения.""" from __future__ import annotations import argparse 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 directory_size(path: Path) -> int: total = 0 if not path.exists(): return 0 for item in path.rglob("*"): if item.is_file() and not item.is_symlink(): try: total += item.stat().st_size except OSError: continue return total def main() -> int: parser = argparse.ArgumentParser(description="Клонировать git-репозиторий") parser.add_argument("source", help="URL или путь к репозиторию") parser.add_argument("target", help="Папка назначения") parser.add_argument("--branch", help="Ветка или тег") parser.add_argument("--depth", type=int, help="Глубина клона") parser.add_argument("--submodules", action="store_true", help="Клонировать submodules") parser.add_argument("--apply", action="store_true", help="Выполнить клонирование") args = parser.parse_args() if not shutil.which("git"): print("Не найден git.") return 2 if args.depth is not None and args.depth < 1: print("Параметр --depth должен быть положительным.") return 2 target = Path(args.target).expanduser() if target.exists(): if not target.is_dir(): print(f"Цель существует и не является папкой: {target}") return 2 if any(target.iterdir()): print(f"Папка назначения не пуста: {target}") return 2 source_path = Path(args.source).expanduser() if source_path.exists(): if git(source_path, "rev-parse", "--git-dir").returncode != 0: print(f"Локальный источник не является git-репозиторием: {source_path}") return 2 source_label = str(source_path.resolve()) else: source_label = args.source command = ["git", "clone"] if args.branch: command += ["--branch", args.branch] if args.depth: command += ["--depth", str(args.depth)] if args.submodules: command += ["--recurse-submodules"] command += [source_label, str(target)] print(f"Источник: {source_label}") print(f"Цель: {target}") print(f"Команда: {shlex.join(command)}") print() if not args.apply: print("Это предпросмотр. Для клонирования добавьте --apply.") return 0 result = subprocess.run(command) if result.returncode != 0: print("git clone завершился с ошибкой.") return result.returncode branch = git(target, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip() commit = git(target, "rev-parse", "--short", "HEAD").stdout.strip() size = directory_size(target / ".git") print() print(f"Ветка: {branch}") print(f"Коммит: {commit}") print(f"Размер .git: {size / (1024 * 1024):.1f} MB") return 0 if __name__ == "__main__": raise SystemExit(main())