How to run custom shell script file before pre commit hook
Asked Answered
B

1

35

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.

Bangka answered 27/12, 2019 at 10:5 Comment(2)
But it wouldn't worked could you be more specific? How did you test that it doesn't work? Any error output?Shellishellie
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)Lownecked
S
55

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

Shellishellie answered 27/12, 2019 at 10:42 Comment(3)
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.Bangka
I have edited the question. Please again check. Third way did not worked.Bangka
Inline one: entry: bash -c 'lines=$(pylint api/ | wc -l) && (( lines > 10)) && exit 1' did not worked.Bangka

© 2022 - 2024 — McMap. All rights reserved.