Chris
Chris

Reputation: 3466

CMake check hash (MD5 / SHA256) for downloaded file

I am using CMake add_custom_command In a Util.cmake script to download a couple of files that will later be used in the build process. These files however may change and I would like to add a way to check the hash value of the local file against a provided value (within CMake) to decide if the file needs to be re-downloaded.

Currently, once the file has been downloaded, CMake will not consider re-downloading it, because the file already exists locally.

In the future, I want to provide a MD5 / SHA256 checksum of that file and make sure the local file is the corect one.

Here is what I am trying to do (this is just an concept example):

add_custom_command( OUTPUT ./file.dat
    COMMAND wget ${FILE_PATH}
)
if (opt_HASH)
    add_custom_command(OUTPUT ${local_HASH}
        COMMAND local_HASH=$(sha256sum ./file.dat)
        DEPENDS ./file.dat
    )
    if (NOT ${opt_HASH} STREQUAL ${local_HASH})
        # throw ERROR
    endif()
endif()

As you can see I only want to detect a mismatch right now and don't even want to auto-download the changed file. The opt_HASH is obviously provided through CMake, but what is important is that this call needs to depend on the file already being downloaded and I seem to be able to do that with a more simpler call to FILE().

PS: If it's somehow easier, I could also use MD5 over SHA256.

Upvotes: 2

Views: 7484

Answers (2)

Th. Thielemann
Th. Thielemann

Reputation: 2825

The usage of add_custom_target could be one solution. By default it will be executed always. The following should work on linux:

add_custom_target(UpdateExternalFiles
    COMMAND "sha256sum -c file.dat.checksum ./file.dat || wget ${FILE_PATH}"
    COMMAND "sha256sum ./file.dat >> file.dat.checksum"
)

First line verifies the checksum and loads the file on differences. The second line updates the checksum.

Note: This snipped assume that file.dat.checksum will be created with the second command.

Upvotes: 0

user2144067
user2144067

Reputation: 142

cmakes FILE command supports hashing: https://cmake.org/cmake/help/v3.8/command/file.html

file(SHA256 ./file.dat CHECKSUM_VARIABLE)

should put the hash into the CHECKSUM_VARIABLE

Upvotes: 8

Related Questions