How do I add clang-formatting to pre-commit hook?

Martina picture Martina · May 3, 2019 · Viewed 8.5k times · Source

I am new to commit hooks as well as Clang formatting and am attempting to integrate the two. I have the pre-commit hook set up and I know how to run the Clang formatting on the command line, but am unsure of how to add it to the file.

This is the code I run in the command line for formatting: clang-format -i -style=llvm fileName

I am also trying to run this on all files that are staged for commit. git diff --cached --name-only

This is my pre-commit file:

hook_enabled=true

# Redirect output to stderr.
exec 1>&2

# If the hook is enabled and there are one or more files added to the commit run
# code formatting.
if [ "$hook_enabled" != "false" ] &&
    test $(git diff --cached --name-only $against | wc -c) != 0
then
    cat <<\EOF
  Code formatting changed some files, please review and re-add files with git add
EOF
    exit 1

I also added the clang-formatting to package.json:

    "pre-commit": "check-clang-format",
    "format": "git-clang-format",

Please help me integrate the clang-formatting.

Answer

Benjamin picture Benjamin · Sep 4, 2019

I'm adding the following to the top of my REPO_ROOT/.git/hooks/pre-commit file:

for FILE in $(git diff --cached --name-only)
do
        clang-format -i $FILE
done

The .clang-format file is placed in the REPO_ROOT.

The other answer and the first comment to the original question doesn't say why it is preferred to avoid this solution, so I'd be happy to hear more about that.