Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
#!/usr/bin/env bash
# Runs clang-format on changed regions before commit.
# To install this, copy it to .git/hooks/pre-commit in your repo.
# Remaining installation checks/instructions will be printed when you commit.
read -d '' help <<- EOF
This repository requires you to install the git clang-format command.
One-time setup steps:
1) install the git-clang-format script in your \$PATH, for example:
curl > /usr/local/bin/git-clang-format
2) make sure git-clang-format is executable:
chmod u+x /usr/local/bin/git-clang-format
In each repository where you use clang-format, add git config keys
so that git clang-format finds your version and config:
git config clangFormat.binary node_modules/.bin/clang-format
git config file
check_clang_format() {
if hash git-clang-format 2>/dev/null; then
echo "SETUP ERROR: no git-clang-format executable found, or it is not executable"
echo "$help"
exit 1
check_git_config() {
if [[ "$(git config --get clangFormat.binary)" != "node_modules/.bin/clang-format" ]]; then
echo "SETUP ERROR: git config clangFormat.binary is wrong."
echo "$help"
exit 1
elif [[ "$(git config --get" != "file" ]]; then
echo "SETUP ERROR: git config is wrong."
echo "$help"
exit 1
readonly out=$(git clang-format -v --diff)
if [[ "$out" == *"no modified files to format"* ]]; then exit 0; fi
if [[ "$out" == *"clang-format did not modify any files"* ]]; then exit 0; fi
echo "ERROR: you need to run git clang-format on your commit"
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment