Coverage for python/lsst/sconsUtils/dependencies.py: 77%
323 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 19:26 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 19:26 +0000
1# This file is part of sconsUtils.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
22"""Dependency configuration and definition."""
24__all__ = ("Configuration", "ExternalConfiguration", "PackageTree", "configure")
26import collections
27import importlib
28import os
29import os.path
30import types
31from sys import platform
33import SCons.Script
34from SCons.Script.SConscript import SConsEnvironment
36from . import eupsForScons, installation, pkgconfig, state
37from .utils import get_conda_prefix, use_conda_compilers
40def configure(packageName, versionString=None, eupsProduct=None, eupsProductPath=None, noCfgFile=False):
41 """Configure a package from its pkg-config template or ups/.cfg files.
43 Aliased as `lsst.sconsUtils.configure`.
45 Usually, LSST packages will call this function through
46 `~lsst.sconsUtils.scripts.BasicSConstruct`.
48 If the build root contains a pkg-config template
49 ``lsst_<packageName>.pc.in``, ``lib/pkgconfig/lsst_<packageName>.pc`` is
50 written from it and the package's dependencies are resolved through
51 pkg-config; ``.cfg`` files are never consulted. Otherwise the
52 dependency tree is loaded recursively from ``.cfg`` files. A package
53 with both a template and a ``ups/<packageName>.cfg`` is an error.
55 Parameters
56 ----------
57 packageName : `str`
58 Name of the package being built; must correspond to a pkg-config
59 template at the build root or a ``.cfg`` file in the ``ups``
60 directory.
61 versionString : `str`, optional
62 Version-control system string to be parsed for version information
63 (``$HeadURL$`` for SVN).
64 eupsProduct : `str`, optional
65 Name of the EUPS product being built. Defaults to and is almost
66 always the name of the package.
67 eupsProductPath : `str`, optional
68 An alternate directory where the package should be installed.
69 noCfgFile : `bool`
70 If True, this package has no ``.cfg`` file. Ignored if the package
71 has a pkg-config template.
73 Returns
74 -------
75 env : `SCons.Environment`
76 An SCons Environment object (which is also available as
77 `lsst.sconsUtils.env`).
78 """
80 if not state.env.GetOption("no_progress"):
81 state.log.info(f"Setting up environment to build package '{packageName}'.")
82 if eupsProduct is None: 82 ↛ 84line 82 didn't jump to line 84 because the condition on line 82 was always true
83 eupsProduct = packageName
84 if versionString is None: 84 ↛ 86line 84 didn't jump to line 86 because the condition on line 84 was always true
85 versionString = "git"
86 state.env["eupsProduct"] = eupsProduct
87 state.env["packageName"] = packageName
88 #
89 # Setup installation directories and variables
90 #
91 SCons.Script.Help(state.opts.GenerateHelpText(state.env))
92 state.env.installing = [t for t in SCons.Script.BUILD_TARGETS if t == "install"]
93 state.env.declaring = [t for t in SCons.Script.BUILD_TARGETS if t == "declare" or t == "current"]
94 state.env.linkFarmDir = state.env.GetOption("linkFarmDir")
95 if state.env.linkFarmDir: 95 ↛ 96line 95 didn't jump to line 96 because the condition on line 95 was never true
96 state.env.linkFarmDir = os.path.abspath(os.path.expanduser(state.env.linkFarmDir))
97 prefix = installation.setPrefix(state.env, versionString, eupsProductPath)
98 state.env["prefix"] = prefix
99 state.env["libDir"] = f"{prefix}/lib"
100 state.env["pythonDir"] = f"{prefix}/python"
101 #
102 # Process dependencies
103 #
104 state.log.traceback = state.env.GetOption("traceback")
105 state.log.verbose = state.env.GetOption("verbose")
106 root = SCons.Script.Dir("#").abspath
107 try:
108 pkgconfig.check_single_format(root, packageName)
109 except pkgconfig.PkgConfigError as err:
110 state.log.fail(str(err))
111 # A pkg-config template selects the pkg-config path, in which case no
112 # .cfg file is ever consulted for this build.
113 usePkgConfig = os.path.exists(pkgconfig.template_path(root, packageName))
114 packages = None if usePkgConfig else PackageTree(packageName, noCfgFile=noCfgFile)
115 state.log.flush() # if we've already hit a fatal error, die now.
116 state.env.libs = {"main": [], "python": [], "test": []}
117 state.env.doxygen = {"tags": [], "includes": []}
118 state.env["CPPPATH"] = []
120 _conda_prefix = get_conda_prefix()
121 # _conda_prefix is usually around, even if not using conda compilers
122 if use_conda_compilers(): 122 ↛ 131line 122 didn't jump to line 131 because the condition on line 122 was always true
123 # if using the conda-force conda compilers, they handle rpath for us
124 _conda_lib = f"{_conda_prefix}/lib"
125 state.env["LIBPATH"] = [_conda_lib]
126 if platform == "darwin": 126 ↛ 127line 126 didn't jump to line 127 because the condition on line 126 was never true
127 state.env["_RPATH"] = f"-rpath {_conda_lib}"
128 else:
129 state.env.AppendUnique(RPATH=[_conda_lib])
130 else:
131 state.env["LIBPATH"] = []
133 # XCPPPATH is a new variable defined by sconsUtils - it's like CPPPATH,
134 # but the headers found there aren't treated as dependencies. This can
135 # make scons a lot faster.
136 state.env["XCPPPATH"] = []
138 if use_conda_compilers(): 138 ↛ 145line 138 didn't jump to line 145 because the condition on line 138 was always true
139 state.env.Append(XCPPPATH=[f"{_conda_prefix}/include"])
141 # XCPPPPREFIX is a replacement for SCons' built-in INCPREFIX. It is used
142 # when compiling headers in XCPPPATH directories. Here, we set it to
143 # `-isystem`, so that those are regarded as "system headers" and warnings
144 # are suppressed.
145 state.env["XCPPPREFIX"] = "-isystem "
147 state.env["_CPPINCFLAGS"] = (
148 "$( ${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE)}"
149 " ${_concat(XCPPPREFIX, XCPPPATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)"
150 )
152 if state.env.linkFarmDir: 152 ↛ 153line 152 didn't jump to line 153 because the condition on line 152 was never true
153 for d in [state.env.linkFarmDir, "#"]:
154 state.env.Append(CPPPATH=os.path.join(d, "include"))
155 state.env.Append(LIBPATH=os.path.join(d, "lib"))
157 if usePkgConfig:
158 state.env.dependencies = _configurePkgConfig(root, packageName)
159 else:
160 if not state.env.GetOption("clean") and not state.env.GetOption("help"): 160 ↛ 162line 160 didn't jump to line 162 because the condition on line 160 was always true
161 packages.configure(state.env)
162 state.env.dependencies = packages
163 if not state.env.GetOption("clean") and not state.env.GetOption("help"):
164 for target in state.env.libs:
165 state.log.info(f"Libraries in target '{target}': {state.env.libs[target]}")
166 state.log.flush()
169def _configurePkgConfig(root, packageName):
170 """Configure the package being built through pkg-config.
172 Parameters
173 ----------
174 root : `str`
175 Absolute path to the build root, holding the package's pkg-config
176 template.
177 packageName : `str`
178 Name of the package being built.
180 Returns
181 -------
182 dependencies : `~lsst.sconsUtils.pkgconfig.PkgConfigDependencies`
183 The resolved dependencies, to be stored as ``env.dependencies``.
184 With ``--clean`` or ``--help`` pkg-config is not run at all and the
185 result is empty; with ``--clean`` and no explicit targets the
186 generated ``.pc`` file is removed instead, unless ``--no-exec`` is
187 also given.
188 """
189 if state.env.GetOption("clean") or state.env.GetOption("help"):
190 if _removesGeneratedPc(state.env, SCons.Script.COMMAND_LINE_TARGETS): 190 ↛ 193line 190 didn't jump to line 193 because the condition on line 190 was always true
191 if pkgconfig.remove_generated_pc(root, packageName):
192 state.log.info(f"Removed {pkgconfig.output_path(root, packageName)}.")
193 empty = pkgconfig.ResolvedDependencies(
194 modules=[],
195 cpppath=[],
196 xcpppath=[],
197 ccflags=[],
198 libpath=[],
199 linkflags=[],
200 libs={"main": [], "python": [], "test": []},
201 doxygen={"tags": [], "includes": []},
202 versions={},
203 )
204 return pkgconfig.PkgConfigDependencies(packageName, empty)
206 try:
207 _writeShims(root)
208 template = pkgconfig.template_path(root, packageName)
209 output = pkgconfig.output_path(root, packageName)
210 if pkgconfig.write_pc_from_template(template, output, state.env["version"]):
211 state.log.info(f"Wrote {output} from {template}.")
212 condaPrefix = get_conda_prefix()
213 runner = pkgconfig.PkgConfig(pkgconfig.build_search_path(root, os.environ), condaPrefix)
214 state.log.info(f"Using pkg-config at '{runner.executable}'.")
215 resolved = pkgconfig.resolve(packageName, runner, condaPrefix)
216 except (pkgconfig.PkgConfigError, OSError) as err:
217 state.log.fail(str(err))
218 state.log.info(f"Configuring package '{packageName}' through pkg-config modules {resolved.modules}.")
219 state.log.info(f"CPPPATH from pkg-config: {resolved.cpppath}")
220 state.log.info(f"XCPPPATH from pkg-config: {resolved.xcpppath}")
221 pkgconfig.apply_to_env(state.env, resolved)
222 return pkgconfig.PkgConfigDependencies(packageName, resolved)
225def _removesGeneratedPc(env, commandLineTargets):
226 """Return whether this SCons invocation removes the generated ``.pc``
227 file.
229 Parameters
230 ----------
231 env : `SCons.Environment.Environment`
232 The environment whose ``clean`` and ``no_exec`` options are read.
233 commandLineTargets : `list`
234 The targets given on the command line.
236 Returns
237 -------
238 removes : `bool`
239 `True` for ``--clean`` with no explicit targets, mirroring the
240 condition `~lsst.sconsUtils.builders.CleanTree` uses so that e.g.
241 ``scons --clean install`` does not remove the file, unless
242 ``--no-exec`` is also given.
243 """
244 return bool(env.GetOption("clean") and not commandLineTargets and not env.GetOption("no_exec"))
247def _writeShims(root):
248 """Write the configure-time pkg-config shims for a build.
250 Parameters
251 ----------
252 root : `str`
253 Absolute path to the build root; the shims are written into its
254 ``.sconf_temp/pkgconfig`` directory.
256 Notes
257 -----
258 A generated shim that cannot be written, e.g. ``numpy.pc`` when
259 ``numpy`` is not importable, is reported through ``state.log.info``
260 rather than treated as an error. `OSError` from writing a file is
261 propagated.
262 """
263 skipped = []
264 pkgconfig.write_shims(os.path.join(root, pkgconfig.GENERATED_SHIM_SUBDIR), skipped=skipped)
265 for message in skipped:
266 state.log.info(f"{message}.")
269class Configuration:
270 """Base class for defining how to configure an LSST sconsUtils package.
272 Aliased as `lsst.sconsUtils.Configuration`.
274 An ``ups/*.cfg`` file should contain an instance of this class called
275 "config". Most LSST packages will be able to use this class directly
276 instead of subclassing it.
278 The only important method is configure(), which modifies an SCons
279 environment to use the package. If a subclass overrides configure,
280 it may not need to call the base class ``__init__()``, whose only
281 purpose is to define a number of instance variables used by configure().
283 Parameters
284 ----------
285 cfgFile : `str`
286 The name of the calling .cfg file, usually just passed in with the
287 special variable ``__file__``. This will be parsed to extract the
288 package name and root.
289 headers : `list` of `str`, optional
290 A list of headers provided by the package, to be used in autoconf-style
291 tests.
292 libs : `list` or `dict`, optional
293 A list or dictionary of libraries provided by the package. If a
294 dictionary is provided, ``libs["main"]`` should contain a list of
295 regular libraries provided by the library. Other keys are "python"
296 and "test", which refer to libraries that are only linked against
297 compiled Python modules and unit tests, respectively. If a list is
298 provided, the list is used as "main". These are used both for
299 autoconf-style tests and to support ``env.getLibs(...)``, which
300 recursively computes the libraries a package must be linked with.
301 hasSwigFiles : `bool`, optional
302 Accepted for backwards compatibility and ignored; SWIG support has
303 been removed from sconsUtils.
304 hasDoxygenInclude : `bool`, optional
305 If True, the package provides a Doxygen include file with the
306 name ``<root>/doc/<name>.inc``.
307 hasDoxygenTag : `bool`, optional
308 If True, the package generates a Doxygen TAG file.
309 includeFileDirs : `collections.abc.Sequence`, optional
310 List of directories that should be searched for include files.
311 libFileDirs : `collections.abc.Sequence`, optional
312 List of directories that should be searched for libraries.
313 eupsProduct : `str`
314 Name of the EUPS product for the package, if different from the name
315 of the ``.cfg`` file.
316 """
318 @staticmethod
319 def parseFilename(cfgFile):
320 """Parse the name of a .cfg file and return package name and root.
322 Parameters
323 ----------
324 cfgFile : `str`
325 Name of a ``.cfg`` file.
327 Returns
328 -------
329 name : `str`
330 Package name
331 root : `str`
332 Root directory.
333 """
334 dir, file = os.path.split(cfgFile)
335 name, ext = os.path.splitext(file)
336 return name, os.path.abspath(os.path.join(dir, ".."))
338 @staticmethod
339 def getEupsData(eupsProduct):
340 """Get EUPS version and product directory for named product.
342 Parameters
343 ----------
344 eupsProduct : `str`
345 EUPS product name.
347 Returns
348 -------
349 version : `str`
350 EUPS product version.
351 productDir : `str`
352 EUPS product root directory.
353 """
354 version, eupsPathDir, productDir, table, flavor = eupsForScons.getEups().findSetupVersion(eupsProduct)
355 if productDir is None: 355 ↛ 357line 355 didn't jump to line 357 because the condition on line 355 was always true
356 productDir = eupsForScons.productDir(eupsProduct)
357 return version, productDir
359 def __init__(
360 self,
361 cfgFile,
362 headers=(),
363 libs=None,
364 hasSwigFiles=True,
365 includeFileDirs=("include",),
366 libFileDirs=("lib",),
367 hasDoxygenInclude=False,
368 hasDoxygenTag=True,
369 eupsProduct=None,
370 ):
371 self.name, self.root = self.parseFilename(cfgFile)
372 if eupsProduct is None: 372 ↛ 374line 372 didn't jump to line 374 because the condition on line 372 was always true
373 eupsProduct = self.name
374 self.eupsProduct = eupsProduct
375 version, productDir = self.getEupsData(self.eupsProduct)
376 if version is not None: 376 ↛ 377line 376 didn't jump to line 377 because the condition on line 376 was never true
377 self.version = version
378 if productDir is None: 378 ↛ 381line 378 didn't jump to line 381 because the condition on line 378 was always true
379 state.log.info(f"Could not find EUPS product dir for '{self.eupsProduct}'; using {self.root}.")
380 else:
381 self.root = os.path.realpath(productDir)
382 self.doxygen = {
383 # Doxygen tag files generated by this package
384 "tags": ([os.path.join(self.root, "doc", f"{self.name}.tag")] if hasDoxygenTag else []),
385 # Doxygen include files to include in the configuration of
386 # dependent products
387 "includes": ([os.path.join(self.root, "doc", f"{self.name}.inc")] if hasDoxygenInclude else []),
388 }
389 if libs is None: 389 ↛ 390line 389 didn't jump to line 390 because the condition on line 389 was never true
390 self.libs = {
391 # Normal libraries provided by this package
392 "main": [self.name],
393 # Libraries provided that should only be linked with Python
394 # modules
395 "python": [],
396 # Libraries provided that should only be linked with unit
397 # test code
398 "test": [],
399 }
400 elif "main" in libs: 400 ↛ 401line 400 didn't jump to line 401 because the condition on line 400 was never true
401 self.libs = libs
402 else:
403 self.libs = {"main": libs, "python": [], "test": []}
404 self.paths = {}
406 for pathName, subDirs in [("CPPPATH", includeFileDirs), ("LIBPATH", libFileDirs)]:
407 self.paths[pathName] = []
409 if state.env.linkFarmDir: 409 ↛ 410line 409 didn't jump to line 410 because the condition on line 409 was never true
410 continue
412 for subDir in subDirs:
413 pathDir = os.path.join(self.root, subDir)
414 if os.path.isdir(pathDir): 414 ↛ 415line 414 didn't jump to line 415 because the condition on line 414 was never true
415 self.paths[pathName].append(pathDir)
417 self.provides = {"headers": tuple(headers), "libs": tuple(self.libs["main"])}
419 def configure(self, conf, packages, build=True):
420 """Update an SCons environment to make use of the package.
422 Parameters
423 ----------
424 conf : `SCons.Configure`
425 An SCons Configure context. The SCons Environment conf.env
426 should be updated by the configure function.
427 packages : `dict`
428 A dictionary containing the configuration modules of all
429 dependencies (or `None` if the dependency was optional and was not
430 found). The ``<module>.config.configure(...)`` method will have
431 already been called on all dependencies.
432 build : `bool`, optional
433 If True, this is the package currently being built, and packages in
434 "buildRequired" and "buildOptional" dependencies will also be
435 present in the packages dict.
436 """
437 conf.env.PrependUnique(**self.paths)
438 state.log.info(f"Configuring package '{self.name}'.")
439 conf.env.doxygen["includes"].extend(self.doxygen["includes"])
440 if not build: 440 ↛ 441line 440 didn't jump to line 441 because the condition on line 440 was never true
441 conf.env.doxygen["tags"].extend(self.doxygen["tags"])
442 for target in self.libs:
443 if target not in conf.env.libs: 443 ↛ 444line 443 didn't jump to line 444 because the condition on line 443 was never true
444 conf.env.libs[target] = self.libs[target].copy()
445 state.log.info(f"Adding '{self.libs[target]}' libraries to target '{target}'.")
446 else:
447 for lib in self.libs[target]: 447 ↛ 448line 447 didn't jump to line 448 because the loop on line 447 never started
448 if lib not in conf.env.libs[target]:
449 conf.env.libs[target].append(lib)
450 state.log.info(f"Adding '{lib}' library to target '{target}'.")
451 return True
454class ExternalConfiguration(Configuration):
455 """A Configuration subclass for external (third-party) packages.
457 Aliased as `lsst.sconsUtils.ExternalConfiguration`.
459 ExternalConfiguration doesn't assume the package uses SWIG or Doxygen,
460 and tells SCons not to consider header files this package provides as
461 dependencies (by setting XCPPPATH instead of CPPPATH). This means things
462 SCons won't waste time looking for changes in it every time you build.
463 Header files in external packages are treated as "system headers": that
464 is, most warnings generated when they are being compiled are suppressed.
466 Parameters
467 ----------
468 cfgFile : `str`
469 The name of the calling ``.cfg`` file, usually just passed in with the
470 special variable ``__file__``. This will be parsed to extract the
471 package name and root.
472 headers : `list`, optional
473 A list of headers provided by the package, to be used in
474 autoconf-style tests.
475 libs : `list` or `dict`, optional
476 A list or dictionary of libraries provided by the package. If a
477 dictionary is provided, ``libs["main"]`` should contain a list of
478 regular libraries provided by the library. Other keys are "python"
479 and "test", which refer to libraries that are only linked against
480 compiled Python modules and unit tests, respectively. If a list is
481 provided, the list is used as "main". These are used both for
482 autoconf-style tests and to support env.getLibs(...), which
483 recursively computes the libraries a package must be linked with.
484 eupsProduct : `str`, optional
485 The EUPS product being built.
486 """
488 def __init__(self, cfgFile, headers=(), libs=None, eupsProduct=None):
489 Configuration.__init__(
490 self,
491 cfgFile,
492 headers,
493 libs,
494 eupsProduct=eupsProduct,
495 hasSwigFiles=False,
496 hasDoxygenTag=False,
497 hasDoxygenInclude=False,
498 )
499 self.paths["XCPPPATH"] = self.paths["CPPPATH"]
500 del self.paths["CPPPATH"]
503class PackageTree:
504 """A class for loading and managing the dependency tree of a package,
505 as defined by its configuration module (.cfg) file.
507 This tree isn't actually stored as a tree; it's flattened into an ordered
508 dictionary as it is recursively loaded.
510 The main SCons produced by configure() and available as
511 `lsst.sconsUtils.env` will contain an instance of this class as
512 ``env.dependencies``.
514 Its can be used like a read-only dictionary to check whether an optional
515 package has been configured; a package that was not found will have a
516 value of None, while a configured package's value will be its imported
517 .cfg module.
519 Parameters
520 ----------
521 primaryName : `str`
522 The name of the primary package being built.
523 noCfgFile : `bool`, optional
524 If True, this package has no .cfg file
526 Notes
527 -----
528 After ``__init__``, ``self.primary`` will be set to the configuration
529 module for the primary package, and ``self.packages`` will be an
530 `OrderedDict` of dependencies (excluding ``self.primary``), ordered
531 such that configuration can proceed in iteration order.
532 """
534 def __init__(self, primaryName, noCfgFile=False):
535 self.cfgPath = state.env.cfgPath
536 self.packages = collections.OrderedDict()
537 self._current = {primaryName}
538 # Packages in the closure of a dependency synthesized from
539 # pkg-config, which are configured as part of it rather than on
540 # their own; see _recurse().
541 self._provided = collections.OrderedDict()
542 # The pkg-config runner used to synthesize configurations for
543 # dependencies without a .cfg file; built on first use by
544 # _pkgconfig(), which sets _pkgconfigFailed if that is impossible.
545 self._pkgconfigInstance = None
546 self._pkgconfigFailed = False
547 self._shimsWritten = False
548 if noCfgFile:
549 self.primary = None
550 return
552 # The pkg-config fallback is for dependencies only; a primary
553 # package without a .cfg file must not pick up e.g. a stale
554 # lib/pkgconfig/lsst_<name>.pc instead.
555 self.primary = self._tryImport(primaryName, allowPkgConfig=False)
556 if self.primary is None:
557 state.log.fail(f"Failed to load primary package configuration for {primaryName}.")
559 missingDeps = []
560 for dependency in self.primary.dependencies.get("required", ()): 560 ↛ 561line 560 didn't jump to line 561 because the loop on line 560 never started
561 if not self._recurse(dependency):
562 missingDeps.append(dependency)
563 if missingDeps: 563 ↛ 564line 563 didn't jump to line 564 because the condition on line 563 was never true
564 state.log.fail('Failed to load required dependencies: "%s"' % '", "'.join(missingDeps))
566 missingDeps = []
567 for dependency in self.primary.dependencies.get("buildRequired", ()): 567 ↛ 568line 567 didn't jump to line 568 because the loop on line 567 never started
568 if not self._recurse(dependency):
569 missingDeps.append(dependency)
570 if missingDeps: 570 ↛ 571line 570 didn't jump to line 571 because the condition on line 570 was never true
571 state.log.fail('Failed to load required build dependencies: "%s"' % '", "'.join(missingDeps))
573 for dependency in self.primary.dependencies.get("optional", ()): 573 ↛ 574line 573 didn't jump to line 574 because the loop on line 573 never started
574 self._recurse(dependency)
576 for dependency in self.primary.dependencies.get("buildOptional", ()): 576 ↛ 577line 576 didn't jump to line 577 because the loop on line 576 never started
577 self._recurse(dependency)
579 name = property(lambda self: self.primary.config.name)
581 @property
582 def versions(self):
583 """Version of every dependency, keyed by package name
584 (`dict` [`str`, `str` or `None`]).
586 A dependency that was not found has a version of `None`, and one
587 whose configuration does not record a version has ``"unknown"``.
588 The closure of a dependency synthesized from pkg-config is
589 included, after the dependencies loaded in their own right.
590 """
591 return {
592 name: (getattr(mod.config, "version", "unknown") if mod is not None else None)
593 for name, mod in self._all().items()
594 }
596 def configure(self, env):
597 """Configure the entire dependency tree in order. and return an
598 updated environment."""
599 conf = env.Configure()
600 for name, module in self.packages.items():
601 if module is None: 601 ↛ 602line 601 didn't jump to line 602 because the condition on line 601 was never true
602 state.log.info(f"Skipping missing optional package {name}.")
603 continue
604 if not module.config.configure(conf, packages=self.packages, build=False): 604 ↛ 600line 604 didn't jump to line 600 because the condition on line 604 was always true
605 state.log.fail(f"{name} was found but did not pass configuration checks.")
606 if self.primary: 606 ↛ 611line 606 didn't jump to line 611 because the condition on line 606 was always true
607 self.primary.config.configure(conf, packages=self.packages, build=True)
608 # reverse the order of libraries in env.libs, so libraries that
609 # fulfill a dependency of another appear after it. required by the
610 # linker to successfully resolve symbols in static libraries.
611 for target in env.libs:
612 env.libs[target].reverse()
613 env = conf.Finish()
614 return env
616 def __contains__(self, name):
617 return name == self.name or name in self.packages or name in self._provided
619 has_key = __contains__
621 def __getitem__(self, name):
622 if name == self.name: 622 ↛ 623line 622 didn't jump to line 623 because the condition on line 622 was never true
623 return self.primary
624 else:
625 return self._all()[name]
627 def get(self, name, default=None):
628 if name == self.name:
629 return self.primary
630 else:
631 return self._all().get(name)
633 def keys(self):
634 k = list(self._all().keys())
635 k.append(self.name)
636 return k
638 def _all(self):
639 """Return ``self.packages`` followed by the provided packages that
640 were not also loaded in their own right. A provided package
641 replaces an optional one of the same name that was not found."""
642 result = collections.OrderedDict(self.packages)
643 for name, module in self._provided.items():
644 if result.get(name) is None: 644 ↛ 643line 644 didn't jump to line 643 because the condition on line 644 was always true
645 result[name] = module
646 return result
648 def _pkgconfig(self):
649 """Return the pkg-config runner used for dependencies without a
650 .cfg file, constructing it on first use.
652 Returns
653 -------
654 pkgconfig : `~lsst.sconsUtils.pkgconfig.PkgConfig` or `None`
655 The runner, or `None` if it cannot be constructed (no conda
656 prefix, or neither ``pkgconf`` nor ``pkg-config`` on ``PATH``).
657 The reason is logged once, and construction is not retried.
658 """
659 if self._pkgconfigInstance is None and not self._pkgconfigFailed:
660 root = SCons.Script.Dir("#").abspath
661 searchPath = pkgconfig.build_search_path(root, os.environ)
662 try:
663 self._pkgconfigInstance = pkgconfig.PkgConfig(searchPath, get_conda_prefix())
664 except pkgconfig.PkgConfigError as err:
665 state.log.info(f"Not looking for pkg-config modules: {err}.")
666 self._pkgconfigFailed = True
667 else:
668 state.log.info(f"Using pkg-config at '{self._pkgconfigInstance.executable}'.")
669 return self._pkgconfigInstance
671 def _tryImport(self, name, allowPkgConfig=True):
672 """Search for and import an individual configuration module from
673 file.
675 Parameters
676 ----------
677 name : `str`
678 Name of the package.
679 allowPkgConfig : `bool`, optional
680 If True (the default) and no ``<name>.cfg`` file is found on
681 the configuration path but pkg-config can find a
682 ``lsst_<name>`` module, a configuration module is synthesized
683 from pkg-config instead; see
684 `~lsst.sconsUtils.pkgconfig.synthesize_cfg_module`. This is
685 False for the primary package, which must have a ``.cfg`` file
686 on this path.
688 Notes
689 -----
690 Before the first configuration module is synthesized, the
691 configure-time shims are written into
692 ``<build root>/.sconf_temp/pkgconfig``, as on the pkg-config path,
693 so that a converted dependency requiring e.g. ``numpy`` can be
694 resolved. Under ``--clean`` or ``--help``, where `configure` is
695 never run, nothing is written or resolved: a ``lsst_<name>``
696 module that is merely present yields a placeholder module with no
697 version.
698 """
699 for path in self.cfgPath:
700 filename = os.path.join(path, name + ".cfg")
701 if os.path.exists(filename):
702 try:
703 # https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
704 # Need to specify SourceFileLoader since the files do not
705 # have a .py extension.
706 module_name = f"{name}_cfg"
707 loader = importlib.machinery.SourceFileLoader(module_name, filename)
708 spec = importlib.util.spec_from_file_location(
709 module_name, filename, submodule_search_locations=None, loader=loader
710 )
711 module = importlib.util.module_from_spec(spec)
712 spec.loader.exec_module(module)
713 except Exception as e:
714 state.log.warn(f"Error loading configuration {filename} ({e})")
715 continue
716 state.log.info(f"Using configuration for package '{name}' at '{filename}'.")
717 if not hasattr(module, "dependencies") or not isinstance(module.dependencies, dict): 717 ↛ 718line 717 didn't jump to line 718 because the condition on line 717 was never true
718 state.log.warn(f"Configuration module for package '{name}' lacks a dependencies dict.")
719 return None
720 if not hasattr(module, "config") or not isinstance(module.config, Configuration): 720 ↛ 721line 720 didn't jump to line 721 because the condition on line 720 was never true
721 state.log.warn(f"Configuration module for package '{name}' lacks a config object.")
722 return None
723 return module
724 if not allowPkgConfig:
725 return None
726 runner = self._pkgconfig()
727 moduleName = pkgconfig.module_name(name)
728 # present() rather than exists(): a module whose Requires cannot be
729 # satisfied is broken, not missing, and must not be skipped as an
730 # absent optional dependency.
731 if runner is not None and runner.present(moduleName):
732 state.log.info(f"Using pkg-config module '{moduleName}' for package '{name}'.")
733 if state.env.GetOption("clean") or state.env.GetOption("help"):
734 return types.SimpleNamespace(dependencies={}, config=types.SimpleNamespace(name=name))
735 if not self._shimsWritten:
736 try:
737 _writeShims(SCons.Script.Dir("#").abspath)
738 except OSError as err:
739 state.log.fail(str(err))
740 self._shimsWritten = True
741 try:
742 return pkgconfig.synthesize_cfg_module(name, runner, get_conda_prefix())
743 except pkgconfig.PkgConfigError as err:
744 state.log.fail(str(err))
745 state.log.info(f"Failed to import configuration for optional package '{name}'.")
747 def _recurse(self, name):
748 """Recursively load a dependency.
750 Parameters
751 ----------
752 name : `str`
753 Name of dependent package.
755 Returns
756 -------
757 loaded : `bool`
758 Was the dependency loaded?
759 """
760 if name in self._current: 760 ↛ 761line 760 didn't jump to line 761 because the condition on line 760 was never true
761 state.log.fail(f"Detected recursive dependency involving package '{name}'")
762 else:
763 self._current.add(name)
764 if name in self.packages: 764 ↛ 765line 764 didn't jump to line 765 because the condition on line 764 was never true
765 self._current.remove(name)
766 return self.packages[name] is not None
767 module = self._tryImport(name)
768 if module is None: 768 ↛ 769line 768 didn't jump to line 769 because the condition on line 768 was never true
769 self.packages[name] = None
770 self._current.remove(name)
771 return False
772 for dependency in module.dependencies.get("required", ()): 772 ↛ 773line 772 didn't jump to line 773 because the loop on line 772 never started
773 if not self._recurse(dependency):
774 # We can't configure this package because a required
775 # dependency wasn't found. But this package might itself be
776 # optional, so we don't die yet.
777 self.packages[name] = None
778 self._current.remove(name)
779 state.log.warn(
780 f"Could not load all dependencies for package '{name}' (missing {dependency})."
781 )
782 return False
783 for dependency in module.dependencies.get("optional", ()): 783 ↛ 784line 783 didn't jump to line 784 because the loop on line 783 never started
784 self._recurse(dependency)
785 # A synthesized module has no dependencies to recurse into, because
786 # its configuration already covers its whole closure; record that
787 # closure so that it is still listed, without configuring it again.
788 for provided, version in getattr(module, "provided", {}).items():
789 if provided not in self._provided: 789 ↛ 788line 789 didn't jump to line 788 because the condition on line 789 was always true
790 self._provided[provided] = types.SimpleNamespace(
791 dependencies={}, config=types.SimpleNamespace(name=provided, version=version)
792 )
793 # This comes last to ensure the ordering puts all dependencies first.
794 self.packages[name] = module
795 self._current.remove(name)
796 return True
799def getLibs(env, categories="main"):
800 """Get the libraries the package should be linked with.
802 Parameters
803 ----------
804 categories : `str`
805 A string containing whitespace-delimited categories. Standard
806 categories are "main", "python", and "test". Default is "main".
807 A special virtual category "self" can be provided, returning
808 the results of targets="main" with the ``env["packageName"]`` removed.
810 Returns
811 -------
812 libs : `list`
813 Libraries to use.
815 Notes
816 -----
817 Typically, main libraries will be linked with ``LIBS=getLibs("self")``,
818 Python modules will be linked with ``LIBS=getLibs("main python")`` and
819 C++-coded test programs will be linked with ``LIBS=getLibs("main test")``.
820 """
821 libs = []
822 removeSelf = False
823 for category in categories.split():
824 if category == "self":
825 category = "main"
826 removeSelf = True
827 for lib in env.libs[category]:
828 if lib not in libs: 828 ↛ 827line 828 didn't jump to line 827 because the condition on line 828 was always true
829 libs.append(lib)
830 if removeSelf:
831 try:
832 libs.remove(env["packageName"])
833 except ValueError:
834 pass
835 return libs
838SConsEnvironment.getLibs = getLibs