tommarshall
tommarshall

Reputation: 2128

How to open terminal editor from within `commit-msg` git hook

I have a commit-msg hook that validates the contents of the commit message.

If that check fails I want to re-open the commit message file my terminal editor so that I can correct the mistake.

I have the following, which prompts the user when the validation fails.

#!/usr/bin/env bash

COMMIT_MSG_FILE="$1"

# If we have a STDIN, use it, otherwise get one
if tty >/dev/null 2>&1; then
  TTY=$(tty)
else
  TTY=/dev/tty
fi

while true; do

  # read lines from file
  COMMIT_MSG_LINES=()
  while IFS= read -r; do
    COMMIT_MSG_LINES+=("$REPLY")
  done < <(cat $COMMIT_MSG_FILE)

  # validate - limit the subject to 50 characters
  test "${#COMMIT_MSG_LINES[0]}" -le 50 && break;

  echo -n "Validation failed. Proceed with commit [y/n]? "
  read REPLY < "$TTY"

  case "$REPLY" in
    Y*|y*) exit 0 ;;
    N*|n*) exit 1 ;;
    *)     $EDITOR $COMMIT_MSG_FILE; continue ;;
  esac

done

Any response other than YyNn should re-open the editor.

However instead, I'm getting the following error:

Received SIGHUP or SIGTERM

When I call the hook manually the script works correctly, so I assume this is something to do with the context in which the hooks are invoked.

How can I get the editor to open from within a commit-msg hook like this?

Upvotes: 4

Views: 380

Answers (1)

tommarshall
tommarshall

Reputation: 2128

Solved it. Explicitly redirecting the TTY to $EDITOR appears to work.

Replaced:

$EDITOR $COMMIT_MSG_FILE

with:

$EDITOR $COMMIT_MSG_FILE < "$TTY"

Upvotes: 1

Related Questions