This guide will walk you through setting up a pre-commit hook for automatically formatting all Python files within the geoe3 directory using black.
- Python 3.x: Ensure you have Python 3 installed on your machine.
- pip: Python's package installer.
First, you'll need to install the pre-commit package. You can do this using pip:
pip install pre-commitIn the root of your repository, create a file named .pre-commit-config.yaml. Add the following configuration to set up black as the pre-commit hook for Python code formatting:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/psf/black
rev: 24.4.0 # Replace with the version of black you are using
hooks:
- id: black
name: black
language_version: python3
# Restrict black to only the `geoe3` directory
additional_dependencies: []
args: [geoe3]repos: Defines the hooks to use. Here, we use theblackformatter from its GitHub repository.rev: Specifies the version ofblack. Make sure to replace it with the version you are using.args: Restrictsblackto format only the Python files within thegeoe3directory.
Navigate to the root of your repository (where the .pre-commit-config.yaml file is located) and install the hook using:
pre-commit installThis command sets up the pre-commit hook so that it will run automatically every time you make a commit.
You can test the hook manually to ensure it works as expected before committing any changes:
pre-commit run --all-filesThis will apply black formatting to all Python files in the geoe3 directory.
Once the hook is installed, every time you make a commit, the black formatter will automatically format your Python code within the geoe3 directory. If any changes are made by black, the commit will fail, allowing you to review the changes before committing again.
If you encounter any issues:
- Make sure
pre-commitis installed correctly. - Ensure your
.pre-commit-config.yamlfile is correctly configured and located in the root of your repository. - Check that you have the correct version of
black.
After following this guide, you will have a working pre-commit hook that formats all Python files in the geoe3 directory using black before every commit.
Enjoy coding with consistent formatting! 🚀