# This file contains a generic workaround to cause a list generated by
# a generator expression to be expanded when used as the COMMAND to
# add_custom_command() or add_custom_target().
# Using this workaround:
#  - include this file in CMakeLists.txt
#  - call expandable_command(<retvar> <command> [arg1] [arg2] ...)
#  - use the <retvar> from above as the COMMAND to add_custom_target()
#       or add_custom_command().
# Example to execute
#  echo a generated list
# code:
#  include(/path/to/expand_command.cmake)
#  expandable_command(cmdline echo $<TARGET_PROPERTY:echo,MSGLIST>)
#  add_custom_target(echo ALL COMMAND ${cmdline} VERBATIM)
#  set_property(TARGET echo PROPERTY MSGLIST a generated list)
if(NOT EXPAND_COMMAND_AS_SCRIPT)
    #==== This section is processed at configuration time when included
    if(COMMAND expandable_command)
        return()
    endif()

    set(EXPAND_COMMAND_SCRIPT "${CMAKE_CURRENT_LIST_FILE}")
    function(expandable_command retvar workdir)
        set(cmdline ${ARGN})
        string(REPLACE ";" "$<SEMICOLON>" cmdline "${cmdline}")
        set(${retvar} "${CMAKE_COMMAND}"
            "-D" "EXPAND_COMMAND_AS_SCRIPT=TRUE"
            "-D" "EXPAND_COMMAND=${cmdline}"
            "-D" "WORKING_DIR=${workdir}"
            "-P" "${EXPAND_COMMAND_SCRIPT}"
            PARENT_SCOPE)
    endfunction(expandable_command)

else()
    #==== This section is the command wrapper run at build time
    message(STATUS "Executing: `${EXPAND_COMMAND}`")
    execute_process(COMMAND ${EXPAND_COMMAND}
        WORKING_DIRECTORY ${WORKING_DIR}
        RESULT_VARIABLE result
        OUTPUT_VARIABLE output
        ERROR_VARIABLE error)
    set(stderr_type "")
    if(result)
        set(stderr_type FATAL_ERROR)
    endif()
    message("${output}")
    if(result OR error)
        message(${stderr_type} "Result: ${result}\n${error}")
    endif()
endif()
