如何在预提交钩子之前运行自定义外壳脚本文件

时间:2019-12-27 10:05:42

标签: 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

但是它行不通。

1 个答案:

答案 0 :(得分:0)

在这里,您可以使用内联bash命令作为预提交的钩子条目

- 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