find_program(clang-format_EXECUTABLE clang-format) mark_as_advanced(clang-format_EXECUTABLE) if(clang-format_EXECUTABLE) add_executable(clang-format IMPORTED) set_target_properties(clang-format PROPERTIES IMPORTED_LOCATION ${clang-format_EXECUTABLE}) endif() function(add_autoformat_target target) get_target_property(source_dir ${target} SOURCE_DIR) get_target_property(sources ${target} SOURCES) foreach(source ${sources}) get_property(generated SOURCE ${source} PROPERTY GENERATED) if(NOT ${generated}) list(APPEND non_generated_sources ${source}) endif() endforeach() add_custom_target(autoformat_${target} COMMAND clang-format -i -- ${non_generated_sources} WORKING_DIRECTORY ${source_dir} COMMENT "Autoformating sources of target ${target}" VERBATIM) if(NOT TARGET autoformat) add_custom_target(autoformat) endif() add_dependencies(autoformat autoformat_${target}) endfunction()