Source code formatter for cmake listfiles.

Overview

cmake lang

https://travis-ci.com/cheshirekow/cmake_format.svg?branch=master https://readthedocs.org/projects/cmake-format/badge/?version=latest

The cmakelang project provides Quality Assurance (QA) tools for cmake:

  • cmake-annotate can generate pretty HTML from your listfiles
  • cmake-format can format your listfiles nicely so that they don't look like crap.
  • cmake-lint can check your listfiles for problems
  • ctest-to can parse a ctest output tree and translate it into a more structured format (either JSON or XML).

Installation

Install from pypi using pip:

pip install cmakelang

Or see the online documentation for additional options.

Integrations

Usage

usage:
cmake-format [-h]
             [--dump-config {yaml,json,python} | -i | -o OUTFILE_PATH]
             [-c CONFIG_FILE]
             infilepath [infilepath ...]

Parse cmake listfiles and format them nicely.

Formatting is configurable by providing a configuration file. The configuration
file can be in json, yaml, or python format. If no configuration file is
specified on the command line, cmake-format will attempt to find a suitable
configuration for each ``inputpath`` by checking recursively checking it's
parent directory up to the root of the filesystem. It will return the first
file it finds with a filename that matches '\.?cmake-format(.yaml|.json|.py)'.

cmake-format can spit out the default configuration for you as starting point
for customization. Run with `--dump-config [yaml|json|python]`.

positional arguments:
  infilepaths

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show program's version number and exit
  -l {error,warning,info,debug}, --log-level {error,warning,info,debug}
  --dump-config [{yaml,json,python}]
                        If specified, print the default configuration to
                        stdout and exit
  --dump {lex,parse,parsedb,layout,markup}
  --no-help             When used with --dump-config, will omit helptext
                        comments in the output
  --no-default          When used with --dump-config, will omit any unmodified
                        configuration value.
  -i, --in-place
  --check               Exit with status code 0 if formatting would not change
                        file contents, or status code 1 if it would
  -o OUTFILE_PATH, --outfile-path OUTFILE_PATH
                        Where to write the formatted file. Default is stdout.
  -c CONFIG_FILES [CONFIG_FILES ...], --config-files CONFIG_FILES [CONFIG_FILES ...]
                        path to configuration file(s)
usage:
cmake-lint [-h]
           [--dump-config {yaml,json,python} | -o OUTFILE_PATH]
           [-c CONFIG_FILE]
           infilepath [infilepath ...]

Check cmake listfile for lint

positional arguments:
  infilepaths

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show program's version number and exit
  -l {error,warning,info,debug}, --log-level {error,warning,info,debug}
  --dump-config [{yaml,json,python}]
                        If specified, print the default configuration to
                        stdout and exit
  -o OUTFILE_PATH, --outfile-path OUTFILE_PATH
                        Write errors to this file. Default is stdout.
  --no-help             When used with --dump-config, will omit helptext
                        comments in the output
  --no-default          When used with --dump-config, will omit any unmodified
                        configuration value.
  --suppress-decorations
                        Suppress the file title decoration and summary
                        statistics
  -c CONFIG_FILES [CONFIG_FILES ...], --config-files CONFIG_FILES [CONFIG_FILES ...]
                        path to configuration file(s)

Configuration

cmake-format accepts configuration files in yaml, json, or python format. An example configuration file is given in the online documentation. Providing the structure of your custom commands will help cmake-format to break them up in a pleasant way, and will help cmake-lint detect improper usages of them.

An example short configuration file in python format is:

# -----------------------------
# Options effecting formatting.
# -----------------------------
with section("format"):

  # How wide to allow formatted cmake files
  line_width = 80

  # How many spaces to tab for indent
  tab_size = 2

  # If true, separate flow control names from their parentheses with a space
  separate_ctrl_name_with_space = False

  # If true, separate function names from parentheses with a space
  separate_fn_name_with_space = False

  # If a statement is wrapped to more than one line, than dangle the closing
  # parenthesis on its own line.
  dangle_parens = False

You may specify a path to one or more configuration files with the --config-file command line option. Otherwise, cmake-format will search the ancestry of each infilepath looking for a configuration file to use. If no configuration file is found it will use sensible defaults.

A automatically detected configuration files may have any name that matches \.?cmake-format(.yaml|.json|.py).

If you'd like to create a new configuration file, cmake-format can help by dumping out the default configuration in your preferred format. You can run cmake-format --dump-config [yaml|json|python] to print the default configuration stdout and use that as a starting point.

Markup

cmake-format is for the exceptionally lazy. It will even format your comments for you. It will reflow your comment text to within the configured line width. It also understands a very limited markup format for a couple of common bits.

rulers: A ruler is a line which starts with and ends with three or more non-alphanum or space characters:

# ---- This is a Ruler ----
# cmake-format will know to keep the ruler separated from the
# paragraphs around it. So it wont try to reflow this text as
# a single paragraph.
# ---- This is also a Ruler ---

list: A list is started on the first encountered list item, which starts with a bullet character (*) followed by a space followed by some text. Subsequent lines will be included in the list item until the next list item is encountered (the bullet must be at the same indentation level). The list must be surrounded by a pair of empty lines. Nested lists will be formatted in nested text:

# here are some lists:
#
# * item 1
# * item 2
#
#   * subitem 1
#   * subitem 2
#
# * second list item 1
# * second list item 2

enumerations: An enumeration is similar to a list but the bullet character is some integers followed by a period. New enumeration items are detected as long as either the first digit or the punctuation lines up in the same column as the previous item. cmake-format will renumber your items and align their labels for you:

# This is an enumeration
#
#   1. item
#   2. item
#   3. item

fences: If you have any text which you do not want to be formatted you can guard it with a pair of fences. Fences are three or more tilde characters:

# ~~~
# This comment is fenced
#   and will not be formatted
# ~~~

