Enabling Git Hooks¶
Git hooks are automated scripts that run at specific points during Git’s execution,
allowing developers to enforce quality standards, automate tasks, and customize Git’s
behavior. The PTB uses the pre-commit framework to
define common Git hooks for Git commits and pushes. The configuration for
pre-commit is provided in a .pre-commit-config.yaml file and described in
Configuration.
Configuration¶
Add a
.pre-commit-config.yamlfile to your project’s root directory. Feel free to take inspiration from the example.pre-commit-config.yaml:.pre-commit-config.yaml
default_stages: [ pre-commit, pre-push ] repos: - repo: local hooks: - id: code-format name: code-format types: [ python ] pass_filenames: false language: system entry: poetry run -- nox -s project:fix stages: [ pre-commit ] - repo: local hooks: - id: type-check name: type-check types: [ python ] pass_filenames: false language: system entry: poetry run -- nox -s lint:typing stages: [ pre-push ] - repo: local hooks: - id: lint name: lint types: [ python ] pass_filenames: false language: system entry: poetry run -- nox -s lint:code stages: [ pre-push ] - repo: https://github.com/pre-commit/pre-commit-hooks rev: v5.0.0 hooks: - id: check-yaml stages: [ pre-commit ] - id: end-of-file-fixer stages: [ pre-commit ] - id: trailing-whitespace stages: [ pre-commit ]
Enable pre-commit hooks for your workspace:
poetry run -- pre-commit install --hook-type pre-commit --hook-type pre-push
Working with pre-commit¶
Committing¶
Once pre-commit has been configured, the process for performing a git commit is:
Make your code changes
git addchanged files andgit commit -m "<message>"pre-commitperforms checks on the changed files and produces an output likecode-format..........................................(no files to check)Skipped check yaml...........................................(no files to check)Skipped fix end of files.........................................................Passed trim trailing whitespace.................................................Passed
If all steps pass, then no action is needed.
If a step fails, then check the output further. If it was an automatic fix, then just add the altered file to your commit and execute your
git commitline again. Otherwise, manual intervention is needed.
Pushing¶
Once pre-commit has been configured, the process for performing a git push is:
Perform one or more iterations of Committing.
git pushpre-commitperforms checks on the changed files and produces an output liketype-check...............................................................Passed lint.....................................................................Passed
If all steps pass, then no action is needed.
If a step fails, then check the output further. The suggested
pre-pushactions given in the Configuration require manual intervention. Create a new commit to resolve the issue & trygit pushagain.