xref: /llvm-project/cmake/Modules/FindPrefixFromConfig.cmake (revision ae72cc72d7064fe0a71d41e0660a1cb6147de46a)
1# Find the prefix from the `*Config.cmake` file being generated.
2#
3# When generating an installed `*Config.cmake` file, we often want to be able
4# to refer to the ancestor directory which contains all the installed files.
5#
6# We want to do this without baking in an absolute path when the config file is
7# generated, in order to allow for a "relocatable" binary distribution that
8# doesn't need to know what path it ends up being installed at when it is
9# built.
10#
11# The solution that we know the relative path that the config file will be at
12# within that prefix, like `"${prefix_var}/lib/cmake/${project}"`, so we count
13# the number of components in that path to figure out how many parent dirs we
14# need to traverse from the location of the config file to get to the prefix
15# dir.
16#
17# out_var:
18#   variable to set the "return value" of the function, which is the code to
19#   include in the config file under construction.
20#
21# prefix_var:
22#   Name of the variable to define in the returned code (not directory for the
23#   faller!) that will contain the prefix path.
24#
25# path_to_leave:
26#   Path from the prefix to the config file, a relative path which we wish to
27#   go up and out from to find the prefix directory.
28function(find_prefix_from_config out_var prefix_var path_to_leave)
29  if(IS_ABSOLUTE "${path_to_leave}")
30    # Because the path is absolute, we don't care about `path_to_leave`
31    # because we can just "jump" to the absolute path rather than work
32    # our way there relatively.
33    set(config_code
34      "# Installation prefix is fixed absolute path"
35      "set(${prefix_var} \"${CMAKE_INSTALL_PREFIX}\")")
36  else()
37    # `path_to_leave` is relative. Relative to what? The install prefix.
38    # We therefore go up enough parent directories to get back to the
39    # install prefix, and avoid hard-coding any absolute paths.
40    set(config_code
41      "# Compute the installation prefix from this LLVMConfig.cmake file location."
42      "get_filename_component(${prefix_var} \"\${CMAKE_CURRENT_LIST_FILE}\" PATH)")
43    # Construct the proper number of get_filename_component(... PATH)
44    # calls to compute the installation prefix.
45    string(REGEX REPLACE "/" ";" _count "${path_to_leave}")
46    foreach(p ${_count})
47      list(APPEND config_code
48        "get_filename_component(${prefix_var} \"\${${prefix_var}}\" PATH)")
49    endforeach(p)
50  endif()
51  string(REPLACE ";" "\n" config_code "${config_code}")
52  set("${out_var}" "${config_code}" PARENT_SCOPE)
53endfunction()
54