Skip to content

Instantly share code, notes, and snippets.

@socantre
Last active November 7, 2022 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save socantre/570816e682a36f0e0126 to your computer and use it in GitHub Desktop.
Save socantre/570816e682a36f0e0126 to your computer and use it in GitHub Desktop.
CMake; download file with specific hash. Probably better to use ExternalProject module to do this instead of doing it manually
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/download.cmake
"set(downloaded_file \"${CMAKE_CURRENT_BINARY_DIR}/pg44800.txt\")\n"
"set(url \"https://www.gutenberg.org/cache/epub/44800/pg44800.txt\")\n"
"set(expected_hash \"5a837b40a0f90211ff2883651f33a865\")\n"
"if (EXISTS \${downloaded_file})\n"
" file(MD5 \${downloaded_file} filehash)\n"
" message(\"\${downloaded_file} exists with hash: \" \${filehash})\n"
" if (\${expected_hash} STREQUAL \${filehash})\n"
" message(\"Hash matches expected hash.\")\n"
" else()\n"
" message(\"Hash does not match expected hash.\")\n"
" file(DOWNLOAD \${url} \${downloaded_file} SHOW_PROGRESS)\n"
" endif()\n"
"else()\n"
" message(\"\${downloaded_file} missing.\")\n"
" file(DOWNLOAD \${url} \${downloaded_file} SHOW_PROGRESS)\n"
"endif()\n"
)
add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/pg44800.txt"
COMMAND ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_BINARY_DIR}/download.cmake"
WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/download.cmake"
COMMENT "Downloading test text file."
VERBATIM
)
add_custom_target(file_download ALL DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/pg44800.txt")
@Justin-Hoffman
Copy link

The CMake "FILE" DOWNLOAD command will accept the additional "EXPECTED_HASH" argument in recent versions of CMake. The example above is obsolete.

See: https://cmake.org/cmake/help/latest/command/file.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment