Creating a pre-commit hook#
Create a Python file in the src/ansys/pre_commit_hooks directory. For example,
new_hook.py
, with a main function:def main(): print("New hook!") return 0 if __name__ == "__main__": main()
Note
The
main
function of the hook must return a non-zero exit code if the hook fails. For the hooks in the Ansys Pre-Commit Hooks repository, the exit code is set to 1 if the hook fails and 0 if the hook passes.Create a Python file to test the hook in the tests directory. For example,
test_new_hook.py
.Add the hook to the
.pre-commit-hooks.yaml
file:- id: "new-hook" name: "New Hook" description: "A new pre-commit hook for the Ansys Pre-Commit Hooks repository" entry: new-hook language: python
In the
.pre-commit-hooks.yaml
file, you can include additional information about the hook in thefiles
,requires-serial
, orpass_filenames
fields. For more information, see the Creating new hooks page in thepre-commit
documentation.Add the hook to the
entry_points
dictionary in thesetup.py
file:entry_points = { "console_scripts": [ "new-hook = ansys.pre_commit_hooks.new_hook:main", ], },
After adding code to the pre-commit hook file, for example,
new_hook.py
, add the hook’s required dependencies to thepyproject.toml
andsetup.py
files if they are not already there:In the
pyproject.toml
file, add the dependency in therequires
list under the[build-system]
section, pinning the dependency to a specific version:[build-system] requires = [ "setuptools>=42.0", "GitPython==3.1.44", ]
In the
setup.py
file, add the dependency to theinstall_requires
list, pinning the dependency to a specific version:install_requires = [ "GitPython==3.1.44", "importlib-metadata==8.6.1", ]