| find_package(Git QUIET REQUIRED) | |
| include(FetchContent) | |
| set(srcRepo ${CMAKE_CURRENT_BINARY_DIR}/srcRepo) | |
| file(REMOVE_RECURSE ${srcRepo}) | |
| file(MAKE_DIRECTORY ${srcRepo}) | |
| # Use a file:// URL. git ignores --depth when cloning a plain local path. | |
| set(repoUrl "file://${srcRepo}") | |
| function(execGitCommand) | |
| execute_process( | |
| WORKING_DIRECTORY ${srcRepo} | |
| COMMAND ${GIT_EXECUTABLE} ${ARGN} | |
| OUTPUT_QUIET | |
| COMMAND_ERROR_IS_FATAL ANY | |
| ) | |
| endfunction() | |
| execGitCommand(-c init.defaultBranch=master init) | |
| execGitCommand(config --add user.email "testauthor@cmake.org") | |
| execGitCommand(config --add user.name testauthor) | |
| execGitCommand(config commit.gpgsign "false") | |
| execGitCommand(config uploadpack.allowReachableSHA1InWant "true") | |
| # Two commits, so that the pinned commit is not the branch tip. | |
| file(TOUCH ${srcRepo}/firstFile.txt) | |
| execGitCommand(add firstFile.txt) | |
| execGitCommand(commit -m "First file") | |
| execute_process( | |
| WORKING_DIRECTORY ${srcRepo} | |
| COMMAND ${GIT_EXECUTABLE} rev-parse HEAD | |
| OUTPUT_VARIABLE pinnedCommit | |
| OUTPUT_STRIP_TRAILING_WHITESPACE | |
| COMMAND_ERROR_IS_FATAL ANY | |
| ) | |
| file(TOUCH ${srcRepo}/secondFile.txt) | |
| execGitCommand(add secondFile.txt) | |
| execGitCommand(commit -m "Second file") | |
| execGitCommand(branch other) | |
| FetchContent_Declare(shallowdep | |
| GIT_REPOSITORY ${repoUrl} | |
| GIT_TAG ${pinnedCommit} | |
| GIT_SHALLOW TRUE | |
| ) | |
| FetchContent_MakeAvailable(shallowdep) | |
| execute_process( | |
| WORKING_DIRECTORY ${shallowdep_SOURCE_DIR} | |
| COMMAND ${GIT_EXECUTABLE} rev-parse HEAD | |
| OUTPUT_VARIABLE head | |
| OUTPUT_STRIP_TRAILING_WHITESPACE | |
| COMMAND_ERROR_IS_FATAL ANY | |
| ) | |
| if(NOT head STREQUAL pinnedCommit) | |
| message(FATAL_ERROR "Checked out ${head}, expected ${pinnedCommit}") | |
| endif() | |
| execute_process( | |
| WORKING_DIRECTORY ${shallowdep_SOURCE_DIR} | |
| COMMAND ${GIT_EXECUTABLE} rev-parse --verify --quiet refs/remotes/origin/other | |
| RESULT_VARIABLE result | |
| OUTPUT_QUIET | |
| ) | |
| if(result EQUAL 0) | |
| message(FATAL_ERROR "Another branch was cloned along with the pinned commit") | |
| endif() |