Note that comment fences guard reflow of comment text, and not cmake code. If you wish to prevent formatting of cmake, code, see below. In addition to fenced-literals, there are three other ways to preserve comment text from markup and/or reflow processing:

  • The --first-comment-is-literal configuration option will exactly preserve the first comment in the file. This is intended to preserve copyright or other formatted header comments.
  • The --literal-comment-pattern configuration option allows for a more generic way to identify comments which should be preserved literally. This configuration takes a regular expression pattern.
  • The --enable-markup configuration option globally enables comment markup processing. It defaults to true so set it to false if you wish to globally disable comment markup processing. Note that trailing whitespace is still chomped from comments.

Disable Formatting Locally

You can locally disable and enable code formatting by using the special comments # cmake-format: off and # cmake-format: on.

Sort Argument Lists

Starting with version 0.5.0, cmake-format can sort your argument lists for you. If the configuration includes autosort=True (the default), it will replace:

add_library(foobar STATIC EXCLUDE_FROM_ALL
            sourcefile_06.cc
            sourcefile_03.cc
            sourcefile_02.cc
            sourcefile_04.cc
            sourcefile_07.cc
            sourcefile_01.cc
            sourcefile_05.cc)

with:

add_library(foobar STATIC EXCLUDE_FROM_ALL
            sourcefile_01.cc
            sourcefile_02.cc
            sourcefile_03.cc
            sourcefile_04.cc
            sourcefile_05.cc
            sourcefile_06.cc
            sourcefile_07.cc)

This is implemented for any argument lists which the parser knows are inherently sortable. This includes the following cmake commands:

  • add_library
  • add_executable

For most other cmake commands, you can use an annotation comment to hint to cmake-format that the argument list is sortable. For instance:

set(SOURCES
    # cmake-format: sortable
    bar.cc
    baz.cc
    foo.cc)

Annotations can be given in a line-comment or a bracket comment. There is a long-form and a short-form for each. The acceptable formats are:

Line Comment long # cmake-format: <tag>
Line Comment short # cmf: <tag>
Bracket Comment long #[[cmake-format: <tag>]]
Bracket Comment short #[[cmf: <tag>]]

In order to annotate a positional argument list as sortable, the acceptable tags are: sortable or sort. For the commands listed above where the positinal argument lists are inherently sortable, you can locally disable sorting by annotating them with unsortable or unsort. For example:

add_library(foobar STATIC
            # cmake-format: unsort
            sourcefile_03.cc
            sourcefile_01.cc
            sourcefile_02.cc)

Note that this is only needed if your configuration has enabled autosort, and you can globally disable sorting by making setting this configuration to False.

Custom Commands

Due to the fact that cmake is a macro language, cmake-format is, by necessity, a semantic source code formatter. In general it tries to make smart formatting decisions based on the meaning of arguments in an otherwise unstructured list of arguments in a cmake statement. cmake-format can intelligently format your custom commands, but you will need to tell it how to interpret your arguments.

Currently, you can do this by adding your command specifications to the additional_commands configuration variables, e.g.:

# Additional FLAGS and KWARGS for custom commands
additional_commands = {
  "foo": {
    "pargs": 2,
    "flags": ["BAR", "BAZ"],
    "kwargs": {
      "HEADERS": '*',
      "SOURCES": '*',
      "DEPENDS": '*',
    }
  }
}

The format is a nested dictionary mapping statement names (dictionary keys) to argument specifications. For the example specification above, the custom command would look something like this:

foo(hello world
    HEADERS a.h b.h c.h d.h
    SOURCES a.cc b.cc c.cc d.cc
    DEPENDS flub buzz bizz
    BAR BAZ)

Reporting Issues and Getting Help

If you encounter any bugs or regressions or if cmake-format doesn't behave in the way that you expect, please post an issue on the github issue tracker. It is especially helpful if you can provide cmake listfile snippets that demonstrate any issues you encounter.

You can also join the #cmake-format channel on our discord server.

Developers

If you want to hack on cmake-format, please see the documentation for contribution rules and guidelines.

Example

Will turn this:

# The following multiple newlines should be collapsed into a single newline




cmake_minimum_required(VERSION 2.8.11)
project(cmakelang_test)

# This multiline-comment should be reflowed
# into a single comment
# on one line

# This comment should remain right before the command call.
# Furthermore, the command call should be formatted
# to a single line.
add_subdirectories(foo bar baz
  foo2 bar2 baz2)

# This very long command should be wrapped
set(HEADERS very_long_header_name_a.h very_long_header_name_b.h very_long_header_name_c.h)

# This command should be split into one line per entry because it has a long argument list.
set(SOURCES source_a.cc source_b.cc source_d.cc source_e.cc source_f.cc source_g.cc source_h.cc)

# The string in this command should not be split
set_target_properties(foo bar baz PROPERTIES COMPILE_FLAGS "-std=c++11 -Wall -Wextra")

# This command has a very long argument and can't be aligned with the command
# end, so it should be moved to a new line with block indent + 1.
some_long_command_name("Some very long argument that really needs to be on the next line.")

# This situation is similar but the argument to a KWARG needs to be on a
# newline instead.
set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-sign-compare -Wno-unused-parameter -xx")

set(HEADERS header_a.h header_b.h # This comment should
                                  # be preserved, moreover it should be split
                                  # across two lines.
    header_c.h header_d.h)


# This part of the comment should
# be formatted
# but...
# cmake-format: off
# This bunny should remain untouched:
# .   _ ∩
#   レヘヽ| |
#     (・x・)
#    c( uu}
# cmake-format: on
#          while this part should
#          be formatted again

# This is a paragraph
#
# This is a second paragraph
#
# This is a third paragraph

# This is a comment
# that should be joined but
# TODO(josh): This todo should not be joined with the previous line.
# NOTE(josh): Also this should not be joined with the todo.

if(foo)
if(sbar)
# This comment is in-scope.
add_library(foo_bar_baz foo.cc bar.cc # this is a comment for arg2
                                      # this is more comment for arg2, it should be joined with the first.
    baz.cc) # This comment is part of add_library

other_command(some_long_argument some_long_argument) # this comment is very long and gets split across some lines

other_command(some_long_argument some_long_argument some_long_argument) # this comment is even longer and wouldn't make sense to pack at the end of the command so it gets it's own lines
endif()
endif()


