Is it possible to create a Swift package project (i.e. as can be created by swift package init ...) using CMake?
The example repository by swiftlang on GitHub doesn’t contain this as an example. And there is no issue that addresses this either (one issue that mentions packages, seems to be about using the binary in an external package project, not creating a package project from CMake).
https://github.com/swiftlang/swift-cmake-examples
I tried compiling a .swift file that requires dependencies specified in a Package.swift file that is in the source folder next to the CMakeLists.txt. As I added the CMakeLists.txt to an existing Swift package project. This didn’t work. Errors about the import statements in the .swift source files are output, that those packages cannot be found.
I also tried adding the Package.swift to the add_executable command.
add_executable(Example Package.swift ${sources})
… but that didn’t work either. The PackageDescription module can also not be found. I was also not sure what adding that file might even do, if it would try to build the project twice (once via CMake and once via the Package.swift file). But it didn’t work.
It of course works to use add_custom_target. And in my case the .build folder is also the CMAKE_CURRENT_BINARY_DIR. Which seems to not conflict with CMake. But not sure if it might. And it is also error-prone. As ${sources} is merely for telling CMake when to run. So in this case a file(GLOB ...) would be required.
add_custom_target(Example ALL
COMMAND swift build
DEPENDS ${sources}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
The build folder for swift can be modified using --scratch-path. So it no longer conflicts.
Update:
I misunderstood that add_custom_target doesn’t require DEPENDS to trigger, it always triggers.
I cannot use add_custom_command, as it would require file(REAL_PATH ...) for a generator expression path I think?: $<IF:$<CONFIG:Debug>,debug,release> (release and debug are symlinks created by swift).
So instead, I now have
add_custom_target(_Example ALL
COMMAND swift build --scratch-path "${CMAKE_CURRENT_BINARY_DIR}/swift"
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
VERBATIM
)
add_executable(Example IMPORTED)
set_target_properties(Example
PROPERTIES
IMPORTED_LOCATION_Debug "${CMAKE_CURRENT_BINARY_DIR}/swift/debug"
IMPORTED_LOCATION_Release "${CMAKE_CURRENT_BINARY_DIR}/swift/release"
)
Using generator Ninja Multi-Config