使用 python 库“预提交”,如何添加运行单个 python 文件的 git 预提交挂钩?

Ros*_*sey 3 git pre-commit-hook pre-commit.com

我正在使用这个库来尝试向我的项目添加预提交挂钩。有很多需要考虑的内容,我认为我想要的预提交检查不需要他们大多数示例使用的大范围。我想做的就是运行一个 python 文件。我想要允许或禁止提交取决于该文件是否退出/完成而没有问题(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"

Run Code Online (Sandbox Code Playgroud)

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

Ant*_*ile 6

八九不离十!有两种方法可以实现此目的:

  1. 将“shebang”( #!/usr/bin/env python) 添加到您的文件中
    • 尽管 shebangs 是 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
    
    Run Code Online (Sandbox Code Playgroud)

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