Search code examples
gitclang-format

Can clang-format tell me if formatting changes are necessary?


Is there an way that you can run clang-format in a mode where it reports if the file meets the specified format? A kind of dry-run mode where it reports if a change is needed, but doesn't make the change. Ideally I'd like clang-format to just return a non-zero exit code if the file needs changes. Or, even more ideally, a non-zero exit code and a list of the files that need changes on standard output.

I'm trying to keep the question generic, so that more people can answer, but what I am trying to do is write a git pre-commit hook that will reject any commits that don't match the expected .clang-format . It's easy to run clang-format on the list of files in the index. But it's hard to know if clang-format actually changed anything.

I have one potential solution based on -output-replacements-xml (that I will post as an answer), but it's a hack and I feel like this should be more straightforward. Comments/suggestions, edits, different answers/approaches are all welcome.


Solution

  • Starting with clang-format-10, you can use the --dry-run and -Werror command line options. They will cause ClangFormat to output any formatting violations to stdout and return a non-zero exit status if any input file was not correctly formatted.

    $ clang-format --dry-run --Werror foo.cpp
    foo.cpp:129:23: error: code should be clang-formatted [-Wclang-format-violations]
            if (rc <= 0) {
    $ echo $?
    1
    

    Originally from my website here: https://rigtorp.se/notes/clang-format/