From e75bb984c97829c0c981d4a95840c412c639db55 Mon Sep 17 00:00:00 2001 From: Ruchir Chawdhry Date: Sat, 31 Oct 2026 19:58:33 +0530 Subject: [PATCH] feat: add uv-based, test-first Python CLI Copier template --- .github/workflows/template-ci.yml | 21 ++++++ README.md | 69 +++++++++++++++++- copier.yml | 37 ++++++++++ template/.github/workflows/ci.yml | 29 ++++++++ template/.gitignore | 14 ++++ template/.python-version.jinja | 1 + template/AGENTS.md | 21 ++++++ template/LICENSE.jinja | 21 ++++++ template/README.md.jinja | 41 +++++++++++ template/pyproject.toml.jinja | 31 ++++++++ .../__init__.py | 1 + .../__main__.py | 6 ++ .../cli.py.jinja | 17 +++++ template/tests/test_cli.py.jinja | 31 ++++++++ .../{{ _copier_conf.answers_file }}.jinja | 2 + tests/test_template.py | 72 +++++++++++++++++++ 16 files changed, 412 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/template-ci.yml create mode 100644 copier.yml create mode 100644 template/.github/workflows/ci.yml create mode 100644 template/.gitignore create mode 100644 template/.python-version.jinja create mode 100644 template/AGENTS.md create mode 100644 template/LICENSE.jinja create mode 100644 template/README.md.jinja create mode 100644 template/pyproject.toml.jinja create mode 100644 template/src/{{ project_name | replace('-', '_') }}/__init__.py create mode 100644 template/src/{{ project_name | replace('-', '_') }}/__main__.py create mode 100644 template/src/{{ project_name | replace('-', '_') }}/cli.py.jinja create mode 100644 template/tests/test_cli.py.jinja create mode 100644 template/{{ _copier_conf.answers_file }}.jinja create mode 100644 tests/test_template.py diff --git a/.github/workflows/template-ci.yml b/.github/workflows/template-ci.yml new file mode 100644 index 0000000..125e556 --- /dev/null +++ b/.github/workflows/template-ci.yml @@ -0,0 +1,21 @@ +name: Verify Copier template + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + generate-and-test: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + - name: Generate project, test CLI and build + run: uv run --no-project --with copier --with pytest pytest tests -q diff --git a/README.md b/README.md index b173440..77dbef6 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,67 @@ -# template-python-cli -A minimal, agent-ready Python CLI template powered by uv, Cyclopts, Rich, Ruff and pytest. Fast to bootstrap, easy to extend. Built with clean architecture, automated testing and GitHub Actions CI. +# copier-python-cli + +A minimal, agent-ready **Copier template for Python CLI apps**, powered by **uv**, **Cyclopts**, **Rich**, **Ruff**, and **pytest**. Fast to bootstrap, easy to extend, and test-first by default. + +## Generate a new CLI + +Install [uv](https://docs.astral.sh/uv/getting-started/installation/), then run: + +```sh +uvx --from copier copier copy gh:RuchirChawdhry/copier-python-cli ./my-cli +cd my-cli +uv sync +uv run my-cli --help +uv run my-cli greet Ada +``` + +`my-cli` in these examples assumes you enter `my-cli` as the project name when prompted. Copier asks for the CLI name, description, author and Python version. The name determines both the installed command (`my-cli`) and importable Python package (`my_cli`). No package-manager choices or post-generation hooks to maintain. + +## Generated project + +```text +my-cli/ +├── .github/workflows/ci.yml +├── .copier-answers.yml +├── .gitignore +├── .python-version +├── AGENTS.md +├── LICENSE +├── README.md +├── pyproject.toml +├── src/my_cli/ +│ ├── __init__.py +│ ├── __main__.py +│ └── cli.py +└── tests/test_cli.py +``` + +### Daily commands + +| Task | Command | +| --- | --- | +| Install dependencies | `uv sync` | +| Run CLI | `uv run my-cli --help` | +| Add runtime dependency | `uv add ` | +| Add development dependency | `uv add --dev ` | +| Test | `uv run pytest -q` | +| Lint | `uv run ruff check .` | +| Format | `uv run ruff format .` | +| Build | `uv build` | + +The generated project installs itself as a package using `uv_build` with a `src/` layout. Its GitHub Actions workflow runs quality checks on pull requests and pushes to `main`. + +## Test the template itself + +```sh +uv run --no-project --with copier --with pytest pytest tests -q +``` + +The template tests generate temporary projects, inspect metadata and file names, and exercise `uv sync`, Ruff, pytest, the installed CLI, and `uv build`. The checks also run automatically in this repository's pull requests. + +## Updating generated projects + +Commit `.copier-answers.yml` and `uv.lock` in each generated application. Once this template has versioned release tags, run `copier update` inside a generated project to incorporate template improvements while retaining project changes. + +## License + +MIT. See [LICENSE](LICENSE). diff --git a/copier.yml b/copier.yml new file mode 100644 index 0000000..1e587cf --- /dev/null +++ b/copier.yml @@ -0,0 +1,37 @@ +_min_copier_version: "9.0.0" +_subdirectory: template + +project_name: + type: str + help: Distribution and CLI name (lowercase kebab-case) + default: my-python-cli + validator: >- + {% if not (project_name | regex_search('^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$')) %} + Use lowercase letters, numbers and single hyphens; start with a letter. + {% endif %} + +description: + type: str + help: One-line description of the project + default: A small, dependable Python command-line tool. + +author_name: + type: str + help: Name to include in the MIT license + default: Your Name + +python_version: + type: str + help: Python version used for local development + choices: + - "3.11" + - "3.12" + - "3.13" + - "3.14" + default: "3.13" + +copyright_year: + type: int + help: Copyright year for the MIT license + default: 2026 + ask: false diff --git a/template/.github/workflows/ci.yml b/template/.github/workflows/ci.yml new file mode 100644 index 0000000..c27d09a --- /dev/null +++ b/template/.github/workflows/ci.yml @@ -0,0 +1,29 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + quality: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + - name: Install project + run: uv sync --group dev + - name: Lint + run: uv run --no-sync ruff check . + - name: Format + run: uv run --no-sync ruff format --check . + - name: Test + run: uv run --no-sync pytest -q + - name: Build distributions + run: uv build diff --git a/template/.gitignore b/template/.gitignore new file mode 100644 index 0000000..a66dc8f --- /dev/null +++ b/template/.gitignore @@ -0,0 +1,14 @@ +.venv/ +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.coverage* +htmlcov/ +build/ +dist/ +*.egg-info/ +.env +.env.* +!.env.example +# Commit uv.lock for reproducible application builds. diff --git a/template/.python-version.jinja b/template/.python-version.jinja new file mode 100644 index 0000000..7773b4e --- /dev/null +++ b/template/.python-version.jinja @@ -0,0 +1 @@ +{{ python_version }} diff --git a/template/AGENTS.md b/template/AGENTS.md new file mode 100644 index 0000000..8317a06 --- /dev/null +++ b/template/AGENTS.md @@ -0,0 +1,21 @@ +# Agent guide + +This is a standalone **uv**-managed Python CLI. Do not mix its environment, dependencies, or commands with other repositories. + +## Working contract + +1. Follow red/green/refactor: add a failing pytest test, implement the smallest change, then refactor. +2. Keep the CLI layer thin (`src/*/cli.py`). Put reusable logic in importable modules and test it directly. +3. Run commands from this repository's root using `uv run` or `uv sync`. Never use system-wide `pip install` for project dependencies. +4. Avoid unrelated refactors or changes to sibling repositories. Add dependencies via `uv add` / `uv add --dev`. +5. Before finishing, run `uv run pytest -q`, `uv run ruff check .`, `uv run ruff format --check .`, and `uv build`. +6. Commit `uv.lock` after the first `uv sync` and whenever dependencies change. + +## Layout + +- `src/`: installable Python package and CLI entry point +- `tests/`: automated behavioral tests +- `pyproject.toml`: one source of truth for metadata, dependencies, tooling, and entry points +- `.github/workflows/ci.yml`: pull-request quality gate + +Keep changes focused, readable, and portable across Windows, Linux, and macOS. diff --git a/template/LICENSE.jinja b/template/LICENSE.jinja new file mode 100644 index 0000000..360dcee --- /dev/null +++ b/template/LICENSE.jinja @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) {{ copyright_year }} {{ author_name }} + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/template/README.md.jinja b/template/README.md.jinja new file mode 100644 index 0000000..2fc72f2 --- /dev/null +++ b/template/README.md.jinja @@ -0,0 +1,41 @@ +# {{ project_name }} + +{{ description }} + +A lightweight Python CLI powered by **uv**, **Cyclopts**, **Rich**, **Ruff**, and **pytest**. + +## Get started + +Install [uv](https://docs.astral.sh/uv/getting-started/installation/), then: + +```sh +uv sync +uv run {{ project_name }} --help +uv run {{ project_name }} greet Ada +``` + +Each project has its own `.venv` managed by uv. Commit `uv.lock` after the first `uv sync`. + +## Development + +```sh +uv run pytest -q +uv run ruff check . +uv run ruff format --check . +uv run ruff format . +uv build +``` + +The CLI entry point is `src/{{ project_name | replace('-', '_') }}/cli.py`. Put reusable logic in separate modules, and write a failing test before changing behavior. See [AGENTS.md](AGENTS.md) for agent conventions. + +## Template updates + +This project was generated with Copier. Keep `.copier-answers.yml` committed to support future updates once the template publishes versioned tags: + +```sh +copier update +``` + +## License + +MIT. See [LICENSE](LICENSE). diff --git a/template/pyproject.toml.jinja b/template/pyproject.toml.jinja new file mode 100644 index 0000000..4e3687e --- /dev/null +++ b/template/pyproject.toml.jinja @@ -0,0 +1,31 @@ +[project] +name = "{{ project_name }}" +version = "0.1.0" +description = {{ description | to_json }} +readme = "README.md" +requires-python = ">={{ python_version }}" +license = "MIT" +dependencies = [ + "cyclopts>=3,<5", + "rich>=13,<15", +] + +[project.scripts] +{{ project_name }} = "{{ project_name | replace('-', '_') }}.cli:app" + +[build-system] +requires = ["uv_build>=0.13.6,<0.14"] +build-backend = "uv_build" + +[dependency-groups] +dev = [ + "pytest>=8,<10", + "ruff>=0.12", +] + +[tool.pytest.ini_options] +testpaths = ["tests"] + +[tool.ruff] +line-length = 100 +target-version = "py{{ python_version | replace('.', '') }}" diff --git a/template/src/{{ project_name | replace('-', '_') }}/__init__.py b/template/src/{{ project_name | replace('-', '_') }}/__init__.py new file mode 100644 index 0000000..be4dfc8 --- /dev/null +++ b/template/src/{{ project_name | replace('-', '_') }}/__init__.py @@ -0,0 +1 @@ +"""Python command-line application.""" diff --git a/template/src/{{ project_name | replace('-', '_') }}/__main__.py b/template/src/{{ project_name | replace('-', '_') }}/__main__.py new file mode 100644 index 0000000..b66bd4b --- /dev/null +++ b/template/src/{{ project_name | replace('-', '_') }}/__main__.py @@ -0,0 +1,6 @@ +"""Allow running the CLI with ``python -m``.""" + +from .cli import app + +if __name__ == "__main__": + app() diff --git a/template/src/{{ project_name | replace('-', '_') }}/cli.py.jinja b/template/src/{{ project_name | replace('-', '_') }}/cli.py.jinja new file mode 100644 index 0000000..10dd62a --- /dev/null +++ b/template/src/{{ project_name | replace('-', '_') }}/cli.py.jinja @@ -0,0 +1,17 @@ +"""Command-line interface. + +Add commands here. Keep reusable business logic in separate modules. +""" + +from cyclopts import App +from rich.console import Console +from rich.markup import escape + +app = App(help={{ description | to_json }}) +console = Console() + + +@app.command +def greet(name: str = "World") -> None: + """Greet someone by name.""" + console.print(f"Hello, [bold cyan]{escape(name)}[/bold cyan]!") diff --git a/template/tests/test_cli.py.jinja b/template/tests/test_cli.py.jinja new file mode 100644 index 0000000..3261698 --- /dev/null +++ b/template/tests/test_cli.py.jinja @@ -0,0 +1,31 @@ +"""CLI contract tests: exercise the installed module as a user would.""" + +import subprocess +import sys + + +def invoke(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-m", "{{ project_name | replace('-', '_') }}", *args], + capture_output=True, + text=True, + check=False, + ) + + +def test_help_lists_greet_command() -> None: + result = invoke("--help") + assert result.returncode == 0, result.stderr + assert "greet" in result.stdout + + +def test_greet_uses_provided_name() -> None: + result = invoke("greet", "Ada") + assert result.returncode == 0, result.stderr + assert "Hello, Ada!" in result.stdout + + +def test_greet_escapes_rich_markup() -> None: + result = invoke("greet", "[red]Ada[/red]") + assert result.returncode == 0, result.stderr + assert "Hello, [red]Ada[/red]!" in result.stdout diff --git a/template/{{ _copier_conf.answers_file }}.jinja b/template/{{ _copier_conf.answers_file }}.jinja new file mode 100644 index 0000000..9a421b6 --- /dev/null +++ b/template/{{ _copier_conf.answers_file }}.jinja @@ -0,0 +1,2 @@ +# Generated by Copier. Do not edit manually; use `copier update`. +{{ _copier_answers | to_nice_yaml -}} diff --git a/tests/test_template.py b/tests/test_template.py new file mode 100644 index 0000000..112d19f --- /dev/null +++ b/tests/test_template.py @@ -0,0 +1,72 @@ +"""End-to-end Copier template smoke tests (run on template PRs).""" + +import subprocess +import tomllib +from pathlib import Path + +import pytest +from copier import run_copy + +TEMPLATE_ROOT = Path(__file__).resolve().parents[1] + + +def command(project: Path, *args: str) -> str: + result = subprocess.run( + args, + cwd=project, + capture_output=True, + text=True, + check=False, + timeout=180, + ) + assert result.returncode == 0, f"{' '.join(args)}\n{result.stdout}\n{result.stderr}" + return result.stdout + + +@pytest.fixture +def sample_project(tmp_path: Path) -> Path: + target = tmp_path / "sample-tool" + run_copy( + str(TEMPLATE_ROOT), + target, + defaults=True, + data={ + "project_name": "sample-tool", + "description": "A CLI for testing template generation.", + "author_name": "Example Author", + "python_version": "3.13", + }, + ) + return target + + +def test_template_generates_project_metadata_and_layout(sample_project: Path) -> None: + metadata = tomllib.loads((sample_project / "pyproject.toml").read_text()) + assert metadata["project"]["name"] == "sample-tool" + assert metadata["project"]["scripts"]["sample-tool"] == "sample_tool.cli:app" + assert metadata["build-system"]["build-backend"] == "uv_build" + assert (sample_project / "src/sample_tool/cli.py").is_file() + assert (sample_project / "tests/test_cli.py").is_file() + assert (sample_project / ".copier-answers.yml").is_file() + assert (sample_project / "AGENTS.md").is_file() + assert (sample_project / ".github/workflows/ci.yml").is_file() + assert "Example Author" in (sample_project / "LICENSE").read_text() + assert not (sample_project / "copier.yml").exists() + assert not (sample_project / "tests/test_template.py").exists() + + +def test_generated_cli_passes_quality_checks(sample_project: Path) -> None: + command(sample_project, "uv", "sync", "--group", "dev") + command(sample_project, "uv", "run", "--no-sync", "ruff", "check", ".") + command(sample_project, "uv", "run", "--no-sync", "ruff", "format", "--check", ".") + command(sample_project, "uv", "run", "--no-sync", "pytest", "-q") + command(sample_project, "uv", "run", "--no-sync", "sample-tool", "--help") + command(sample_project, "uv", "build") + + +def test_other_slug_keeps_module_and_entrypoint_consistent(tmp_path: Path) -> None: + target = tmp_path / "another-cli" + run_copy(str(TEMPLATE_ROOT), target, defaults=True, data={"project_name": "another-cli"}) + metadata = tomllib.loads((target / "pyproject.toml").read_text()) + assert metadata["project"]["scripts"]["another-cli"] == "another_cli.cli:app" + assert (target / "src/another_cli/__main__.py").is_file()