python - 如何在预提交 Hook 之前运行自定义 shell 脚本文件

标签 python git pre-commit-hook pre-commit pre-commit.com

在我的 python 项目中,我有 pre-commit-config.YAML,我想在其中创建我的自定义文件。

如果 python lint 错误大于特定数字,则此文件的目的是使 git commit 失败。以下命令将用于计算行数

pylint api/ | wc -l

有人可以建议一些方法。我是 MAC 和 Python 生态系统的新手?

编辑
sh 文件看起来像这样。
#!/bin/sh
a=$(pylint source/ | wc -l)
b=20

errorsCount="$(echo "${a}" | tr -d '[:space:]')"

if [ $errorsCount -gt $b ]
then
    exit 1
fi

我试过
repos:
- repo: local
  hooks:
    - id: custom-script-file
      name: custom-script-file
      entry: hooks/pre-commit.sh
      language: script
      types: [python]
      pass_filenames: false

但它不会奏效。

最佳答案

以下是使用内联 bash 命令作为预提交 Hook 条目的方法

- repo: local
  hooks:
    - id: pylint-error-count
      name: pylint-error-count
      entry: bash -c 'lines=$(pylint api/ | wc -l) && (( lines > 10)) && exit 1'
      language: system
      types: [python]
      pass_filenames: false

您还可以编写脚本并以这种方式调用它:
      entry: path/relavite/to/repo/root/pylint_validator.sh
      language: script

注意:wc -l不是准确的错误计数。

编辑:添加更多选项
- repo: local
  hooks:
    - id: simple-pylint
      name: simple-pylint
      entry: pylint
      args: ["api/"]
      language: system
      types: [python]
      pass_filenames: false

    - id: inline-pylint-with-bash
      name: inline-pylint-with-bash
      entry: bash -c 'lines=$(pylint api/ | wc -l) && (( lines > 10)) && exit 1'
      language: system
      types: [python]
      pass_filenames: false

    - id: custom-script-file
      name: custom-script-file
      entry: relative/path/to/repo/root/check_pylint.sh
      language: script
      types: [python]
      pass_filenames: false

关于python - 如何在预提交 Hook 之前运行自定义 shell 脚本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59499061/

相关文章:

python - NumPy 数组中滑动窗口中的最大值

python - pygame中移动 Sprite 之间的碰撞

git - 为什么暂存目录也叫 Index/Git Index?

git 总是在列中显示分支

git - 是否可以在一个Git项目的所有分支中执行一个 'grep search'?

typescript-eslint/预提交 Hook (monorepo): Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser

python - opencv和picamera(V2)在高分辨率下出现白/蓝平衡错误

python - 使用 Flask 和 RotatingFileHandler 进行原子日志文件轮换

bash - Windows 上的 Git 预提交 bash 脚本

git pre-commit 钩子(Hook)代码格式化与部分提交?