Feature request: Universal enforcement of CMake script formatting

Hi,

I think official enforcement of “correct” CMake code formatting would make reading and writing CMake code significantly faster and easier. I’d like to see a tool from Kitware that ships with CMake and can be run on a CMake file to make it comply with Kitware’s official style guidelines for CMake code format. I’d even go so far as to have CMake complain about formatting at configuration-time.

Motivation:

  • I wish I had auto-formatting tools when writing CMake code,
  • I really wish other developers in my company had auto-formatting tools when writing CMake code,
  • I think arguing about CMake formatting guidelines is a form of bikeshedding - I’d rather not think about it and blindly follow the official guidelines,
  • If you google “CMake coding style”, the first three results are from KDE, ROS, and Jetbrains. I bet they wish they could stop publishing guidelines and just say “use the official tool”,
  • In this talk, Chandler Carruth (Google DevOps, C++ standards committee, all-round smart guy) says “[clang-format, a C++ auto-formatting tool, is] the single largest improvement in your productivity as a developer”. I think the same might apply to CMake.

Caveats:

  • If Kitware choose different standardisations to existing codebases, they might be upset. If there’s an auto-formatting tool then maybe they won’t be very upset,
  • I’m aware of tools like this, which are a great start, but I’d like to see greater adoption and more universality,
  • I’m not a CMake developer, nor have I ever written any lexing/parsing code, so I have no idea how much effort this entails.

Thanks,
Tom

CMake’s…loose syntax makes this very hard. Knowing whether a function argument is a keyword or not, how many arguments it takes after that, etc. is really hard. Not to mention what kind of effects quoting or variable expansions have at various places, etc. “Standard” commands could probably have some standard syntax formatting since the argument sets are “known”, but user-defined commands can have all kinds of logic applied to them.

FWIW, my rules are basically along the lines of:

  • 2 space indent
  • spaces after “control flow” commands (if, else, function, while, return, continue, end*, etc.), otherwise no space
  • quote all variable expansions except:
    • when if cares
    • when it is a list of arguments
  • for argument blocks, vertical alignment is good (whether hanging indents or not)

Not to discourage anyone else from trying, but figuring out how to apply these rules to arbitrary code is not something I think is a good use of my time at least.