Creating a pre-commit hook#

  1. 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.

  2. Create a Python file to test the hook in the tests directory. For example, test_new_hook.py.

  3. 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 the files, requires-serial, or pass_filenames fields. For more information, see the Creating new hooks page in the pre-commit documentation.

  4. Add the hook to the entry_points dictionary in the setup.py file:

    entry_points = {
        "console_scripts": [
            "new-hook = ansys.pre_commit_hooks.new_hook:main",
        ],
    },
    
  5. After adding code to the pre-commit hook file, for example, new_hook.py, add the hook’s required dependencies to the pyproject.toml and setup.py files if they are not already there:

    In the pyproject.toml file, add the dependency in the requires 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 the install_requires list, pinning the dependency to a specific version:

    install_requires = [
        "GitPython==3.1.44",
        "importlib-metadata==8.6.1",
    ]