Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .github/workflows/template-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
name: Template CI

on:
pull_request:
types: [opened, synchronize, reopened]

permissions:
contents: read

concurrency:
group: template-ci-${{ github.event.pull_request.number }}
cancel-in-progress: true

jobs:
validate:
uses: RuchirChawdhry/ci-workflows/.github/workflows/copier-ci.yml@main
29 changes: 19 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

A lean, reusable Copier template for agent-ready Python CLI applications. ⚡

**Stack:** uv · Python 3.14.7 · Cyclopts · ruamel.yaml · Rich · platformdirs · Loguru · orjson · SQLite · Ruff · pytest · pytest-testmon · Go Task.
**Stack:** uv · Python 3.14.7 · Cyclopts · ruamel.yaml · Rich · platformdirs · Loguru · orjson · SQLite · Ruff · pytest · pytest-testmon · pre-commit · Go Task.

## Generate a project

Expand All @@ -27,18 +27,27 @@ Commit the generated `uv.lock` for reproducible development and CI.
- Read-only environment diagnostics, platform-aware SQLite persistence with WAL enabled by default and Rich progress reporting.
- Shared agent-friendly flags on all application subcommands: --json, --jsonl, --quiet, --verbose; machine output is compact UTF-8 serialized with orjson.
- Cross-platform Taskfile.yml with standardized development, focused/full testing, installation, cleanup and diagnostics tasks.
- Version-controlled pre-commit hooks for automatic Ruff lint fixes and formatting of staged Python files; installed by `task setup` after Git initialization.
- Real pytest tests for logic and CLI, Ruff formatting/lint settings, `.python-version`.
- `AGENTS.md` with repo-local TDD and agent-environment guidance.
- PR-only GitHub Actions callers for the central **python-cli** and **python-build** workflows.
- MIT license, `.gitignore`, Copier answers for future `copier update`.

## Why the template repo never runs these workflows
## Continuous integration

