From 26409775eed37402b70b95aa18cc41e007d9dac0 Mon Sep 17 00:00:00 2001 From: trisdoan Date: Wed, 11 Feb 2026 10:12:35 +0700 Subject: [PATCH 1/3] chore: initialize docs --- .gitignore | 4 + README.md | 341 ++++++++++++++++++- docs/INDEX.md | 116 +++++++ docs/code-standards.md | 531 ++++++++++++++++++++++++++++++ docs/codebase-summary.md | 279 ++++++++++++++++ docs/deployment-guide.md | 692 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 1955 insertions(+), 8 deletions(-) create mode 100644 docs/INDEX.md create mode 100644 docs/code-standards.md create mode 100644 docs/codebase-summary.md create mode 100644 docs/deployment-guide.md diff --git a/.gitignore b/.gitignore index 42f20c5..3854de1 100644 --- a/.gitignore +++ b/.gitignore @@ -214,3 +214,7 @@ __marimo__/ # Streamlit .streamlit/secrets.toml +.claude/ +.opencode/ +plans/ +.repomixignore diff --git a/README.md b/README.md index 43cd730..2f51cf6 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,343 @@ # Trobz Python Template -[Copier](https://github.com/copier-org/copier) template for Python projects managed by [uv](https://github.com/astral-sh/uv). +A modern [Copier](https://copier.readthedocs.io/) template for Python projects managed by [uv](https://docs.astral.sh/uv/). Scaffold production-ready CLI applications and web services with zero boilerplate, modern tooling, and best practices built-in. + +**Current Version:** 1.1.0 ## Features -- [uv](https://github.com/astral-sh/uv) setup, with pre-defined `pyproject.toml` -- Pre-configured tools for code formatting: - [ruff](https://github.com/charliermarsh/ruff), -- Tests run with [pytest](https://github.com/pytest-dev/pytest) -- Support for GitHub workflows -- Auto-generated `CHANGELOG.md` from Git (conventional) commits +- **Project Type Support** + - CLI applications with [Typer](https://typer.tiangolo.com/) + - Web services with [FastAPI](https://fastapi.tiangolo.com/) or [Flask](https://flask.palletsprojects.com/) + +- **Modern Python Tooling** + - [uv](https://docs.astral.sh/uv/) for fast dependency management + - [ruff](https://docs.astral.sh/ruff/) for linting and formatting + - [pytest](https://docs.pytest.org/) for testing + - [ty](https://github.com/asottile/py) for static type checking + - [pre-commit](https://pre-commit.com/) for code quality gates + +- **GitHub Integration** + - Automated testing on multiple Python versions (3.10, 3.11, 3.12, 3.13) + - Pre-commit checks on every push + - Semantic versioning with [conventional commits](https://www.conventionalcommits.org/) + - Optional PyPI publishing with Trusted Publishing + - Custom GitHub Action for consistent environment setup + +- **Developer Experience** + - Interactive prompts with input validation + - Makefile with helpful commands + - Pre-configured code quality tools + - Health endpoints for services + - Environment-based configuration + +- **Production-Ready** + - AGPL-3.0 license for open-source compliance + - Type hints throughout codebase + - Comprehensive error handling + - Security best practices built-in ## Quick Start +### Prerequisites + +- Python 3.12+ (for running the template generator) +- Copier (install via `pip install copier`) +- Git (for version control) + +### Generate a New Project + +```bash +# Create a new CLI application +copier copy "https://github.com/trobz/trobz-python-template.git" ./my-cli-app + +# Or create a new FastAPI service +copier copy "https://github.com/trobz/trobz-python-template.git" ./my-api-service +``` + +### Follow Interactive Prompts + +``` +project_name? [my-project]: My Awesome App +package_name? [my_awesome_app]: +project_description? Your app description +project_type? [cli]: + 1. cli + 2. service + > 1 +repository_namespace? [trobz]: myorg +repository_name? [my-awesome-app]: +author_username? [my-username]: jane-doe +author_email? [jane@example.com]: +enable_github_action? [False]: True +``` + +### Start Developing + +```bash +cd my-awesome-app + +# Install dependencies and pre-commit hooks +make install + +# Run code quality checks +make check + +# Run tests +make test + +# For services: run the application +make serve +``` + +## Project Type Details + +### CLI Application + +Generate a command-line tool using Typer: + +```bash +copier copy "https://github.com/trobz/trobz-python-template.git" ./my-cli +# Select: project_type = cli +``` + +**Generated structure:** +``` +my-cli/ +├── my_cli/ +│ ├── __init__.py +│ └── main.py # Typer CLI app +├── tests/ +├── Makefile +└── pyproject.toml +``` + +**Example usage:** +```bash +$ make install +$ uv run my-cli hello World +Hello World +``` + +**Customize by:** +- Adding more commands with `@app.command()` decorators +- Adding options with `typer.Option()` +- Building sophisticated CLI hierarchies + +### Service Application (FastAPI) + +Generate a modern async web service: + +```bash +copier copy "https://github.com/trobz/trobz-python-template.git" ./my-api +# Select: project_type = service, service_framework = fastapi +``` + +**Generated structure:** +``` +my-api/ +├── my_api/ +│ ├── __init__.py +│ ├── main.py # FastAPI app +│ └── settings.py # Pydantic settings +├── .env.sample # Config template +├── tests/ +├── Makefile +└── pyproject.toml +``` + +**Example usage:** +```bash +$ make install + +# Start the server +$ make serve +INFO: Uvicorn running on http://0.0.0.0:8000 +INFO: Application startup complete + +# Test endpoints +$ curl http://localhost:8000/ +{"Hello":"World","env":"local"} + +$ curl http://localhost:8000/health +{"status":"ok"} + +# View API documentation +$ open http://localhost:8000/docs +``` + +**Key features:** +- Automatic OpenAPI/Swagger docs at `/docs` +- Async route support for high concurrency +- Pydantic request/response validation +- Uvicorn ASGI server included + +### Service Application (Flask) + +Generate a lightweight web service: + +```bash +copier copy "https://github.com/trobz/trobz-python-template.git" ./my-service +# Select: project_type = service, service_framework = flask +``` + +**Similar structure to FastAPI but with:** +- Synchronous route handling +- Familiar Flask patterns +- Smaller dependency footprint +- WSGI-compatible + +## Configuration and Customization + +### Environment Variables + +Service projects use `.env` files for configuration: + ```bash -copier copy "https://github.com/trobz/trobz-python-template.git" /path/to/your/new/project +# Copy template to actual config +cp .env.sample .env.local + +# Edit with your settings +ENVIRONMENT=development +DEBUG=true +SERVER_PORT=8001 ``` + +**Configuration precedence:** +1. `.env.local` (highest priority, not tracked) +2. `.env` (tracked, can be committed) +3. Environment variables (system-level) +4. Defaults in Settings class + +### Making Project Decisions + +Edit generated files to customize: + +```python +# Add dependencies: uv add requests +# Add new routes (services): edit my_package/main.py +# Add new commands (CLI): edit my_package/main.py +# Modify settings (services): edit my_package/settings.py +# Update workflows: edit .github/workflows/ +``` + +## Development Workflow + +### Available Commands + +All projects include a Makefile with common tasks: + +```bash +make install # Install dependencies and pre-commit hooks +make check # Lint, format, and type-check code +make test # Run pytest with coverage +make build # Build distribution wheel +make help # Show all available commands + +# Services only: +make serve # Run the FastAPI/Flask application +``` + +### Code Quality Gates + +Before committing, code must pass: + +```bash +# Local checks (pre-commit hooks) +make check # Ruff formatting/linting, pre-commit + +# Commit must follow conventional format +# Example: feat(auth): add JWT support + +# CI checks (GitHub Actions) +make test # Tests on Python 3.10-3.13 +``` + +### Version Management + +Versions bump automatically based on commits: + +```bash +# Regular feature +git commit -m "feat(api): add user endpoint" # → 1.1.0 + +# Bug fix +git commit -m "fix(auth): resolve token bug" # → 1.0.1 + +# Breaking change +git commit -m "refactor!: change API response format" # → 2.0.0 +``` + +## GitHub Actions Integration (Optional) + +Enable during template generation with `enable_github_action = true`: + +**Included workflows:** + +| Workflow | Trigger | Purpose | +|---|---|---| +| test.yaml | PR & main push | Run tests on Python 3.10-3.13 | +| pre-commit.yaml | PR & main push | Linting and formatting checks | +| release.yaml | Tags | Semantic versioning and PyPI publish | + +**PyPI Publishing (Optional)** + +Enable with `publish_to_pypi = true` to automatically publish: +1. Create GitHub repo secrets: `PYPI_TOKEN` +2. Set token to PyPI Trusted Publishing +3. On version tag, automatically published to PyPI + +## Documentation + +Comprehensive documentation available: + +- **[Project Overview & Requirements](./docs/project-overview-pdr.md)** - Vision, goals, and roadmap +- **[Code Standards](./docs/code-standards.md)** - Coding conventions and quality requirements +- **[System Architecture](./docs/system-architecture.md)** - Template design and data flows +- **[Codebase Summary](./docs/codebase-summary.md)** - Directory structure and components + +## Requirements + +### For Template Generator + +- Python 3.12+ +- Copier 8.0+ +- Git + +### For Generated Projects + +- Python 3.10+ (template supports 3.10, 3.11, 3.12, 3.13) +- uv (automatically used by Makefile) +- Standard Unix tools (make, git) + +## License + +This template is licensed under the **AGPL-3.0 License**. Generated projects inherit this license. + +## Contributing + +Contributions are welcome! Please: + +1. Read the [Code Standards](./docs/code-standards.md) +2. Follow conventional commit format +3. Ensure tests pass: `make test` +4. Ensure code passes checks: `make check` +5. Create a pull request with a clear description + +## Support + +- **Issues**: Report bugs and request features via [GitHub Issues](https://github.com/trobz/trobz-python-template/issues) +- **Discussions**: Ask questions in [GitHub Discussions](https://github.com/trobz/trobz-python-template/discussions) +- **Documentation**: See the [docs](./docs/) directory + +## Changelog + +See [CHANGELOG.md](./CHANGELOG.md) for detailed version history and changes. + +## Related Projects + +- [Copier](https://copier.readthedocs.io/) - Template engine +- [uv](https://docs.astral.sh/uv/) - Python package manager +- [Typer](https://typer.tiangolo.com/) - CLI framework +- [FastAPI](https://fastapi.tiangolo.com/) - Web framework +- [Ruff](https://docs.astral.sh/ruff/) - Linter and formatter diff --git a/docs/INDEX.md b/docs/INDEX.md new file mode 100644 index 0000000..bf4c8c4 --- /dev/null +++ b/docs/INDEX.md @@ -0,0 +1,116 @@ +# Documentation Index + +Welcome to the Trobz Python Template documentation. This index helps you find the information you need. + +## Quick Navigation + +### Getting Started + +New to the template? Start here: + +1. **[README.md](../README.md)** - Project overview, features, and quick start + +### For Developers + +Building with the template: + +2. **[code-standards.md](code-standards.md)** - Code quality standards and conventions +3. **[codebase-summary.md](codebase-summary.md)** - Project structure reference + + +## Document Overview + +### README.md (Main Entry Point) +**Purpose:** Project introduction and feature overview +**Length:** 344 lines +**Audience:** Everyone +**Key Sections:** +- Features overview +- Quick start guide +- Project type details (CLI, FastAPI, Flask) +- Configuration guide +- Development workflow +- GitHub Actions integration +- Support and resources + +### docs/codebase-summary.md +**Purpose:** Codebase structure and organization reference +**Length:** 288 lines +**Audience:** Developers, architects +**Key Sections:** +- Directory structure +- Key components +- Template variables +- Conditional rendering +- Generated project structure +- Build system overview + +### docs/code-standards.md +**Purpose:** Coding conventions and quality standards +**Length:** 532 lines +**Audience:** Developers +**Key Sections:** +- Project structure and organization +- File naming conventions +- Python standards (PEP 8) +- Linting rules (Ruff) +- Import organization +- Type hints and docstrings +- Testing requirements (80%+ coverage) +- Git workflow (conventional commits) +- Pre-commit hooks +- Error handling patterns +- Security standards + +## By Topic + +### Template Usage +- [codebase-summary.md](codebase-summary.md) + +### CLI Applications +- [README.md - CLI Application](../README.md#cli-application) + +### Web Services +- [README.md - FastAPI Service](../README.md#service-application-fastapi) +- [README.md - Flask Service](../README.md#service-application-flask) + +### Code Quality +- [code-standards.md](code-standards.md) +- [code-standards.md - Linting (Ruff)](code-standards.md#linting-ruff) +- [code-standards.md - Testing](code-standards.md#testing-requirements) +- [code-standards.md - Pre-commit Hooks](code-standards.md#pre-commit-hooks) + +### Development Workflow +- [code-standards.md - Code Organization](code-standards.md#code-organization) +- [code-standards.md - Git and Version Control](code-standards.md#git-and-version-control) +- [README.md - Development Workflow](../README.md#development-workflow) + +## Common Tasks + +### I want to create a new CLI project +1. Read [README.md - Quick Start](../README.md#quick-start) +2. Follow [deployment-guide.md - Using the Template](deployment-guide.md#using-the-template) +3. Refer to [README.md - CLI Application](../README.md#cli-application) for examples +4. Check [deployment-guide.md - CLI Development](deployment-guide.md#cli-development) + +### I want to create a new web service +1. Read [README.md - Quick Start](../README.md#quick-start) +2. Follow [deployment-guide.md - Using the Template](deployment-guide.md#using-the-template) +3. Choose framework: [README.md - FastAPI Service](../README.md#service-application-fastapi) or [Flask Service](../README.md#service-application-flask) +4. Check [deployment-guide.md - Service Development](deployment-guide.md#service-development) + +### I need to deploy a generated project +1. Read [deployment-guide.md - Service Deployment](deployment-guide.md#service-deployment) +2. Choose deployment method (Gunicorn, Docker, Systemd, Heroku, AWS, etc.) +3. Configure environment: [deployment-guide.md - Configuration](deployment-guide.md#configuration-for-deployment) +4. Set up CI/CD: [deployment-guide.md - GitHub Actions](deployment-guide.md#github-actions-configuration) + +### I need to understand code standards +1. Read [code-standards.md](code-standards.md) +2. Check specific sections: [naming conventions](code-standards.md#file-naming-conventions), [linting](code-standards.md#linting-ruff), [testing](code-standards.md#testing-requirements) +3. Review [git workflow](code-standards.md#git-and-version-control) and [conventional commits](code-standards.md#conventional-commits) + +### I'm having issues with the template +1. Check [deployment-guide.md - Troubleshooting](deployment-guide.md#troubleshooting) +2. Look for your issue in the common problems section +3. Read [README.md - Support](../README.md#support) for additional help diff --git a/docs/code-standards.md b/docs/code-standards.md new file mode 100644 index 0000000..4f873c3 --- /dev/null +++ b/docs/code-standards.md @@ -0,0 +1,531 @@ +# Code Standards and Guidelines + +## Overview + +This document defines the code quality standards, tooling configuration, and conventions used in the Trobz Python Template and all generated projects. All code must follow these standards before being committed. + +## Code Organization + +### Project Structure + +``` +{project}/ +├── {package_name}/ +│ ├── __init__.py # Package initialization +│ ├── main.py # Application entry point +│ └── settings.py # Configuration (services only) +├── tests/ +│ └── test_*.py # Test files matching pattern +├── .github/ +│ └── workflows/ # CI/CD workflows +├── Makefile # Build and development commands +├── pyproject.toml # Project configuration +├── ruff.toml # Linting and formatting config +├── ty.toml # Type checker config +├── .pre-commit-config.yaml # Pre-commit hooks +├── .gitignore # Git ignore rules +└── README.md # Project documentation +``` + +### File Naming Conventions + +| Type | Pattern | Example | +|---|---|---| +| Python modules | snake_case | `user_service.py`, `api_handlers.py` | +| Test files | `test_*.py` | `test_user_service.py` | +| Classes | PascalCase | `UserService`, `ApiHandler` | +| Functions | snake_case | `get_user()`, `validate_email()` | +| Constants | SCREAMING_SNAKE_CASE | `MAX_RETRIES`, `DEFAULT_TIMEOUT` | +| Private members | `_leading_underscore` | `_internal_cache`, `_helper()` | + +### Module Structure + +Keep files under 200 lines for maintainability: + +```python +"""Module docstring describing purpose.""" + +# Standard library imports +import os +import sys +from typing import Optional + +# Third-party imports +import requests +from pydantic import BaseModel + +# Local imports +from . import settings + +# Constants +DEFAULT_TIMEOUT = 30 +MAX_RETRIES = 3 + +# Classes +class MyClass: + """Class docstring.""" + pass + +# Functions +def my_function(): + """Function docstring.""" + pass + +# Entry point +if __name__ == "__main__": + pass +``` + +## Code Quality Standards + +### Python Standards + +**Python Version**: 3.10+ for generated projects, 3.12+ for template generator + +**Encoding**: UTF-8 (no encoding declaration needed in Python 3) + +**Line Length**: 88 characters (Ruff default, Black-compatible) + +**Indentation**: 4 spaces (never tabs) + +### Linting (Ruff) + +Configuration in `ruff.toml`: + +```toml +line-length = 88 +target-version = "py310" + +[lint] +select = ["E", "F", "I", "N", "W"] # Error, Pyflakes, Import sort, Naming, Warnings +ignore = ["E203", "E501"] + +[lint.isort] +profile = "black" +``` + +#### Enabled Rules + +| Code | Category | Description | +|---|---|---| +| E | Error | PEP 8 errors (whitespace, indentation) | +| F | PyFlakes | Logic errors (unused imports, undefined names) | +| I | isort | Import sorting and organization | +| N | pep8-naming | Naming convention violations | +| W | Warning | PEP 8 warnings (blank lines, line breaks) | + +#### Disabled Rules + +- **E203**: Whitespace before colon (conflicts with formatters) +- **E501**: Line too long (handled by formatter) + +### Import Organization + +Order (enforced by isort): + +1. Future imports: `from __future__ import annotations` +2. Standard library: `import os`, `from typing import ...` +3. Third-party: `import requests`, `from pydantic import ...` +4. Local: `from . import settings`, `from .models import User` + +Blank line separates each group. + +```python +from __future__ import annotations + +import os +import sys +from typing import Optional + +import requests +from pydantic import BaseModel + +from . import settings +from .models import User +``` + +### Type Hints + +All functions and methods must include type hints: + +```python +def get_user(user_id: int) -> Optional[User]: + """Retrieve user by ID.""" + # Implementation + pass + +class UserService: + def create_user(self, name: str, email: str) -> User: + """Create new user.""" + pass + + def list_users(self) -> list[User]: + """List all users.""" + pass +``` + +### Docstrings + +Use Google-style docstrings for classes and functions: + +```python +def calculate_total(items: list[int], tax_rate: float = 0.1) -> float: + """Calculate total with tax. + + Args: + items: List of item prices. + tax_rate: Tax percentage as decimal (default 0.1 for 10%). + + Returns: + Total price including tax. + + Raises: + ValueError: If tax_rate is negative. + """ + if tax_rate < 0: + raise ValueError("tax_rate must be non-negative") + return sum(items) * (1 + tax_rate) + +class UserService: + """Service for managing user operations. + + Attributes: + db: Database connection. + cache: Optional cache instance. + """ + + def __init__(self, db: Database, cache: Optional[Cache] = None): + """Initialize UserService. + + Args: + db: Database connection instance. + cache: Optional cache for performance. + """ + self.db = db + self.cache = cache +``` + +### Formatting (Ruff Format) + +Automatically applied via `make check`: + +- Consistent quote style (prefer double quotes) +- Consistent spacing around operators +- Consistent import formatting +- Consistent string formatting + +### Type Checking (ty) + +Static type verification configured in `ty.toml`. Run via `make check`: + +```bash +make check # Runs ty type checker +``` + +Fix type errors before committing. + +## Git and Version Control + +### Conventional Commits + +All commits must follow conventional commit format: + +``` +(): + + + +