Files
new-python/new_python/scaffold.py
T

119 lines
4.0 KiB
Python

"""Create new python projects from the versioned template."""
import re
import subprocess
from collections.abc import Sequence
from pathlib import Path
from new_python.render import DEFAULT_PYTHON, render
NAME_PATTERN = re.compile(r"^[a-z]+(-[a-z]+)*$")
NAME_RULE = "lowercase a-z words separated by single hyphens"
INITIAL_COMMIT_MESSAGE = "Add project scaffold from the new-python template"
class ScaffoldError(Exception):
"""A refusal caused by invalid input or an unusable target."""
def validate_name(name: str) -> str:
"""Return *name* when it matches the naming rule, else refuse loudly."""
if not NAME_PATTERN.match(name):
raise ScaffoldError(f"invalid name {name!r}: must be {NAME_RULE}")
return name
def target_dir(name: str, parent: Path) -> Path:
"""Return *parent* / *name*, refusing when that directory already exists."""
target = parent / name
if target.exists():
raise ScaffoldError(f"target directory already exists: {target}")
return target
def parent_dir(explicit: Path | None) -> Path:
"""Return the parent for a new project: *explicit* when given, else cwd."""
if explicit is None:
return Path.cwd()
if not explicit.is_dir():
raise ScaffoldError(f"--dir is not an existing directory: {explicit}")
return explicit
def ensure_python(python_version: str) -> None:
"""Refuse unless *python_version* is installed under pyenv."""
result = subprocess.run(
["pyenv", "prefix", python_version],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
raise ScaffoldError(
f"python {python_version} is not installed under pyenv; "
f"run 'pyenv install {python_version}' or pass --python"
)
def install_packages(packages: Sequence[str], cwd: Path) -> None:
"""Install runtime *packages* into the project at *cwd* via pipenv."""
if not packages:
return
_run(["pipenv", "install", *packages], cwd)
def scaffold(
name: str,
packages: Sequence[str] = (),
parent: Path | None = None,
python_version: str = DEFAULT_PYTHON,
) -> Path:
"""Create a new project at *parent* / *name* and return its path.
Refuses invalid names, existing targets, and python versions not
installed under pyenv before creating anything. Then renders and
writes the template, initializes git, installs the dev environment
and any runtime *packages* via pipenv, makes the pre-hook initial
commit, and installs the pre-commit hook.
"""
validate_name(name)
resolved_parent = parent_dir(parent)
target = target_dir(name, resolved_parent)
ensure_python(python_version)
files = render(name, python_version)
_write_files(files, target)
_run(["git", "init", "-b", "main"], target)
_run(["pipenv", "install", "--dev", "--python", python_version], target)
install_packages(packages, target)
_run(["git", "add", "-A"], target)
_run(["git", "commit", "-m", INITIAL_COMMIT_MESSAGE], target)
_run(["just", "install-hooks"], target)
return target
def _write_files(files: dict[str, str], target: Path) -> None:
"""Write rendered *files* under *target*, hooks/pre-commit executable."""
for rel, content in files.items():
path = target / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
if rel == "hooks/pre-commit":
path.chmod(0o755)
def _run(command: Sequence[str], cwd: Path) -> None:
"""Run *command* quietly in *cwd*, wrapping any failure in ScaffoldError.
Output is captured and discarded on success; on failure the command's
stderr is included in the refusal so the cause reaches the user.
"""
try:
subprocess.run(command, cwd=cwd, check=True, capture_output=True, text=True)
except subprocess.CalledProcessError as exc:
detail = (exc.stderr or "").strip()
message = f"{' '.join(command)} failed with exit code {exc.returncode}"
raise ScaffoldError(f"{message}: {detail}" if detail else message) from exc