Skip to content

Automatically format generated C++ code using clang-format

Description

When checking the generated code I always find myself running clang-format in my editor to comfortably read it. Since it is already generated, I think it would be a sensible addition to run a formatter on the code right after generating it. clang-format would be the obvious choice for that.

I did some fiddling with CMake and found that executing clang-format from CMake after the files have been generated is cumbersome: add_custom_command() does not work with an inplace formatting of the files because dependent files and output files must be different. So I figured it would make more sense to install the clang-format Python package and format the file contents before writing them into a file. By default, clang-format may receive standard input and will paste the formatted code into standard output. This can be conveniently collected with subprocess.check_output and the result can be written into the actual file.

Proposal

  • Add clang-format to install_requires of the setup.py. This installs the clang-format binary into the dune-env, making sure that it's always available.
  • In generate_file(), do not write directly into a file but into a long string. Pass this string to the stdin of clang-format via the subprocess.check_output() function. Then write its output into the actual file.
  • Define a default formatting style, e.g., Mozilla.
  • Check for the presence of a .clang-format style file in the top-level project directory. If present, use the defined style with the -style=file option of clang-format. This requires that clang-format is executed from a shell in the directory containing the .clang-format file, which can be achieved by passing the cwd=<dir> argument to check_output().