qgadrian/elixir_git_hooks

Returning non-zero status code from executable script for commit-msg hook does not abort git commit

djantea opened this issue · 1 comments

Hi,

In the Git documentation for commit-msg git hook it says that "Exiting with a non-zero status causes the command to abort".

But if I configure elixir_git_hooks as follows:

config/config.exs:

config :git_hooks,
    verbose: true,
    hooks: [
      commit_msg: [
        tasks: [
          {:file, "./priv/conv_commit_msg_check.sh", include_hook_args: true}
        ]
      ]
    ]

./priv/conv_commit_msg_check.sh:

#!/bin/sh
MSG_FILE=$1
MSG_HEAD=$(head -1 $MSG_FILE)

export REGEX='^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([a-z]+\))?: [a-z ]+$'
export ERROR_MSG="Commit message format must match regex \"${REGEX}\""

if [[ ! $MSG_HEAD =~ $REGEX ]]; then
  echo "Bad commit head \"$MSG_HEAD\""
  echo $ERROR_MSG
  exit 1
fi

exit 0

When I commit with an invalid message, I get:

↗ Running hooks for :commit_msg
Bad commit head "Ok."
Commit message format must match regex "^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([a-z]+\))?: [a-z ]+$"
[master 631f559] Ok.
 2 files changed, 26 insertions(+), 1 deletion(-)
 create mode 100755 priv/conv_commit_msg_check.sh

So, the git hook script works (it prints "Bad commit head"), but the commit is not aborted.

This is because elixir_git_hooks is running mix git_hooks.run commit_msg "$@", but as far as I know, mix <task> will always return 0 status code even when you do exit(1) from your code in Mix.Tasks.<task>.run(_).

The only way to force mix <task> to return a non-zero return code is to raise an error from the mix task run(_) function.

So I guess that changing the call to error_exit() from lib/mix/tasks/git_hooks/run.ex#L138 to instead raise an exception will fix this, at least in the case of commit-msg git hook. But I am not sure if this is OK for the other git-hooks.

Thank you,
Dan

Hey @djantea thank you for the report 🙌

Mix tasks can indeed return an exit code. The problem is when running a script file the lib was missing matching the exit code for the execution.

I publish a new release with a fix.