PatchIfNotAlreadyPatched.cmake 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #
  2. # Copyright (c) Contributors to the Open 3D Engine Project.
  3. # For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. #
  5. # SPDX-License-Identifier: Apache-2.0 OR MIT
  6. #
  7. #
  8. # This file is used to patch a file only if it has not already been patched.
  9. # This is useful for patching a file that is fetched by FetchContent, which
  10. # does not have a built-in way to only apply a patch if it has not already been
  11. # applied.
  12. # Usage:
  13. # cmake -P PatchIfNotAlreadyPatched.cmake <patchfile>
  14. # it expects the current working directory to be in the root of the repository
  15. # for which the patch applies and uses `git apply` to patch it.
  16. # note that CMAKE_ARGV0 will be the cmake executable
  17. # and that CMAKE_ARGV1 will be -P to enable the script mode
  18. # and that CMAKE_ARGV2 will be the name of this script file itself,
  19. # so we start at CMAKE_ARGV3 to get the first argument passed to this script.
  20. set(PATCH_FILE_NAME "${CMAKE_ARGV3}")
  21. set(PATCH_ALREADY_APPLIED "")
  22. # Check if the patch has already been applied.
  23. # if this command returns 0 it means that reversing the patch was successful
  24. # which means the patch was already applied.
  25. execute_process(
  26. COMMAND git apply --check --reverse "${PATCH_FILE_NAME}"
  27. RESULT_VARIABLE PATCH_ALREADY_APPLIED
  28. OUTPUT_QUIET
  29. ERROR_QUIET
  30. )
  31. if (PATCH_ALREADY_APPLIED STREQUAL "0")
  32. message(STATUS "Skipping already applied patch ${PATCH_FILE_NAME} in dir ${CMAKE_BINARY_DIR}")
  33. else()
  34. message(STATUS "Cleaning directory before patch...")
  35. execute_process(COMMAND git restore .)
  36. execute_process(COMMAND git clean -fdx)
  37. message(STATUS "Applying patch ${PATCH_FILE_NAME} at ${CMAKE_BINARY_DIR}...")
  38. execute_process(
  39. COMMAND git apply --ignore-whitespace "${PATCH_FILE_NAME}"
  40. RESULT_VARIABLE PATCH_RESULT
  41. )
  42. if (NOT PATCH_RESULT EQUAL 0)
  43. message(FATAL_ERROR "Failed to apply patch")
  44. else()
  45. message(STATUS "Patch applied successfully")
  46. endif()
  47. endif()