Files
douyi_guaji_main/bootstrap_deps.py
T

240 lines
7.1 KiB
Python

#!/usr/bin/env python3
"""
One-click dependency bootstrap for this repository.
Default behavior:
1. Create/update a virtual environment at .venv
2. Upgrade pip/setuptools/wheel in that environment
3. Install dependencies from requirements.txt
Examples:
python bootstrap_deps.py
python bootstrap_deps.py --minimal
python bootstrap_deps.py --no-venv
python bootstrap_deps.py --index-url https://pypi.tuna.tsinghua.edu.cn/simple
"""
from __future__ import annotations
import argparse
import shlex
import subprocess
import sys
from pathlib import Path
from typing import Iterable, Sequence
def _echo(message: str) -> None:
print(message, flush=True)
def _format_cmd(cmd: Sequence[str]) -> str:
return " ".join(shlex.quote(part) for part in cmd)
def _run(cmd: Sequence[str], *, cwd: Path, dry_run: bool = False) -> None:
_echo(f"$ {_format_cmd(cmd)}")
if dry_run:
return
subprocess.run(cmd, cwd=str(cwd), check=True)
def _resolve_requirements(repo_root: Path, args: argparse.Namespace) -> Path:
if args.requirements:
req = Path(args.requirements).expanduser()
if not req.is_absolute():
req = repo_root / req
else:
req_name = "requirements-minimal.txt" if args.minimal else "requirements.txt"
req = repo_root / req_name
return req.resolve()
def _resolve_venv_python(venv_dir: Path) -> Path:
candidates = (
venv_dir / "Scripts" / "python.exe",
venv_dir / "Scripts" / "python",
venv_dir / "bin" / "python",
)
for candidate in candidates:
if candidate.exists():
return candidate.resolve()
raise FileNotFoundError(
f"Could not find a Python executable in virtual environment: {venv_dir}"
)
def _build_pip_index_args(args: argparse.Namespace) -> list[str]:
pip_args: list[str] = []
if args.index_url:
pip_args += ["--index-url", args.index_url]
for item in args.extra_index_url:
pip_args += ["--extra-index-url", item]
for item in args.trusted_host:
pip_args += ["--trusted-host", item]
if args.no_cache_dir:
pip_args.append("--no-cache-dir")
if args.prefer_binary:
pip_args.append("--prefer-binary")
return pip_args
def _validate_python_version() -> None:
if sys.version_info < (3, 10):
raise RuntimeError(
f"Python 3.10+ is required. Current interpreter: {sys.version.split()[0]}"
)
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Bootstrap project dependencies in a migration-friendly way."
)
parser.add_argument(
"--venv-dir",
default=".venv",
help="Virtual environment directory (default: .venv).",
)
parser.add_argument(
"--no-venv",
action="store_true",
help="Install into the current Python environment instead of creating/using a venv.",
)
parser.add_argument(
"--python",
default="",
help="Python executable used to create the virtual environment.",
)
parser.add_argument(
"--minimal",
action="store_true",
help="Install requirements-minimal.txt instead of requirements.txt.",
)
parser.add_argument(
"--requirements",
default="",
help="Custom requirements file path (overrides --minimal).",
)
parser.add_argument(
"--skip-pip-upgrade",
action="store_true",
help="Skip upgrading pip/setuptools/wheel.",
)
parser.add_argument(
"--index-url",
default="",
help="Base package index URL for pip install.",
)
parser.add_argument(
"--extra-index-url",
action="append",
default=[],
help="Extra package index URL for pip install (repeatable).",
)
parser.add_argument(
"--trusted-host",
action="append",
default=[],
help="Trusted host passed to pip install (repeatable).",
)
parser.add_argument(
"--no-cache-dir",
action="store_true",
help="Pass --no-cache-dir to pip.",
)
parser.add_argument(
"--prefer-binary",
action="store_true",
help="Prefer binary wheels when possible.",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Print commands without executing them.",
)
return parser.parse_args()
def main() -> int:
_validate_python_version()
args = _parse_args()
repo_root = Path(__file__).resolve().parent
requirements_path = _resolve_requirements(repo_root, args)
if not requirements_path.exists():
raise FileNotFoundError(f"Requirements file not found: {requirements_path}")
if args.no_venv:
install_python = Path(sys.executable).resolve()
_echo(f"Using current interpreter: {install_python}")
else:
venv_dir = Path(args.venv_dir).expanduser()
if not venv_dir.is_absolute():
venv_dir = repo_root / venv_dir
creator_python = (args.python or sys.executable).strip()
if not _resolve_venv_python_if_exists(venv_dir):
_echo(f"Creating virtual environment: {venv_dir}")
_run([creator_python, "-m", "venv", str(venv_dir)], cwd=repo_root, dry_run=args.dry_run)
else:
_echo(f"Virtual environment already exists: {venv_dir}")
install_python = _resolve_venv_python(venv_dir)
_echo(f"Using virtual environment interpreter: {install_python}")
pip_base = [str(install_python), "-m", "pip"]
pip_index_args = _build_pip_index_args(args)
if not args.skip_pip_upgrade:
_echo("Upgrading pip, setuptools, and wheel...")
_run(
[*pip_base, "install", "--upgrade", "pip", "setuptools", "wheel", *pip_index_args],
cwd=repo_root,
dry_run=args.dry_run,
)
_echo(f"Installing dependencies from: {requirements_path}")
_run(
[*pip_base, "install", "-r", str(requirements_path), *pip_index_args],
cwd=repo_root,
dry_run=args.dry_run,
)
if not args.no_venv:
_echo("")
_echo("Done.")
if sys.platform.startswith("win"):
_echo(r"Activate with: .venv\Scripts\Activate.ps1")
else:
_echo("Activate with: source .venv/bin/activate")
else:
_echo("")
_echo("Done (installed into current interpreter).")
return 0
def _resolve_venv_python_if_exists(venv_dir: Path) -> Path | None:
candidates: Iterable[Path] = (
venv_dir / "Scripts" / "python.exe",
venv_dir / "Scripts" / "python",
venv_dir / "bin" / "python",
)
for candidate in candidates:
if candidate.exists():
return candidate.resolve()
return None
if __name__ == "__main__":
try:
raise SystemExit(main())
except subprocess.CalledProcessError as exc:
_echo("")
_echo(f"Command failed with exit code {exc.returncode}.")
raise SystemExit(exc.returncode)
except Exception as exc: # pragma: no cover - defensive entrypoint guard
_echo("")
_echo(f"Bootstrap failed: {exc}")
raise SystemExit(1)