Motivation
In this post, I would show how to use custom Python and Shell scripts used in pre-commit. pre-commit is a framework for managing and maintaining multi-language pre-commit hooks.
I regularly use pre-commit hooks like trimming trailing-white or end-of-file-fixer etc. Besides those, this time I try to run a custom Python script which checks for some rules.
(Note: For basic usage, please refer to https://pre-commit.com/ . )
Code
Python Script
Example custom.py
file for the custom check.
import sysprint("Hello from custom.py") # Stdout only printed when Failedtry:
1 / 0
except Exception as e:
sys.exit(e)
To tell that the script failed, return non-zero exit(). sys.exit(e)
returns the message e “division by zero
” and exit code:1
.
Note that stdout “Hello from custom.py” is only shown when Failed.Add those lines to .pre-commit-config.yaml
. With those settings, python will run the custom script.
- repo: local
hooks:
- id: custom-script-py
name: custom-script-py
entry: python custom.py
language: python
pass_filenames: false
To test the config, run:
pre-commit run --all-files
Output will be like:
custom-script-py..................................Failed
- hook id: custom-script-py
- exit code: 1Hello from custom.py
division by zero
Shell Script
Example of custom.sh
file:
#!/bin/bashecho "Hello from custom.sh"expr 1 / 0
Add this to .pre-commit-config.yaml
file.
- repo: local
hooks:
- id: custom-script-sh
name: custom-script-sh
entry: custom.sh
language: script
pass_filenames: false
Output will be like:
custom-script-sh..................................Failed
- hook id: custom-script-sh
- exit code: 2Hello from custom.sh
expr: division by zero
Summary
I have shown examples to run custom Python and Shell scripts with pre-commit.