Rosey
Rosey

Reputation: 821

Using the python library "pre-commit", how can I add a git pre-commit hook that runs a single python file?

I am using this library to try and add a pre-commit hook to my project. It's a lot to take in and I don't think the pre-commit check I want needs the large scope most of their examples use. All I want to do, is run a single python file. Depending on if that file exited/finished without issue (IE no exceptions raised) is what I want to allow or disallow commits on. I have made a .pre-commit-config.yaml but I don't know how to make it run only a single file.

I basically want typing git commit -m "whatever" to automatically run python myfile.py <- and based on the exit code of this, allow or prevent a commit. any idea on what my yaml should look like?

Here is what I have so far:

repos:
-   repo: local
    hooks:
    - id: translation-file-check
      name: Check Translation Files Are Aligned
      description: This hook ensures that all translation files share the same set of keys and generates a CSV if there are no issues
      language: python
      entry: "./dir/subdir/myfile.py"

But I get the following error: .An unexpected error has occurred: OSError: [WinError 193] %1 is not a valid Win32 application I think because it is expecting this .py file to be a .exe or something even though I set language to python...

Upvotes: 3

Views: 1963

Answers (1)

anthony sottile
anthony sottile

Reputation: 69824

pretty close! there's two ways to make this work:

  1. add a "shebang" (#!/usr/bin/env python) to your file
    • even though shebangs are a posix thing, pre-commit contains code which normalizes platforms and makes them work on windows as well!
  2. use entry: python ./dir/subdir/myfile.py

    repos:
    -   repo: local
        hooks:
        - id: translation-file-check
          name: Check Translation Files Are Aligned
          description: This hook ensures that all translation files share the same set of keys and generates a CSV if there are no issues
          language: python
          entry: python ./dir/subdir/myfile.py
    

(disclaimer: I am the author of pre-commit)

Upvotes: 7

Related Questions