Debian Codegraph @

mesonbuild/modules/pkgconfig.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2015-2022 The Meson development team
3
4 from __future__ import annotations
5 from collections import defaultdict
6 from dataclasses import dataclass
7 from pathlib import PurePath, PurePosixPath
8 import itertools
9 import os
10 import typing as T
11
12 from . import NewExtensionModule, ModuleInfo
13 from . import ModuleReturnValue
14 from .. import build
15 from .. import dependencies
16 from .. import mesonlib
17 from ..options import OptionKey
18 from .. import mlog
19 from ..options import BUILTIN_DIR_OPTIONS
20 from ..dependencies.pkgconfig import PkgConfigDependency, PkgConfigInterface
21 from ..interpreter.primitives import OptionString
22 from ..interpreter.type_checking import D_MODULE_VERSIONS_KW, INSTALL_DIR_KW, VARIABLES_KW, NoneType
23 from ..interpreterbase import FeatureNew, FeatureDeprecated, FeatureBroken
24 from ..interpreterbase.decorators import ContainerTypeInfo, KwargInfo, typed_kwargs, typed_pos_args
25
26 if T.TYPE_CHECKING:
27 from typing_extensions import TypedDict
28
29 from . import ModuleState
30 from .. import mparser
31 from ..interpreter import Interpreter
32
33 ANY_DEP = T.Union[dependencies.Dependency, build.LinkableTargetTypes, str]
34 REQS = T.Union[dependencies.Dependency, build.LibTypes, str]
35 LIBS = T.Union[build.LibTypes, str]
36
37 class GenerateKw(TypedDict):
38
39 version: T.Optional[str]
40 name: T.Optional[str]
41 filebase: T.Optional[str]
42 description: T.Optional[str]
43 url: str
44 license: str
45 subdirs: T.List[str]
46 conflicts: T.List[str]
47 dataonly: bool
48 # Executable is not accepted by the DSL, but the DependenciesHelper
49 # has to handle it for link_with so use ANY_DEP here.
50 libraries: T.List[ANY_DEP]
51 libraries_private: T.List[ANY_DEP]
52 requires: T.List[REQS]
53 requires_private: T.List[REQS]
54 install_dir: T.Optional[str]
55 d_module_versions: T.List[T.Union[str, int]]
56 extra_cflags: T.List[str]
57 cflags_private: T.List[str]
58 variables: T.Dict[str, str]
59 uninstalled_variables: T.Dict[str, str]
60 unescaped_variables: T.Dict[str, str]
61 unescaped_uninstalled_variables: T.Dict[str, str]
62
63
64 _PKG_LIBRARIES: KwargInfo[T.List[ANY_DEP]] = KwargInfo(
65 'libraries',
66 ContainerTypeInfo(list, (str, dependencies.Dependency,
67 build.SharedLibrary, build.StaticLibrary,
68 build.CustomTarget, build.CustomTargetIndex)),
69 default=[],
70 listify=True,
71 )
72
73 _PKG_REQUIRES: KwargInfo[T.List[REQS]] = KwargInfo(
74 'requires',
75 ContainerTypeInfo(list, (str, build.SharedLibrary, build.StaticLibrary, dependencies.Dependency)),
76 default=[],
77 listify=True,
78 )
79
80
81 def _as_str(obj: object) -> str:
82 assert isinstance(obj, str)
83 return obj
84
85
86 @dataclass
87 class MetaData:
88
89 filebase: str
90 display_name: str
91 location: mparser.BaseNode
92 warned: bool = False
93
94
95 class DependenciesHelper:
96 def __init__(self, state: ModuleState, name: str, metadata: T.Dict[str, MetaData]) -> None:
97 self.state = state
98 self.name = name
99 self.metadata = metadata
100 self.pub_libs: T.List[LIBS] = []
101 self.pub_reqs: T.List[str] = []
102 self.priv_libs: T.List[LIBS] = []
103 self.priv_reqs: T.List[str] = []
104 self.cflags: T.List[str] = []
105 self.cflags_private: T.List[str] = []
106 self.version_reqs: T.DefaultDict[str, T.Set[str]] = defaultdict(set)
107 self.link_whole_targets: T.List[build.StaticTargetTypes] = []
108 self.uninstalled_incdirs: mesonlib.OrderedSet[str] = mesonlib.OrderedSet()
109
110 def add_pub_libs(self, libs: T.List[ANY_DEP]) -> None:
111 p_libs, reqs, cflags = self._process_libs(libs, True)
112 self.pub_libs = p_libs + self.pub_libs # prepend to preserve dependencies
113 self.pub_reqs += reqs
114 self.cflags += cflags
115
116 def add_priv_libs(self, libs: T.List[ANY_DEP]) -> None:
117 p_libs, reqs, _ = self._process_libs(libs, False)
118 self.priv_libs = p_libs + self.priv_libs
119 self.priv_reqs += reqs
120
121 def add_pub_reqs(self, reqs: T.List[REQS]) -> None:
122 self.pub_reqs += self._process_reqs(reqs)
123
124 def add_priv_reqs(self, reqs: T.List[REQS]) -> None:
125 self.priv_reqs += self._process_reqs(reqs)
126
127 def _check_generated_pc_deprecation(self, obj: build.LibTypes) -> None:
128 if obj.get_id() in self.metadata:
129 return
130 data = self.metadata[obj.get_id()]
131 if data.warned:
132 return
133 mlog.deprecation('Library', mlog.bold(obj.name), 'was passed to the '
134 '"libraries" keyword argument of a previous call '
135 'to generate() method instead of first positional '
136 'argument.', 'Adding', mlog.bold(data.display_name),
137 'to "Requires" field, but this is a deprecated '
138 'behaviour that will change in version 2.0 '
139 'of Meson. Please report the issue if this '
140 'warning cannot be avoided in your case.',
141 location=data.location)
142 data.warned = True
143
144 def _process_reqs(self, reqs: T.Sequence[REQS]) -> T.List[str]:
145 '''Returns string names of requirements'''
146 processed_reqs: T.List[str] = []
147 for obj in mesonlib.listify(reqs):
148 if not isinstance(obj, str):
149 FeatureNew.single_use('pkgconfig.generate requirement from non-string object', '0.46.0', self.state.subproject)
150 if (isinstance(obj, (build.CustomTarget, build.CustomTargetIndex, build.SharedLibrary, build.StaticLibrary))
151 and obj.get_id() in self.metadata):
152 self._check_generated_pc_deprecation(obj)
153 processed_reqs.append(self.metadata[obj.get_id()].filebase)
154 elif isinstance(obj, PkgConfigDependency):
155 if obj.found():
156 processed_reqs.append(obj.name)
157 self.add_version_reqs(obj.name, obj.version_reqs)
158 elif isinstance(obj, str):
159 name, version_req = self.split_version_req(obj)
160 if name is None:
161 continue
162 processed_reqs.append(name)
163 self.add_version_reqs(name, [version_req] if version_req is not None else None)
164 elif isinstance(obj, dependencies.Dependency) and not obj.found():
165 pass
166 elif isinstance(obj, dependencies.ExternalDependency) and obj.name == 'threads':
167 pass
168 elif isinstance(obj, dependencies.InternalDependency) and all(lib.get_id() in self.metadata for lib in obj.libraries):
169 FeatureNew.single_use('pkgconfig.generate requirement from internal dependency', '1.9.0',
170 self.state.subproject, location=self.state.current_node)
171 # Ensure BothLibraries are resolved:
172 if self.pub_libs and isinstance(self.pub_libs[0], build.StaticLibrary):
173 obj = obj.get_as_static(recursive=True)
174 else:
175 obj = obj.get_as_shared(recursive=True)
176 for lib in obj.libraries:
177 processed_reqs.append(self.metadata[lib.get_id()].filebase)
178 else:
179 raise mesonlib.MesonException('requires argument not a string, '
180 'library with pkgconfig-generated file, '
181 'pkgconfig-dependency object, or '
182 'internal-dependency object with '
183 f'pkgconfig-generated file, got {obj!r}')
184 return processed_reqs
185
186 def add_cflags(self, cflags: T.List[str]) -> None:
187 self.cflags += mesonlib.stringlistify(cflags)
188
189 def add_cflags_private(self, cflags_private: T.List[str]) -> None:
190 self.cflags_private += mesonlib.stringlistify(cflags_private)
191
192 def _add_uninstalled_incdirs(self, incdirs: T.List[build.IncludeDirs], subdir: T.Optional[str] = None) -> None:
193 for i in incdirs:
194 curdir = i.curdir
195 for d in itertools.chain(i.incdirs, i.extra_build_dirs):
196 path = os.path.join(curdir, d)
197 self.uninstalled_incdirs.add(path)
198 if subdir is not None:
199 self.uninstalled_incdirs.add(subdir)
200
201 def _process_libs(
202 self, libs: T.List[ANY_DEP], public: bool
203 ) -> T.Tuple[T.List[LIBS], T.List[str], T.List[str]]:
204 libs = mesonlib.listify(libs)
205 processed_libs: T.List[LIBS] = []
206 processed_reqs: T.List[str] = []
207 processed_cflags: T.List[str] = []
208 for obj in libs:
209 if (isinstance(obj, (build.CustomTarget, build.CustomTargetIndex, build.SharedLibrary, build.StaticLibrary))
210 and obj.get_id() in self.metadata):
211 self._check_generated_pc_deprecation(obj)
212 processed_reqs.append(self.metadata[obj.get_id()].filebase)
213 elif isinstance(obj, dependencies.ExternalDependency) and obj.name == 'valgrind':
214 pass
215 elif isinstance(obj, PkgConfigDependency):
216 if obj.found():
217 processed_reqs.append(obj.name)
218 self.add_version_reqs(obj.name, obj.version_reqs)
219 elif isinstance(obj, dependencies.InternalDependency):
220 if obj.found():
221 if obj.objects:
222 raise mesonlib.MesonException('.pc file cannot refer to individual object files.')
223
224 # Ensure BothLibraries are resolved:
225 if self.pub_libs and isinstance(self.pub_libs[0], build.StaticLibrary):
226 obj = obj.get_as_static(recursive=True)
227 else:
228 obj = obj.get_as_shared(recursive=True)
229
230 processed_libs += obj.get_link_args()
231 processed_cflags += obj.get_compile_args()
232 self._add_lib_dependencies(obj.libraries, obj.whole_libraries, obj.ext_deps, public, private_external_deps=True)
233 self._add_uninstalled_incdirs(obj.get_include_dirs())
234 elif isinstance(obj, dependencies.Dependency):
235 if obj.found():
236 processed_libs += obj.get_link_args()
237 processed_cflags += obj.get_compile_args()
238 elif isinstance(obj, build.SharedLibrary) and obj.shared_library_only:
239 # Do not pull dependencies for shared libraries because they are
240 # only required for static linking. Adding private requires has
241 # the side effect of exposing their cflags, which is the
242 # intended behaviour of pkg-config but force Debian to add more
243 # than needed build deps.
244 # See https://bugs.freedesktop.org/show_bug.cgi?id=105572
245 processed_libs.append(obj)
246 self._add_uninstalled_incdirs(obj.get_include_dirs(), obj.get_subdir())
247 elif isinstance(obj, (build.SharedLibrary, build.StaticLibrary)):
248 processed_libs.append(obj)
249 self._add_uninstalled_incdirs(obj.get_include_dirs(), obj.get_subdir())
250 # If there is a static library in `Libs:` all its deps must be
251 # public too, otherwise the generated pc file will never be
252 # usable without --static.
253 self._add_lib_dependencies(obj.link_targets,
254 obj.link_whole_targets,
255 obj.external_deps,
256 isinstance(obj, build.StaticLibrary) and public)
257 elif isinstance(obj, (build.CustomTarget, build.CustomTargetIndex)):
258 if not obj.is_linkable_target():
259 raise mesonlib.MesonException('library argument contains a not linkable custom_target.')
260 FeatureNew.single_use('custom_target in pkgconfig.generate libraries', '0.58.0', self.state.subproject)
261 processed_libs.append(obj)
262 elif isinstance(obj, str):
263 processed_libs.append(obj)
264 else:
265 raise mesonlib.MesonException(f'library argument of type {type(obj).__name__} not a string, library or dependency object.')
266
267 return processed_libs, processed_reqs, processed_cflags
268
269 def _add_lib_dependencies(
270 self, link_targets: T.Sequence[build.LinkableTargetTypes],
271 link_whole_targets: T.Sequence[build.StaticTargetTypes],
272 external_deps: T.List[dependencies.Dependency],
273 public: bool,
274 private_external_deps: bool = False) -> None:
275 add_libs = self.add_pub_libs if public else self.add_priv_libs
276 # Recursively add all linked libraries
277 for t in link_targets:
278 # Internal libraries (uninstalled static library) will be promoted
279 # to link_whole, treat them as such here.
280 if t.is_internal():
281 # `is_internal` shouldn't return True for anything but a
282 # StaticLibrary, or a CustomTarget that is a StaticLibrary
283 assert isinstance(t, (build.StaticLibrary, build.CustomTarget, build.CustomTargetIndex)), 'for mypy'
284 self._add_link_whole(t, public)
285 else:
286 add_libs([t])
287 for t in link_whole_targets:
288 self._add_link_whole(t, public)
289 # And finally its external dependencies
290 if private_external_deps:
291 self.add_priv_libs(T.cast('T.List[ANY_DEP]', external_deps))
292 else:
293 add_libs(T.cast('T.List[ANY_DEP]', external_deps))
294
295 def _add_link_whole(self, t: build.StaticTargetTypes, public: bool) -> None:
296 # Don't include static libraries that we link_whole. But we still need to
297 # include their dependencies: a static library we link_whole
298 # could itself link to a shared library or an installed static library.
299 # Keep track of link_whole_targets so we can remove them from our
300 # lists in case a library is link_with and link_whole at the same time.
301 # See remove_dups() below.
302 self.link_whole_targets.append(t)
303 if isinstance(t, build.BuildTarget):
304 self._add_lib_dependencies(t.link_targets, t.link_whole_targets, t.external_deps, public)
305
306 def add_version_reqs(self, name: str, version_reqs: T.Optional[T.List[str]]) -> None:
307 if version_reqs:
308 # Note that pkg-config is picky about whitespace.
309 # 'foo > 1.2' is ok but 'foo>1.2' is not.
310 # foo, bar' is ok, but 'foo,bar' is not.
311 self.version_reqs[name].update(version_reqs)
312
313 def split_version_req(self, s: str) -> T.Tuple[T.Optional[str], T.Optional[str]]:
314 stripped_str = s.strip()
315 if not stripped_str:
316 mlog.warning('Required dependency was found to be an empty string. Did you mean to pass an empty array?')
317 return None, None
318 for op in ['>=', '<=', '!=', '==', '=', '>', '<']:
319 pos = stripped_str.find(op)
320 if pos < 0:
321 continue
322 if pos == 0:
323 raise mesonlib.MesonException(f'required versioned dependency "{s}" is missing the dependency\'s name.')
324 stripped_str, version = stripped_str[0:pos].strip(), stripped_str[pos:].strip()
325 if not stripped_str:
326 raise mesonlib.MesonException(f'required versioned dependency "{s}" is missing the dependency\'s name.')
327 return stripped_str, version
328 return stripped_str, None
329
330 def format_vreq(self, vreq: str) -> str:
331 # vreq are '>=1.0' and pkgconfig wants '>= 1.0'
332 for op in ['>=', '<=', '!=', '==', '=', '>', '<']:
333 if vreq.startswith(op):
334 return op + ' ' + vreq[len(op):]
335 return vreq
336
337 def format_reqs(self, reqs: T.List[str]) -> str:
338 result: T.List[str] = []
339 for name in reqs:
340 vreqs = self.version_reqs.get(name, None)
341 if vreqs:
342 result += [name + ' ' + self.format_vreq(vreq) for vreq in sorted(vreqs)]
343 else:
344 result += [name]
345 return ', '.join(result)
346
347 def remove_dups(self) -> None:
348 # Set of ids that have already been handled and should not be added any more
349 exclude: T.Set[str] = set()
350
351 # We can't just check if 'x' is excluded because we could have copies of
352 # the same SharedLibrary object for example.
353 def _ids(x: LIBS) -> T.Iterable[str]:
354 if isinstance(x, str):
355 yield x
356 else:
357 if x.get_id() in self.metadata:
358 yield self.metadata[x.get_id()].display_name
359 yield x.get_id()
360
361 # Exclude 'x' in all its forms and return if it was already excluded
362 def _add_exclude(x: LIBS) -> bool:
363 was_excluded = False
364 for i in _ids(x):
365 if i in exclude:
366 was_excluded = True
367 else:
368 exclude.add(i)
369 return was_excluded
370
371 # link_whole targets are already part of other targets, exclude them all.
372 for t in self.link_whole_targets:
373 _add_exclude(t)
374
375 # Mypy thinks these overlap, but since List is invariant they don't,
376 # `List[str]`` is not a valid input to `List[str | BuildTarget]`.
377 # pylance/pyright gets this right, but for mypy we have to ignore the
378 # error
379 @T.overload
380 def _fn(xs: T.List[str], libs: bool = False) -> T.List[str]: ...
381
382 @T.overload
383 def _fn(xs: T.List[LIBS], libs: bool = False) -> T.List[LIBS]: ...
384
385 def _fn(xs: T.Union[T.List[str], T.List[LIBS]], libs: bool = False) -> T.Union[T.List[str], T.List[LIBS]]:
386 # Remove duplicates whilst preserving original order
387 result = []
388 for x in xs:
389 # Don't de-dup unknown strings to avoid messing up arguments like:
390 # ['-framework', 'CoreAudio', '-framework', 'CoreMedia']
391 known_flags = ['-pthread']
392 cannot_dedup = libs and isinstance(x, str) and \
393 not x.startswith(('-l', '-L')) and \
394 x not in known_flags
395 if not cannot_dedup and _add_exclude(x):
396 continue
397 result.append(x)
398 return result
399
400 # Handle lists in priority order: public items can be excluded from
401 # private and Requires can excluded from Libs.
402 self.pub_reqs = _fn(self.pub_reqs)
403 self.pub_libs = _fn(self.pub_libs, True)
404 self.priv_reqs = _fn(self.priv_reqs)
405 self.priv_libs = _fn(self.priv_libs, True)
406 # Reset exclude list just in case some values can be both cflags and libs.
407 exclude = set()
408 self.cflags = _fn(self.cflags)
409 self.cflags_private = _fn(self.cflags_private)
410
411 class PkgConfigModule(NewExtensionModule):
412
413 INFO = ModuleInfo('pkgconfig')
414
415 # Track already generated pkg-config files This is stored as a class
416 # variable so that multiple `import()`s share metadata
417 devenv: T.Optional[mesonlib.EnvironmentVariables] = None
418 _metadata: T.ClassVar[T.Dict[str, MetaData]] = {}
419
420 def __init__(self) -> None:
421 super().__init__()
422 self.methods.update({
423 'generate': self.generate,
424 })
425
426 def postconf_hook(self, b: build.Build) -> None:
427 if self.devenv is not None:
428 b.devenv.append(self.devenv)
429
430 def _get_lname(self, l: build.LibTypes, msg: str, pcfile: str) -> str:
431 if isinstance(l, (build.CustomTargetIndex, build.CustomTarget)):
432 basename = os.path.basename(l.get_filename())
433 name = os.path.splitext(basename)[0]
434 if name.startswith('lib'):
435 name = name[3:]
436 return name
437 # Nothing special
438 if not l.name_prefix_set:
439 return l.name
440 # Sometimes people want the library to start with 'lib' everywhere,
441 # which is achieved by setting name_prefix to '' and the target name to
442 # 'libfoo'. In that case, try to get the pkg-config '-lfoo' arg correct.
443 if l.prefix == '' and l.name.startswith('lib'):
444 return l.name[3:]
445 # If the library is imported via an import library which is always
446 # named after the target name, '-lfoo' is correct.
447 if isinstance(l, build.SharedLibrary) and l.import_filename:
448 return l.name
449 # In other cases, we can't guarantee that the compiler will be able to
450 # find the library via '-lfoo', so tell the user that.
451 mlog.warning(msg.format(l.name, 'name_prefix', l.name, pcfile))
452 return l.name
453
454 def _escape(self, value: T.Union[str, PurePath]) -> str:
455 '''
456 We cannot use quote_arg because it quotes with ' and " which does not
457 work with pkg-config and pkgconf at all.
458 '''
459 # We should always write out paths with / because pkg-config requires
460 # spaces to be quoted with \ and that messes up on Windows:
461 # https://bugs.freedesktop.org/show_bug.cgi?id=103203
462 if isinstance(value, PurePath):
463 value = value.as_posix()
464 return value.replace(' ', r'\ ')
465
466 def _make_relative(self, prefix: T.Union[PurePath, str], subdir: T.Union[PurePath, str],
467 path_class: T.Type[PurePath]) -> PurePosixPath:
468 prefix = path_class(prefix)
469 subdir = path_class(subdir)
470 try:
471 libdir = subdir.relative_to(prefix)
472 except ValueError:
473 libdir = subdir
474 # pathlib joining makes sure absolute libdir is not appended to '${prefix}'
475 return '${prefix}' / PurePosixPath(libdir)
476
477 def _get_relocatable_prefix(self, pkgroot: str, prefix: PurePath,
478 path_class: T.Type[PurePath]) -> PurePosixPath:
479 '''Compute the prefix variable for relocatable pkg-config files.
480
481 Returns a path expression like '${pcfiledir}/../..' that represents
482 the relative path from the pkgconfig directory up to the installation prefix.
483 '''
484 pkgroot_ = path_class(pkgroot)
485 if not pkgroot_.is_absolute():
486 pkgroot_ = prefix / pkgroot
487 elif prefix not in pkgroot_.parents:
488 raise mesonlib.MesonException('Pkgconfig prefix cannot be outside of the prefix '
489 'when pkgconfig.relocatable=true. '
490 f'Pkgconfig prefix is {pkgroot_}.')
491 # relative_to only works for subpaths
492 rel = pkgroot_.relative_to(prefix)
493 return '${pcfiledir}' / PurePosixPath(*(['..'] * len(rel.parts)))
494
495 def _generate_pkgconfig_file(self, state: ModuleState, deps: DependenciesHelper,
496 subdirs: T.List[str], name: str,
497 description: str, url: str, version: str,
498 license: str,
499 pcfile: str, conflicts: T.List[str],
500 variables: T.List[T.Tuple[str, str]],
501 unescaped_variables: T.List[T.Tuple[str, str]],
502 uninstalled: bool = False, dataonly: bool = False,
503 pkgroot: T.Optional[str] = None) -> None:
504 coredata = state.environment.get_coredata()
505 referenced_vars = set()
506 optnames = [x.name for x in BUILTIN_DIR_OPTIONS.keys()]
507
508 if not dataonly:
509 # includedir is always implied, although libdir may not be
510 # needed for header-only libraries
511 referenced_vars |= {'prefix', 'includedir'}
512 if deps.pub_libs or deps.priv_libs:
513 referenced_vars |= {'libdir'}
514 # also automatically infer variables referenced in other variables
515 implicit_vars_warning = False
516 redundant_vars_warning = False
517 varnames = set()
518 varstrings = set()
519 for k, v in variables + unescaped_variables:
520 varnames |= {k}
521 varstrings |= {v}
522 for optname in optnames:
523 optvar = f'${{{optname}}}'
524 if any(x.startswith(optvar) for x in varstrings):
525 if optname in varnames:
526 redundant_vars_warning = True
527 else:
528 # these 3 vars were always "implicit"
529 if dataonly or optname not in {'prefix', 'includedir', 'libdir'}:
530 implicit_vars_warning = True
531 referenced_vars |= {'prefix', optname}
532 if redundant_vars_warning:
533 FeatureDeprecated.single_use('pkgconfig.generate variable for builtin directories', '0.62.0',
534 state.subproject, 'They will be automatically included when referenced',
535 state.current_node)
536 if implicit_vars_warning:
537 FeatureNew.single_use('pkgconfig.generate implicit variable for builtin directories', '0.62.0',
538 state.subproject, location=state.current_node)
539
540 if uninstalled:
541 outdir = os.path.join(state.environment.build_dir, 'meson-uninstalled')
542 if not os.path.exists(outdir):
543 os.mkdir(outdir)
544 pure_path_class = PurePath
545 prefix = PurePath(state.environment.get_build_dir())
546 srcdir = PurePath(state.environment.get_source_dir())
547 else:
548 pure_path_class = state.environment.machines.host.pure_path_class
549 outdir = state.environment.scratch_dir
550 prefix = pure_path_class(_as_str(coredata.optstore.get_value_for(OptionKey('prefix'))))
551 if pkgroot:
552 prefix = self._get_relocatable_prefix(pkgroot, prefix, pure_path_class)
553 # relocatable paths will never have a drive letter
554 pure_path_class = PurePosixPath
555
556 fname = os.path.join(outdir, pcfile)
557 with open(fname, 'w', encoding='utf-8') as ofile:
558 for optname in optnames:
559 if optname in referenced_vars - varnames:
560 if optname == 'prefix':
561 ofile.write('prefix={}\n'.format(self._escape(prefix)))
562 else:
563 dirpath = PurePath(_as_str(coredata.optstore.get_value_for(OptionKey(optname))))
564 ofile.write('{}={}\n'.format(optname, self._escape('${prefix}' / dirpath)))
565 if uninstalled and not dataonly:
566 ofile.write('srcdir={}\n'.format(self._escape(srcdir)))
567 if variables or unescaped_variables:
568 ofile.write('\n')
569 for k, v in variables:
570 ofile.write('{}={}\n'.format(k, self._escape(v)))
571 for k, v in unescaped_variables:
572 ofile.write(f'{k}={v}\n')
573 ofile.write('\n')
574 ofile.write(f'Name: {name}\n')
575 if description:
576 ofile.write(f'Description: {description}\n')
577 if url:
578 ofile.write(f'URL: {url}\n')
579 if license:
580 ofile.write(f'License: {license}\n')
581 ofile.write(f'Version: {version}\n')
582 reqs_str = deps.format_reqs(deps.pub_reqs)
583 if reqs_str:
584 ofile.write(f'Requires: {reqs_str}\n')
585 reqs_str = deps.format_reqs(deps.priv_reqs)
586 if reqs_str:
587 ofile.write(f'Requires.private: {reqs_str}\n')
588 if conflicts:
589 ofile.write('Conflicts: {}\n'.format(' '.join(conflicts)))
590
591 def generate_libs_flags(libs: T.List[LIBS]) -> T.Iterable[str]:
592 msg = 'Library target {0!r} has {1!r} set. Compilers ' \
593 'may not find it from its \'-l{2}\' linker flag in the ' \
594 '{3!r} pkg-config file.'
595 Lflags = []
596 for l in libs:
597 if isinstance(l, str):
598 yield l
599 else:
600 install_dir: T.Union[str, bool]
601 if uninstalled:
602 install_dir = os.path.dirname(state.backend.get_target_filename_abs(l))
603 custom_install_dir = True
604 else:
605 _i = l.install_dir
606 custom_install_dir = l.has_custom_install_dir
607 if isinstance(l, build.BuildTarget):
608 install_dir = _i[0] if _i else l.get_default_install_dir()[0]
609 else:
610 install_dir = _i[0] if _i else ''
611 if install_dir is False:
612 continue
613 if isinstance(l, build.BuildTarget) and 'cs' in l.compilers:
614 if custom_install_dir:
615 Lflag = '-r{}/{}'.format(self._escape(self._make_relative(prefix, install_dir, pure_path_class)),
616 l.filename)
617 else:
618 Lflag = '-r${libdir}/%s' % l.filename
619 else:
620 if custom_install_dir:
621 Lflag = '-L{}'.format(self._escape(self._make_relative(prefix, install_dir, pure_path_class)))
622 else:
623 Lflag = '-L${libdir}'
624 if Lflag not in Lflags:
625 Lflags.append(Lflag)
626 yield Lflag
627 lname = self._get_lname(l, msg, pcfile)
628 # If using a custom suffix, the compiler may not be able to
629 # find the library
630 if isinstance(l, build.BuildTarget) and l.name_suffix_set:
631 mlog.warning(msg.format(l.name, 'name_suffix', lname, pcfile))
632 if isinstance(l, (build.CustomTarget, build.CustomTargetIndex)) or 'cs' not in l.compilers:
633 yield f'-l{lname}'
634
635 if deps.pub_libs:
636 ofile.write('Libs: {}\n'.format(' '.join(generate_libs_flags(deps.pub_libs))))
637 if deps.priv_libs:
638 ofile.write('Libs.private: {}\n'.format(' '.join(generate_libs_flags(deps.priv_libs))))
639
640 cflags: T.List[str] = []
641 if uninstalled:
642 for d in deps.uninstalled_incdirs:
643 for basedir in ['${prefix}', '${srcdir}']:
644 path = self._escape(PurePosixPath(basedir, d))
645 cflags.append(f'-I{path}')
646 else:
647 for d in subdirs:
648 if d == '.':
649 cflags.append('-I${includedir}')
650 else:
651 cflags.append('-I' + self._escape(PurePosixPath('${includedir}', d)))
652 cflags += [self._escape(f) for f in deps.cflags]
653 if cflags and not dataonly:
654 ofile.write('Cflags: {}\n'.format(' '.join(cflags)))
655
656 cflags_private: T.List[str] = [self._escape(f) for f in deps.cflags_private]
657 if cflags_private and not dataonly:
658 ofile.write('Cflags.private: {}\n'.format(' '.join(cflags_private)))
659
660 @typed_pos_args('pkgconfig.generate', optargs=[(build.SharedLibrary, build.StaticLibrary)])
661 @typed_kwargs(
662 'pkgconfig.generate',
663 D_MODULE_VERSIONS_KW.evolve(since='0.43.0'),
664 INSTALL_DIR_KW,
665 KwargInfo('cflags_private', ContainerTypeInfo(list, str), default=[], listify=True, since='1.9.0'),
666 KwargInfo('conflicts', ContainerTypeInfo(list, str), default=[], listify=True),
667 KwargInfo('dataonly', bool, default=False, since='0.54.0'),
668 KwargInfo('description', (str, NoneType)),
669 KwargInfo('extra_cflags', ContainerTypeInfo(list, str), default=[], listify=True, since='0.42.0'),
670 KwargInfo('filebase', (str, NoneType), validator=lambda x: 'must not be an empty string' if x == '' else None),
671 KwargInfo('name', (str, NoneType), validator=lambda x: 'must not be an empty string' if x == '' else None),
672 KwargInfo('subdirs', ContainerTypeInfo(list, str), default=[], listify=True),
673 KwargInfo('url', str, default=''),
674 KwargInfo('license', str, default='', since='1.9.0'),
675 KwargInfo('version', (str, NoneType)),
676 VARIABLES_KW.evolve(name="unescaped_uninstalled_variables", since='0.59.0'),
677 VARIABLES_KW.evolve(name="unescaped_variables", since='0.59.0'),
678 VARIABLES_KW.evolve(name="uninstalled_variables", since='0.54.0', since_values={dict: '0.56.0'}),
679 VARIABLES_KW.evolve(since='0.41.0', since_values={dict: '0.56.0'}),
680 _PKG_LIBRARIES,
681 _PKG_LIBRARIES.evolve(name='libraries_private'),
682 _PKG_REQUIRES,
683 _PKG_REQUIRES.evolve(name='requires_private'),
684 )
685 def generate(self, state: ModuleState,
686 args: T.Tuple[T.Optional[T.Union[build.SharedLibrary, build.StaticLibrary]]],
687 kwargs: GenerateKw) -> ModuleReturnValue:
688 default_version = state.project_version
689 default_install_dir: T.Optional[str] = None
690 default_description: T.Optional[str] = None
691 default_name: T.Optional[str] = None
692 mainlib: T.Optional[T.Union[build.SharedLibrary, build.StaticLibrary]] = None
693 default_subdirs = ['.']
694 if args[0]:
695 FeatureNew.single_use('pkgconfig.generate optional positional argument', '0.46.0', state.subproject)
696 mainlib = args[0]
697 default_name = mainlib.name
698 default_description = state.project_name + ': ' + mainlib.name
699 install_dir = mainlib.get_custom_install_dir()
700 if mainlib.has_custom_install_dir and install_dir and isinstance(install_dir[0], str):
701 default_install_dir = os.path.join(install_dir[0], 'pkgconfig')
702 if isinstance(install_dir[0], OptionString):
703 default_install_dir = OptionString(default_install_dir, os.path.join(install_dir[0].optname, 'pkgconfig'))
704 else:
705 if kwargs['version'] is None:
706 FeatureNew.single_use('pkgconfig.generate implicit version keyword', '0.46.0', state.subproject)
707 msg = ('pkgconfig.generate: if a library is not passed as a '
708 'positional argument, the {!r} keyword argument is '
709 'required.')
710 if kwargs['name'] is None:
711 raise build.InvalidArguments(msg.format('name'))
712 if kwargs['description'] is None:
713 raise build.InvalidArguments(msg.format('description'))
714
715 dataonly = kwargs['dataonly']
716 if dataonly:
717 default_subdirs = []
718 blocked_vars = ['libraries', 'libraries_private', 'requires_private', 'extra_cflags', 'cflags_private', 'subdirs']
719 # Mypy can't figure out that this TypedDict index is correct, without repeating T.Literal for the entire list
720 if any(kwargs[k] for k in blocked_vars): # type: ignore
721 raise mesonlib.MesonException(f'Cannot combine dataonly with any of {blocked_vars}')
722 default_install_dir = OptionString(os.path.join(state.environment.get_datadir(), 'pkgconfig'), os.path.join('{datadir}', 'pkgconfig'))
723
724 subdirs = kwargs['subdirs'] or default_subdirs
725 if any(mesonlib.path_has_root(d) for d in subdirs):
726 FeatureBroken.single_use('subdirs cannot be absolute', '1.10.2', state.subproject,
727 'This never worked; absolute paths ended up in Cflags without the -I option.',
728 location=state.current_node)
729
730 version = kwargs['version'] if kwargs['version'] is not None else default_version
731 name = kwargs['name'] if kwargs['name'] is not None else default_name
732 assert isinstance(name, str), 'for mypy'
733 filebase = kwargs['filebase'] if kwargs['filebase'] is not None else name
734 description = kwargs['description'] if kwargs['description'] is not None else default_description
735 url = kwargs['url']
736 license = kwargs['license']
737 conflicts = kwargs['conflicts']
738
739 # Prepend the main library to public libraries list. This is required
740 # so dep.add_pub_libs() can handle dependency ordering correctly and put
741 # extra libraries after the main library.
742 libraries = kwargs['libraries'].copy()
743 if mainlib:
744 libraries.insert(0, mainlib)
745
746 deps = DependenciesHelper(state, filebase, self._metadata)
747 deps.add_pub_libs(libraries)
748 deps.add_priv_libs(kwargs['libraries_private'])
749 deps.add_pub_reqs(kwargs['requires'])
750 deps.add_priv_reqs(kwargs['requires_private'])
751 deps.add_cflags(kwargs['extra_cflags'])
752 deps.add_cflags_private(kwargs['cflags_private'])
753
754 dversions = kwargs['d_module_versions']
755 if dversions:
756 compiler = state.environment.coredata.compilers.host.get('d')
757 if compiler:
758 deps.add_cflags(compiler.get_feature_args(
759 {'versions': dversions, 'import_dirs': [], 'debug': [], 'unittest': False}, None))
760
761 deps.remove_dups()
762
763 def parse_variable_list(vardict: T.Dict[str, str]) -> T.List[T.Tuple[str, str]]:
764 reserved = ['prefix', 'libdir', 'includedir']
765 variables = []
766 for name, value in vardict.items():
767 if not value:
768 FeatureNew.single_use('empty variable value in pkg.generate', '1.4.0', state.subproject, location=state.current_node)
769 if not dataonly and name in reserved:
770 raise mesonlib.MesonException(f'Variable "{name}" is reserved')
771 variables.append((name, value))
772 return variables
773
774 variables = parse_variable_list(kwargs['variables'])
775 unescaped_variables = parse_variable_list(kwargs['unescaped_variables'])
776
777 pcfile = filebase + '.pc'
778 pkgroot = pkgroot_name = kwargs['install_dir'] or default_install_dir
779 if isinstance(pkgroot, OptionString):
780 pkgroot_name = pkgroot.optname
781 if pkgroot is None:
782 m = state.environment.machines.host
783 if m.is_freebsd():
784 pkgroot = os.path.join(_as_str(state.environment.coredata.optstore.get_value_for(OptionKey('prefix'))), 'libdata', 'pkgconfig')
785 pkgroot_name = os.path.join('{prefix}', 'libdata', 'pkgconfig')
786 elif m.is_haiku():
787 pkgroot = os.path.join(_as_str(state.environment.coredata.optstore.get_value_for(OptionKey('prefix'))), 'develop', 'lib', 'pkgconfig')
788 pkgroot_name = os.path.join('{prefix}', 'develop', 'lib', 'pkgconfig')
789 else:
790 pkgroot = os.path.join(_as_str(state.environment.coredata.optstore.get_value_for(OptionKey('libdir'))), 'pkgconfig')
791 pkgroot_name = os.path.join('{libdir}', 'pkgconfig')
792 relocatable = state.get_option('pkgconfig.relocatable')
793 self._generate_pkgconfig_file(state, deps, subdirs, name, description, url,
794 version, license, pcfile, conflicts, variables,
795 unescaped_variables, False, dataonly,
796 pkgroot=pkgroot if relocatable else None)
797 res = build.Data([mesonlib.File(True, state.environment.get_scratch_dir(), pcfile)], pkgroot, pkgroot_name, None, state.subproject, install_tag='devel')
798 variables = parse_variable_list(kwargs['uninstalled_variables'])
799 unescaped_variables = parse_variable_list(kwargs['unescaped_uninstalled_variables'])
800
801 pcfile = filebase + '-uninstalled.pc'
802 self._generate_pkgconfig_file(state, deps, subdirs, name, description, url,
803 version, license, pcfile, conflicts, variables,
804 unescaped_variables, uninstalled=True, dataonly=dataonly)
805 # Associate the main library with this generated pc file. If the library
806 # is used in any subsequent call to the generated, it will generate a
807 # 'Requires:' or 'Requires.private:'.
808 # Backward compatibility: We used to set 'generated_pc' on all public
809 # libraries instead of just the main one. Keep doing that but warn if
810 # anyone is relying on that deprecated behaviour.
811 if mainlib:
812 if mainlib.get_id() not in self._metadata:
813 self._metadata[mainlib.get_id()] = MetaData(
814 filebase, name, state.current_node)
815 else:
816 mlog.warning('Already generated a pkg-config file for', mlog.bold(mainlib.name))
817 else:
818 for lib in deps.pub_libs:
819 if not isinstance(lib, str) and lib.get_id() not in self._metadata:
820 self._metadata[lib.get_id()] = MetaData(
821 filebase, name, state.current_node)
822 if self.devenv is None:
823 self.devenv = PkgConfigInterface.get_env(state.environment, mesonlib.MachineChoice.HOST, uninstalled=True)
824 return ModuleReturnValue(res, [res])
825
826
827 def initialize(interp: Interpreter) -> PkgConfigModule:
828 return PkgConfigModule()