Files
ollama/llama/compat/compat.cmake
jmorganca 436f2e2b15 llama/compat: make patch-apply idempotent
FetchContent's PATCH_COMMAND runs after each update step — including on
incremental rebuilds. `git apply` fails when the patch is already applied,
which bricks the build until the dev wipes build/ entirely.

Fix by routing the apply through a small apply-patch.cmake helper that
checks `git apply --reverse --check` first. If the patch cleanly reverses,
it's already applied and we skip. Otherwise apply forward. Both branches
surface real errors (drift against upstream, missing patch file, etc.).

Verified: fresh configure+build applies the patch once; re-running the
same commands is a no-op with no errors.
2026-04-20 09:29:34 -07:00

52 lines
2.1 KiB
CMake

# llama.cpp compatibility shim — CMake integration
#
# Include this file BEFORE calling FetchContent_Declare(llama_cpp ...) to
# patch the fetched upstream llama.cpp with Ollama's in-process compat
# layer. Example usage:
#
# include(${CMAKE_CURRENT_SOURCE_DIR}/../compat/compat.cmake)
#
# FetchContent_Declare(
# llama_cpp
# GIT_REPOSITORY ...
# GIT_TAG ${LLAMA_CPP_GIT_TAG}
# GIT_SHALLOW TRUE
# PATCH_COMMAND ${OLLAMA_LLAMA_CPP_COMPAT_PATCH_COMMAND}
# UPDATE_DISCONNECTED TRUE
# )
#
# The compat layer consists of:
# 1. Two new source files dropped into the fetched tree's src/
# (llama-ollama-compat.{h,cpp}) — Ollama-owned.
# 2. A small patch (upstream-edits.patch) that wires the new files into
# the build and adds call-sites in upstream loaders.
set(_compat_dir ${CMAKE_CURRENT_LIST_DIR})
# Expose a single variable the main CMakeLists passes into FetchContent's
# PATCH_COMMAND. Uses CMake's own `-E copy` for cross-platform file copy.
# The patch itself is applied via a small CMake script so the step is
# idempotent — re-configuring or rebuilding won't fail with "already applied".
set(OLLAMA_LLAMA_CPP_COMPAT_PATCH_COMMAND
${CMAKE_COMMAND} -E copy
"${_compat_dir}/llama-ollama-compat.h"
"src/llama-ollama-compat.h"
COMMAND ${CMAKE_COMMAND} -E copy
"${_compat_dir}/llama-ollama-compat.cpp"
"src/llama-ollama-compat.cpp"
COMMAND ${CMAKE_COMMAND}
-DPATCH_FILE=${_compat_dir}/upstream-edits.patch
-P ${_compat_dir}/apply-patch.cmake
CACHE INTERNAL "llama.cpp compat patch command for FetchContent")
# Also export the individual paths in case callers want to do something
# custom (e.g. emit a dependency on the patch so reconfigures re-apply).
set(OLLAMA_LLAMA_CPP_COMPAT_PATCH_FILE
"${_compat_dir}/upstream-edits.patch"
CACHE INTERNAL "Path to the llama.cpp compat patch")
set(OLLAMA_LLAMA_CPP_COMPAT_SOURCES
"${_compat_dir}/llama-ollama-compat.h"
"${_compat_dir}/llama-ollama-compat.cpp"
CACHE INTERNAL "Source files copied into llama.cpp's src/ dir")