set(_test_formatter_script "${CMAKE_CURRENT_SOURCE_DIR}/test-formatter.sh")

function (add_formatter_test formatter name path expect)
  if (_formatter_test_version)
    set(test_name "${formatter}-${_formatter_test_version}-${name}")
  else ()
    set(test_name "${formatter}-${name}")
  endif ()
  add_test(
    NAME    "${test_name}"
    COMMAND "${_test_formatter_script}"
            "${format_${formatter}_script}"
            "${path}"
            "${expect}"
            ${_formatter_test_version}
    WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${name}")
  # Ensure that tests working on the same files do not run concurrently.
  set_property(TEST "${test_name}" APPEND
    PROPERTY
      RESOURCE_LOCK "${formatter}/${name}/${path}")

  set(reason "check")
  if (name STREQUAL "format")
    set(reason "reformat")
  endif ()
  set_property(TEST "${test_name}" APPEND
    PROPERTY
      ENVIRONMENT "GHOSTFLOW_FORMAT_REASON=${reason}")
endfunction ()

get_property(formatters GLOBAL PROPERTY formatters)
foreach (formatter IN LISTS formatters)
  get_property(versioned GLOBAL
    PROPERTY "formatter_${formatter}_versioned")
  get_property(have_tools GLOBAL
    PROPERTY "formatter_${formatter}_tools")
  get_property("format_${formatter}_script" GLOBAL
    PROPERTY "formatter_${formatter}_script")

  add_formatter_test("${formatter}" no-file noexist.txt fail)

  if (have_tools)
    add_subdirectory("${formatter}")
  else ()
    add_formatter_test("${formatter}" no-tools "format.txt" "fail")
  endif ()

  if (versioned)
    foreach (_formatter_test_version IN LISTS "TOOL_VERSIONS_${formatter}")
      add_subdirectory("${formatter}" "${CMAKE_CURRENT_BINARY_DIR}/${formatter}-${_formatter_test_version}")
    endforeach ()
  endif ()
endforeach ()
