PathManip

Operation to manipulate paths by extending the cmake_path() command. It requires CMake 4.0.1 or newer.

Only syntactic aspects of paths are handled, there is no interaction of any kind with any underlying file system. A path may represent a non-existing path or even one that is not allowed to exist on the current file system or platform , no error is raised when a file do not exist.

For operations that do interact with the filesystem, see the FileManip module and the file() command.

Synopsis

path_manip(STRIP_PATH <file-list-var> BASE_DIR <dir-path> [OUTPUT_VARIABLE <output-list-var>])
path_manip(GET_COMPONENT [<file-path>...] MODE <mode> OUTPUT_VARIABLE <output-list-var>)

Usage

path_manip(STRIP_PATH <file-list-var> BASE_DIR <dir-path> [OUTPUT_VARIABLE <output-list-var>])

Removes the BASE_DIR prefix from each file or directory path in <file-list-var>. The result is stored either in-place in <file-list-var>, or in the variable specified by <output-list-var>, if the OUTPUT_VARIABLE option is provided. BASE_DIR must be provided without trailing slash. A path can be relative or absolute. The result is an empty list if the input list is empty.

Example usage:

set(files
  "src/main.cpp"
  "src"
  "${CMAKE_SOURCE_DIR}/src/main.cpp"
  "${CMAKE_SOURCE_DIR}/src"
  "fake/directory/file.cpp"
  "fake/directory"
  "${CMAKE_SOURCE_DIR}/fake/directory/file.cpp"
  "${CMAKE_SOURCE_DIR}/fake/directory")
path_manip(STRIP_PATH files BASE_DIR "${CMAKE_SOURCE_DIR}")
# output is:
#   src/main.cpp;src;src/main.cpp;src;fake/directory/file.cpp;fake/directory;fake/directory/file.cpp;fake/directory
path_manip(GET_COMPONENT [<file-path>...] MODE <mode> OUTPUT_VARIABLE <output-list-var>)

Extracts a specific component defined by MODE from each path to a file or a directory in the given <file-path> list and stores the result in the variable specified by OUTPUT_VARIABLE option. A path can be relative or absolute. The result is an empty list if the input list is empty.

The MODE argument determines which component to extract and must be one of:

  • DIRECTORY - Directory without file name.

  • NAME - File name without directory.

Example usage:

set(files
  "src/main.cpp"
  "src"
  "${CMAKE_SOURCE_DIR}/src/main.cpp"
  "${CMAKE_SOURCE_DIR}/src"
  "fake/directory/file.cpp"
  "fake/directory"
  "${CMAKE_SOURCE_DIR}/fake/directory/file.cpp"
  "${CMAKE_SOURCE_DIR}/fake/directory")
path_manip(GET_COMPONENT ${files} MODE DIRECTORY OUTPUT_VARIABLE dirs)
# dirs is:
#   src;src;/full/path/to/src;/full/path/to/src;fake/directory;fake;full/path/to/fake/directory;full/path/to/fake
path_manip(GET_COMPONENT ${files} MODE NAME OUTPUT_VARIABLE filenames)
# filenames is:
#   main.cpp;src;main.cpp;src;file.cpp;directory;file.cpp;directory