Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save qrealka/d0112f4f8a92f597e826267fc51c8292 to your computer and use it in GitHub Desktop.
Save qrealka/d0112f4f8a92f597e826267fc51c8292 to your computer and use it in GitHub Desktop.
#!/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 https://raw.githubusercontent.com/llvm-mirror/clang/master/tools/clang-format/git-clang-format > /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 clangFormat.style file
EOF
check_clang_format() {
if hash git-clang-format 2>/dev/null; then
return
else
echo "SETUP ERROR: no git-clang-format executable found, or it is not executable"
echo "$help"
exit 1
fi
}
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 clangFormat.style)" != "file" ]]; then
echo "SETUP ERROR: git config clangFormat.style is wrong."
echo "$help"
exit 1
fi
}
check_clang_format
check_git_config
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