5 # Find clang-format executable.
10 # This module defines the following variables:
12 # ``CLANG_FORMAT_FOUND``, ``ClangFormat_FOUND``
14 # ``CLANG_FORMAT_EXECUTABLE``
16 # ``CLANG_FORMAT_VERSION``
21 # .. command:: add_clang_format
25 # add_clang_format(target [VERBOSE]
26 # [WORKING_DIRECTORY dir] [COMMENT comment]
27 # [OPTIONS opt ...] [SOURCES src ...] [src ...]
30 include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
31 find_program(CLANG_FORMAT_EXECUTABLE NAMES clang-format)
32 mark_as_advanced(CLANG_FORMAT_EXECUTABLE)
34 if(EXISTS "${CLANG_FORMAT_EXECUTABLE}")
35 execute_process(COMMAND ${CLANG_FORMAT_EXECUTABLE} --version OUTPUT_VARIABLE CLANG_FORMAT_VERSION)
36 string(REGEX REPLACE ".*version ([^\n ]+).*" "\\1" CLANG_FORMAT_VERSION "${CLANG_FORMAT_VERSION}")
39 find_package_handle_standard_args(ClangFormat
43 CLANG_FORMAT_EXECUTABLE
49 set(CLANG_FORMAT_FOUND 1)
50 function(add_clang_format target)
51 cmake_parse_arguments(CLANG_FORMAT "VERBOSE" "WORKING_DIRECTORY;COMMENT" "SOURCES" ${ARGN})
52 list(APPEND CLANG_FORMAT_SOURCES ${CLANG_FORMAT_UNPARSED_ARGUMENTS})
53 list(APPEND CLANG_FORMAT_OPTIONS --style=file -i)
54 if(CLANG_FORMAT_VERBOSE)
55 list(INSERT CLANG_FORMAT_OPTIONS 0 --verbose)
57 if(NOT CLANG_FORMAT_WORKING_DIRECTORY)
58 set(CLANG_FORMAT_WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
60 if(NOT CLANG_FORMAT_COMMENT)
61 set(CLANG_FORMAT_COMMENT "Formatting ${target} using clang-format")
63 add_custom_target(${target} # https://clang.llvm.org/docs/ClangFormat.html
64 ${CLANG_FORMAT_EXECUTABLE} ${CLANG_FORMAT_OPTIONS} ${CLANG_FORMAT_SOURCES}
65 WORKING_DIRECTORY ${CLANG_FORMAT_WORKING_DIRECTORY}
66 COMMENT "${CLANG_FORMAT_COMMENT}"