Sunday, June 24, 2018

Skip the Pre-Commit Hook on Git Rebase or Merge

When you want to skip the git pre-commit hook for a single commit, it's easy — you just add the --no-verify flag (or -n for short) to the git commit command:

git commit --no-verify

But to skip multiple commits executed by another git command, like rebase or merge, the --no-verify flag doesn't work. The best way I've found to skip the pre-commit hook in that case is to code the hook to check for a custom environment variable (I like to use NO_VERIFY), and skip the pre-commit logic if it's not empty. For example, the pre-commit.sh script in my Google Java Format Pre-Commit Hook has a block of code like this at the top of the file, which skips the main functionality of the pre-commit hook if the NO_VERIFY environment variable has been set to anything other than an empty string:

if [ "$NO_VERIFY" ]; then
    echo 'pre-commit hook skipped' 1>&2
    exit 0
fi

So when I want to skip that pre-commit hook when doing a complicated rebase or merge, I simply run the following commands in the same shell:

export NO_VERIFY=1
git rebase -i master # or `git merge some-branch` or whatever
export NO_VERIFY=

Monday, June 18, 2018

Google Java Format Pre-Commit Hook

My team decided to standardize on the Google Java Style Guide for formatting Java code; and not finding a drop-in git pre-commit hook for the Google Java Format library, I whipped one up and pushed it to GitHub as the Google Java Format Pre-Commit Hook project.

To use it, clone the repo, and link its pre-commit.sh script as the .git/hooks/pre-commit script in whatever project you want to use it with (or call it from your existing .git/hooks/pre-commit script, if you already have one). The script automatically downloads the Google Java Format library, and runs it over all staged .java files whenever you make a commit (and fails the commit if there are any formatting issues it can't automatically clean up).

You can skip the hook by including the --no-verify flag on an individual commit, or by setting the NO_VERIFY environment variable in your shell to be not empty prior to running a sequence of commits (like a merge or rebase). Full details for install and usage are in the project README.