A pre-commit hook is a script that is executed before a commit is made in version control systems such as Git. Pre-commit hooks can be used to perform tasks such as running tests, linting code, or checking for formatting errors. The pre-commit hook provides an extra layer of automation to make sure only valid code is committed to the repository.
Pre-commit hooks can be used for the following tasks:
Checking formatting errors
Enforcing coding standards
Checkpointing data before making changes to the repository
Undoing undesirable commits.
The pre-commit package is available on PyPI and can be installed using the
pip install pre-commit command.
After installing the package, you can create a
.pre-commit-config.yaml file in the project's root directory, which contains the configuration for the pre-commit hooks. You can then add the desired pre-commit hooks to this file and include the command(s) that should be executed in each hook. Finally, you can run the
pre-commit install command from the root directory to install the pre-commit hooks and enable them for the project.
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: detect-aws-credentials args: ["--allow-missing-credentials"] - id: detect-private-key - id: check-added-large-files - id: check-symlinks - id: check-merge-conflict - id: check-yaml - id: debug-statements - repo: https://github.com/ambv/black rev: 23.1.0 hooks: - id: black args: ["--line-length", "80"] - repo: https://github.com/PyCQA/bandit rev: "1.7.5" hooks: - id: bandit args: ["--skip", "B101", "B703", "B308"] - repo: https://github.com/PyCQA/flake8 rev: 6.0.0 hooks: - id: flake8 args: ["--config", "setup.cfg"] - repo: https://github.com/pycqa/isort rev: 5.12.0 hooks: - id: isort args: [ "--profile", "black", "--line-length", "80",]
This pre-commit hook configuration will run several checks on your code before it is committed. The
detect-aws-credentials hook will ensure that AWS credentials are not accidentally added to your project files.
detect-private-key hook will detect any private key files in your changes. The
check-added-large-files hook will check for large files added to your repo.
check-symlinks hook will make sure no broken symlinks are added.
check-merge-conflict hook will detect merge conflicts in your changes.
check-yaml hook will check YAML files for errors.
debug-statements hook will detect debug statements in your code.
black hook will check your code for formatting using the Black code style.
bandit hook will check your code for any potential security issues.
flake8 hook will check for code style compliance. It will also look for configuration files in
And finally, the
isort hook will check your imports for proper sorting.