bashgitgithookspre-commit-hook

git pre-commit hook does not open commit_template based on GIT_EDITOR value


I am developing a functionality for more automatic Git commits. We are using a pre-commit hook, and the idea of the hook is to request a task ID and summary, then write them to the commit template. We also want the template to be opened with the cursor on the third line.

After the pre-commit hook execution, the template opens and everything is fine, except that the cursor is not on the third line. I have tried many different ways to achieve this, mostly with the git config core.editor command and the GIT_EDITOR variable.

In the pre-commit hook:

original_editor=$(git var GIT_EDITOR)

export GIT_EDITOR="nano +3"

Debugging lines just before the exit of the script:

# Debugging line
echo "Original editor: $original_editor"
echo "Using core.editor: $(git config --global core.editor)"  # Debugging line
echo "Using git_editor: $(git var GIT_EDITOR)"  # Debugging line

Terminal output:

Original editor: nano
Using core.editor: nano
Using git_editor: nano +3

However, the cursor is still on the first line in the commit message template.

For example, if I export GIT_EDITOR before the execution of the pre-commit hook, then it works, and the cursor is on the third line.


Solution

  • The pre-commit hook is just a gatekeeper: if the script exits with status 0, then the commit happens, and if the script exits with any other status then the commit doesn't happen. That's handy for enforcing a lot of things (such as "don't commit secrets"), but that's also all pre-commit does.

    As @phd pointed out (several times) in the comments, hooks are executed as subprocesses, so they won't have any persistent effect on the shell environment. You'll need to write an alias or shell script if you want to do what you've described.