# This very long command should be broken up along keyword arguments
foo(nonkwarg_a nonkwarg_b HEADERS a.h b.h c.h d.h e.h f.h SOURCES a.cc b.cc d.cc DEPENDS foo bar baz)

# This command uses a string with escaped quote chars
foo(some_arg some_arg "This is a \"string\" within a string")

# This command uses an empty string
foo(some_arg some_arg "")

# This command uses a multiline string
foo(some_arg some_arg "
    This string is on multiple lines
")

# No, I really want this to look ugly
# cmake-format: off
add_library(a b.cc
  c.cc         d.cc
           e.cc)
# cmake-format: on

into this:

# The following multiple newlines should be collapsed into a single newline

cmake_minimum_required(VERSION 2.8.11)
project(cmakelang_test)

# This multiline-comment should be reflowed into a single comment on one line

# This comment should remain right before the command call. Furthermore, the
# command call should be formatted to a single line.
add_subdirectories(foo bar baz foo2 bar2 baz2)

# This very long command should be wrapped
set(HEADERS very_long_header_name_a.h very_long_header_name_b.h
            very_long_header_name_c.h)

# This command should be split into one line per entry because it has a long
# argument list.
set(SOURCES
    source_a.cc
    source_b.cc
    source_d.cc
    source_e.cc
    source_f.cc
    source_g.cc
    source_h.cc)

# The string in this command should not be split
set_target_properties(foo bar baz PROPERTIES COMPILE_FLAGS
                                             "-std=c++11 -Wall -Wextra")

# This command has a very long argument and can't be aligned with the command
# end, so it should be moved to a new line with block indent + 1.
some_long_command_name(
  "Some very long argument that really needs to be on the next line.")

# This situation is similar but the argument to a KWARG needs to be on a newline
# instead.
set(CMAKE_CXX_FLAGS
    "-std=c++11 -Wall -Wno-sign-compare -Wno-unused-parameter -xx")

set(HEADERS
    header_a.h header_b.h # This comment should be preserved, moreover it should
                          # be split across two lines.
    header_c.h header_d.h)

# This part of the comment should be formatted but...
# cmake-format: off
# This bunny should remain untouched:
# .   _ ∩
#   レヘヽ| |
#     (・x・)
#    c( uu}
# cmake-format: on
# while this part should be formatted again

# This is a paragraph
#
# This is a second paragraph
#
# This is a third paragraph

# This is a comment that should be joined but
# TODO(josh): This todo should not be joined with the previous line.
# NOTE(josh): Also this should not be joined with the todo.

if(foo)
  if(sbar)
    # This comment is in-scope.
    add_library(
      foo_bar_baz
      foo.cc bar.cc # this is a comment for arg2 this is more comment for arg2,
                    # it should be joined with the first.
      baz.cc) # This comment is part of add_library

    other_command(
      some_long_argument some_long_argument) # this comment is very long and
                                             # gets split across some lines

    other_command(
      some_long_argument some_long_argument some_long_argument) # this comment
                                                                # is even longer
                                                                # and wouldn't
                                                                # make sense to
                                                                # pack at the
                                                                # end of the
                                                                # command so it
                                                                # gets it's own
                                                                # lines
  endif()
endif()

# This very long command should be broken up along keyword arguments
foo(nonkwarg_a nonkwarg_b
    HEADERS a.h b.h c.h d.h e.h f.h
    SOURCES a.cc b.cc d.cc
    DEPENDS foo
    bar baz)

# This command uses a string with escaped quote chars
foo(some_arg some_arg "This is a \"string\" within a string")

# This command uses an empty string
foo(some_arg some_arg "")

# This command uses a multiline string
foo(some_arg some_arg "
    This string is on multiple lines
")

# No, I really want this to look ugly
# cmake-format: off
add_library(a b.cc
  c.cc         d.cc
           e.cc)
# cmake-format: on
Comments
  • CMake targets for cmake-format

    CMake targets for cmake-format

    It'd be nice to have something like https://github.com/TheLartians/Format.cmake/ for cmake-format.

    A particular feature I'm interested in is identifying CMake modules repositories to use their cmake-format configuration file (or using cmake-genparsers to generate it). These can be used by the targets, so that end users get semantic formatting of imported commands without having to add to their own configuration files.

    I was thinking of using CMake cache variables and properties like in https://github.com/TheLartians/CPM.cmake/blob/master/cmake/CPM.cmake to implement a CMake module of this feature.

    Alternatively, the command cmake-format could do it itself. Perhaps by having a per-user/system-wide configuration file where it would store paths to CMake modules repositories, along with the generated configuration files for repositories that don't include a cmake-format configuration file.

    If this is out of scope, could you, @TheLartians, maybe be interested in adding it to https://github.com/TheLartians/Format.cmake/? I'm asking because the name doesn't suggest it's limited to clang or C++, even though I guess that's what's CMake is predominantly used for.

    opened by JohelEGP 18
  • End of line corruption when writing bracket comment

    End of line corruption when writing bracket comment

    I am seeing an issue since the last release when formatting files in-place with bracket comments and Windows line endings such as this CMakeLists.txt. When formatted in-place, the lines of the bracket comment pick up an extra carriage return, but the rest of the file is written correctly. The output seems correct when writing to stdout or using Unix line endings.

    opened by ianbenz 17
  • Set default line-ending option to auto

    Set default line-ending option to auto

    I have my Windows environment with some cmake files.

    After running cmake-format (I do it inside pre-commit) I get dozens of line ending changes

    
    warning: LF will be replaced by CRLF in sdk/CMakeLists.txt.
    The file will have its original line endings in your working directory
    
    

    That's very unfortunate because that seems to be the only option I need to customize from the default config, IMO it would be much more useful to have auto by default (as Git does)

    feature-request acknowledged 
    opened by okainov 15
  • No handler for logger, error in Circle CI

    No handler for logger, error in Circle CI

    Traceback (most recent call last):
      File "/usr/local/bin/cmake-format", line 8, in <module>
        sys.exit(main())
      File "/usr/local/lib/python2.7/dist-packages/cmake_format/__main__.py", line 499, in main
        outtext, reflow_valid = process_file(cfg, intext, args.dump)
      File "/usr/local/lib/python2.7/dist-packages/cmake_format/__main__.py", line 122, in process_file
        parse_tree = parse.parse(tokens, ctx)
      File "/usr/local/lib/python2.7/dist-packages/cmake_format/parse/__init__.py", line 41, in parse
        return BodyNode.consume(ctx, tokens)
      File "/usr/local/lib/python2.7/dist-packages/cmake_format/parse/body_nodes.py", line 70, in consume
        tokens[0].begin.line, tokens[0].begin.col))
    AssertionError: Unexpected UNQUOTED_LITERAL token at 76:0
    No handlers could be found for logger "cmake-format"
    No handlers could be found for logger "cmake-format"
    No handlers could be found for logger "cmake-format"
    No handlers could be found for logger "cmake-format"
    

    Environment: Docker image is bionic ubuntu.

    Any cmake-format command in circleci config is taking too much time to complete. Please look into this.

    opened by kumaran-14 15
  • How to apply customized config file

    How to apply customized config file

    Hi!

    When my customized file was applied to vscode, I got the following error:

    " Command failed: cmake-format --config-file d:\totalcmd\util\VSCode-win32-x64-1.38.1 - Traceback (most recent call last): File "C:\Python27\Scripts\cmake-format-script.py", line 11, in load_entry_point('cmake-format==0.6.4', 'console_scripts', 'cmake-format')() File "c:\python27\lib\site-packages\cmake_format_main_.py", line 472, in main "You cannot mix stdin as an input with other input files" AssertionError: You cannot mix stdin as an input with other input files"

    my settings.json "cmakeFormat.args": [ "--config-file d:\totalcmd\util\VSCode-win32-x64-1.38.1" ],

    my setting.json is attached.

    Merry Christmas!

    settings.json.txt

    opened by SE-June 15
  • Competing heuristics for 2+ argument statements that are one character short of fitting on a single line.

    Competing heuristics for 2+ argument statements that are one character short of fitting on a single line.

    1. # cmake-format: off gets indented, the matching # cmake-format: on remains unindented. Personally I prefer them both unindented as before.
    2. This set() command is formatted very differently than other set() commands before and after. Not clear why.

    Thanks very much!

    bug acknowledged 
    opened by mikew-lunarg 10
  • if conditions with many elements can get pretty messy

    if conditions with many elements can get pretty messy

    Combining conditions with the variable (NOT X) and Breaking on () would help a lot

    https://aomedia-review.googlesource.com/c/aom/+/57102/3/test/test.cmake

        if (("${var}" MATCHES "_TEST_" AND NOT
             "${var}" MATCHES
             "_DATA_\|_CMAKE_\|INTRA_PRED\|_COMPILED\|_HOSTING\|_PERF_\|CODER_")
            OR (CONFIG_AV1_ENCODER AND CONFIG_ENCODE_PERF_TESTS AND
                "${var}" MATCHES "_ENCODE_PERF_TEST_")
            OR (CONFIG_AV1_DECODER AND CONFIG_DECODE_PERF_TESTS AND
                "${var}" MATCHES "_DECODE_PERF_TEST_")
            OR (CONFIG_AV1_ENCODER AND "${var}" MATCHES "_TEST_ENCODER_")
            OR (CONFIG_AV1_DECODER AND  "${var}" MATCHES "_TEST_DECODER_"))
          list(APPEND aom_test_source_vars ${var})
        endif ()
    
    

    converted

        if((
           "${var}"
           MATCHES
           "_TEST_"
           AND
           NOT
           "${var}"
           MATCHES
           "_DATA_\|_CMAKE_\|INTRA_PRED\|_COMPILED\|_HOSTING\|_PERF_\|CODER_"
           )
           OR
           (
           CONFIG_AV1_ENCODER
           AND
           CONFIG_ENCODE_PERF_TESTS
           AND
           "${var}"
           MATCHES
           "_ENCODE_PERF_TEST_"
           )
           OR
           (
           CONFIG_AV1_DECODER
           AND
           CONFIG_DECODE_PERF_TESTS
           AND
           "${var}"
           MATCHES
           "_DECODE_PERF_TEST_"
           )
           OR
           (
           CONFIG_AV1_ENCODER
           AND
           "${var}"
           MATCHES
           "_TEST_ENCODER_"
           )
           OR
           (
           CONFIG_AV1_DECODER
           AND
           "${var}"
           MATCHES
           "_TEST_DECODER_"
           ))
    
    

    https://aomedia-review.googlesource.com/c/aom/+/57102/3/test/test_data_download_worker.cmake if (NOT AOM_ROOT OR NOT AOM_CONFIG_DIR OR NOT AOM_TEST_FILE OR NOT AOM_TEST_CHECKSUM)

    converted to

    if(NOT
       AOM_ROOT
       OR
       NOT
       AOM_CONFIG_DIR
       OR
       NOT
       AOM_TEST_FILE
       OR
       NOT
       AOM_TEST_CHECKSUM)
    
    opened by johannkoenig 10
  • Fixed typos and bugs in vscode extension

    Fixed typos and bugs in vscode extension

    At first I just wanted to fix a typo but I found some other issues. I was having issues setting a path and couldn't get anything to run. It looks like the extension was incompatible with the current release of cmake-format? Anyway, this fixes it for me

    opened by UebelAndre 9
  • Question of understanding regarding always_wrap

    Question of understanding regarding always_wrap

    I have some CMakeLists.txt file with e.g.

    cmake_minimum_required(VERSION 3.5)
    
    option(CONFIG_OPT_WARNINGS_AS_ERROR "Use -Werror option for gcc" OFF)
    
    set(SOURCES src/File1.cpp src/File2.cpp src/File3.cpp src/File4.cpp src/File5.cpp)
    

    I would like it to be formatted in the following way:

    cmake_minimum_required(VERSION 3.5)
    
    option(CONFIG_OPT_WARNINGS_AS_ERROR "Use -Werror option for gcc" OFF)
    
    set(SOURCES
        src/File1.cpp
        src/File2.cpp
        src/File3.cpp
        src/File4.cpp
        src/File5.cpp
        )
    

    I assumed I can achieve this by using always_wrap. Hence, in my json options file for CMake-Format I put the line:

    "always_wrap": ["set"],
    

    However, the set list doesn't get wrapped. Rather, with my settings the file looks this:

    cmake_minimum_required(VERSION 3.5)
    
    option(CONFIG_OPT_WARNINGS_AS_ERROR "Use -Werror option for gcc" OFF)
    
    set(SOURCES src/File1.cpp src/File2.cpp src/File3.cpp src/File4.cpp
                src/File5.cpp
        )
    

    Is my expectation regarding always_wrap wrong? How can I achieve the desired formatting for my example?

    For reference, I attach the entire json configuation file. CMakeFormatOptions.zip

    acknowledged fix-in-flight 
    opened by Weeena 9
  • Formatting of files containing @VARIABLE@ fails

    Formatting of files containing @[email protected] fails

    Hey again,

    I just tested the new version (0.5.0) and encountered an issue with formatting of cmake files expected to be run through a configure_file command. Specifically I have a Config.cmake.in file containing the template for the exported ProjectConfig.cmake file. This file contains the line

    @[email protected]
    

    which causes an error:

    AssertionError: Unexpected UNQUOTED_LITERAL token at 1:0
    

    EDIT: Maybe this didn't work before and I just noticed

    feature-request fix-in-flight 
    opened by yeganer 9
  • Force sources for add_library onto separate lines

    Force sources for add_library onto separate lines

    Hey, I just found this tool and it's amazing! However I have an issue that bothers me.

    If the arguments to add_library fit onto one line, they'll get mashed together like so:

    add_library(
        foo src/file1.c src/file2.c
    )
    

    However if the list of files is long enough the lines are wrapped like so:

    add_library(
        foo
        src/file1.c
        src/file2.c
        src/file3.c
        src/file4.c
        src/file5.c
    )
    

    I want consistent formatting like the 2nd example, even if all arguments would fit in one line. That way adding a file to the list of sources does not cause a sudden wrap of all arguments which results in an ugly diff in git.

    I've tried changing the algorithm order but that messes up the formatting for other commands. Same with changing max_subargs_per_line. Any suggestions on how to achieve the desired formatting? Looking at the code suggests my request is not possible right now but you are planning to expand the per-command settings. In general I think it would be great if we could specify for each argument if it should be wrapped or not.

    What I this means is configuring add_library to have pargs = [1, '+'] and then somehow configure the + to always wrap. Maybe like that: pargs = [1, {'value': '+', 'always_wrap': True}]. I can think of several other commands where this kind of fine-grained control would be useful. For example one could want to wrap the PUBLIC and PRIVATE libraries in target_link_libraries.

    It would be really cool to have such a feature. If you think my proposal is a good solution, I could try to make a prototype.

    feature-request acknowledged 
    opened by yeganer 9
  • Compatibility with `argparse-manpage`

    Compatibility with `argparse-manpage`

    https://pypi.org/project/argparse-manpage/

    • Refactor construction of argparse.ArgumentParser into a get_argparser() function in each binary.
    • Set prog property (the default uses sys.arg[0] which breaks with argparse-manpage, arguably this is an argparse-manpage bug).
    • Set the man_short_description property based on the first line of the description. This is used as a summary in the NAME section of the man page.
    opened by ijc 0
  • Update TestConfigInclude._test_passed to support Python 3.11

    Update TestConfigInclude._test_passed to support Python 3.11

    Update snippet from linked page.

    Reported in https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1028176

    Copyright assignment is in https://github.com/cheshirekow/cmake_format/pull/305

    opened by ijc 0
  • Bump qs from 6.10.1 to 6.11.0 in /cmakelang/vscode_extension

    Bump qs from 6.10.1 to 6.11.0 in /cmakelang/vscode_extension

    Bumps qs from 6.10.1 to 6.11.0.

    Changelog

    Sourced from qs's changelog.

    6.11.0

    • [New] [Fix] stringify: revert 0e903c0; add commaRoundTrip option (#442)
    • [readme] fix version badge

    6.10.5

    • [Fix] stringify: with arrayFormat: comma, properly include an explicit [] on a single-item array (#434)

    6.10.4

    • [Fix] stringify: with arrayFormat: comma, include an explicit [] on a single-item array (#441)
    • [meta] use npmignore to autogenerate an npmignore file
    • [Dev Deps] update eslint, @ljharb/eslint-config, aud, has-symbol, object-inspect, tape

    6.10.3

    • [Fix] parse: ignore __proto__ keys (#428)
    • [Robustness] stringify: avoid relying on a global undefined (#427)
    • [actions] reuse common workflows
    • [Dev Deps] update eslint, @ljharb/eslint-config, object-inspect, tape

    6.10.2

    • [Fix] stringify: actually fix cyclic references (#426)
    • [Fix] stringify: avoid encoding arrayformat comma when encodeValuesOnly = true (#424)
    • [readme] remove travis badge; add github actions/codecov badges; update URLs
    • [Docs] add note and links for coercing primitive values (#408)
    • [actions] update codecov uploader
    • [actions] update workflows
    • [Tests] clean up stringify tests slightly
    • [Dev Deps] update eslint, @ljharb/eslint-config, aud, object-inspect, safe-publish-latest, tape
    Commits
    • 56763c1 v6.11.0
    • ddd3e29 [readme] fix version badge
    • c313472 [New] [Fix] stringify: revert 0e903c0; add commaRoundTrip option
    • 95bc018 v6.10.5
    • 0e903c0 [Fix] stringify: with arrayFormat: comma, properly include an explicit `[...
    • ba9703c v6.10.4
    • 4e44019 [Fix] stringify: with arrayFormat: comma, include an explicit [] on a s...
    • 113b990 [Dev Deps] update object-inspect
    • c77f38f [Dev Deps] update eslint, @ljharb/eslint-config, aud, has-symbol, tape
    • 2cf45b2 [meta] use npmignore to autogenerate an npmignore file
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies javascript 
    opened by dependabot[bot] 0
  • cmake-lint expects UPPERCASE macro names but cmake-format makes all invocations lowercase

    cmake-lint expects UPPERCASE macro names but cmake-format makes all invocations lowercase

    Out of the box, cmake-lint will expect macro names to be all uppercase, yet cmake-format will make all invocations of a macro lowercase (which would only be correct for invocations of functions).

    As mentioned in https://github.com/cheshirekow/cmake_format/issues/73, cmake-format would require to parse CMake scripts (like CMake itself) to distinguish between the too, but this leads to a situation where files formatted by cmake-format will never be able to pass the linter.

    Maybe changing the guidelines used by cmake-lint to accept macros as lowercase (like functions) could help.

    opened by PatTheMav 0
  • Request: Add ability to blacklist line breaks after certain words

    Request: Add ability to blacklist line breaks after certain words

    I'd like the ability to set keywords to never have a newline follow, like "NOT" and "DEFINED" - seems dumb/ugly to format code to

    if(NOT
        DEFINED
        CMAKE_...
    )
    

    or maybe just not apply max_pargs_hwrap/max_rows_cmdline to if() statements? (I'm not sure which setting is making this happen).

    opened by AaronDMarasco 0
Releases(pseudo-staging)
  • v0.6.13(Aug 19, 2020)

  • v0.6.12(Aug 19, 2020)

    This release includes mostly internal housekeeping. The code organization was overhauled to better represent the division between different components.The cmake_format package has been replaced by cmakelang, with`format` now a subpackage. All the first class tools are now subpackages of cmakelang. For now, I'll leave the github repository at cmake_format but there's a good chance I'll move it to cmakelang in the future. Big refactors like this have a tendency to expose gaps in coverage so please report any breakages you observe.

    In addition, the configuration now includes options for using tab characters in listfiles (though, I'm not sure who in the right mind would choose to do so). If enabled, the formatter will translate indentations from spaces to tabs,and the linter will enforce a consistent tab policy.

    This release also includes a couple of minor bug fixes. See the release notes for more details.

    Source code(tar.gz)
    Source code(zip)
    cmake-format-0.6.12.vsix(499.58 KB)
    cmakelang-0.6.12-py3-none-any.whl(131.35 KB)
    cmakelang-0.6.12.tar.gz(97.41 KB)
  • v0.6.11(Jul 17, 2020)

    This release adds argcomplete handling to enable automatic shellcompletion to cmake-format and cmake-lint. argcomplete is not an installation dependency so if you wish to enable completion please install`argcomplete` (e.g. via pip) and then activate it (see the documentation for argcomplete).

    The visual studio code extension now supports variable substitution for thingslike ${workspaceRoot} and ${workspaceFolder} in the args and cwd configuration options.

    There is a new configuration option to disable formatting. This can be specified in a config file to conveniently no-op formatting within a subdirectory (such as third-party source code) of a project.

    Source code(tar.gz)
    Source code(zip)
    cmake-format-0.6.11.vsix(499.58 KB)
    cmake_format-0.6.11-py3-none-any.whl(162.14 KB)
    cmake_format-0.6.11.tar.gz(125.00 KB)
  • v0.6.10(Apr 21, 2020)

    This release fixes a number of issues with cmake-lint and activates cmake-lint as part of the lint build step in CI for this project and the upstream repository. There is still a lot of work to do on cmake-lint but at this point it is in a less experimental state and I am sufficiently confident in it enough to suggest that you start using it. Feel free to report any issues you encounter with it.

    This release also includes some cleanup work under the hood of cmake-format and the parsing code. Most notably, the command specifications for all of the cmake functions and macros defined in standard modules have been generated using genparsers and are now included by default. I have not audited all of them so the detected specifications are probably not all correct. Please let me know if you observe any problems with them.

    Source code(tar.gz)
    Source code(zip)
    cmake-format-0.6.10.vsix(503.83 KB)
    cmake_format-0.6.10-py3-none-any.whl(160.12 KB)
    cmake_format-0.6.10.tar.gz(120.14 KB)
  • v0.6.9(Feb 10, 2020)

    The parser now performs token look-ahead when parsing a comment within astatement. This allows it to determine whether a comment belongs to the currentsemantic node or one higher up in the tree (previously it would assign allcomments to the most recent semantic node). This should prevent some unusualindentation of comments within deep statements.

    Some cmake-lint crashes have been fixed and the test coverage has increasedsignificantly. There are still some outstanding issues but it should crash lessfrequently and with more helpful information.

    Detailed documentation for configuration options is now generatedautomatically, including default value, command line syntax, and exampleconfiguration file entry.

    Source code(tar.gz)
    Source code(zip)
    cmake-format-0.6.9.vsix(503.82 KB)
    cmake_format-0.6.9-py3-none-any.whl(151.29 KB)
    cmake_format-0.6.9.tar.gz(126.15 KB)
  • v0.6.8(Jan 31, 2020)

    There is now an embeded a database of known variables and properties.cmake-lint uses this database to implement checks on assignment/use ofvariables that are likely to be typos of a builtin variable name. There arealso two new configuration options vartags and proptags that canbe used to affect how the parser and formatter treat certain variables andproperties.

    Line comments within a statement are now consumed the same as line comments atblock-scope. This means that your multiline mid-statement comments will bereflowed whereas they would previously have been left alone.

    The CI Build has gotten a little more complicated. Generated documentationsources are no longer committed to the repository. Instead, they are pushed toa separate staging repository from which the read-the-docs pages are built.

    Source code(tar.gz)
    Source code(zip)
    cmake_format-0.6.8-py3-none-any.whl(153.38 KB)
    cmake_format-0.6.8.tar.gz(131.82 KB)
  • v0.6.7(Jan 23, 2020)

    With this release, the specification format for custom commands has been updated to enable a number of new features. Positional argument groups now support "tags" which can be used to influence the formatting for some special cases. The format now also supports multiple positional argument groups. Lastly, there is a new experimental tool cmake-genparsers which can automatically generate parser specifications from your custom commands that use the standard cmake_parse_arguments.

    There is a new configuration option max_rows_cmdline which applies only to shell commands and determines when a shell command should nest under it's keyword argument.

    Source code(tar.gz)
    Source code(zip)
  • v0.6.6(Jan 16, 2020)

    The configuration datastructures have been overhauled and configuration options are now separated into different groupings based on which part of the processing pipeline they are relevent to. Legacy configuration files (without sections) are still supported, though they may be deprecated in the future. cmake-format can update your configuration file for you with the following command:

      cmake-format --config-file <your-config> --dump-config <your-format> \
        --no-help --no-default
    

    There is a new configuration option explicit_trailing_pattern which can be used to define a particular character sequence used by comments that are explicitly matched as trailing comments of an argument or statement. See the docs for more information.

    Configuration files can now include additional configuration files. This might help keep configurations organized if you are maintaining a database of custom command definitions.

    Source code(tar.gz)
    Source code(zip)
  • v0.6.5(Dec 26, 2019)

    This is largely a maintenance release, implementing explicit parse logic for all cmake commands that don't already have parsers. One additional configuration option is added allowing cmake-lint to globally ignore specific lint ids.

    Source code(tar.gz)
    Source code(zip)
  • v0.6.4(Dec 19, 2019)

    This release includes implementations for many more lint checkers. Under the hood there was a pretty significant refactor of the parser, though none of the parse logic has changed. The refactor was primarily to split up the very large parser module, and to make it easier to access qualifiers of the parse tree during lint checks.

    You can see a running list of all the implemented checkers at the docs

    Source code(tar.gz)
    Source code(zip)
  • v0.6.3(Dec 13, 2019)

    This release finally includes some progress on a long-standing goal: a cmake-linter built on the same foundation as the formatter. As of this release The cmake-format python package now comes with both the cmake-format and cmake-lint programs. The linter is still in a relatively early state and lacks many features, but should continue to grow with the formatter in future releases.

    Along with the new linter, this release also includes some reorganization of the documentation in order to more clearly separate information about the different programs that are distributed from this repository.

    Source code(tar.gz)
    Source code(zip)
  • v0.6.2(Dec 3, 2019)

    This is a maintenance release. Some additional command parsers have moved out of the standard parse model improving the parse of these commands. This release also includes some groundwork scripts to parse the usage strings in the cmake help text. Additionally:

    • --in-place will preserve file mode
    • The new --check command line option will not format the file, but exit with non-zero status if any changes would be made
    • The new --require-valid-layout option will exit with non-zero status if an admissible layout is not found.
    Source code(tar.gz)
    Source code(zip)
  • v0.6.0(Oct 15, 2019)

    This release includes a significant refactor of the formatting logic. Details of the new algorithm are described in the documentation. As a result of the algorithm changes, some config options have changed too. The following config options are removed:

    • max_subargs_per_line (see max_pargs_hwrap)
    • nest_threshold (see min_prefix_chars)
    • algorithm_order (see layout_passes)

    And the following config options have been added:

    • max_subgroups_hwrap
    • max_pargs_hwrap
    • dangle_align
    • min_prefix_chars
    • max_prefix_chars
    • max_lines_hwrap
    • layout_passes
    • enable_sort

    Also as a result of the algorithm changes, the default layout has changed. By default, cmake-format will now prefer to nest long lists rather than aligning them to the opening parenthesis of a statement. Also, due to the new configuration options, the output of cmake-format is likely to be different with your current configs.

    Additionally, cmake-format will now tend to prefer a normal "horizontal" wrap for relatively long lists of positional arguments (e.g. source files in add_library) whereas it would previously prefer a vertical layout (one-entry per line). This is a consequence of an ambiguity between which positional arguments should be vertical versus which should be wrapped. Two planned features (layout tags and positional semantics) should help to provide enough control to get the layout you want in these lists.

    I acknowledge that it is not ideal for formatting to change between releases but this is an unfortunate inevitability at this stage of development. The changes in this release eliminate a number of inconsistencies and also adds the groundwork for future planned features and options. Hopefully we are getting close to a stable state and a 1.0 release.

    Source code(tar.gz)
    Source code(zip)
  • v0.5.5(Sep 26, 2019)

    This is a maintenance release fixing a few minor bugs and enhancements. One new feature is that the --config command line option now accepts a list of config files, which should allow for including multiple databases of command specifications

    Source code(tar.gz)
    Source code(zip)
  • v0.5.4(Jul 23, 2019)

    This is a maintenance release fixing a couple of bugs and adding some missing documentation. One notable feature added is that, during in-place formatting, if the file content is unchanged cmake-format will no-longer write the file.

    Source code(tar.gz)
    Source code(zip)
  • v0.5.2(May 30, 2019)

    This release fixes a few bugs and does some internal prep work for upcoming format algorithm changes. The documentation on the format algorithm is a little ahead of the code state in this release. Also, the documentation theme has changed to something based on read-the-docs (I hope you like it).

    • Add missing forms of add_library() and add_executable()
    • --autosort now defaults to False (it can be somewhat suprising) and it doesn't always get it right.
    • Configuration options in --help and in the example configurations from --dump-config are now split into hopefully meaningful sections.
    • cmake-format no longer tries to infer "keywords" or "flags" from COMMAND strings. This matching wasn't good enough as there is way too much variance in how programs design their command line options.
    Source code(tar.gz)
    Source code(zip)
  • v0.5.1(May 3, 2019)

    The 0.5.0 release involved some pretty big changes to the parsing engine and introduced a new format algorithm. These two things combined unfortunately lead to a lot of new bugs. The full battery of pre-release tests wasn't run and so a lot of those issues popped up after release. Hopefully most of those are squashed in this release.

    • Fixed lots of bugs introduced in 0.5.0
    • cmake-format has a channel on discord now. Come chat about it at https://discord.gg/NgjwyPy
    Source code(tar.gz)
    Source code(zip)
  • v0.5.0(May 3, 2019)

    • Overhauled the parser logic enabling arbitrary implementations of statement parsers. The generic statement parser is now implemented by the standard_parse function (or the StandardParser functor, which is used to load legacy additional_commands).

    • New custom parser logic for deep cmake statements such as:

      • install
      • file
      • ExternalProject_XXX
      • FetchContent_XXX
    • cmake-format can now sort your argument lists for you (such as lists of files). This enabled with the autosort config option. Some argument lists are inherently sortable (e.g. the list of sources supplied to add_library or add_executable). Other commands (e.g. set() which cannot be inferred sortable can be explicitly tagged using a comment at the beginning of the list. See the README for more information.

    • A consequence of the above is that the parse tree for set() has changed, and so it's default formatting in many cases has also changed. You can restore the old behavior by adding the following to your config:

      additional_commands = {
        "set": {
          "flags": ["FORCE", "PARENT_SCOPE"],
          "kwargs": {
            "CACHE": "*"
          }
        }
      }
      
    • The default command case has changed from lower to canonical (which is a new option). In most cases this is the same as lower but for some standard, non-builtin commands the canonical spelling is CamelCase (i.e. ExternalProject_Add).

    • There is a new cmake-annotate program distributed with the package. It can generate semantic HTML renderings of your listfiles (see the documentation for details).

    Source code(tar.gz)
    Source code(zip)
Owner
null
📦 CMake's missing package manager. A small CMake script for setup-free, cross-platform, reproducible dependency management.

Setup-free CMake dependency management CPM.cmake is a CMake script that adds dependency management capabilities to CMake. It's built as a thin wrapper

CPM.cmake 1.6k Jan 9, 2023
CMake checks cache helper modules – for fast CI CMake builds!

cmake-checks-cache Cross platform CMake projects do platform introspection by the means of "Check" macros. Have a look at CMake's How To Write Platfor

Cristian Adam 65 Dec 6, 2022
CMake scripts for painless usage of SuiteSparse+METIS from Visual Studio and the rest of Windows/Linux/OSX IDEs supported by CMake

CMake scripts for painless usage of Tim Davis' SuiteSparse (CHOLMOD,UMFPACK,AMD,LDL,SPQR,...) and METIS from Visual Studio and the rest of Windows/Lin

Jose Luis Blanco-Claraco 395 Dec 24, 2022
cmake-font-lock - Advanced, type aware, highlight support for CMake

cmake-font-lock - Advanced, type aware, highlight support for CMake

Anders Lindgren 39 Oct 2, 2022
cmake-avr - a cmake toolchain for AVR projects

cmake-avr - a cmake toolchain for AVR projects Testing the example provided The toolchain was created and tested within the following environment: Lin

Matthias Kleemann 163 Dec 5, 2022
Make CMake less painful when trying to write Modern Flexible CMake

Izzy's eXtension Modules IXM is a CMake library for writing Modern flexible CMake. This means: Reducing the amount of CMake written Selecting reasonab

IXM 107 Sep 1, 2022
unmaintained - CMake module to activate certain C++ standard, feature checks and appropriate automated workarounds - basically an improved version of cmake-compile-features

Compatibility This library provides an advanced target_compile_features() and write_compiler_detection_header(). The problem with those is that they a

Jonathan Müller 74 Dec 26, 2022
[CMake] [BSD-2] CMake module to find ICU

FindICU.cmake A CMake module to find International Components for Unicode (ICU) Library Note that CMake, since its version 3.7.0, includes a FindICU m

julp 29 Nov 2, 2022
A CMake addon that avoids you writing boilerplate code for resource management.

SHader INJ(I)ector SHINJI (originally SHader INJector) is a CMake addon that avoids you writing boilerplate code for resource management and exposes s

Lorenzo Rutayisire 6 Dec 14, 2022
A set of cmake modules to assist in building code

CMake 3 Tools Warning: These tools are being replaced by the Modern CMake. Some of the tools are still being maintained for now, but new projects shou

null 201 Dec 21, 2022
CMake module for downloading an external project's source at configure time

DownloadProject Platform Build status Linux Mac OSX Windows (VS2015) This repository contains a generalized implementation for downloading an external

Crascit Pty Ltd 433 Dec 16, 2022
CMake project for BL602 RISC-V processor

bl602_cmake_base CMake project for BL602 RISC-V processor How to build NOTE : This project uses a pre-compiled version of the Buffalo SDK (bl_iot_sdk)

null 9 Jan 6, 2022
A CMake toolchain file for iOS, macOS, watchOS & tvOS C/C++/Obj-C++ development

A CMake toolchain file for iOS, macOS, watchOS & tvOS C/C++/Obj-C++ development

Alexander Widerberg 1.4k Jan 4, 2023
curl cmake module libcurl build with msvc x86

curl-msvc Infomation curl cmake module libcurl build with MSVC10.0 arch (x86 | i386) source from https://github.com/curl/curl tags: curl-7_79_1 Usage

Jason Payne 0 May 16, 2022
NeoWorld is a resampler using the CMake build system

NeoWorld is a resampler using the CMake build system. It's designed for utsu, OpenUTAU, and UTAU.

null 5 Dec 23, 2022
A CMake starter template using CPM

Cmake Starter About A lightweight Cmake project meant for a binary application (not a shared library), tests with catch2 are configured, CPM is the pa

Matt Williams 1 Jul 14, 2022
Non-intrusive CMake dependency management

cmodule Non-intrusive CMake dependency management. Normally CMake's find_package() looks for packages installed on host system (and compiled for host

scapix.com 14 Sep 29, 2022
Simple library for embedding static resources into C++ binaries using CMake

libromfs libromfs is an easy way to bundle resources directly into any C++ application and access them through a simple interface. The main advantage

WerWolv 28 Nov 30, 2022
Project to enable using CMake from a Maven build.

CMake-Maven-Project Introduction A Maven project for the CMake build system. It can be used by including it as a plugin within your Maven project's po

null 60 Nov 14, 2022