Add scaffold flow: template to committed project with pinned python
This commit is contained in:
@@ -5,10 +5,14 @@ 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."""
|
||||
@@ -38,6 +42,21 @@ def parent_dir(explicit: Path | None) -> Path:
|
||||
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:
|
||||
@@ -46,3 +65,51 @@ def install_packages(packages: Sequence[str], cwd: Path) -> None:
|
||||
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
|
||||
|
||||
|
||||
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* inside *cwd*, wrapping any failure in ScaffoldError."""
|
||||
try:
|
||||
subprocess.run(command, cwd=cwd, check=True)
|
||||
except subprocess.CalledProcessError as exc:
|
||||
raise ScaffoldError(f"{' '.join(command)} failed with exit code {exc.returncode}") from exc
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Tests for the full scaffold flow."""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from new_python.render import DEFAULT_PYTHON
|
||||
from new_python.scaffold import INITIAL_COMMIT_MESSAGE, ScaffoldError, scaffold
|
||||
|
||||
|
||||
def _stub_cmd(monkeypatch, tmp_path: Path, name: str, exit_code: int = 0) -> Path:
|
||||
"""Put a recording stub *name* on PATH; each call appends args then a separator."""
|
||||
bin_dir = tmp_path / "bin"
|
||||
bin_dir.mkdir(exist_ok=True)
|
||||
record = tmp_path / f"{name}-calls.txt"
|
||||
stub = bin_dir / name
|
||||
stub.write_text(
|
||||
"#!/bin/sh\n"
|
||||
f'printf \'%s\\n\' "$@" >> "{record}"\n'
|
||||
f'echo "----" >> "{record}"\n'
|
||||
f"exit {exit_code}\n"
|
||||
)
|
||||
stub.chmod(0o755)
|
||||
monkeypatch.setenv("PATH", f"{bin_dir}:{os.environ['PATH']}")
|
||||
return record
|
||||
|
||||
|
||||
def _calls(record: Path) -> list[list[str]]:
|
||||
"""Return the recorded invocations as lists of arguments."""
|
||||
return [c.splitlines() for c in record.read_text().split("----\n") if c.strip()]
|
||||
|
||||
|
||||
def test_scaffold_creates_the_full_project(monkeypatch, tmp_path: Path):
|
||||
"""Scaffold writes the template, inits git, pins pipenv, commits, installs hooks."""
|
||||
pyenv = _stub_cmd(monkeypatch, tmp_path, "pyenv")
|
||||
pipenv = _stub_cmd(monkeypatch, tmp_path, "pipenv")
|
||||
just = _stub_cmd(monkeypatch, tmp_path, "just")
|
||||
parent = tmp_path / "projects"
|
||||
parent.mkdir()
|
||||
|
||||
target = scaffold("demo-project", parent=parent)
|
||||
|
||||
assert target == parent / "demo-project"
|
||||
assert (target / "AGENTS.md").read_text().startswith("# demo-project\n")
|
||||
assert (target / "demo_project" / "__init__.py").exists()
|
||||
assert (target / ".git").is_dir()
|
||||
assert (target / "hooks" / "pre-commit").stat().st_mode & 0o111
|
||||
|
||||
subject = subprocess.run(
|
||||
["git", "-C", str(target), "log", "--format=%s"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
assert subject.stdout.strip() == INITIAL_COMMIT_MESSAGE
|
||||
status = subprocess.run(
|
||||
["git", "-C", str(target), "status", "--porcelain"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
assert status.stdout == ""
|
||||
|
||||
assert _calls(pyenv) == [["prefix", DEFAULT_PYTHON]]
|
||||
assert _calls(pipenv) == [["install", "--dev", "--python", DEFAULT_PYTHON]]
|
||||
assert _calls(just) == [["install-hooks"]]
|
||||
|
||||
|
||||
def test_scaffold_passes_packages_to_a_second_pipenv_call(monkeypatch, tmp_path: Path):
|
||||
"""Runtime packages reach pipenv after the dev environment install."""
|
||||
_stub_cmd(monkeypatch, tmp_path, "pyenv")
|
||||
pipenv = _stub_cmd(monkeypatch, tmp_path, "pipenv")
|
||||
_stub_cmd(monkeypatch, tmp_path, "just")
|
||||
parent = tmp_path / "projects"
|
||||
parent.mkdir()
|
||||
|
||||
scaffold("demo-project", packages=["mutagen"], parent=parent)
|
||||
|
||||
assert _calls(pipenv) == [
|
||||
["install", "--dev", "--python", DEFAULT_PYTHON],
|
||||
["install", "mutagen"],
|
||||
]
|
||||
|
||||
|
||||
def test_scaffold_refuses_missing_python_before_creating_anything(monkeypatch, tmp_path: Path):
|
||||
"""An unavailable python pin refuses loudly and creates nothing."""
|
||||
_stub_cmd(monkeypatch, tmp_path, "pyenv", exit_code=1)
|
||||
_stub_cmd(monkeypatch, tmp_path, "pipenv")
|
||||
_stub_cmd(monkeypatch, tmp_path, "just")
|
||||
parent = tmp_path / "projects"
|
||||
parent.mkdir()
|
||||
|
||||
with pytest.raises(ScaffoldError) as exc:
|
||||
scaffold("demo-project", parent=parent)
|
||||
|
||||
assert f"pyenv install {DEFAULT_PYTHON}" in str(exc.value)
|
||||
assert not (parent / "demo-project").exists()
|
||||
|
||||
|
||||
def test_scaffold_refuses_invalid_names_first(monkeypatch, tmp_path: Path):
|
||||
"""An invalid name refuses before any other work happens."""
|
||||
pyenv = _stub_cmd(monkeypatch, tmp_path, "pyenv")
|
||||
parent = tmp_path / "projects"
|
||||
parent.mkdir()
|
||||
|
||||
with pytest.raises(ScaffoldError):
|
||||
scaffold("Demo-Project", parent=parent)
|
||||
|
||||
assert not pyenv.exists()
|
||||
assert not (parent / "Demo-Project").exists()
|
||||
Reference in New Issue
Block a user