5 # Find black executable.
10 # This module defines the following variables:
14 # ``BLACK_EXECUTABLE``
21 # .. command:: add_black
25 # add_black(target [QUIET] [VERBOSE]
26 # [WORKING_DIRECTORY dir] [COMMENT comment]
27 # [OPTIONS opt ...] [SOURCES src ...] [src ...]
30 include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
32 if(EXISTS "${Python_EXECUTABLE}")
33 execute_process(COMMAND ${Python_EXECUTABLE} -c "import black; print(black.__version__)"
34 ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE BLACK_VERSION
39 set(BLACK_EXECUTABLE ${Python_EXECUTABLE} -m black)
41 find_program(BLACK_EXECUTABLE NAMES black)
42 mark_as_advanced(BLACK_EXECUTABLE)
46 if(NOT BLACK_VERSION AND EXISTS "${BLACK_EXECUTABLE}")
47 execute_process(COMMAND ${BLACK_EXECUTABLE} --version ERROR_QUIET OUTPUT_VARIABLE BLACK_VERSION)
48 string(REGEX REPLACE "black[^0-9]+([^\n ]+).*" "\\1" BLACK_VERSION "${BLACK_VERSION}")
51 find_package_handle_standard_args(Black
61 function(add_black target)
62 cmake_parse_arguments(BLACK "QUIET;VERBOSE" "WORKING_DIRECTORY;COMMENT" "OPTIONS;SOURCES" ${ARGN})
63 list(APPEND BLACK_SOURCES ${BLACK_UNPARSED_ARGUMENTS})
65 list(INSERT BLACK_OPTIONS 0 --quiet)
68 list(INSERT BLACK_OPTIONS 0 --verbose)
70 if(NOT BLACK_WORKING_DIRECTORY)
71 set(BLACK_WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
74 set(BLACK_COMMENT "Formatting ${target} using black")
76 add_custom_target(${target} # https://black.readthedocs.io/en/stable
77 ${BLACK_EXECUTABLE} ${BLACK_OPTIONS} ${BLACK_SOURCES}
78 WORKING_DIRECTORY ${BLACK_WORKING_DIRECTORY}
79 COMMENT "${BLACK_COMMENT}"