fix when -DLIBA_JAVASCRIPT=1 and -DLIBA_CXX=0
[liba.git] / cmake / FindBlack.cmake
blobea11e8f105a507a1be18f219f2d830f1b53c4068
1 #.rst:
2 # FindBlack
3 # ---------
5 # Find black executable.
7 # Result Variables
8 # ^^^^^^^^^^^^^^^^
10 # This module defines the following variables:
12 # ``BLACK_FOUND``
14 # ``BLACK_EXECUTABLE``
16 # ``BLACK_VERSION``
18 # Functions
19 # ^^^^^^^^^
21 # .. command:: add_black
23 #   ::
25 #     add_black(target [QUIET] [VERBOSE]
26 #         [WORKING_DIRECTORY dir] [COMMENT comment]
27 #         [OPTIONS opt ...] [SOURCES src ...] [src ...]
28 #     )
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
35   )
36 endif()
38 if(BLACK_VERSION)
39   set(BLACK_EXECUTABLE ${Python_EXECUTABLE} -m black)
40 else()
41   find_program(BLACK_EXECUTABLE NAMES black)
42   mark_as_advanced(BLACK_EXECUTABLE)
43   set(BLACK_VERSION)
44 endif()
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]+([^ ]+).*" "\\1" BLACK_VERSION "${BLACK_VERSION}")
49 endif()
51 find_package_handle_standard_args(Black
52   FOUND_VAR
53     BLACK_FOUND
54   REQUIRED_VARS
55     BLACK_EXECUTABLE
56   VERSION_VAR
57     BLACK_VERSION
60 if(BLACK_FOUND)
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})
64     if(BLACK_QUIET)
65       list(INSERT BLACK_OPTIONS 0 --quiet)
66     endif()
67     if(BLACK_VERBOSE)
68       list(INSERT BLACK_OPTIONS 0 --verbose)
69     endif()
70     if(NOT BLACK_WORKING_DIRECTORY)
71       set(BLACK_WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
72     endif()
73     if(NOT BLACK_COMMENT)
74       set(BLACK_COMMENT "Formatting ${target} using black")
75     endif()
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}"
80     )
81   endfunction()
82 endif()