Debian Codegraph @

mesonbuild/dependencies/dub.py

raw
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 .pkgconfig import PkgConfigDependency
8 from ..mesonlib import (Popen_safe, join_args, version_compare, version_compare_many)
9 from ..options import OptionKey
10 from ..programs import ExternalProgram
11 from .. import mlog
12 from enum import Enum
13 import re
14 import os
15 import json
16 import typing as T
17
18 if T.TYPE_CHECKING:
19 from typing_extensions import TypedDict
20
21 from ..environment import Environment
22 from .base import DependencyObjectKWs
23
24 # Definition of what `dub describe` returns (only the fields used by Meson)
25 class DubDescription(TypedDict):
26 platform: T.List[str]
27 architecture: T.List[str]
28 buildType: str
29 packages: T.List[DubPackDesc]
30 targets: T.List[DubTargetDesc]
31
32 class DubPackDesc(TypedDict):
33 name: str
34 version: str
35 active: bool
36 configuration: str
37 path: str
38 targetType: str
39 targetFileName: str
40
41 class DubTargetDesc(TypedDict):
42 rootPackage: str
43 linkDependencies: T.List[str]
44 buildSettings: DubBuildSettings
45 cacheArtifactPath: str
46
47 class DubBuildSettings(TypedDict):
48 importPaths: T.List[str]
49 stringImportPaths: T.List[str]
50 versions: T.List[str]
51 mainSourceFile: str
52 sourceFiles: T.List[str]
53 dflags: T.List[str]
54 libs: T.List[str]
55 lflags: T.List[str]
56
57 class FindTargetEntry(TypedDict):
58 search: str
59 artifactPath: str
60
61 class DubDescriptionSource(Enum):
62 Local = 'local'
63 External = 'external'
64
65 class DubDependency(ExternalDependency):
66 # dub program and version
67 class_dubbin: T.Optional[T.Tuple[ExternalProgram, str]] = None
68 class_dubbin_searched = False
69 class_cache_dir = ''
70
71 type_name = DependencyTypeName('dub')
72
73 # Map Meson Compiler ID's to Dub Compiler ID's
74 _ID_MAP: T.Mapping[str, str] = {
75 'dmd': 'dmd',
76 'gcc': 'gdc',
77 'llvm': 'ldc',
78 }
79
80 def __init__(self, name: str, environment: 'Environment', kwargs: DependencyObjectKWs):
81 kwargs['language'] = 'd'
82 super().__init__(name, environment, kwargs)
83 from ..compilers.d import DCompiler, d_feature_args
84
85 _temp_comp = super().get_compiler()
86 assert isinstance(_temp_comp, DCompiler)
87 self.compiler = _temp_comp
88
89 if kwargs.get('required') is not None:
90 self.required = kwargs['required']
91
92 if DubDependency.class_dubbin is None and not DubDependency.class_dubbin_searched:
93 DubDependency.class_dubbin = self._check_dub()
94 DubDependency.class_dubbin_searched = True
95 if DubDependency.class_dubbin is None:
96 if self.required:
97 raise DependencyException('DUB not found.')
98 return
99
100 (self.dubbin, dubver) = DubDependency.class_dubbin # pylint: disable=unpacking-non-sequence
101
102 assert isinstance(self.dubbin, ExternalProgram)
103
104 # Check Dub's compatibility with Meson
105 self._search_in_cache = version_compare(dubver, '<=1.31.1')
106 self._use_cache_describe = version_compare(dubver, '>=1.35.0')
107 self._dub_has_build_deep = version_compare(dubver, '>=1.35.0')
108
109 if not self._search_in_cache and not self._use_cache_describe:
110 if self.required:
111 raise DependencyException(
112 f'DUB version {dubver} is not compatible with Meson'
113 " (can't locate artifacts in DUB's cache). Upgrade to Dub >= 1.35.")
114 else:
115 mlog.warning(f'DUB dependency {name} not found because Dub {dubver} '
116 "is not compatible with Meson. (Can't locate artifacts in DUB's cache)."
117 ' Upgrade to Dub >= 1.35')
118 return
119
120 mlog.debug('Determining dependency {!r} with DUB executable '
121 '{!r}'.format(name, self.dubbin.get_path()))
122
123 # we need to know the target architecture
124 dub_arch = self.compiler.arch
125
126 # we need to know the build type as well
127 dub_buildtype = str(environment.coredata.optstore.get_value_for(OptionKey('buildtype')))
128 # MESON types: choices=['plain', 'debug', 'debugoptimized', 'release', 'minsize', 'custom'])),
129 # DUB types: debug (default), plain, release, release-debug, release-nobounds, unittest, profile, profile-gc,
130 # docs, ddox, cov, unittest-cov, syntax and custom
131 if dub_buildtype == 'debugoptimized':
132 dub_buildtype = 'release-debug'
133 elif dub_buildtype == 'minsize':
134 dub_buildtype = 'release'
135
136 result = self._get_dub_description(dub_arch, dub_buildtype)
137 if result is None:
138 return
139 description, build_cmd, description_source = result
140 dub_comp_id = self._ID_MAP[self.compiler.get_id()]
141
142 self.compile_args = []
143 self.link_args = self.raw_link_args = []
144
145 show_buildtype_warning = False
146
147 # collect all targets
148 targets = {t['rootPackage']: t for t in description['targets']}
149
150 def find_package_target(pkg: DubPackDesc) -> bool:
151 nonlocal show_buildtype_warning
152 # try to find a static library in a DUB folder corresponding to
153 # version, configuration, compiler, arch and build-type
154 # if can find, add to link_args.
155 # link_args order is meaningful, so this function MUST be called in the right order
156 pack_id = f'{pkg["name"]}@{pkg["version"]}'
157 tgt_desc = targets[pkg['name']]
158 (tgt_file, compatibilities) = self._find_target_in_cache(description, pkg, tgt_desc, dub_comp_id)
159 if tgt_file is None:
160 if not compatibilities:
161 mlog.error(mlog.bold(pack_id), 'not found')
162 elif 'compiler' not in compatibilities:
163 mlog.error(mlog.bold(pack_id), 'found but not compiled with ', mlog.bold(dub_comp_id))
164 elif dub_comp_id != 'gdc' and 'compiler_version' not in compatibilities:
165 mlog.error(mlog.bold(pack_id), 'found but not compiled with',
166 mlog.bold(f'{dub_comp_id}-{self.compiler.version}'))
167 elif 'arch' not in compatibilities:
168 mlog.error(mlog.bold(pack_id), 'found but not compiled for', mlog.bold(dub_arch))
169 elif 'platform' not in compatibilities:
170 mlog.error(mlog.bold(pack_id), 'found but not compiled for',
171 mlog.bold('.'.join(description['platform'])))
172 elif 'configuration' not in compatibilities:
173 mlog.error(mlog.bold(pack_id), 'found but not compiled for the',
174 mlog.bold(pkg['configuration']), 'configuration')
175 else:
176 mlog.error(mlog.bold(pack_id), 'not found')
177
178 mlog.log('You may try the following command to install the necessary DUB libraries:')
179 mlog.log(mlog.bold(build_cmd))
180
181 return False
182
183 if 'build_type' not in compatibilities:
184 mlog.warning(mlog.bold(pack_id), 'found but not compiled as', mlog.bold(dub_buildtype))
185 show_buildtype_warning = True
186
187 self.link_args.append(tgt_file)
188 return True
189
190 # Main algorithm:
191 # 1. Ensure that the target is a compatible library type (not dynamic)
192 # 2. Find a compatible built library for the main dependency
193 # 3. Do the same for each sub-dependency.
194 # link_args MUST be in the same order than the "linkDependencies" of the main target
195 # 4. Add other build settings (imports, versions etc.)
196
197 # 1
198 packages: T.Dict[str, DubPackDesc] = {}
199 found_it = False
200 for pkg in description['packages']:
201 packages[pkg['name']] = pkg
202
203 if not pkg['active']:
204 continue
205
206 # check that the main dependency is indeed a library
207 if pkg['name'] == name:
208 if pkg['targetType'] not in ['library', 'sourceLibrary', 'staticLibrary']:
209 mlog.error(mlog.bold(name), "found but it isn't a static library, it is:",
210 pkg['targetType'])
211 return
212
213 if self.version_reqs is not None:
214 ver = pkg['version']
215 if not version_compare_many(ver, self.version_reqs)[0]:
216 mlog.error(mlog.bold(f'{name}@{ver}'),
217 'does not satisfy all version requirements of:',
218 ' '.join(self.version_reqs))
219 return
220
221 found_it = True
222 self.version = pkg['version']
223 self.pkg = pkg
224
225 if not found_it:
226 mlog.error(f'Could not find {name} in DUB description.')
227 if description_source is DubDescriptionSource.Local:
228 mlog.log('Make sure that the dependency is registered for your dub project by running:')
229 mlog.log(mlog.bold(f'dub add {name}'))
230 elif description_source is DubDescriptionSource.External:
231 # `dub describe pkg` did not contain the pkg
232 raise RuntimeError(f'`dub describe` succeeded but it does not contains {name}')
233 return
234
235 if name not in targets:
236 if self.pkg['targetType'] == 'sourceLibrary':
237 # source libraries have no associated targets,
238 # but some build settings like import folders must be found from the package object.
239 # Current algo only get these from "buildSettings" in the target object.
240 # Let's save this for a future PR.
241 # (See openssl DUB package for example of sourceLibrary)
242 mlog.error('DUB targets of type', mlog.bold('sourceLibrary'), 'are not supported.')
243 else:
244 mlog.error('Could not find target description for', mlog.bold(self.name))
245 return
246
247 # Current impl only supports static libraries
248 self.static = True
249
250 # 2
251 if not find_package_target(self.pkg):
252 return
253
254 # 3
255 for link_dep in targets[name]['linkDependencies']:
256 pkg = packages[link_dep]
257 if not find_package_target(pkg):
258 return
259
260 if show_buildtype_warning:
261 mlog.log('If it is not suitable, try the following command and reconfigure Meson with', mlog.bold('--clearcache'))
262 mlog.log(mlog.bold(build_cmd))
263
264 # 4
265 bs = targets[name]['buildSettings']
266
267 for flag in bs['dflags']:
268 self.compile_args.append(flag)
269
270 for path in bs['importPaths']:
271 self.compile_args.append('-I' + path)
272
273 for path in bs['stringImportPaths']:
274 if 'import_dir' not in d_feature_args[self.compiler.id]:
275 break
276 flag = d_feature_args[self.compiler.id]['import_dir']
277 self.compile_args.append(f'{flag}={path}')
278
279 for ver in bs['versions']:
280 if 'version' not in d_feature_args[self.compiler.id]:
281 break
282 flag = d_feature_args[self.compiler.id]['version']
283 self.compile_args.append(f'{flag}={ver}')
284
285 if bs['mainSourceFile']:
286 self.compile_args.append(bs['mainSourceFile'])
287
288 # pass static libraries
289 # linkerFiles are added during step 3
290 # for file in bs['linkerFiles']:
291 # self.link_args.append(file)
292
293 for file in bs['sourceFiles']:
294 # sourceFiles may contain static libraries
295 if file.endswith('.lib') or file.endswith('.a'):
296 self.link_args.append(file)
297
298 for flag in bs['lflags']:
299 self.link_args.append(flag)
300
301 is_windows = self.env.machines.host.is_windows()
302 if is_windows:
303 winlibs = ['kernel32', 'user32', 'gdi32', 'winspool', 'shell32', 'ole32',
304 'oleaut32', 'uuid', 'comdlg32', 'advapi32', 'ws2_32']
305
306 for lib in bs['libs']:
307 if os.name != 'nt':
308 # trying to add system libraries by pkg-config
309 pkgdep = PkgConfigDependency(lib, environment, {'required': True, 'silent': True, 'native': self.for_machine})
310 if pkgdep.is_found:
311 for arg in pkgdep.get_compile_args():
312 self.compile_args.append(arg)
313 for arg in pkgdep.get_link_args():
314 self.link_args.append(arg)
315 for arg in pkgdep.get_link_args(raw=True):
316 self.raw_link_args.append(arg)
317 continue
318
319 if is_windows and lib in winlibs:
320 self.link_args.append(lib + '.lib')
321 continue
322
323 # fallback
324 self.link_args.append('-l'+lib)
325
326 self.is_found = True
327
328 # Get the dub description needed to resolve the dependency and a
329 # build command that can be used to build the dependency in case it is
330 # not present.
331 def _get_dub_description(self, dub_arch: str, dub_buildtype: str) -> T.Optional[T.Tuple[DubDescription, str, DubDescriptionSource]]:
332 def get_build_command() -> T.List[str]:
333 if self._dub_has_build_deep:
334 cmd = ['dub', 'build', '--deep']
335 else:
336 cmd = ['dub', 'run', '--yes', 'dub-build-deep', '--']
337
338 return cmd + [
339 '--arch=' + dub_arch,
340 '--compiler=' + self.compiler.get_exelist()[-1],
341 '--build=' + dub_buildtype,
342 ]
343
344 # Ask dub for the package
345 describe_cmd = [
346 'describe', '--arch=' + dub_arch,
347 '--build=' + dub_buildtype, '--compiler=' + self.compiler.get_exelist()[-1]
348 ]
349 helper_build = join_args(get_build_command())
350 source = DubDescriptionSource.Local
351 ret, res, err = self._call_dubbin(describe_cmd)
352 if ret == 0:
353 return (json.loads(res), helper_build, source)
354 else:
355 mlog.debug('DUB describe (raw) failed: ' + err)
356
357 pack_spec = self.name
358 if self.version_reqs is not None:
359 if len(self.version_reqs) > 1:
360 mlog.error('Multiple version requirements are not supported for raw dub dependencies.')
361 mlog.error("Please specify only an exact version like '1.2.3'")
362 raise DependencyException('Multiple version requirements are not solvable for raw dub dependencies')
363 elif len(self.version_reqs) == 1:
364 pack_spec += '@' + self.version_reqs[0]
365
366 describe_cmd = [
367 'describe', pack_spec, '--arch=' + dub_arch,
368 '--build=' + dub_buildtype, '--compiler=' + self.compiler.get_exelist()[-1]
369 ]
370 helper_build = join_args(get_build_command() + [pack_spec])
371 source = DubDescriptionSource.External
372 ret, res, err = self._call_dubbin(describe_cmd)
373 if ret == 0:
374 return (json.loads(res), helper_build, source)
375
376 mlog.debug('DUB describe failed: ' + err)
377 if 'locally' in err:
378 mlog.error(mlog.bold(pack_spec), 'is not present locally. You may try the following command:')
379 mlog.log(mlog.bold(helper_build))
380 return None
381
382 # This function finds the target of the provided JSON package, built for the right
383 # compiler, architecture, configuration...
384 # It returns (target|None, {compatibilities})
385 # If None is returned for target, compatibilities will list what other targets were found without full compatibility
386 def _find_target_in_cache(self, desc: DubDescription, pkg_desc: DubPackDesc,
387 tgt_desc: DubTargetDesc, dub_comp_id: str
388 ) -> T.Tuple[T.Optional[str], T.Set[str]]:
389 mlog.debug('Searching in DUB cache for compatible', pkg_desc['targetFileName'])
390
391 # recent DUB versions include a direct path to a compatible cached artifact
392 if self._use_cache_describe:
393 tgt_file = tgt_desc['cacheArtifactPath']
394 if os.path.exists(tgt_file):
395 return (tgt_file, {'configuration', 'platform', 'arch', 'compiler', 'compiler_version', 'build_type'})
396 else:
397 return (None, set())
398
399 assert self._search_in_cache
400
401 # try to find a string like library-debug-linux.posix-x86_64-ldc_2081-EF934983A3319F8F8FF2F0E107A363BA
402
403 # fields are:
404 # - configuration
405 # - build type
406 # - platform
407 # - architecture
408 # - compiler id (dmd, ldc, gdc)
409 # - compiler version or frontend id or frontend version?
410
411 comp_versions = self._get_comp_versions_to_find(dub_comp_id)
412
413 # build_type is not in check_list because different build types might be compatible.
414 # We do show a WARNING that the build type is not the same.
415 # It might be critical in release builds, and acceptable otherwise
416 check_list = {'configuration', 'platform', 'arch', 'compiler', 'compiler_version'}
417 compatibilities: T.Set[str] = set()
418
419 for entry in self._cache_entries(pkg_desc):
420 target = entry['artifactPath']
421 if not os.path.exists(target):
422 # unless Dub and Meson are racing, the target file should be present
423 # when the directory is present
424 mlog.debug("WARNING: Could not find a Dub target: " + target)
425 continue
426
427 # we build a new set for each entry, because if this target is returned
428 # we want to return only the compatibilities associated to this target
429 # otherwise we could miss the WARNING about build_type
430 comps: T.Set[str] = set()
431
432 search = entry['search']
433
434 mlog.debug('searching compatibility in ' + search)
435 mlog.debug('compiler_versions', comp_versions)
436
437 if pkg_desc['configuration'] in search:
438 comps.add('configuration')
439
440 if desc['buildType'] in search:
441 comps.add('build_type')
442
443 if all(platform in search for platform in desc['platform']):
444 comps.add('platform')
445
446 if all(arch in search for arch in desc['architecture']):
447 comps.add('arch')
448
449 if dub_comp_id in search:
450 comps.add('compiler')
451
452 if not comp_versions or any(cv in search for cv in comp_versions):
453 comps.add('compiler_version')
454
455 if check_list.issubset(comps):
456 mlog.debug('Found', target)
457 return (target, comps)
458 else:
459 compatibilities = set.union(compatibilities, comps)
460
461 return (None, compatibilities)
462
463 def _cache_entries(self, pkg_desc: DubPackDesc) -> T.List[FindTargetEntry]:
464 # the "old" cache is the `.dub` directory in every package of ~/.dub/packages
465 dub_build_path = os.path.join(pkg_desc['path'], '.dub', 'build')
466
467 if not os.path.exists(dub_build_path):
468 mlog.warning('No such cache folder:', dub_build_path)
469 return []
470
471 mlog.debug('Checking in DUB cache folder', dub_build_path)
472
473 return [
474 {
475 'search': dir_entry,
476 'artifactPath': os.path.join(dub_build_path, dir_entry, pkg_desc['targetFileName'])
477 }
478 for dir_entry in os.listdir(dub_build_path)
479 ]
480
481 def _get_comp_versions_to_find(self, dub_comp_id: str) -> T.List[str]:
482 # Get D frontend version implemented in the compiler, or the compiler version itself
483 # gdc doesn't support this
484
485 if dub_comp_id == 'gdc':
486 return []
487
488 comp_versions = [self.compiler.version]
489
490 ret, res = self._call_compbin(['--version'])[0:2]
491 if ret != 0:
492 mlog.error('Failed to run', mlog.bold(' '.join(self.dubbin.get_command() + ['--version'])))
493 return []
494 d_ver_reg = re.search('v[0-9].[0-9][0-9][0-9].[0-9]', res) # Ex.: v2.081.2
495
496 if d_ver_reg is not None:
497 frontend_version = d_ver_reg.group()
498 frontend_id = frontend_version.rsplit('.', 1)[0].replace(
499 'v', '').replace('.', '') # Fix structure. Ex.: 2081
500 comp_versions.extend([frontend_version, frontend_id])
501
502 return comp_versions
503
504 def _call_dubbin(self, args: T.List[str], env: T.Optional[T.Dict[str, str]] = None) -> T.Tuple[int, str, str]:
505 assert isinstance(self.dubbin, ExternalProgram)
506 p, out, err = Popen_safe(self.dubbin.get_command() + args, env=env, cwd=self.env.get_source_dir())
507 return p.returncode, out.strip(), err.strip()
508
509 def _call_compbin(self, args: T.List[str], env: T.Optional[T.Dict[str, str]] = None) -> T.Tuple[int, str, str]:
510 p, out, err = Popen_safe(self.compiler.get_exelist() + args, env=env)
511 return p.returncode, out.strip(), err.strip()
512
513 def _check_dub(self) -> T.Optional[T.Tuple[ExternalProgram, str]]:
514
515 def find() -> T.Optional[T.Tuple[ExternalProgram, str]]:
516 dubbin = ExternalProgram('dub', silent=True)
517
518 if not dubbin.found():
519 return None
520
521 try:
522 p, out = Popen_safe(dubbin.get_command() + ['--version'])[0:2]
523 if p.returncode != 0:
524 mlog.warning('Found dub {!r} but couldn\'t run it'
525 ''.format(' '.join(dubbin.get_command())))
526 return None
527
528 except (FileNotFoundError, PermissionError):
529 return None
530
531 vermatch = re.search(r'DUB version (\d+\.\d+\.\d+.*), ', out.strip())
532 if vermatch:
533 dubver = vermatch.group(1)
534 else:
535 mlog.warning(f"Found dub {' '.join(dubbin.get_command())} but couldn't parse version in {out.strip()}")
536 return None
537
538 return (dubbin, dubver)
539
540 found = find()
541
542 if found is None:
543 mlog.log('Found DUB:', mlog.red('NO'))
544 else:
545 (dubbin, dubver) = found
546 mlog.log('Found DUB:', mlog.bold(dubbin.get_path()),
547 '(version %s)' % dubver)
548
549 return found