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-formattoinstall_requiresof thesetup.py. This installs theclang-formatbinary into thedune-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 thestdinofclang-formatvia thesubprocess.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-formatstyle file in the top-level project directory. If present, use the defined style with the-style=fileoption ofclang-format. This requires thatclang-formatis executed from a shell in the directory containing the.clang-formatfile, which can be achieved by passing thecwd=<dir>argument tocheck_output().