Pre-commit is a fantastic tool that runs checks before each commit, ensuring code quality and consistency. This guide will show you how to integrate pre-commit with your NEMDataTools project, specifically working with UV for dependency management.
First, add pre-commit to your development dependencies in pyproject.toml:
[project.optional-dependencies]
dev = [
"pytest>=6.0",
"pytest-cov>=2.12",
"black>=25.0.0",
"mypy>=1.14.0",
"isort>=6.0.0",
"pre-commit>=3.3.2",
"ruff>=0.5.0",
"commitizen>=4.4.0",
]Install the updated development dependencies:
# Make sure your virtual environment is activated
uv pip install -e ".[dev]"Create a .pre-commit-config.yaml file in the root of your project with the configuration provided in the artifacts.
This configuration includes:
- Basic file checks (YAML, TOML, trailing whitespace, etc.)
- Code formatting with Black
- Import sorting with isort
- Style checking with flake8
- Type checking with mypy
- Python upgrades with pyupgrade
- Commit message formatting with commitizen
# Install the pre-commit hooks
pre-commit install
# Also install the commit message hook
pre-commit install --hook-type commit-msgYou can run pre-commit manually on all files:
pre-commit run --all-filesWhen you need to update pre-commit or its dependencies:
# Update dependencies
uv pip install --upgrade -e ".[dev]"
# Update pre-commit hooks
pre-commit autoupdate- Local Development: Pre-commit will automatically run before each commit
- CI/CD Pipeline: Add pre-commit to your GitHub Actions workflow
Example GitHub Actions step:
- name: Run pre-commit
run: |
uv pip install pre-commit
pre-commit run --all-filesYou can customize the .pre-commit-config.yaml file to suit your needs:
- Add hooks: There are many pre-commit hooks available
- Adjust parameters: Modify hook arguments to suit your project
- Skip hooks: Use
SKIP=hook_id git committo skip specific hooks
The provided configuration includes commitizen, which enforces a standard commit message format. Commits will follow the Conventional Commits specification:
type(scope): description
[optional body]
[optional footer(s)]
Examples:
feat: add new downloader functionfix(cache): resolve issue with file lockingdocs: update README with UV instructions
If you encounter issues:
- Hooks failing: Read the error message and fix the issue
- Skip hooks temporarily:
SKIP=flake8 git commit -m "message" - Update hooks:
pre-commit autoupdate - Reinstall hooks:
pre-commit uninstall && pre-commit install
- Editor Integration: Many editors have pre-commit plugins
- Automated fixes: Most hooks will automatically fix issues when possible
- Performance: Some hooks can be slow (like mypy) - you can exclude them for rapid development