Kedar Shinde
Kedar Shinde

Reputation: 429

How to run custom shell script file before pre commit hook

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.

Upvotes: 37

Views: 38897

Answers (1)

RafalS
RafalS

Reputation: 6334

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

Upvotes: 59

Related Questions