Skip to content

Add code formatting checker and enforcement in CI

Daniel Joseph Antrim requested to merge dantrim_enforce_code_formatting into devel

What

This MR adds code style formatting based on clang-format.

Getting clang-format

A relevant and up-to-date version of clang-format can be installed to your machine using pip, which just picks out the relevant source files from the Clang repositories that are relevant for the clang-format utility.

Style Definitions

The code formatting is defined in the .clang-format file located in the repository's top-level. It is based on the Google formatting and generated via clang-format itself:

$ clang-format --style=Google --dump-config

Checking the code formatting locally

A user can use the script run-clang-format.py (from Sarcasm/run-clang-format) located under the ci/ directory,

$ ./ci/run-clang-format.py -r ./src/

which will print to the screen the git-styled diffs showing which changes are required (and for which files) in order to make that code satisfy the formatting rules.

Checking the code formatting in the CI

This MR adds a new step in the CI process, called format_check. It runs the following command:

$ ./ci/run-clang-format.py -r ./src/ ./arduino/ --extensions c,h,cpp,hpp,cxx,hxx,ino

If files are found that do not satisfy the formatting rules, the format_check stage of the CI will fail.

In order to fix the CI failing (if it is), users can inspect the CI logs and/or simply run the run-clang-format.py script locally to see which files are in issue.

Applying the code formatting rules to code

By supplying the -i option to the ./ci/run-clang-format.py script, changes will be applied in place to any of the files not satisfying the formatting rules. So if you find that the format_check stage of the CI is failing, you can simply run

$ ./ci/run-clang-format.py -r ./src/ ./arduino/ --extensions c,h,cpp,hpp,cxx,hxx,ino -i
$ git add <changed files>
$ git push <remote>

Ignoring files in the format checking

The ./ci/run-clang-format.py script checks the .clang-format-ignore file for any files and or patterns to exclude from the matching.

TODO

  • Remove cpplint usage, and rely only on run-clang-format
  • Define .clang-format-ignore to specify "exclude" list from the format checking, as opposed to burying the "exclude" list in bash/check_format.sh

Related issues/MR

MR !24 (closed)

Edited by Daniel Joseph Antrim

Merge request reports