32

In my python project, I have pre-commit-config.YAML where I want to create my custom file.

The intention of this file is fail git commit if python lint errors are greater than certain numbers. The following command will be used to count lines

pylint api/ | wc -l

Can someone please suggest some approach. I am new to the MAC and Python ecosystem?

EDIT sh file looks like this.

#!/bin/sh
a=$(pylint source/ | wc -l)
b=20

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

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

I tried

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

But it wouldn't worked.

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
Kedar Shinde
  • 379
  • 1
  • 4
  • 5
  • 1
    `But it wouldn't worked` could you be more specific? How did you test that it doesn't work? Any error output? – RafalS Dec 27 '19 at 13:04
  • guessing, your "wouldn't worked" is that it's being `Skipped`? try it with `--all-files` or by setting `always_run: true` (if you want it to always run) – anthony sottile Dec 27 '19 at 17:56

1 Answers1

46

Here's what you could do to use inline bash command as pre-commit hook entry

- 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

You can also write a script and invoke it this way:

      entry: path/relavite/to/repo/root/pylint_validator.sh
      language: script

NOTE: wc -l is not an accurate count of errors.

EDIT: adding more options

- 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

RafalS
  • 5,834
  • 1
  • 20
  • 25
  • Thank you for your answer. Can you let me know it using a pluggable script file? I would be adding more checks. I will verify it and mark it as an answer later. I appreciate your help. – Kedar Shinde Dec 27 '19 at 10:44
  • I have edited the question. Please again check. Third way did not worked. – Kedar Shinde Dec 27 '19 at 11:02
  • Inline one: entry: bash -c 'lines=$(pylint api/ | wc -l) && (( lines > 10)) && exit 1' did not worked. – Kedar Shinde Dec 27 '19 at 11:13