Skip to content

Setup pre commit hook to format code

Razvan Stancioiu edited this page Jan 23, 2021 · 2 revisions

Setup pre-commit hook to format C++ code with clang-format

Check the version of Clang Format that it is already in cache: sudo apt-cache search clang-format.

Take the most recent version (at the time of the creation of the page clang-format-11) sudo apt-get install clang-format-11.

Create a .clang-format file at the root of the repository.

Create a file called "pre-commit" inside ".git/hooks" folder. This script, as shown in the example "pre-commit.sample", will be called before writing the commit message, so we can safely modify it to format the files that we want. The content of the file should do the following:

#!/bin/sh

# Search all the file with the extension *.hpp and *.cpp in the
# local repository and format them.
exec find . -iname *.hpp -o -iname *.cpp | xargs clang-format-11 -i

# As the modificated files are not directly added to the commit,
# we need to add them
exec git add *.cpp *.hpp

Clone this wiki locally