0

git clang-format is a handy tool to run clang-format on only the lines touched by a git patch. I want to stop myself accidentally committing and pushing patches that I've forgotten to run git-clang-format on. E.g. by adding a check to .git/hooks/pre-commit that makes sure git clang-format HEAD~1 has nothing to do. However it doesn't look like the return code ever changes.

clang-format itself has --dry-run -Werror: Can clang-format tell me if formatting changes are necessary?

Unfortunately it doesn't look like git-clang-format supports it, or has a way to forward on the argument. Is there a programmatic way to know if there are changes?

$ git clang-format -Werror --diff HEAD~1 -q
usage: git clang-format [OPTIONS] [<commit>] [<commit>] [--] [<file>...]
git-clang-format: error: unrecognized arguments: -Werror
jozxyqk
  • 16,424
  • 12
  • 91
  • 180
  • Given that [git-clang-format is a simple Python program](https://github.com/llvm-mirror/clang/blob/aa231e4be75ac4759c236b755c57876f76e3cf05/tools/clang-format/git-clang-format#L167-L181), you could easily *add* some kind of exit-status option to it. Take a look at the lines in the link. – torek Oct 14 '22 at 23:57
  • There's an idea. Thanks for the link! – jozxyqk Oct 15 '22 at 04:58

2 Answers2

0

As a workaround, I'm checking stdout to see if there were no changes in a --diff:

# Use -q to suppress 'no changes' message and then grep for any lines printed
git clang-format --diff HEAD~1 -q | grep '^' --color=never

# Alternative: use awk to search for the 'no changes' messages and return the result
# This is a bad because the message could change in future versions
git clang-format --diff HEAD~1 | awk '/^no modified files to format|^clang-format did not modify any files/{result=1;}/^/{print} END{ exit !result}'

Since both use a pipe, color in the diff is removed. To keep color in the output during a .git/hooks/pre-commit hook I'm running it twice... :(

#!/bin/bash
git clang-format --diff HEAD~1 -q
if git clang-format --diff HEAD~1 -q | grep -m 1 '^' >/dev/null; then
    echo >&2 "Failed clang-format check. Run: git clang-format HEAD~1"
    exit 1
fi
jozxyqk
  • 16,424
  • 12
  • 91
  • 180
0

git-clang-format now returns error code 1

You should update your LLVM installation.

Fabian Keßler
  • 563
  • 3
  • 12