gitgit-commitgithookspre-commit-hook

Issues with commit message when pre-commit hook changes files


I have prepared the following pre-commit hook:

#!/bin/sh

# Run flake8 and mypy
flake8 ./src
FLAKE8_EXIT_CODE=$?

mypy ./src
MYPY_EXIT_CODE=$?

# If either flake8 or mypy return an error, skip black and the commit process
if [ $FLAKE8_EXIT_CODE -ne 0 ] || [ $MYPY_EXIT_CODE -ne 0 ]; then
  echo "flake8 or mypy checks failed. Skipping black and commit."
  exit 1
fi
black .
git add -u

if ! git diff-index --quiet HEAD; then
  git commit --no-verify -m "Same message all the times!"
fi

Note that black . reformat the files and therefore I have a second git add -u. To avoid infinite recursions, I added a last check that git commit with --no-verify, but then the commit message is the same for every commit and I like to avoid it. Instead, I want to be prompted for a commit message when I enter the last if branch. I tried to use read command inside the last if branch but with no success. I would also like to avoid external tools as pre-commit, but I would rather a native solution, if possible.

How to fix it?


Solution

  • I'd suggest to do the same for black as for pyflakes and mypy: run it as a checker, and refuse the commit if the checker fails, but don't actually reformat the code. So you'll always have to run black manually, but it won't reformat files without you seeing and knowing it.

    black --check .
    

    can do that (you can send the output of that check to /dev/null to reduce commit-hook noise if you want to). It (also) returns a non-zero value when the check fails, indicating black would reformat the code.


    But for what you specifically want, perhaps

    git commit --no-verify --amend --no-edit
    

    does that: it keeps the last commit message by amending the current commit (and doesn't open an editor for adjusting the commit message).