Add CLI and bin entrypoint: quiet runs, refusals on stderr

This commit is contained in:
jay
2026-11-09 14:33:49 -05:00
parent 1e4ffa5971
commit 342e005561
7 changed files with 249 additions and 79 deletions
+59
View File
@@ -0,0 +1,59 @@
"""Command-line interface for scaffolding new python projects."""
import argparse
import sys
from pathlib import Path
from new_python.render import DEFAULT_PYTHON
from new_python.scaffold import ScaffoldError, scaffold
def main(argv: list[str] | None = None) -> int:
"""Parse *argv*, scaffold the project, and return an exit code."""
parser = argparse.ArgumentParser(
prog="new-python",
description="Scaffold a new python project from the versioned template.",
)
parser.add_argument(
"name",
help="project name: lowercase a-z words separated by single hyphens",
)
parser.add_argument(
"--packages",
nargs="+",
default=[],
metavar="PKG",
help="runtime packages for pipenv to install",
)
parser.add_argument(
"--dir",
type=Path,
default=None,
metavar="PATH",
help="parent directory for the new repo (default: current directory)",
)
parser.add_argument(
"--python",
default=DEFAULT_PYTHON,
metavar="VERSION",
help=f"python version pin (default: {DEFAULT_PYTHON})",
)
args = parser.parse_args(argv)
try:
target = scaffold(
args.name,
packages=args.packages,
parent=args.dir,
python_version=args.python,
)
except ScaffoldError as exc:
print(f"new-python: {exc}", file=sys.stderr)
return 1
print(target)
return 0
if __name__ == "__main__":
sys.exit(main())
+10 -7
View File
@@ -61,10 +61,7 @@ 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
_run(["pipenv", "install", *packages], cwd)
def scaffold(
@@ -108,8 +105,14 @@ def _write_files(files: dict[str, str], target: Path) -> None:
def _run(command: Sequence[str], cwd: Path) -> None:
"""Run *command* inside *cwd*, wrapping any failure in ScaffoldError."""
"""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)
subprocess.run(command, cwd=cwd, check=True, capture_output=True, text=True)
except subprocess.CalledProcessError as exc:
raise ScaffoldError(f"{' '.join(command)} failed with exit code {exc.returncode}") from 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