The workflow source lives in `template/.github/workflows/ci.yml.jinja`, **not**
`.github/workflows/` at this repository's root. GitHub only detects workflows in the
root `.github/workflows/`, so nothing is activated here. Copier emits the normal
`.github/workflows/ci.yml` only into generated projects. Generated workflows run on
**pull requests only**, never `push`, `schedule`, or manual dispatch.
This repository has a root workflow, `.github/workflows/template-ci.yml`,
which calls the central [Copier validation workflow](https://github.com/RuchirChawdhry/ci-workflows/blob/main/.github/workflows/copier-ci.yml).
It runs when a pull request is opened, updated or reopened. It tests the template
contracts, renders the current revision, runs Ruff and pytest on the generated
project, builds and checks distributions, and installs the wheel for functional smoke tests on Ubuntu 24.04.
The central workflow explicitly runs `tests/smoke_installed.py` against the
installed console script via `CLI_EXECUTABLE`, outside the generated project.
The tests cover machine output, configuration, SQLite WAL and doctor diagnostics. New commits cancel older runs for the same PR.

The generated application's independent workflow lives under
`template/.github/workflows/ci.yml.jinja`. Copier renders it into the generated
project; it is not run in this template repository. Generated workflows remain
PR-only.

The CI jobs reference:

Expand All @@ -51,12 +60,12 @@ reproducibility is required; the user-managed central workflows remain the sourc
## Test this template itself

```sh
uv run --no-project --with copier --with pytest pytest tests -q
uv run --no-project --with copier==9.14.1 --with pytest --with PyYAML pytest tests -q
```

The tests generate a sample application and assert package metadata, imports,
Copier update context, and isolated PR-only workflow placement. No GitHub Actions
workflows are registered in this template repository.
Copier update context, and separation of the template-validation and generated-project
PR-only workflows.

## Philosophy

Expand Down
13 changes: 13 additions & 0 deletions template/.pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
repos:
- repo: local
hooks:
- id: ruff-check
name: Ruff lint fixes
entry: uv run --no-sync ruff check --fix --force-exclude
language: system
types: [python]
- id: ruff-format
name: Ruff format
entry: uv run --no-sync ruff format --force-exclude
language: system
types: [python]
5 changes: 3 additions & 2 deletions template/AGENTS.md.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@ installation, other project virtual environments, or shared CI workflow reposito
- Dependencies: `uv sync --group dev` (commit `uv.lock`).
- CLI: Cyclopts; prefer existing cyclopts.types aliases (File, ExistingFile, Directory, ExistingDirectory, PositiveInt, NonNegativeInt, Port) when their semantics match; use native Parameter/Group validators for custom constraints; do not duplicate CLI validation in command bodies. Use dispatch tables for mutually exclusive action selection after Cyclopts validates the arguments. Terminal output: Rich; YAML: ruamel.yaml with safe loading.
- Configuration: use `config.py`, platformdirs and persistent `config.yml`; do not create alternate settings systems. Use native Cyclopts Yaml loading for argument defaults under cli.<command>; do not merge arguments manually. Use root flags --init-config, --config-path, --show-config; retain set-config as a subcommand.
- Logging: initialize `LoggingConfig` in business commands; use Loguru for diagnostics and Rich for user-facing output. Keep logs off stdout and do not log secrets. Optional synchronous @log_call in logging_utils.py traces entry, timing and failure type; native @logger.catch(reraise=True) logs exceptions. Never swallow failures; do not stack both decorators on the same function.
- Logging: initialize `LoggingConfig` in business commands; use named `file_level` and `console_level` settings, with shared `--verbose` (DEBUG) and `--quiet` overrides; never add numeric logging levels; use Loguru for diagnostics and Rich for user-facing output. Keep logs off stdout and do not log secrets. Optional synchronous @log_call in logging_utils.py traces entry, timing and failure type; native @logger.catch(reraise=True) logs exceptions. Never swallow failures; do not stack both decorators on the same function.
- Persistence: use database.py and parameterized sqlite3 queries with WAL enabled by default; expose project-specific commands rather than generic database setters/getters. Keep YAML for settings, SQLite for application data.
- Diagnostics: extend doctor.py with read-only checks; never dump configuration or create files; preserve full parser diagnostics.
- Output: accept shared OutputOptions on every subcommand, emit data via Output.emit() without wrapping commands in repeated error handlers, and use Output.progress()/track() for progress. Keep stdout machine-readable; JSON/JSONL use orjson exclusively for serialization and automatically disable color and progress. Do not introduce parallel JSON output implementations. Do not add redundant color flags. Send diagnostics and errors to stderr.
- Output: accept shared OutputOptions on every subcommand with the immutable DEFAULT_OUTPUT_OPTIONS singleton (no constructor calls in argument defaults), emit data via Output.emit() without wrapping commands in repeated error handlers, and use Output.progress()/track() for progress. Keep stdout machine-readable; JSON/JSONL use orjson exclusively for serialization and automatically disable color and progress. Do not introduce parallel JSON output implementations. Do not add redundant color flags. Send diagnostics and errors to stderr.
- Errors: let expected domain failures raise ApplicationError from errors.py. The cli.main entrypoint handles those, filesystem, SQLite and YAML failures once; Cyclopts owns parse errors and exit-code handling. Preserve original exception messages, including YAML parser diagnostics. Do not catch unexpected programming exceptions or duplicate the entrypoint handler in commands.
- Development commands: use Taskfile.yml for setup, dev, test, test:all, lint, fix, build, install, clean, doctor and update. Test runner: pytest with pytest-testmon for changed-code selection; lint/format: Ruff. Use the full suite for subprocess or external-resource changes and final verification. Do not invent alternate task runners.
- Git hooks: initialize Git before task setup; setup installs pre-commit hooks using the project's Ruff. If formatting changes files, review and stage the fixes, then retry the commit. Do not bypass hooks.
- CI: PR-only callers of `RuchirChawdhry/ci-workflows`. Never duplicate shared workflow logic here.

Avoid fetching dependencies globally or modifying system configuration.
46 changes: 32 additions & 14 deletions template/README.md.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ Commit the generated `uv.lock` for repeatable dependency resolution and CI runs.
uv run {{ cli_command }} --config-path
uv run {{ cli_command }} --init-config
uv run {{ cli_command }} --show-config
uv run {{ cli_command }} set-config logging.level DEBUG
uv run {{ cli_command }} set-config logging.verbosity 2
uv run {{ cli_command }} hello --verbosity 1
uv run {{ cli_command }} set-config logging.file_level DEBUG
uv run {{ cli_command }} set-config logging.console_level DEBUG
uv run {{ cli_command }} hello --verbose
```

Settings live in the platform-specific user configuration directory as `config.yml`.
Expand All @@ -46,13 +46,13 @@ on the sample `hello` command to select a different file.

```yaml
logging:
level: INFO
verbosity: 0
file_level: INFO
console_level: WARNING
file_enabled: true
```

`LoggingConfig` in `config.py` controls logging. Console verbosity is 0=WARNING,
1=INFO, 2=DEBUG, 3=TRACE. The file level is independent. File logs rotate at 5 MB
`LoggingConfig` in `config.py` validates named levels using Loguru. The console
and file levels are independent. File logs rotate at 5 MB
and old logs are retained for 7 days; disable file logging with `file_enabled: false`.
Logs go to stderr and the platform-specific log directory (`app.log`), not stdout.
The example `hello` command initializes logging at command execution; use the same
Expand All @@ -69,8 +69,7 @@ both `.yml` and `.yaml` as well as SQLite filenames.
Use `ExistingFile` or `ExistingDirectory` when the target must already exist,
`NonExistentFile` for a new output target, `Directory` for a directory that may
need creation, and `PositiveInt`, `NonNegativeInt` or `Port` for matching numeric
constraints. Use custom validators only for project-specific restrictions, such
as logging verbosity from 0 through 3.
constraints. Use custom validators only for project-specific restrictions.

See [Cyclopts types](https://cyclopts.readthedocs.io/en/stable/types.html).

Expand All @@ -83,7 +82,6 @@ defaults in the same YAML file, under the `cli` namespace:
cli:
hello:
name: Ada
verbosity: 1
```

```sh
Expand Down Expand Up @@ -177,11 +175,11 @@ JSON/JSONL automatically disable progress and ANSI styling, including when FORCE
is set; they are mutually exclusive. No separate color flag is needed. Human-readable
results use Rich's automatic terminal and color detection.
Quiet and verbose are mutually exclusive. Cyclopts group validators reject conflicting
flags before command execution, and its numeric validator constrains CLI verbosity.
flags before command execution.
Logs, progress and errors go to stderr;
commands exit nonzero on errors. Cyclopts help and parse errors remain textual.
The legacy numeric `hello --verbosity` option is retained. Verbose raises the
console level to at least DEBUG; quiet suppresses console logs, not file logs.
Verbose selects DEBUG for the console; quiet suppresses console logs, not file logs.
For TRACE or another named level, set `logging.console_level` in YAML.
Machine output contains no Rich formatting. Both formats use orjson to write compact
UTF-8 bytes directly to stdout, with one newline per document or record. Dates use
ISO 8601, unsupported object values fall back to str, and supported non-string keys
Expand Down Expand Up @@ -262,8 +260,28 @@ It runs for pull requests, not pushes or schedules. No PyPI publishing is enable

## Updating from the Copier template

The `.copier-answers.yml` tracks the source template and your answers:
The `.copier-answers.yml` tracks the source template and your answers.
If updating an older generated project, migrate the user configuration: rename
`logging.level` to `logging.file_level`, replace `logging.verbosity` with
`logging.console_level` (0=WARNING, 1=INFO, 2=DEBUG, 3=TRACE), and remove any
numeric `verbosity` defaults under `cli`. No automatic configuration migration is performed.


```sh
uvx copier update
```


## Git hooks

Initialize Git before running `task setup`. Setup installs the version-controlled
pre-commit hooks when run at the root of a Git working tree. For a project
generated before Git initialization, run `task setup` again after `git init`.

On each commit, Ruff applies safe lint fixes and formats staged Python files.
Pre-commit protects unstaged edits, and if a hook changes a file, the commit
stops so you can review and stage the fixes before retrying. Hooks use the same
Ruff version and configuration as `task fix` and CI, without a second tool environment.

To format all tracked Python files manually, run
`uv run pre-commit run --all-files`.
4 changes: 4 additions & 0 deletions template/Taskfile.yml.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ tasks:
desc: Initialize the development environment
cmds:
- uv sync --group dev
- |
if git rev-parse --show-toplevel >/dev/null 2>&1 && [ -z "$(git rev-parse --show-prefix)" ]; then
uv run --no-sync pre-commit install
fi

dev:
desc: Run the application from the development environment
Expand Down
6 changes: 3 additions & 3 deletions template/config.example.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# File logging level and independent console verbosity.
# Independent named Loguru levels for file and console logging.
logging:
level: INFO
verbosity: 0 # 0=WARNING, 1=INFO, 2=DEBUG, 3=TRACE
file_level: INFO
console_level: WARNING
file_enabled: true

# Optional defaults for command arguments; explicit CLI arguments take priority.
Expand Down
2 changes: 1 addition & 1 deletion template/pyproject.toml.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ dependencies = [
"{{ cli_command }}" = "{{ package_name }}.cli:main"

[dependency-groups]
dev = ["pytest", "pytest-testmon", "ruff"]
dev = ["pre-commit", "pytest", "pytest-testmon", "ruff"]

[tool.uv.build-backend]
module-name = "{{ package_name }}"
Expand Down
28 changes: 14 additions & 14 deletions template/src/{{ package_name }}/cli.py.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ from rich.text import Text
from ruamel.yaml import YAML
from ruamel.yaml.error import YAMLError

from . import database
from . import config as settings
from . import database
from .doctor import CHECK_COUNT, run_checks
from .errors import ApplicationError
from .output import Output, OutputOptions
Expand All @@ -28,7 +28,7 @@ CONFIG_ACTIONS = Group("Configuration actions", validator=validators.MutuallyExc
CONFIG_PATH_EXCLUSION = Group(
"Configuration path restriction", show=False, validator=validators.MutuallyExclusive()
)
Verbosity = Annotated[int | None, Parameter(validator=validators.Number(gte=0, lte=3))]
DEFAULT_OUTPUT_OPTIONS = OutputOptions()

app = App(
name="{{ cli_command }}",
Expand All @@ -51,16 +51,13 @@ def hello(
name: str = "world",
*,
config: File | None = None,
verbosity: Verbosity = None,
options: OutputOptions = OutputOptions(),
options: OutputOptions = DEFAULT_OUTPUT_OPTIONS,
) -> None:
"""Print a friendly greeting; demonstrate logging and structured results."""
output = Output(options)
logging = settings.LoggingConfig.from_config(settings.read_settings(config))
if output.options.verbose:
verbosity = max(2, logging.verbosity if verbosity is None else verbosity)
logging.configure(
verbosity,
verbose=output.options.verbose,
quiet=output.options.quiet,
no_color=output.machine,
)
Expand Down Expand Up @@ -96,7 +93,7 @@ def configuration(
config_path: Annotated[bool, Parameter(group=(CONFIG_ACTIONS, CONFIG_PATH_EXCLUSION))] = False,
show_config: Annotated[bool, Parameter(group=CONFIG_ACTIONS)] = False,
path: Annotated[File | None, Parameter(group=CONFIG_PATH_EXCLUSION)] = None,
options: OutputOptions = OutputOptions(),
options: OutputOptions = DEFAULT_OUTPUT_OPTIONS,
) -> None:
"""Manage the application configuration.

Expand All @@ -117,15 +114,18 @@ def configuration(
if action is not None:
action()
return
if path is not None or options != OutputOptions():
if path is not None or options != DEFAULT_OUTPUT_OPTIONS:
raise ApplicationError("Select a configuration flag or a subcommand")
app.help_print([])



@app.command
def set_config(
key: str, value: str, *, path: File | None = None, options: OutputOptions = OutputOptions()
key: str,
value: str,
*,
path: File | None = None,
options: OutputOptions = DEFAULT_OUTPUT_OPTIONS,
) -> None:
"""Set a dotted configuration key to a YAML value."""
output = Output(options)
Expand All @@ -135,7 +135,7 @@ def set_config(


@app.command
def doctor(*, options: OutputOptions = OutputOptions()) -> int:
def doctor(*, options: OutputOptions = DEFAULT_OUTPUT_OPTIONS) -> int:
"""Diagnose Python, platform, configuration, paths and SQLite without writing."""
output = Output(options)
output.note("Checking runtime and local storage")
Expand All @@ -155,15 +155,15 @@ def doctor(*, options: OutputOptions = OutputOptions()) -> int:


@app.command
def db_path(*, options: OutputOptions = OutputOptions()) -> None:
def db_path(*, options: OutputOptions = DEFAULT_OUTPUT_OPTIONS) -> None:
"""Print the default SQLite database path without initializing it."""
output = Output(options)
path = str(database.default_database_path())
output.emit({"path": path}, human=path)


@app.command
def db_list(*, path: File | None = None, options: OutputOptions = OutputOptions()) -> None:
def db_list(*, path: File | None = None, options: OutputOptions = DEFAULT_OUTPUT_OPTIONS) -> None:
"""List records in deterministic key order."""
output = Output(options)
output.note("Listing SQLite records")
Expand Down
Loading