| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2013-2021 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from .base import ExternalDependency, DependencyException, DependencyTypeName |
| 7 |
from ..mesonlib import is_windows, MesonException, PerMachine |
| 8 |
from ..cmake import CMakeExecutor, CMakeTraceParser, CMakeException, CMakeToolchain, CMakeExecScope, check_cmake_args, resolve_cmake_trace_targets, cmake_is_debug |
| 9 |
from .. import mlog |
| 10 |
import importlib.resources |
| 11 |
from pathlib import Path |
| 12 |
import functools |
| 13 |
import re |
| 14 |
import os |
| 15 |
import shutil |
| 16 |
import textwrap |
| 17 |
import typing as T |
| 18 |
|
| 19 |
if T.TYPE_CHECKING: |
| 20 |
from ..compilers.compilers import Language |
| 21 |
from ..cmake import CMakeTarget |
| 22 |
from ..environment import Environment |
| 23 |
from ..envconfig import MachineInfo |
| 24 |
from ..interpreter.type_checking import PkgConfigDefineType |
| 25 |
from .base import DependencyObjectKWs |
| 26 |
|
| 27 |
class CMakeInfo(T.NamedTuple): |
| 28 |
module_paths: T.List[str] |
| 29 |
cmake_root: str |
| 30 |
archs: T.List[str] |
| 31 |
common_paths: T.List[str] |
| 32 |
|
| 33 |
class CMakeDependency(ExternalDependency): |
| 34 |
# The class's copy of the CMake path. Avoids having to search for it |
| 35 |
# multiple times in the same Meson invocation. |
| 36 |
class_cmakeinfo: PerMachine[T.Optional[CMakeInfo]] = PerMachine(None, None) |
| 37 |
# Version string for the minimum CMake version |
| 38 |
class_cmake_version = '>=3.4' |
| 39 |
# CMake generators to try (empty for no generator) |
| 40 |
class_cmake_generators = ['', 'Ninja', 'Unix Makefiles', 'Visual Studio 10 2010'] |
| 41 |
class_working_generator: T.Optional[str] = None |
| 42 |
|
| 43 |
type_name = DependencyTypeName('cmake') |
| 44 |
|
| 45 |
def _gen_exception(self, msg: str) -> DependencyException: |
| 46 |
return DependencyException(f'Dependency {self.name} not found: {msg}') |
| 47 |
|
| 48 |
def _main_cmake_file(self) -> str: |
| 49 |
return 'CMakeLists.txt' |
| 50 |
|
| 51 |
def _extra_cmake_opts(self) -> T.List[str]: |
| 52 |
return [] |
| 53 |
|
| 54 |
def _map_module_list(self, modules: T.List[T.Tuple[str, bool]], components: T.List[T.Tuple[str, bool]]) -> T.List[T.Tuple[str, bool]]: |
| 55 |
# Map the input module list to something else |
| 56 |
# This function will only be executed AFTER the initial CMake |
| 57 |
# interpreter pass has completed. Thus variables defined in the |
| 58 |
# CMakeLists.txt can be accessed here. |
| 59 |
# |
| 60 |
# Both the modules and components inputs contain the original lists. |
| 61 |
return modules |
| 62 |
|
| 63 |
def _map_component_list(self, modules: T.List[T.Tuple[str, bool]], components: T.List[T.Tuple[str, bool]]) -> T.List[T.Tuple[str, bool]]: |
| 64 |
# Map the input components list to something else. This |
| 65 |
# function will be executed BEFORE the initial CMake interpreter |
| 66 |
# pass. Thus variables from the CMakeLists.txt can NOT be accessed. |
| 67 |
# |
| 68 |
# Both the modules and components inputs contain the original lists. |
| 69 |
return components |
| 70 |
|
| 71 |
def _original_module_name(self, module: str) -> str: |
| 72 |
# Reverse the module mapping done by _map_module_list for |
| 73 |
# one module |
| 74 |
return module |
| 75 |
|
| 76 |
def __init__(self, name: str, environment: 'Environment', kwargs: DependencyObjectKWs, force_use_global_compilers: bool = False) -> None: |
| 77 |
super().__init__(name, environment, kwargs) |
| 78 |
self.is_libtool = False |
| 79 |
|
| 80 |
# Gather a list of all languages to support |
| 81 |
self.language_list: T.List[Language] |
| 82 |
language = kwargs.get('language') |
| 83 |
if language is None or force_use_global_compilers: |
| 84 |
compilers = environment.coredata.compilers[self.for_machine] |
| 85 |
candidates: T.List[Language] = ['c', 'cpp', 'fortran', 'objc', 'objcpp'] |
| 86 |
self.language_list = [x for x in candidates if x in compilers] |
| 87 |
else: |
| 88 |
self.language_list = [language] |
| 89 |
|
| 90 |
# Add additional languages if required |
| 91 |
if 'fortran' in self.language_list: |
| 92 |
self.language_list.append('c') |
| 93 |
|
| 94 |
# Ensure that the list is unique |
| 95 |
self.language_list = list(set(self.language_list)) |
| 96 |
|
| 97 |
# Where all CMake "build dirs" are located |
| 98 |
self.cmake_root_dir = environment.scratch_dir |
| 99 |
|
| 100 |
# T.List of successfully found modules |
| 101 |
self.found_modules: T.List[str] = [] |
| 102 |
|
| 103 |
# Store a copy of the CMake path on the object itself so it is |
| 104 |
# stored in the pickled coredata and recovered. |
| 105 |
# |
| 106 |
# TODO further evaluate always using MachineChoice.BUILD |
| 107 |
self.cmakebin = CMakeExecutor(environment, CMakeDependency.class_cmake_version, self.for_machine, silent=self.silent) |
| 108 |
if not self.cmakebin.found(): |
| 109 |
msg = f'CMake binary for machine {self.for_machine} not found. Giving up.' |
| 110 |
if self.required: |
| 111 |
raise DependencyException(msg) |
| 112 |
mlog.debug(msg) |
| 113 |
return |
| 114 |
|
| 115 |
# Setup the trace parser |
| 116 |
self.traceparser = CMakeTraceParser(self.cmakebin.version(), self._get_build_dir(), self.env) |
| 117 |
|
| 118 |
cm_args = kwargs.get('cmake_args', []) |
| 119 |
cm_args = check_cmake_args(cm_args) |
| 120 |
if CMakeDependency.class_cmakeinfo[self.for_machine] is None: |
| 121 |
CMakeDependency.class_cmakeinfo[self.for_machine] = self._get_cmake_info(cm_args) |
| 122 |
cmakeinfo = CMakeDependency.class_cmakeinfo[self.for_machine] |
| 123 |
if cmakeinfo is None: |
| 124 |
raise self._gen_exception('Unable to obtain CMake system information') |
| 125 |
self.cmakeinfo = cmakeinfo |
| 126 |
|
| 127 |
package_version = kwargs.get('cmake_package_version', '') |
| 128 |
components = [(x, True) for x in kwargs.get('components', [])] |
| 129 |
modules = [(x, True) for x in kwargs.get('modules', [])] |
| 130 |
modules += [(x, False) for x in kwargs.get('optional_modules', [])] |
| 131 |
cm_path = [x if os.path.isabs(x) else os.path.join(environment.get_source_dir(), x) for x in kwargs.get('cmake_module_path', [])] |
| 132 |
if cm_path: |
| 133 |
cm_args.append('-DCMAKE_MODULE_PATH=' + ';'.join(cm_path)) |
| 134 |
if not self._preliminary_find_check(name, cm_path, self.cmakebin.get_cmake_prefix_paths(), environment.machines[self.for_machine]): |
| 135 |
mlog.debug('Preliminary CMake check failed. Aborting.') |
| 136 |
return |
| 137 |
self._detect_dep(name, package_version, modules, components, cm_args) |
| 138 |
|
| 139 |
def __repr__(self) -> str: |
| 140 |
return f'<{self.__class__.__name__} {self.name}: {self.is_found} {self.version_reqs}>' |
| 141 |
|
| 142 |
def _get_cmake_info(self, cm_args: T.List[str]) -> T.Optional[CMakeInfo]: |
| 143 |
mlog.debug("Extracting basic cmake information") |
| 144 |
|
| 145 |
# Try different CMake generators since specifying no generator may fail |
| 146 |
# in cygwin for some reason |
| 147 |
gen_list = [] |
| 148 |
# First try the last working generator |
| 149 |
if CMakeDependency.class_working_generator is not None: |
| 150 |
gen_list += [CMakeDependency.class_working_generator] |
| 151 |
gen_list += CMakeDependency.class_cmake_generators |
| 152 |
|
| 153 |
temp_parser = CMakeTraceParser(self.cmakebin.version(), self._get_build_dir(), self.env) |
| 154 |
toolchain = CMakeToolchain(self.cmakebin, self.env, self.for_machine, CMakeExecScope.DEPENDENCY, self._get_build_dir()) |
| 155 |
toolchain.write() |
| 156 |
|
| 157 |
for i in gen_list: |
| 158 |
mlog.debug('Try CMake generator: {}'.format(i if len(i) > 0 else 'auto')) |
| 159 |
|
| 160 |
# Prepare options |
| 161 |
cmake_opts = temp_parser.trace_args() + toolchain.get_cmake_args() + ['.'] |
| 162 |
cmake_opts += cm_args |
| 163 |
if len(i) > 0: |
| 164 |
cmake_opts = ['-G', i] + cmake_opts |
| 165 |
|
| 166 |
# Run CMake |
| 167 |
ret1, out1, err1 = self._call_cmake(cmake_opts, 'CMakePathInfo.txt') |
| 168 |
|
| 169 |
# Current generator was successful |
| 170 |
if ret1 == 0: |
| 171 |
CMakeDependency.class_working_generator = i |
| 172 |
break |
| 173 |
|
| 174 |
mlog.debug(f'CMake failed to gather system information for generator {i} with error code {ret1}') |
| 175 |
mlog.debug(f'OUT:\n{out1}\n\n\nERR:\n{err1}\n\n') |
| 176 |
|
| 177 |
# Check if any generator succeeded |
| 178 |
if ret1 != 0: |
| 179 |
return None |
| 180 |
|
| 181 |
try: |
| 182 |
temp_parser.parse(err1) |
| 183 |
except MesonException: |
| 184 |
return None |
| 185 |
|
| 186 |
def process_paths(l: T.List[str]) -> T.Set[str]: |
| 187 |
if is_windows(): |
| 188 |
# Cannot split on ':' on Windows because its in the drive letter |
| 189 |
tmp = [x.split(os.pathsep) for x in l] |
| 190 |
else: |
| 191 |
# https://github.com/mesonbuild/meson/issues/7294 |
| 192 |
tmp = [re.split(r':|;', x) for x in l] |
| 193 |
flattened = [x for sublist in tmp for x in sublist] |
| 194 |
return set(flattened) |
| 195 |
|
| 196 |
# Extract the variables and sanity check them |
| 197 |
root_paths_set = process_paths(temp_parser.get_cmake_var('MESON_FIND_ROOT_PATH')) |
| 198 |
root_paths_set.update(process_paths(temp_parser.get_cmake_var('MESON_CMAKE_SYSROOT'))) |
| 199 |
root_paths = sorted(root_paths_set) |
| 200 |
root_paths = [x for x in root_paths if os.path.isdir(x)] |
| 201 |
module_paths_set = process_paths(temp_parser.get_cmake_var('MESON_PATHS_LIST')) |
| 202 |
rooted_paths: T.List[str] = [] |
| 203 |
for j in [Path(x) for x in root_paths]: |
| 204 |
for p in [Path(x) for x in module_paths_set]: |
| 205 |
rooted_paths.append(str(j / p.relative_to(p.anchor))) |
| 206 |
module_paths = sorted(module_paths_set.union(rooted_paths)) |
| 207 |
module_paths = [x for x in module_paths if os.path.isdir(x)] |
| 208 |
archs = temp_parser.get_cmake_var('MESON_ARCH_LIST') |
| 209 |
|
| 210 |
common_paths = ['lib', 'lib32', 'lib64', 'libx32', 'share', ''] |
| 211 |
for i in archs: |
| 212 |
common_paths += [os.path.join('lib', i)] |
| 213 |
|
| 214 |
res = CMakeInfo( |
| 215 |
module_paths=module_paths, |
| 216 |
cmake_root=temp_parser.get_cmake_var('MESON_CMAKE_ROOT')[0], |
| 217 |
archs=archs, |
| 218 |
common_paths=common_paths, |
| 219 |
) |
| 220 |
|
| 221 |
mlog.debug(f' -- Module search paths: {res.module_paths}') |
| 222 |
mlog.debug(f' -- CMake root: {res.cmake_root}') |
| 223 |
mlog.debug(f' -- CMake architectures: {res.archs}') |
| 224 |
mlog.debug(f' -- CMake lib search paths: {res.common_paths}') |
| 225 |
|
| 226 |
return res |
| 227 |
|
| 228 |
@staticmethod |
| 229 |
@functools.lru_cache(maxsize=None) |
| 230 |
def _cached_listdir(path: str) -> T.Tuple[T.Tuple[str, str], ...]: |
| 231 |
try: |
| 232 |
return tuple((x, str(x).lower()) for x in os.listdir(path)) |
| 233 |
except OSError: |
| 234 |
return tuple() |
| 235 |
|
| 236 |
@staticmethod |
| 237 |
@functools.lru_cache(maxsize=None) |
| 238 |
def _cached_isdir(path: str) -> bool: |
| 239 |
try: |
| 240 |
return os.path.isdir(path) |
| 241 |
except OSError: |
| 242 |
return False |
| 243 |
|
| 244 |
def _preliminary_find_check(self, name: str, module_path: T.List[str], prefix_path: T.List[str], machine: 'MachineInfo') -> bool: |
| 245 |
lname = str(name).lower() |
| 246 |
|
| 247 |
# Checks <path>, <path>/cmake, <path>/CMake |
| 248 |
def find_module(path: str) -> bool: |
| 249 |
for i in [path, os.path.join(path, 'cmake'), os.path.join(path, 'CMake')]: |
| 250 |
if not self._cached_isdir(i): |
| 251 |
continue |
| 252 |
|
| 253 |
# Check the directory case insensitive |
| 254 |
content = self._cached_listdir(i) |
| 255 |
candidates = ['Find{}.cmake', '{}Config.cmake', '{}-config.cmake'] |
| 256 |
candidates = [x.format(name).lower() for x in candidates] |
| 257 |
if any(x[1] in candidates for x in content): |
| 258 |
return True |
| 259 |
return False |
| 260 |
|
| 261 |
# Search in <path>/(lib/<arch>|lib*|share) for cmake files |
| 262 |
def search_lib_dirs(path: str) -> bool: |
| 263 |
for i in [os.path.join(path, x) for x in self.cmakeinfo.common_paths]: |
| 264 |
if not self._cached_isdir(i): |
| 265 |
continue |
| 266 |
|
| 267 |
# Check <path>/(lib/<arch>|lib*|share)/cmake/<name>*/ |
| 268 |
cm_dir = os.path.join(i, 'cmake') |
| 269 |
if self._cached_isdir(cm_dir): |
| 270 |
content = self._cached_listdir(cm_dir) |
| 271 |
content = tuple(x for x in content if x[1].startswith(lname)) |
| 272 |
for k in content: |
| 273 |
if find_module(os.path.join(cm_dir, k[0])): |
| 274 |
return True |
| 275 |
|
| 276 |
# <path>/(lib/<arch>|lib*|share)/<name>*/ |
| 277 |
# <path>/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/ |
| 278 |
content = self._cached_listdir(i) |
| 279 |
content = tuple(x for x in content if x[1].startswith(lname)) |
| 280 |
for k in content: |
| 281 |
if find_module(os.path.join(i, k[0])): |
| 282 |
return True |
| 283 |
|
| 284 |
return False |
| 285 |
|
| 286 |
# Check the user provided and system module paths |
| 287 |
for i in module_path + [os.path.join(self.cmakeinfo.cmake_root, 'Modules')]: |
| 288 |
if find_module(i): |
| 289 |
return True |
| 290 |
|
| 291 |
# Check the user provided prefix paths |
| 292 |
for i in prefix_path: |
| 293 |
if search_lib_dirs(i): |
| 294 |
return True |
| 295 |
|
| 296 |
# Check PATH |
| 297 |
system_env: T.List[str] = [] |
| 298 |
for i in os.environ.get('PATH', '').split(os.pathsep): |
| 299 |
if i.endswith('/bin') or i.endswith('\\bin'): |
| 300 |
i = i[:-4] |
| 301 |
if i.endswith('/sbin') or i.endswith('\\sbin'): |
| 302 |
i = i[:-5] |
| 303 |
system_env += [i] |
| 304 |
|
| 305 |
# Check the system paths |
| 306 |
for i in self.cmakeinfo.module_paths + system_env: |
| 307 |
if find_module(i): |
| 308 |
return True |
| 309 |
|
| 310 |
if search_lib_dirs(i): |
| 311 |
return True |
| 312 |
|
| 313 |
content = self._cached_listdir(i) |
| 314 |
content = tuple(x for x in content if x[1].startswith(lname)) |
| 315 |
for k in content: |
| 316 |
if search_lib_dirs(os.path.join(i, k[0])): |
| 317 |
return True |
| 318 |
|
| 319 |
# Mac framework support |
| 320 |
if machine.is_darwin(): |
| 321 |
for j in [f'{lname}.framework', f'{lname}.app']: |
| 322 |
for k in content: |
| 323 |
if k[1] != j: |
| 324 |
continue |
| 325 |
if find_module(os.path.join(i, k[0], 'Resources')) or find_module(os.path.join(i, k[0], 'Version')): |
| 326 |
return True |
| 327 |
|
| 328 |
# Check the environment path |
| 329 |
env_path = os.environ.get(f'{name}_DIR') |
| 330 |
if env_path and find_module(env_path): |
| 331 |
return True |
| 332 |
|
| 333 |
# Check the Linux CMake registry |
| 334 |
linux_reg = Path.home() / '.cmake' / 'packages' |
| 335 |
for p in [linux_reg / name, linux_reg / lname]: |
| 336 |
if p.exists(): |
| 337 |
return True |
| 338 |
|
| 339 |
return False |
| 340 |
|
| 341 |
def _detect_dep(self, name: str, package_version: str, modules: T.List[T.Tuple[str, bool]], components: T.List[T.Tuple[str, bool]], args: T.List[str]) -> None: |
| 342 |
# Detect a dependency with CMake using the '--find-package' mode |
| 343 |
# and the trace output (stderr) |
| 344 |
# |
| 345 |
# When the trace output is enabled CMake prints all functions with |
| 346 |
# parameters to stderr as they are executed. Since CMake 3.4.0 |
| 347 |
# variables ("${VAR}") are also replaced in the trace output. |
| 348 |
mlog.debug('\nDetermining dependency {!r} with CMake executable ' |
| 349 |
'{!r}'.format(name, self.cmakebin.executable_path())) |
| 350 |
|
| 351 |
# Try different CMake generators since specifying no generator may fail |
| 352 |
# in cygwin for some reason |
| 353 |
gen_list = [] |
| 354 |
# First try the last working generator |
| 355 |
if CMakeDependency.class_working_generator is not None: |
| 356 |
gen_list += [CMakeDependency.class_working_generator] |
| 357 |
gen_list += CMakeDependency.class_cmake_generators |
| 358 |
|
| 359 |
# Map the components |
| 360 |
comp_mapped = self._map_component_list(modules, components) |
| 361 |
toolchain = CMakeToolchain(self.cmakebin, self.env, self.for_machine, CMakeExecScope.DEPENDENCY, self._get_build_dir()) |
| 362 |
toolchain.write() |
| 363 |
|
| 364 |
for i in gen_list: |
| 365 |
mlog.debug('Try CMake generator: {}'.format(i if len(i) > 0 else 'auto')) |
| 366 |
|
| 367 |
# Prepare options |
| 368 |
cmake_opts = [] |
| 369 |
cmake_opts += [f'-DNAME={name}'] |
| 370 |
cmake_opts += ['-DARCHS={}'.format(';'.join(self.cmakeinfo.archs))] |
| 371 |
cmake_opts += [f'-DVERSION={package_version}'] |
| 372 |
cmake_opts += ['-DCOMPS={}'.format(';'.join([x[0] for x in comp_mapped]))] |
| 373 |
cmake_opts += ['-DSTATIC={}'.format('ON' if self.static else 'OFF')] |
| 374 |
cmake_opts += args |
| 375 |
cmake_opts += self.traceparser.trace_args() |
| 376 |
cmake_opts += toolchain.get_cmake_args() |
| 377 |
cmake_opts += self._extra_cmake_opts() |
| 378 |
cmake_opts += ['.'] |
| 379 |
if len(i) > 0: |
| 380 |
cmake_opts = ['-G', i] + cmake_opts |
| 381 |
|
| 382 |
# Run CMake |
| 383 |
ret1, out1, err1 = self._call_cmake(cmake_opts, self._main_cmake_file()) |
| 384 |
|
| 385 |
# Current generator was successful |
| 386 |
if ret1 == 0: |
| 387 |
CMakeDependency.class_working_generator = i |
| 388 |
break |
| 389 |
|
| 390 |
mlog.debug(f'CMake failed for generator {i} and package {name} with error code {ret1}') |
| 391 |
mlog.debug(f'OUT:\n{out1}\n\n\nERR:\n{err1}\n\n') |
| 392 |
|
| 393 |
# Check if any generator succeeded |
| 394 |
if ret1 != 0: |
| 395 |
return |
| 396 |
|
| 397 |
try: |
| 398 |
self.traceparser.parse(err1) |
| 399 |
except CMakeException as e: |
| 400 |
e2 = self._gen_exception(str(e)) |
| 401 |
if self.required: |
| 402 |
raise |
| 403 |
else: |
| 404 |
self.compile_args = [] |
| 405 |
self.link_args = [] |
| 406 |
self.is_found = False |
| 407 |
self.reason = e2 |
| 408 |
return |
| 409 |
|
| 410 |
# Whether the package is found or not is always stored in PACKAGE_FOUND |
| 411 |
self.is_found = self.traceparser.var_to_bool('PACKAGE_FOUND') |
| 412 |
if not self.is_found: |
| 413 |
not_found_message = self.traceparser.get_cmake_var('PACKAGE_NOT_FOUND_MESSAGE') |
| 414 |
if len(not_found_message) > 0: |
| 415 |
mlog.notice( |
| 416 |
'CMake reported that the package {} was not found with the following reason:\n' |
| 417 |
'{}'.format(name, not_found_message[0]), fatal=False) |
| 418 |
else: |
| 419 |
mlog.debug( |
| 420 |
'CMake reported that the package {} was not found, ' |
| 421 |
'even though Meson\'s preliminary check succeeded.'.format(name)) |
| 422 |
raise self._gen_exception('PACKAGE_FOUND is false') |
| 423 |
|
| 424 |
# Try to detect the version |
| 425 |
vers_raw = self.traceparser.get_cmake_var('PACKAGE_VERSION') |
| 426 |
|
| 427 |
if len(vers_raw) > 0: |
| 428 |
self.version = vers_raw[0] |
| 429 |
self.version.strip('"\' ') |
| 430 |
|
| 431 |
# Post-process module list. Used in derived classes to modify the |
| 432 |
# module list (append prepend a string, etc.). |
| 433 |
modules = self._map_module_list(modules, components) |
| 434 |
autodetected_module_list = False |
| 435 |
|
| 436 |
# Try guessing a CMake target if none is provided |
| 437 |
if len(modules) == 0: |
| 438 |
for i in self.traceparser.targets: |
| 439 |
tg = i.lower() |
| 440 |
lname = name.lower() |
| 441 |
if f'{lname}::{lname}' == tg or lname == tg.replace('::', ''): |
| 442 |
mlog.debug(f'Guessed CMake target \'{i}\'') |
| 443 |
modules = [(i, True)] |
| 444 |
autodetected_module_list = True |
| 445 |
break |
| 446 |
|
| 447 |
# Failed to guess a target --> try the old-style method |
| 448 |
if len(modules) == 0: |
| 449 |
# Warn when there might be matching imported targets but no automatic match was used |
| 450 |
partial_modules: T.List[CMakeTarget] = [] |
| 451 |
for k, v in self.traceparser.targets.items(): |
| 452 |
tg = k.lower() |
| 453 |
lname = name.lower() |
| 454 |
if tg.startswith(f'{lname}::'): |
| 455 |
partial_modules += [v] |
| 456 |
if partial_modules: |
| 457 |
mlog.warning(textwrap.dedent(f'''\ |
| 458 |
Could not find and exact match for the CMake dependency {name}. |
| 459 |
|
| 460 |
However, Meson found the following partial matches: |
| 461 |
|
| 462 |
{[x.name for x in partial_modules]} |
| 463 |
|
| 464 |
Using imported is recommended, since this approach is less error prone |
| 465 |
and better supported by Meson. Consider explicitly specifying one of |
| 466 |
these in the dependency call with: |
| 467 |
|
| 468 |
dependency('{name}', modules: ['{name}::<name>', ...]) |
| 469 |
|
| 470 |
Meson will now continue to use the old-style {name}_LIBRARIES CMake |
| 471 |
variables to extract the dependency information since no explicit |
| 472 |
target is currently specified. |
| 473 |
|
| 474 |
''')) |
| 475 |
mlog.debug('More info for the partial match targets:') |
| 476 |
for tgt in partial_modules: |
| 477 |
mlog.debug(tgt) |
| 478 |
|
| 479 |
incDirs = [x for x in self.traceparser.get_cmake_var('PACKAGE_INCLUDE_DIRS') if x] |
| 480 |
defs = [x for x in self.traceparser.get_cmake_var('PACKAGE_DEFINITIONS') if x] |
| 481 |
libs_raw = [x for x in self.traceparser.get_cmake_var('PACKAGE_LIBRARIES') if x] |
| 482 |
|
| 483 |
# CMake has a "fun" API, where certain keywords describing |
| 484 |
# configurations can be in the *_LIBRARIES variables. See: |
| 485 |
# - https://github.com/mesonbuild/meson/issues/9197 |
| 486 |
# - https://gitlab.freedesktop.org/libnice/libnice/-/issues/140 |
| 487 |
# - https://cmake.org/cmake/help/latest/command/target_link_libraries.html#overview (the last point in the section) |
| 488 |
libs: T.List[str] = [] |
| 489 |
cfg_matches = True |
| 490 |
is_debug = cmake_is_debug(self.env) |
| 491 |
cm_tag_map = {'debug': is_debug, 'optimized': not is_debug, 'general': True} |
| 492 |
for i in libs_raw: |
| 493 |
if i.lower() in cm_tag_map: |
| 494 |
cfg_matches = cm_tag_map[i.lower()] |
| 495 |
continue |
| 496 |
if cfg_matches: |
| 497 |
libs += [i] |
| 498 |
# According to the CMake docs, a keyword only works for the |
| 499 |
# directly the following item and all items without a keyword |
| 500 |
# are implicitly `general` |
| 501 |
cfg_matches = True |
| 502 |
|
| 503 |
# Try to use old style variables if no module is specified |
| 504 |
if len(libs) > 0: |
| 505 |
self.compile_args = [f'-I{x}' for x in incDirs] + defs |
| 506 |
self.link_args = [] |
| 507 |
for j in libs: |
| 508 |
rtgt = resolve_cmake_trace_targets(j, self.traceparser, self.env, clib_compiler=self.clib_compiler) |
| 509 |
self.link_args += rtgt.libraries |
| 510 |
self.compile_args += [f'-I{x}' for x in rtgt.include_directories] |
| 511 |
self.compile_args += rtgt.public_compile_opts |
| 512 |
mlog.debug(f'using old-style CMake variables for dependency {name}') |
| 513 |
mlog.debug(f'Include Dirs: {incDirs}') |
| 514 |
mlog.debug(f'Compiler Definitions: {defs}') |
| 515 |
mlog.debug(f'Libraries: {libs}') |
| 516 |
return |
| 517 |
|
| 518 |
# Even the old-style approach failed. Nothing else we can do here |
| 519 |
self.is_found = False |
| 520 |
raise self._gen_exception('CMake: failed to guess a CMake target for {}.\n' |
| 521 |
'Try to explicitly specify one or more targets with the "modules" property.\n' |
| 522 |
'Valid targets are:\n{}'.format(name, list(self.traceparser.targets.keys()))) |
| 523 |
|
| 524 |
# Set dependencies with CMake targets |
| 525 |
# recognise arguments we should pass directly to the linker |
| 526 |
incDirs = [] |
| 527 |
compileOptions = [] |
| 528 |
libraries = [] |
| 529 |
|
| 530 |
for i, required in modules: |
| 531 |
if i not in self.traceparser.targets: |
| 532 |
if not required: |
| 533 |
mlog.warning('CMake: Optional module', mlog.bold(self._original_module_name(i)), 'for', mlog.bold(name), 'was not found') |
| 534 |
continue |
| 535 |
raise self._gen_exception('CMake: invalid module {} for {}.\n' |
| 536 |
'Try to explicitly specify one or more targets with the "modules" property.\n' |
| 537 |
'Valid targets are:\n{}'.format(self._original_module_name(i), name, list(self.traceparser.targets.keys()))) |
| 538 |
|
| 539 |
if not autodetected_module_list: |
| 540 |
self.found_modules += [i] |
| 541 |
|
| 542 |
rtgt = resolve_cmake_trace_targets(i, self.traceparser, self.env, |
| 543 |
clib_compiler=self.clib_compiler, |
| 544 |
not_found_warning=lambda x: |
| 545 |
mlog.warning('CMake: Dependency', mlog.bold(x), 'for', mlog.bold(name), 'was not found') |
| 546 |
) |
| 547 |
incDirs += rtgt.include_directories |
| 548 |
compileOptions += rtgt.public_compile_opts |
| 549 |
libraries += rtgt.libraries + rtgt.link_flags |
| 550 |
|
| 551 |
# Make sure all elements in the lists are unique and sorted |
| 552 |
incDirs = sorted(set(incDirs)) |
| 553 |
compileOptions = sorted(set(compileOptions)) |
| 554 |
libraries = sort_link_args(libraries) |
| 555 |
|
| 556 |
mlog.debug(f'Include Dirs: {incDirs}') |
| 557 |
mlog.debug(f'Compiler Options: {compileOptions}') |
| 558 |
mlog.debug(f'Libraries: {libraries}') |
| 559 |
|
| 560 |
self.compile_args = compileOptions + [f'-I{x}' for x in incDirs] |
| 561 |
self.link_args = libraries |
| 562 |
|
| 563 |
def _get_build_dir(self) -> Path: |
| 564 |
build_dir = Path(self.cmake_root_dir) / f'cmake_{self.name}' |
| 565 |
build_dir.mkdir(parents=True, exist_ok=True) |
| 566 |
return build_dir |
| 567 |
|
| 568 |
def _setup_cmake_dir(self, cmake_file: str) -> Path: |
| 569 |
# Setup the CMake build environment and return the "build" directory |
| 570 |
build_dir = self._get_build_dir() |
| 571 |
|
| 572 |
# Remove old CMake cache so we can try out multiple generators |
| 573 |
cmake_cache = build_dir / 'CMakeCache.txt' |
| 574 |
cmake_files = build_dir / 'CMakeFiles' |
| 575 |
if cmake_cache.exists(): |
| 576 |
cmake_cache.unlink() |
| 577 |
shutil.rmtree(cmake_files.as_posix(), ignore_errors=True) |
| 578 |
|
| 579 |
# Insert language parameters into the CMakeLists.txt and write new CMakeLists.txt |
| 580 |
cmake_txt = importlib.resources.read_text('mesonbuild.dependencies.data', cmake_file, encoding = 'utf-8') |
| 581 |
|
| 582 |
# In general, some Fortran CMake find_package() also require C language enabled, |
| 583 |
# even if nothing from C is directly used. An easy Fortran example that fails |
| 584 |
# without C language is |
| 585 |
# find_package(Threads) |
| 586 |
# To make this general to |
| 587 |
# any other language that might need this, we use a list for all |
| 588 |
# languages and expand in the cmake Project(... LANGUAGES ...) statement. |
| 589 |
from ..cmake import language_map |
| 590 |
cmake_language = [language_map[x] for x in self.language_list if x in language_map] |
| 591 |
if not cmake_language: |
| 592 |
cmake_language += ['NONE'] |
| 593 |
|
| 594 |
cmake_txt = textwrap.dedent(""" |
| 595 |
cmake_minimum_required(VERSION ${{CMAKE_VERSION}}) |
| 596 |
project(MesonTemp LANGUAGES {}) |
| 597 |
""").format(' '.join(cmake_language)) + cmake_txt |
| 598 |
|
| 599 |
cm_file = build_dir / 'CMakeLists.txt' |
| 600 |
cm_file.write_text(cmake_txt, encoding='utf-8') |
| 601 |
mlog.cmd_ci_include(cm_file.absolute().as_posix()) |
| 602 |
|
| 603 |
return build_dir |
| 604 |
|
| 605 |
def _call_cmake(self, |
| 606 |
args: T.List[str], |
| 607 |
cmake_file: str, |
| 608 |
env: T.Optional[T.Dict[str, str]] = None) -> T.Tuple[int, T.Optional[str], T.Optional[str]]: |
| 609 |
build_dir = self._setup_cmake_dir(cmake_file) |
| 610 |
return self.cmakebin.call(args, build_dir, env=env) |
| 611 |
|
| 612 |
def log_details(self) -> str: |
| 613 |
modules = [self._original_module_name(x) for x in self.found_modules] |
| 614 |
modules = sorted(set(modules)) |
| 615 |
if modules: |
| 616 |
return 'modules: ' + ', '.join(modules) |
| 617 |
return '' |
| 618 |
|
| 619 |
def get_variable(self, *, cmake: T.Optional[str] = None, pkgconfig: T.Optional[str] = None, |
| 620 |
configtool: T.Optional[str] = None, internal: T.Optional[str] = None, |
| 621 |
system: T.Optional[str] = None, default_value: T.Optional[str] = None, |
| 622 |
pkgconfig_define: PkgConfigDefineType = None) -> str: |
| 623 |
if cmake and self.traceparser is not None: |
| 624 |
try: |
| 625 |
v = self.traceparser.vars[cmake] |
| 626 |
except KeyError: |
| 627 |
pass |
| 628 |
else: |
| 629 |
# CMake does NOT have a list datatype. We have no idea whether |
| 630 |
# anything is a string or a string-separated-by-; Internally, |
| 631 |
# we treat them as the latter and represent everything as a |
| 632 |
# list, because it is convenient when we are mostly handling |
| 633 |
# imported targets, which have various properties that are |
| 634 |
# actually lists. |
| 635 |
# |
| 636 |
# As a result we need to convert them back to strings when grabbing |
| 637 |
# raw variables the user requested. |
| 638 |
return ';'.join(v) |
| 639 |
if default_value is not None: |
| 640 |
return default_value |
| 641 |
raise DependencyException(f'Could not get cmake variable and no default provided for {self!r}') |
| 642 |
|
| 643 |
|
| 644 |
def sort_link_args(args: T.List[str]) -> T.List[str]: |
| 645 |
itr = iter(args) |
| 646 |
result: T.Set[T.Union[T.Tuple[str], T.Tuple[str, str]]] = set() |
| 647 |
|
| 648 |
while True: |
| 649 |
try: |
| 650 |
arg = next(itr) |
| 651 |
except StopIteration: |
| 652 |
break |
| 653 |
|
| 654 |
if arg == '-framework': |
| 655 |
# Frameworks '-framework ...' are two arguments that need to stay together |
| 656 |
try: |
| 657 |
arg2 = next(itr) |
| 658 |
except StopIteration: |
| 659 |
raise MesonException(f'Linker arguments contain \'-framework\' with no argument value: {args}') |
| 660 |
|
| 661 |
result.add((arg, arg2)) |
| 662 |
else: |
| 663 |
result.add((arg,)) |
| 664 |
|
| 665 |
return [x for xs in sorted(result) for x in xs] |