使用 python 库 "pre-commit",如何添加运行单个 python 文件的 git 预提交挂钩?

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

我正在使用 this 库尝试向我的项目添加预提交挂钩。要接受的内容很多,我认为我想要的预提交检查不需要他们的大多数示例使用的大范围。我只想 运行 一个 python 文件。取决于该文件 exited/finished 是否没有问题(IE 没有引发异常)是我想要允许或禁止提交的内容。我制作了一个 .pre-commit-config.yaml,但我不知道如何将它制作成 运行 只有一个文件。

我基本上想输入 git commit -m "whatever" 以自动 运行 python myfile.py <- 并根据此退出代码允许或阻止提交。知道我的 yaml 应该是什么样子吗?

这是我目前的情况:

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"

但我收到以下错误:.An unexpected error has occurred: OSError: [WinError 193] %1 is not a valid Win32 application 我认为是因为它期望此 .py 文件是 .exe 或其他内容,即使我将 language 设置为 python。 ..

非常接近!有两种方法可以完成这项工作:

  1. 将 "shebang" (#!/usr/bin/env python) 添加到您的文件
    • 尽管 shebang 是 posix 的东西,pre-commit 包含规范化平台并使它们在 windows 上也能工作的代码!
  2. 使用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
    

(免责声明:我是 pre-commit 的作者)