example: check if write access to path

At CMake configure time I often need to test if a directory or file is writable. One example is to fatal_error if CMAKE_INSTALL_PREFIX is not in a writable location for users not so experienced with CMake or building programs in general.

file(TOUCH) and file(MAKE_DIRECTORY) don’t halt the configure step till erroring at the end of configure.

What I do instead is like this snippet to generate a fatal_error with text telling the user what to try:

set(test_path /path/to/test/.ignore)
# could be done with random string filename in the desired path

execute_process(COMMAND ${CMAKE_COMMAND} -E touch ${test_path}
RESULT_VARIABLE ret
)
if(NOT ret EQUAL "0")
  message(FATAL_ERROR "No write access to ${test_path}
  <text for user to resolve issue>")
endif()

While still not so elegant, since CMake 3.21 you can use file(COPY_FILE) and include the RESULT keyword to see if that succeeded. You could try copying a trivial empty file into the destination and removing it again. Basically the same approach as yours, just without having to shell out to a separate process.

yes that would nice if file(TOUCH) and file(MAKE_DIRECTORY) could have RESULT added

Please file an issue for this. It’ll get lost here :slight_smile: .

1 Like