Files
cmake/Tests/RunCMake/CMP0222/CMP0222-OLD.cmake
T
Mickaël Germain 860583ceac if: Add PATH_IS_PREFIX operator
Testing whether one path is a prefix of another is possible today with
cmake_path(IS_PREFIX), but the idiom needs a separate statement plus a
scratch variable and takes the prefix as a variable name, so projects
reach for if(path MATCHES "^${prefix}") instead.  That is wrong whenever
the prefix contains a regex metacharacter, and it accepts siblings,
because '^/a/b' matches '/a/bc'.

Add a binary operator where the left operand is the candidate prefix and
the right is the path, matching the operand order of cmake_path(IS_PREFIX)
and $<PATH:IS_PREFIX> so that the same operation reads the same way on all
three surfaces.  Neither operand is normalized, matching the default of
cmake_path(IS_PREFIX) and the existing PATH_EQUAL operator, so '.' and
'..' are compared as ordinary components.  The test is non-strict, purely
lexical, and applies no relative-to-absolute reconciliation.

Add policy CMP0222 for compatibility, modeled on CMP0139.  The keyword
is consumed as an operator only when it appears in the second argument
slot, so a variable named PATH_IS_PREFIX keeps working in unary and
left-operand position.  What the policy covers is such a variable
appearing after another token, as in if(NOT PATH_IS_PREFIX AND other),
which becomes a configure error under NEW.

Since the operator is an if() spelling of cmake_path(IS_PREFIX) and shares
its implementation, test it by asserting the two agree over a corpus of
inputs rather than by restating expected values.  Those are pinned by the
cmake_path(IS_PREFIX) test, so the operator's tests stay limited to what
has no command equivalent, and no platform branching is needed because
parity holds whatever the host path model answers.

Fixes: #28040
2026-09-10 07:09:47 -04:00

14 lines
348 B
CMake

cmake_policy(SET CMP0222 OLD)
# Still usable as a value under OLD. Must come first: the case below is
# fatal.
set(PATH_IS_PREFIX "value")
if(PATH_IS_PREFIX STREQUAL "value")
else()
message(SEND_ERROR "PATH_IS_PREFIX not usable as a value under OLD")
endif()
if("/path1" PATH_IS_PREFIX "/path2")
message("PATH_IS_PREFIX recognized")
endif()