Skip to content

Instantly share code, notes, and snippets.

@jasonk
Last active February 6, 2023 23:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonk/69238f98d09ff8e381fd054abc0b5936 to your computer and use it in GitHub Desktop.
Save jasonk/69238f98d09ff8e381fd054abc0b5936 to your computer and use it in GitHub Desktop.
Pull request message hooks for hub

I'm a big fan of hub, but I found myself wishing for the ability to use git hooks on pull-request messages the same way you can on commit messages with prepare-commit-msg and commit-msg hooks. People have been asking for hub to be able to do this for a while, but until that happens, here is a way you can do it yourself, right now.

To use this, just drop the script below into your $PATH somewhere, and make sure you have your $EDITOR environment variable set to whatever command runs your real editor, and then set your $GIT_EDITOR environment variable to run the hub-editor script.

The way this works is that when hub-editor is invoked with a file named PULLREQ_EDITMSG (which is the filename hub uses for editing pull requests) then it will run the prepare-pull-request-msg and pull-request-msg scripts from your .git/hooks directory (if they exist and are executable). If hub-editor is invoked with any other filename, then it just bails out to your real editor.

export EDITOR=vim
export GIT_EDITOR=hub-editor
hub pull-request
#!/bin/bash
set -euo pipefail
if [ "$(basename "$1")" != "PULLREQ_EDITMSG" ]; then
# shellcheck disable=SC2086 # we want word-splitting if $EDITOR has args
exec $EDITOR "$@"
fi
FILE="$1"
DIR="$(dirname "$FILE")"
die() { echo "$1 exited with non-zero exit code" 1>&2; exit 1; }
BEFORE="prepare-pull-request-msg"
AFTER="pull-request-msg"
if [ -x "$DIR/hooks/$BEFORE" ]; then
"$DIR/hooks/$BEFORE" "$FILE" || die "$BEFORE"
fi
"$EDITOR" "$FILE" || die "$EDITOR"
if [ -x "$DIR/hooks/$AFTER" ]; then
"$DIR/hooks/$AFTER" "$FILE" || die "$AFTER"
fi
#!/bin/bash
# This is an example of a prepare-pull-request-msg hook you can put into a repos .git/hooks directory.
# It searches for a pull_request_template.md file and if one is found prepends it to the pull-request message.
# See https://help.github.com/en/articles/creating-a-pull-request-template-for-your-repository
FILE="$1"
DIR="$(dirname "$FILE")"
TOPDIR="$(dirname "$DIR")"
TEMPLATES=(
"pull_request_template.md"
"docs/pull_request_template.md"
".github/pull_request_template.md"
)
TMPL=""
for T in "${TEMPLATES[@]}"; do
if [ -f "$TOPDIR/$T" ]; then
TMPL="$T";
break
fi
done
if [ -n "$TMPL" ]; then
cp "$FILE" "$FILE.bak"
(
cat "$TOPDIR/$TMPL"
cat "$FILE.bak"
) > "$FILE"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment