Files
new-python/new_python/scaffold.py
T

49 lines
1.6 KiB
Python

"""Create new python projects from the versioned template."""
import re
import subprocess
from collections.abc import Sequence
from pathlib import Path
NAME_PATTERN = re.compile(r"^[a-z]+(-[a-z]+)*$")
NAME_RULE = "lowercase a-z words separated by single hyphens"
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 install_packages(packages: Sequence[str], cwd: Path) -> None:
"""Install runtime *packages* into the project at *cwd* via pipenv."""
if not packages:
return
try:
subprocess.run(["pipenv", "install", *packages], cwd=cwd, check=True)
except subprocess.CalledProcessError as exc:
raise ScaffoldError(f"pipenv install failed with exit code {exc.returncode}") from exc