clang-format is an auto code formatter. I use it for C/C++ projects.
Some options for fomatting specified in .clang-format file don't work for versions 10 and below. Most of the linux PCs use Ubuntu which packages this software based on Ubuntu OS version. And even the latest Ubuntu OS version might not include the latest clang-format software version. Thus the options in the format file will be unrecognized when running on a system which has older clang-format software.
Solution: docker
I came across a well maintained, frequently updated, permissive Apache 2.0 licensed docker image xianpengshen/clang-tools which has all the latest versions of clang-format (versions 17, 18, etc.).
Format 1 file -
docker run --volume $PWD:/src --user $UID xianpengshen/clang-tools:18 clang-format -i list.cNotes -
--volume-> lets docker to access your filesystem$PWD:/src-> I don't understand this part--user $UID-> If you don't specify this then the file after the formatting changes will have changed ownership (that ofrootuser). You won't be able to make further changes to the file created asrootuser unless you runsudo chown [...]. This option keeps the current user of the system as the owner of the file.xianpengshen/clang-tools:18-> use version 18 for clang-format from this docker image. It will pull the image if not found on your system. And since we already use tizenrt docker image to build our code, therefore, I assume that docker is already installed and your USER is in docker group or you have sudo rights.-i-> change the file inplace instead of outputting on stdout.- Use version 18 to detect
.clang-format-ignorefile. I don't know why but I couldn't achieve it using version 17, although it should be achievable.
Format all files (.c, .cpp and .h) recursively from current directory -
find . -name "*.cpp" -o -name "*.c" -o -name "*.h" | xargs -I {} docker run --volume $PWD:/src --user $UID xianpengshen/clang-tools:17 clang-format -i {}- partially taken from a blog post
- partially taken from stackoverflow
The above method is local-only usage. You can do it, but you will often forget it. Therefore, we need a bot to do it. However, it should not do it for all the commits because otherwise it will be hectic to git pull everytime after git push on one branch. So, I would like to run it only on PRs.
- clang-format-lint -> runs clang-format on files
- add-commit -> commits the result
Sample PR on my public github repo -
In this PR, see the github workflow file, the .clang-format file and .clang-format-ignore file.
- screen width size - 80 vs 120?
- clang-format still doesn't have good support for formatting initialization of elements of an array of struct one workaround this is to mark that code part for skip-formatting -
// clang-format off
my_struct array[] = { {.member1 = something1, .member2 = something2, }, {.member1 = otherthing1, .member2 = otherthing2, }, };
// clang-format on