diff --git a/.cursor/rules/python_guidelines.mdc b/.cursor/rules/python_guidelines.mdc new file mode 100644 index 0000000..c9502b2 --- /dev/null +++ b/.cursor/rules/python_guidelines.mdc @@ -0,0 +1,101 @@ +--- +description: Python coding standards and best practices +globs: ["**/*.py"] +alwaysApply: true +--- + +# Python Coding Standards + +## Python Version and Features +- Target Python 3.12+ features and syntax +- Use modern Python features like pattern matching, improved error messages, and new typing features + +## Code Quality and Documentation +- Write clear and concise comments for each function +- Ensure functions have descriptive names and include comprehensive type hints +- Provide docstrings following PEP 257 conventions for all public functions and classes +- Use the `typing` module for type annotations (e.g., `List[str]`, `Dict[str, int]`, `Optional[str]`) +- Break down complex functions into smaller, more manageable functions +- Always prioritize readability and clarity over cleverness + +## Code Structure and Organization +- Follow the existing import order: standard library, third-party, local imports +- Use blank lines to separate functions, classes, and code blocks appropriately +- Do NOT create indented blank lines in .py scripts +- Break down complex logic into smaller, well-named functions +- Use Pydantic models for data validation when appropriate + +## Type Hints and Annotations +- Include proper type hints for all function parameters and return types +- Use `typing` module extensively for complex types +- Add type hints for class attributes and instance variables +- Use `Optional` for nullable values, `Union` for multiple types +- Prefer `list[str]` over `List[str]` (Python 3.9+ syntax) + +## Code Style and Formatting +- Follow PEP 8 style guide strictly +- Use 4 spaces for indentation (no tabs) +- Keep lines under 88 characters (Black-compatible) +- Place docstrings immediately after `def` or `class` keyword +- No trailing whitespace on blank lines +- Use ruff for linting and formatting: `uv run ruff check --fix` + +## Error Handling and Edge Cases +- Handle edge cases explicitly with clear error messages +- Write comprehensive exception handling with specific exception types +- Include comments explaining edge cases and expected behavior +- Validate inputs and provide meaningful error messages +- Use context managers for resource management + +## Testing Requirements +- Write unit tests for all public functions and methods +- Name test files with `test_` prefix +- Use descriptive test function names that explain what is being tested +- Leverage pytest fixtures from `conftest.py` +- Use parametrized tests for multiple test cases +- Add appropriate pytest markers for test categorization +- Include docstrings in test functions explaining test cases + +## Package Management +- Use `uv` as the Python package manager +- Run commands with `uv run ` when outside activated environment +- Use `uv sync` to install dependencies and create virtual environment +- Activate with `source .venv/bin/activate` when needed + +## Documentation Standards +- Include docstrings for all public functions, classes, and methods +- Document the purpose and usage of external libraries in comments +- Explain algorithmic approaches and design decisions in comments +- Provide examples in docstrings when helpful +- Keep comments up-to-date with code changes + +## Example Function Structure +```python +def calculate_area(radius: float) -> float: + """ + Calculate the area of a circle given the radius. + + Args: + radius: The radius of the circle + + Returns: + The area of the circle, calculated as π * radius^2 + + Raises: + ValueError: If radius is negative + """ + if radius < 0: + raise ValueError("Radius cannot be negative") + import math + return math.pi * radius ** 2 +``` + +## Code Review Checklist +- [ ] All functions have type hints and docstrings +- [ ] Code follows PEP 8 and is formatted with ruff +- [ ] Edge cases are handled appropriately +- [ ] Tests cover critical functionality +- [ ] No indented blank lines +- [ ] Imports are properly organized +- [ ] Error handling is comprehensive +- [ ] Code is readable and well-commented diff --git a/.cursorrules b/.cursorrules new file mode 100644 index 0000000..ac44649 --- /dev/null +++ b/.cursorrules @@ -0,0 +1,95 @@ +# Python Coding Rules for Cursor + +## Python Version and Features +- Target Python 3.12+ features and syntax +- Use modern Python features like pattern matching, improved error messages, and new typing features + +## Code Quality and Documentation +- Write clear and concise comments for each function +- Ensure functions have descriptive names and include comprehensive type hints +- Provide docstrings following PEP 257 conventions for all public functions and classes +- Use the `typing` module for type annotations (e.g., `List[str]`, `Dict[str, int]`, `Optional[str]`) +- Break down complex functions into smaller, more manageable functions +- Always prioritize readability and clarity over cleverness + +## Code Structure and Organization +- Follow the existing import order: standard library, third-party, local imports +- Use blank lines to separate functions, classes, and code blocks appropriately +- Do NOT create indented blank lines in .py scripts +- Break down complex logic into smaller, well-named functions +- Use Pydantic models for data validation when appropriate + +## Type Hints and Annotations +- Include proper type hints for all function parameters and return types +- Use `typing` module extensively for complex types +- Add type hints for class attributes and instance variables +- Use `Optional` for nullable values, `Union` for multiple types +- Prefer `list[str]` over `List[str]` (Python 3.9+ syntax) + +## Code Style and Formatting +- Follow PEP 8 style guide strictly +- Use 4 spaces for indentation (no tabs) +- Keep lines under 88 characters (Black-compatible) +- Place docstrings immediately after `def` or `class` keyword +- No trailing whitespace on blank lines +- Use ruff for linting and formatting: `uv run ruff check --fix` + +## Error Handling and Edge Cases +- Handle edge cases explicitly with clear error messages +- Write comprehensive exception handling with specific exception types +- Include comments explaining edge cases and expected behavior +- Validate inputs and provide meaningful error messages +- Use context managers for resource management + +## Testing Requirements +- Write unit tests for all public functions and methods +- Name test files with `test_` prefix +- Use descriptive test function names that explain what is being tested +- Leverage pytest fixtures from `conftest.py` +- Use parametrized tests for multiple test cases +- Add appropriate pytest markers for test categorization +- Include docstrings in test functions explaining test cases + +## Package Management +- Use `uv` as the Python package manager +- Run commands with `uv run ` when outside activated environment +- Use `uv sync` to install dependencies and create virtual environment +- Activate with `source .venv/bin/activate` when needed + +## Documentation Standards +- Include docstrings for all public functions, classes, and methods +- Document the purpose and usage of external libraries in comments +- Explain algorithmic approaches and design decisions in comments +- Provide examples in docstrings when helpful +- Keep comments up-to-date with code changes + +## Example Function Structure +```python +def calculate_area(radius: float) -> float: + """ + Calculate the area of a circle given the radius. + + Args: + radius: The radius of the circle + + Returns: + The area of the circle, calculated as π * radius^2 + + Raises: + ValueError: If radius is negative + """ + if radius < 0: + raise ValueError("Radius cannot be negative") + import math + return math.pi * radius ** 2 +``` + +## Code Review Checklist +- [ ] All functions have type hints and docstrings +- [ ] Code follows PEP 8 and is formatted with ruff +- [ ] Edge cases are handled appropriately +- [ ] Tests cover critical functionality +- [ ] No indented blank lines +- [ ] Imports are properly organized +- [ ] Error handling is comprehensive +- [ ] Code is readable and well-commented diff --git a/.github/ISSUE_TEMPLATE/instructions/python.instructions.md b/.github/ISSUE_TEMPLATE/instructions/python.instructions.md new file mode 100644 index 0000000..e13f5a0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/instructions/python.instructions.md @@ -0,0 +1,79 @@ +--- +description: 'Python coding conventions and guidelines' +applyTo: '**/*.py' +--- + +# Python Coding Conventions + +## Python Instructions + +- Target Python 3.12+ features and syntax. +- Write clear and concise comments for each function. +- Ensure functions have descriptive names and include type hints. +- Provide docstrings following PEP 257 conventions. +- Use the `typing` module for type annotations (e.g., `List[str]`, `Dict[str, int]`). +- Break down complex functions into smaller, more manageable functions. + +## General Instructions + +- Always prioritize readability and clarity. +- For algorithm-related code, include explanations of the approach used. +- Write code with good maintainability practices, including commensts on why certain design decisions were made. +- Handle edge cases and write clear exception handling. +- For libraries or external dependencies, mention their usage and purpose in comments. +- Use consistent naming conventions and follow language-specific best practices. +- Write concise, efficient, and idiomatic code that is also easily understandable. +- [uv](https://docs.astral.sh/uv/) is used as Python package manager: + - Use `uv sync` to install dependencies and create virtual environment + - Activate with `source .venv/bin/activate` or use `uv run ` + - All commands should be prefixed with `uv run` when outside activated environment + +### When creating new Python files: +1. Include proper type hints for all function parameters and return types +2. Add docstrings for classes and public methods +3. Follow the existing import order (standard library, third-party, local) +4. Use Pydantic models for data validation when appropriate + +## Code Style and Formatting + +- Follow the **PEP 8** style guide for Python. +- Maintain proper indentation (use 4 spaces for each level of indentation). +- Ensure lines do not exceed 88 characters(Black-compatible). +- Place function and class docstrings immediately after the `def` or `class` keyword. +- Use blank lines to separate functions, classes, and code blocks where appropriate. +- Do not leave whitespace from black line -> `W293 Blank line contains whitespace` +- [ruff](https://docs.astral.sh/ruff/) is used as linter and formatter: + - Use `uv run ruff check ` to check for linting issues + - Use `uv run ruff check --fix` to automatically fix linting issues + +## Edge Cases and Testing + +- Always include test cases for critical paths of the application. +- Account for common edge cases like empty inputs, invalid data types, and large datasets. +- Include comments for edge cases and the expected behavior in those cases. +- Write unit tests for functions and document them with docstrings explaining the test cases. + +### For test files: +1. Name test files with `test_` prefix +2. Use descriptive test function names +3. Leverage pytest fixtures from `conftest.py` +4. Use parametrized tests for multiple test cases +5. Add appropriate markers for test categorization + + +## Example of Proper Documentation + +```python +def calculate_area(radius: float) -> float: + """ + Calculate the area of a circle given the radius. + + Parameters: + radius (float): The radius of the circle. + + Returns: + float: The area of the circle, calculated as π * radius^2. + """ + import math + return math.pi * radius ** 2 +``` diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..05ccff3 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,146 @@ +# GitHub Copilot Instructions for Python Project Template + +This is a modern Python project template designed with best practices for maintainable, scalable Python applications. + +## Project Overview + +### Technology Stack +- **Python**: 3.12+ (managed by uv) +- **Package Management**: [uv](https://docs.astral.sh/uv/) - extremely fast Python package manager +- **Testing**: pytest with coverage reporting +- **Linting & Formatting**: Ruff (replaces black, isort, flake8) +- **Task Runner**: [Task](https://taskfile.dev/) (replaces Makefiles) +- **Pre-commit**: Automated code quality checks +- **Configuration**: Pydantic Settings with environment-based configs +- **Containerization**: Docker with uv support +- **CI/CD**: GitHub Actions with caching + +### Project Structure +``` +src/ +├── configuration/ # Pydantic-based configuration management +│ ├── config_settings.py # Environment-specific settings +│ └── config_test.py # Configuration tests +└── test/ # Test suite + ├── conftest.py # Pytest fixtures and configuration + └── test_*.py # Test files +``` + +## Development Guidelines + +### Environment Setup +- Use `uv sync` to install dependencies and create virtual environment +- Activate with `source .venv/bin/activate` or use `uv run ` +- All commands should be prefixed with `uv run` when outside activated environment + +### Code Style & Quality +- **Import style**: Use Ruff's isort-compatible import sorting +- **Type hints**: Required for all public functions and methods +- **Docstrings**: Use Google-style docstrings for classes and functions + +### Testing Practices +- Tests located in `src/test/` directory +- Use pytest markers for test categorization: + - `@pytest.mark.slow` for slow tests + - `@pytest.mark.test_mark` for testing purposes +- Test coverage target: 80%+ +- Run tests with: `uv run pytest ./src/test` + +### Configuration Management +- Use Pydantic Settings for all configuration +- Environment-specific configs in `pyproject.toml` under `[config.]` +- Required environment variable: `ENVIRONMENT` (e.g., "local", "dev", "prod") +- Configuration priority order: + 1. CLI arguments + 2. Environment-specific pyproject.toml table + 3. Default pyproject.toml table + 4. Environment variables + +### Available Tasks (Taskfile.yml) +- `task linter`: Run Ruff linter with auto-fix +- `task formatter`: Run Ruff formatter +- `task checker`: Run mypy type checking +- `task run-test`: Execute test suite +- `task precommit`: Run pre-commit hooks +- `task check_updatable_libs`: Check for dependency updates + + +### For configuration-related code: +1. Extend `SourceSettings` or `BasicSettings` classes +2. Use `Field` with `alias` for environment variable mapping +3. Include proper type annotations +4. Add validation methods when necessary + +### Docker considerations: +- Use multi-stage builds when possible +- Install dependencies with `uv sync --frozen` +- Set `ENVIRONMENT` variable appropriately +- Mount source code as volumes for development + +### Dependencies: +- Add runtime dependencies with: `uv add package-name` +- Add dev dependencies with: `uv add --group dev package-name` +- Keep dependencies minimal and well-justified +- Pin major versions for stability + +## Pre-commit and CI/CD + +### Pre-commit hooks run: +- Trailing whitespace removal +- End-of-file fixing +- YAML/TOML validation +- Ruff linting and formatting +- UV dependency validation + +### CI pipeline includes: +- Multi-OS testing (Ubuntu, macOS) +- Python 3.12 +- Dependency caching +- Pre-commit hook validation +- Full test suite execution + +## Best Practices + +1. **Test-driven development** - Write tests for new functionality +2. **Small, focused commits** - Use conventional commit messages +3. **Environment variables** - Never hardcode configuration values +4. **Error handling** - Use proper exception handling and logging +5. **Performance** - Leverage uv's speed for dependency operations +6. **Security** - Use `safety` for vulnerability scanning + +## Common Patterns + +### Adding a new configuration setting: +```python +class BasicSettings(SourceSettings): + new_setting: str = Field( + alias="NEW_SETTING", + description="Description of the setting" + ) +``` + +### Creating a new test: +```python +import pytest + +def test_new_functionality(): + # Arrange + expected = "expected_value" + + # Act + result = function_under_test() + + # Assert + assert result == expected +``` + +### Adding a new dependency: +```bash +# Runtime dependency +uv add package-name + +# Development dependency +uv add --group dev package-name +``` + +Remember: This template prioritizes developer experience, code quality, and maintainability. All suggestions should align with these principles. diff --git a/.github/prompts/create-pr-description.prompt.md b/.github/prompts/create-pr-description.prompt.md new file mode 100644 index 0000000..348119e --- /dev/null +++ b/.github/prompts/create-pr-description.prompt.md @@ -0,0 +1,122 @@ +--- +mode: 'agent' +description: 'Generate a comprehensive PR description based on changes and fill it in a predefined template.' +tools: ['changes', 'codebase', 'search', 'usages', 'githubRepo', 'fetch', 'runCommands', 'runTasks'] +--- + +# PR Description Generator + +You are an agent and your task is to generate a comprehensive PR description based on changes and fill it in a predefined template. + +please keep going until the user’s query is completely resolved, before ending your turn and yielding back to the user. + +You MUST iterate and keep going until the problem is solved. + +Your knowledge on everything is out of date because your training date is in the past, so you should not rely on your internal knowledge but should use #fetch_webpage to proactively gather up-to-date information. + +You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully. + +# Workflow +1. Understand your current branch and the target branch of the PR by running `git` command. +2. If PR is not already created from current branch then target branch should be one of ['develop', 'main', 'master']. +3. Identify the changes made in the PR by reviewing the changes by running `git diff` command. +4. Deeply understand the change while investigating the codebase. +5. Research the relevant documentation on the internet by reading relevant articles, documentation, and forums. +6. Develop a clear, step-by-step plan. Address the major and minor changes. Display the changes in a bullet point list. +7. Generate a comprehensive PR description using the template below, return it in markdown format. +8. Return the URL for PR creation in the end. + + +### PR Description Template: + +```markdown +## Summary + + +## Type of Change + +- [ ] 🐛 Bug fix (non-breaking change which fixes an issue) +- [ ] ✨ New feature (non-breaking change which adds functionality) +- [ ] 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected) +- [ ] 📚 Documentation update +- [ ] 🔧 Refactoring (no functional changes) +- [ ] 🧪 Test improvements +- [ ] 🚀 Performance improvements +- [ ] 🔒 Security improvements + +## Changes Made + + +### Modified Files: + + +### New Files: + + +### Deleted Files: + + +## Technical Details + + +## Testing + +- [ ] Unit tests added/updated +- [ ] Integration tests added/updated +- [ ] Manual testing performed +- [ ] Existing tests still pass + +## Impact Assessment + + +### Breaking Changes: + + +### Dependencies: + + +### Performance Impact: + + +## Screenshots/Examples + + +## Checklist + +- [ ] Code follows project coding standards +- [ ] Self-review of code completed +- [ ] Code is properly commented +- [ ] Tests have been added/updated +- [ ] Documentation has been updated +- [ ] No merge conflicts +- [ ] All CI checks pass + +## Additional Notes + +``` + +### Specific Instructions: + +1. **Start with source control analysis** using #changes to get a complete picture of all modifications +2. **Analyze the codebase context** using #codebase to understand the project structure and conventions +3. **Search for related files** using #search to find configuration files, tests, and documentation that might be affected +4. **Find code relationships** using #usages to understand how modified functions/classes are used throughout the codebase +5. **Check GitHub context** using @github to understand any related issues, existing PRs, or repository-specific context +6. **Generate content for each section** of the template based on the actual changes discovered +7. **Be specific and detailed** - avoid generic descriptions, reference actual file names and functions +8. **Include technical context** that would be helpful for reviewers, including dependency changes and architectural impacts +9. **Highlight important changes** that might affect other parts of the system based on usage analysis +10. **Suggest appropriate testing** based on the type of changes made and existing test patterns found +11. **Check all relevant boxes** in the type of change and checklist sections based on your analysis +12. **Identify potential impacts** including breaking changes, performance, or security implications using code relationships +13. **Provide actionable information** for code reviewers with specific file references and change summaries + +### Output Guidelines: + +- **Use clear, professional language** +- **Be concise but comprehensive** +- **Include relevant technical details** +- **Format using proper Markdown** +- **Fill in all applicable template sections** +- **Leave placeholder comments only for sections that don't apply** +- **Ensure the description helps reviewers understand both the "what" and "why"** diff --git a/Changelog.md b/Changelog.md index 47a126f..bf4592c 100644 --- a/Changelog.md +++ b/Changelog.md @@ -2,7 +2,25 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) -## Current version [0.2.0] - 2025-08-31 +## Current version [0.3.0] - 2025-09-09 + +### Added +- Comprehensive AI coding instructions and development guidelines +- `.cursor/rules/python_guidelines.mdc` - Cursor AI editor rules with Python coding standards +- `.cursorrules` - Main Cursor AI editor configuration file +- `.github/ISSUE_TEMPLATE/instructions/python.instructions.md` - GitHub issue template instructions +- `.github/copilot-instructions.md` - GitHub Copilot specific instructions for the project template +- `.github/prompts/create-pr-description.prompt.md` - Automated PR description generation template +- Multi-platform AI assistant support (Cursor, GitHub Copilot, general AI) +- Standardized Python 3.12+ coding practices and conventions +- Type hints and comprehensive documentation requirements +- Error handling and edge case management guidelines +- Modern development tool integration (Ruff, pytest, uv, Docker) + +### Changed +- Renamed `src/configuration/config_test.py` to `src/configuration/config_example.py` for better clarity and naming convention + +## [0.2.0] - 2025-08-31 ### Changed - **BREAKING**: Migrated from Poetry to [uv](https://docs.astral.sh/uv/) for Python package and dependency management diff --git a/pyproject.toml b/pyproject.toml index 87c28e1..4584485 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "python-project-template" -version = "0.2.0" +version = "0.3.0" description = "" authors = [ {name = "ZequnZ", email = "zequn.zhou007@gmail.com"} diff --git a/src/configuration/config_test.py b/src/configuration/config_example.py similarity index 100% rename from src/configuration/config_test.py rename to src/configuration/config_example.py diff --git a/uv.lock b/uv.lock index bf1f531..87eef5c 100644 --- a/uv.lock +++ b/uv.lock @@ -691,7 +691,7 @@ wheels = [ [[package]] name = "python-project-template" -version = "0.1.0" +version = "0.3.0" source = { virtual = "." } dependencies = [ { name = "pydantic" },