Skip to content

Instantly share code, notes, and snippets.

@jonchurch
Created July 11, 2023 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonchurch/5443e1790f194370eb546cf76a13508a to your computer and use it in GitHub Desktop.
Save jonchurch/5443e1790f194370eb546cf76a13508a to your computer and use it in GitHub Desktop.
#!/bin/sh
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to abort the commit.
#
# Will skip linting if the commit is a merge commit
# to avoid introducing formatting diffs on already committed code
PATH=$PATH:/usr/local/bin:/usr/local/sbin
echo --------------------------------------------
echo Starting Git hook: pre-commit
# Check if this is a merge commit
if git rev-parse --verify MERGE_HEAD >/dev/null 2>&1; then
echo "This is a merge commit, skipping lint..."
exit 0
fi
echo Invoking node scripts/precommit
node scripts/precommit
@jonchurch
Copy link
Author

MERGE_HEAD is akin to HEAD, they are pseudorefs which live in the git dir.

Specifically for MERGE_HEAD, its presence is how git internals determine if we are in the middle of a merge. It should point to the commit we are merging into our branch (that's the simple version, at least).

The command git rev-parse takes commit-ish objects and resolves their SHA. MERGE_HEAD is a commitish, but we don't really care about the SHA, just the command's exit code.

That's where --verify comes in, it will ensure the object we pass the command exists and points to a valid commit. Not super important for our usecase, since we just want to stop the precommit hook when MERGE_HEAD is present, not necessarily when it is valid. Verify helps us determine if we have a valid MERGE_HEAD present.

That does represent an edgecase for our use, if the user does have a MERGE_HEAD but it is invalid, the command would exit 1, and we'd run our precommit hook. Verify is very commonly used with rev-parse for its validation feature and predictable exit if something is amiss. Users should not have invalid MERGE_HEAD unless something went really really wrong, and they'd have to likely manually delete it to fix the situation.

As for references, the git docs don't have a page just for MERGE_HEAD, or HEAD, since it's considered an internal, but it is something that is commonly used for determining if a merge in in process. Because git itself uses that pseudoref to do so. You can see references to it on the merge docs and sprinkled throughout the docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment