# Running various test suites against LuaJIT.

# See the rationale in the root CMakeLists.txt.
cmake_minimum_required(VERSION 3.1 FATAL_ERROR)

include(MakeLuaPath)

find_program(LUACHECK luacheck)
if(LUACHECK)
  # XXX: The tweak below relates to luacheck problem with paths.
  # If the working directory or one used in luacheck options is
  # not a real path, luacheck doesn't handle it the right way.
  # Hence the paths used by luacheck in CMake ought to be resolved
  # to the real ones. For more info, see the following issue.
  # https://github.com/mpeterv/luacheck/issues/208
  get_filename_component(LUACHECK_SOURCE_DIR "${PROJECT_SOURCE_DIR}" REALPATH)
  get_filename_component(LUACHECK_BINARY_DIR "${PROJECT_BINARY_DIR}" REALPATH)
  set(LUACHECK_RC ${LUACHECK_SOURCE_DIR}/.luacheckrc)
  file(GLOB_RECURSE LUACHECK_DEPS ${LUACHECK_SOURCE_DIR}/*.lua)
  add_custom_target(${PROJECT_NAME}-luacheck
    DEPENDS ${LUACHECK_RC} ${LUACHECK_DEPS}
  )
  add_custom_command(TARGET ${PROJECT_NAME}-luacheck
    COMMENT "Running luacheck static analysis"
    COMMAND
      ${LUACHECK} ${LUACHECK_SOURCE_DIR}
        --codes
        --config ${LUACHECK_RC}
        # XXX: jit/vmdef.lua is an autogenerated Lua source, so
        # there is no need to run luacheck against it. Hence
        # explicitly exclude this file from the list for check.
        --exclude-files ${LUACHECK_BINARY_DIR}/src/jit/vmdef.lua
    # XXX: Filenames in .luacheckrc are considered relative to
    # the working directory, hence luacheck should be run in the
    # project root directory.
    WORKING_DIRECTORY ${LUACHECK_SOURCE_DIR}
  )
else()
  add_custom_target(${PROJECT_NAME}-luacheck)
  add_custom_command(TARGET ${PROJECT_NAME}-luacheck
    COMMENT "`luacheck' is not found, so ${PROJECT_NAME}-luacheck target is dummy"
  )
endif()

set(LUAJIT_TEST_COMMAND "${LUAJIT_TEST_BINARY} -e dofile[[${LUAJIT_TEST_INIT}]]")
separate_arguments(LUAJIT_TEST_COMMAND)

add_subdirectory(LuaJIT-tests)
add_subdirectory(PUC-Rio-Lua-5.1-tests)
add_subdirectory(lua-Harness-tests)
add_subdirectory(tarantool-tests)

add_custom_target(${PROJECT_NAME}-test DEPENDS
  LuaJIT-tests
  PUC-Rio-Lua-5.1-tests
  lua-Harness-tests
  tarantool-tests
)

if(LUAJIT_USE_TEST)
  if(POLICY CMP0037)
    if(CMAKE_VERSION VERSION_LESS 3.11)
      # CMake below 3.11 reserves the name 'test'. Use old policy.
      # https://cmake.org/cmake/help/v3.11/release/3.11.html#other-changes
      cmake_policy(SET CMP0037 OLD)
    else()
      # Starting from CMake 3.11 the name 'test' is reserved in
      # special cases and can be used as a target name.
      cmake_policy(SET CMP0037 NEW)
    endif()
  endif(POLICY CMP0037)

  add_custom_target(test DEPENDS
    ${PROJECT_NAME}-test
    ${PROJECT_NAME}-luacheck
  )
endif()
