Coverage for python/lsst/sconsUtils/dependencies.py: 9%

287 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-26 06:02 +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/>. 

21 

22"""Dependency configuration and definition.""" 

23 

24__all__ = ("Configuration", "ExternalConfiguration", "PackageTree", "configure") 

25 

26import collections 

27import importlib 

28import os 

29import os.path 

30from sys import platform 

31 

32import SCons.Script 

33from SCons.Script.SConscript import SConsEnvironment 

34 

35from . import eupsForScons, installation, state 

36from .utils import get_conda_prefix, use_conda_compilers 

37 

38 

39def configure(packageName, versionString=None, eupsProduct=None, eupsProductPath=None, noCfgFile=False): 

40 """Recursively configure a package using ups/.cfg files. 

41 

42 Aliased as `lsst.sconsUtils.configure`. 

43 

44 Usually, LSST packages will call this function through 

45 `~lsst.sconsUtils.scripts.BasicSConstruct`. 

46 

47 Parameters 

48 ---------- 

49 packageName : `str` 

50 Name of the package being built; must correspond to a ``.cfg`` file 

51 in the ``ups`` directory. 

52 versionString : `str`, optional 

53 Version-control system string to be parsed for version information 

54 (``$HeadURL$`` for SVN). 

55 eupsProduct : `str`, optional 

56 Name of the EUPS product being built. Defaults to and is almost 

57 always the name of the package. 

58 eupsProductPath : `str`, optional 

59 An alternate directory where the package should be installed. 

60 noCfgFile : `bool` 

61 If True, this package has no ``.cfg`` file. 

62 

63 Returns 

64 ------- 

65 env : `SCons.Environment` 

66 An SCons Environment object (which is also available as 

67 `lsst.sconsUtils.env`). 

68 """ 

69 

70 if not state.env.GetOption("no_progress"): 

71 state.log.info(f"Setting up environment to build package '{packageName}'.") 

72 if eupsProduct is None: 

73 eupsProduct = packageName 

74 if versionString is None: 

75 versionString = "git" 

76 state.env["eupsProduct"] = eupsProduct 

77 state.env["packageName"] = packageName 

78 # 

79 # Setup installation directories and variables 

80 # 

81 SCons.Script.Help(state.opts.GenerateHelpText(state.env)) 

82 state.env.installing = [t for t in SCons.Script.BUILD_TARGETS if t == "install"] 

83 state.env.declaring = [t for t in SCons.Script.BUILD_TARGETS if t == "declare" or t == "current"] 

84 state.env.linkFarmDir = state.env.GetOption("linkFarmDir") 

85 if state.env.linkFarmDir: 

86 state.env.linkFarmDir = os.path.abspath(os.path.expanduser(state.env.linkFarmDir)) 

87 prefix = installation.setPrefix(state.env, versionString, eupsProductPath) 

88 state.env["prefix"] = prefix 

89 state.env["libDir"] = f"{prefix}/lib" 

90 state.env["pythonDir"] = f"{prefix}/python" 

91 # 

92 # Process dependencies 

93 # 

94 state.log.traceback = state.env.GetOption("traceback") 

95 state.log.verbose = state.env.GetOption("verbose") 

96 packages = PackageTree(packageName, noCfgFile=noCfgFile) 

97 state.log.flush() # if we've already hit a fatal error, die now. 

98 state.env.libs = {"main": [], "python": [], "test": []} 

99 state.env.doxygen = {"tags": [], "includes": []} 

100 state.env["CPPPATH"] = [] 

101 

102 _conda_prefix = get_conda_prefix() 

103 # _conda_prefix is usually around, even if not using conda compilers 

104 if use_conda_compilers(): 

105 # if using the conda-force conda compilers, they handle rpath for us 

106 _conda_lib = f"{_conda_prefix}/lib" 

107 state.env["LIBPATH"] = [_conda_lib] 

108 if platform == "darwin": 

109 state.env["_RPATH"] = f"-rpath {_conda_lib}" 

110 else: 

111 state.env.AppendUnique(RPATH=[_conda_lib]) 

112 else: 

113 state.env["LIBPATH"] = [] 

114 

115 # XCPPPATH is a new variable defined by sconsUtils - it's like CPPPATH, 

116 # but the headers found there aren't treated as dependencies. This can 

117 # make scons a lot faster. 

118 state.env["XCPPPATH"] = [] 

119 

120 if use_conda_compilers(): 

121 state.env.Append(XCPPPATH=[f"{_conda_prefix}/include"]) 

122 

123 # XCPPPPREFIX is a replacement for SCons' built-in INCPREFIX. It is used 

124 # when compiling headers in XCPPPATH directories. Here, we set it to 

125 # `-isystem`, so that those are regarded as "system headers" and warnings 

126 # are suppressed. 

127 state.env["XCPPPREFIX"] = "-isystem " 

128 

129 state.env["_CPPINCFLAGS"] = ( 

130 "$( ${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE)}" 

131 " ${_concat(XCPPPREFIX, XCPPPATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)" 

132 ) 

133 state.env["_SWIGINCFLAGS"] = ( 

134 state.env["_CPPINCFLAGS"].replace("CPPPATH", "SWIGPATH").replace("XCPPPREFIX", "SWIGINCPREFIX") 

135 ) 

136 

137 if state.env.linkFarmDir: 

138 for d in [state.env.linkFarmDir, "#"]: 

139 state.env.Append(CPPPATH=os.path.join(d, "include")) 

140 state.env.Append(LIBPATH=os.path.join(d, "lib")) 

141 state.env["SWIGPATH"] = state.env["CPPPATH"] 

142 

143 if not state.env.GetOption("clean") and not state.env.GetOption("help"): 

144 packages.configure(state.env, check=state.env.GetOption("checkDependencies")) 

145 for target in state.env.libs: 

146 state.log.info(f"Libraries in target '{target}': {state.env.libs[target]}") 

147 state.env.dependencies = packages 

148 state.log.flush() 

149 

150 

151class Configuration: 

152 """Base class for defining how to configure an LSST sconsUtils package. 

153 

154 Aliased as `lsst.sconsUtils.Configuration`. 

155 

156 An ``ups/*.cfg`` file should contain an instance of this class called 

157 "config". Most LSST packages will be able to use this class directly 

158 instead of subclassing it. 

159 

160 The only important method is configure(), which modifies an SCons 

161 environment to use the package. If a subclass overrides configure, 

162 it may not need to call the base class ``__init__()``, whose only 

163 purpose is to define a number of instance variables used by configure(). 

164 

165 Parameters 

166 ---------- 

167 cfgFile : `str` 

168 The name of the calling .cfg file, usually just passed in with the 

169 special variable ``__file__``. This will be parsed to extract the 

170 package name and root. 

171 headers : `list` of `str`, optional 

172 A list of headers provided by the package, to be used in autoconf-style 

173 tests. 

174 libs : `list` or `dict`, optional 

175 A list or dictionary of libraries provided by the package. If a 

176 dictionary is provided, ``libs["main"]`` should contain a list of 

177 regular libraries provided by the library. Other keys are "python" 

178 and "test", which refer to libraries that are only linked against 

179 compiled Python modules and unit tests, respectively. If a list is 

180 provided, the list is used as "main". These are used both for 

181 autoconf-style tests and to support ``env.getLibs(...)``, which 

182 recursively computes the libraries a package must be linked with. 

183 hasSwigFiles : `bool`, optional 

184 If True, the package provides SWIG interface files in 

185 ``<root>/python``. 

186 hasDoxygenInclude : `bool`, optional 

187 If True, the package provides a Doxygen include file with the 

188 name ``<root>/doc/<name>.inc``. 

189 hasDoxygenTag : `bool`, optional 

190 If True, the package generates a Doxygen TAG file. 

191 includeFileDirs : `collections.abc.Sequence`, optional 

192 List of directories that should be searched for include files. 

193 libFileDirs : `collections.abc.Sequence`, optional 

194 List of directories that should be searched for libraries. 

195 eupsProduct : `str` 

196 Name of the EUPS product for the package, if different from the name 

197 of the ``.cfg`` file. 

198 """ 

199 

200 @staticmethod 

201 def parseFilename(cfgFile): 

202 """Parse the name of a .cfg file and return package name and root. 

203 

204 Parameters 

205 ---------- 

206 cfgFile : `str` 

207 Name of a ``.cfg`` file. 

208 

209 Returns 

210 ------- 

211 name : `str` 

212 Package name 

213 root : `str` 

214 Root directory. 

215 """ 

216 dir, file = os.path.split(cfgFile) 

217 name, ext = os.path.splitext(file) 

218 return name, os.path.abspath(os.path.join(dir, "..")) 

219 

220 @staticmethod 

221 def getEupsData(eupsProduct): 

222 """Get EUPS version and product directory for named product. 

223 

224 Parameters 

225 ---------- 

226 eupsProduct : `str` 

227 EUPS product name. 

228 

229 Returns 

230 ------- 

231 version : `str` 

232 EUPS product version. 

233 productDir : `str` 

234 EUPS product root directory. 

235 """ 

236 version, eupsPathDir, productDir, table, flavor = eupsForScons.getEups().findSetupVersion(eupsProduct) 

237 if productDir is None: 

238 productDir = eupsForScons.productDir(eupsProduct) 

239 return version, productDir 

240 

241 def __init__( 

242 self, 

243 cfgFile, 

244 headers=(), 

245 libs=None, 

246 hasSwigFiles=True, 

247 includeFileDirs=("include",), 

248 libFileDirs=("lib",), 

249 hasDoxygenInclude=False, 

250 hasDoxygenTag=True, 

251 eupsProduct=None, 

252 ): 

253 self.name, self.root = self.parseFilename(cfgFile) 

254 if eupsProduct is None: 

255 eupsProduct = self.name 

256 self.eupsProduct = eupsProduct 

257 version, productDir = self.getEupsData(self.eupsProduct) 

258 if version is not None: 

259 self.version = version 

260 if productDir is None: 

261 state.log.info(f"Could not find EUPS product dir for '{self.eupsProduct}'; using {self.root}.") 

262 else: 

263 self.root = os.path.realpath(productDir) 

264 self.doxygen = { 

265 # Doxygen tag files generated by this package 

266 "tags": ([os.path.join(self.root, "doc", f"{self.name}.tag")] if hasDoxygenTag else []), 

267 # Doxygen include files to include in the configuration of 

268 # dependent products 

269 "includes": ([os.path.join(self.root, "doc", f"{self.name}.inc")] if hasDoxygenInclude else []), 

270 } 

271 if libs is None: 

272 self.libs = { 

273 # Normal libraries provided by this package 

274 "main": [self.name], 

275 # Libraries provided that should only be linked with Python 

276 # modules 

277 "python": [], 

278 # Libraries provided that should only be linked with unit 

279 # test code 

280 "test": [], 

281 } 

282 elif "main" in libs: 

283 self.libs = libs 

284 else: 

285 self.libs = {"main": libs, "python": [], "test": []} 

286 self.paths = {} 

287 if hasSwigFiles: 

288 self.paths["SWIGPATH"] = [os.path.join(self.root, "python")] 

289 else: 

290 self.paths["SWIGPATH"] = [] 

291 

292 for pathName, subDirs in [("CPPPATH", includeFileDirs), ("LIBPATH", libFileDirs)]: 

293 self.paths[pathName] = [] 

294 

295 if state.env.linkFarmDir: 

296 continue 

297 

298 for subDir in subDirs: 

299 pathDir = os.path.join(self.root, subDir) 

300 if os.path.isdir(pathDir): 

301 self.paths[pathName].append(pathDir) 

302 

303 self.provides = {"headers": tuple(headers), "libs": tuple(self.libs["main"])} 

304 

305 def addCustomTests(self, tests): 

306 """Add custom SCons configuration tests to the Configure Context 

307 passed to the configure() method. 

308 

309 This needs to be done up-front so we can pass in a dictionary of 

310 custom tests when calling ``env.Configure()``, and use the same 

311 configure context for all packages. 

312 

313 Parameters 

314 ---------- 

315 tests : `dict` 

316 A dictionary to add custom tests to. This will be passed as the 

317 custom_tests argument to ``env.Configure()``. 

318 """ 

319 pass 

320 

321 def configure(self, conf, packages, check=False, build=True): 

322 """Update an SCons environment to make use of the package. 

323 

324 Parameters 

325 ---------- 

326 conf : `SCons.Configure` 

327 An SCons Configure context. The SCons Environment conf.env 

328 should be updated by the configure function. 

329 packages : `dict` 

330 A dictionary containing the configuration modules of all 

331 dependencies (or `None` if the dependency was optional and was not 

332 found). The ``<module>.config.configure(...)`` method will have 

333 already been called on all dependencies. 

334 check : `bool`, optional 

335 If True, perform autoconf-style tests to verify that key 

336 components are in fact in place. 

337 build : `bool`, optional 

338 If True, this is the package currently being built, and packages in 

339 "buildRequired" and "buildOptional" dependencies will also be 

340 present in the packages dict. 

341 """ 

342 assert not (check and build) 

343 conf.env.PrependUnique(**self.paths) 

344 state.log.info(f"Configuring package '{self.name}'.") 

345 conf.env.doxygen["includes"].extend(self.doxygen["includes"]) 

346 if not build: 

347 conf.env.doxygen["tags"].extend(self.doxygen["tags"]) 

348 for target in self.libs: 

349 if target not in conf.env.libs: 

350 conf.env.libs[target] = self.libs[target].copy() 

351 state.log.info(f"Adding '{self.libs[target]}' libraries to target '{target}'.") 

352 else: 

353 for lib in self.libs[target]: 

354 if lib not in conf.env.libs[target]: 

355 conf.env.libs[target].append(lib) 

356 state.log.info(f"Adding '{lib}' library to target '{target}'.") 

357 if check: 

358 for header in self.provides["headers"]: 

359 if not conf.CheckCXXHeader(header): 

360 return False 

361 for lib in self.libs["main"]: 

362 if not conf.CheckLib(lib, autoadd=False, language="C++"): 

363 return False 

364 return True 

365 

366 

367class ExternalConfiguration(Configuration): 

368 """A Configuration subclass for external (third-party) packages. 

369 

370 Aliased as `lsst.sconsUtils.ExternalConfiguration`. 

371 

372 ExternalConfiguration doesn't assume the package uses SWIG or Doxygen, 

373 and tells SCons not to consider header files this package provides as 

374 dependencies (by setting XCPPPATH instead of CPPPATH). This means things 

375 SCons won't waste time looking for changes in it every time you build. 

376 Header files in external packages are treated as "system headers": that 

377 is, most warnings generated when they are being compiled are suppressed. 

378 

379 Parameters 

380 ---------- 

381 cfgFile : `str` 

382 The name of the calling ``.cfg`` file, usually just passed in with the 

383 special variable ``__file__``. This will be parsed to extract the 

384 package name and root. 

385 headers : `list`, optional 

386 A list of headers provided by the package, to be used in 

387 autoconf-style tests. 

388 libs : `list` or `dict`, optional 

389 A list or dictionary of libraries provided by the package. If a 

390 dictionary is provided, ``libs["main"]`` should contain a list of 

391 regular libraries provided by the library. Other keys are "python" 

392 and "test", which refer to libraries that are only linked against 

393 compiled Python modules and unit tests, respectively. If a list is 

394 provided, the list is used as "main". These are used both for 

395 autoconf-style tests and to support env.getLibs(...), which 

396 recursively computes the libraries a package must be linked with. 

397 eupsProduct : `str`, optional 

398 The EUPS product being built. 

399 """ 

400 

401 def __init__(self, cfgFile, headers=(), libs=None, eupsProduct=None): 

402 Configuration.__init__( 

403 self, 

404 cfgFile, 

405 headers, 

406 libs, 

407 eupsProduct=eupsProduct, 

408 hasSwigFiles=False, 

409 hasDoxygenTag=False, 

410 hasDoxygenInclude=False, 

411 ) 

412 self.paths["XCPPPATH"] = self.paths["CPPPATH"] 

413 del self.paths["CPPPATH"] 

414 

415 

416def CustomCFlagCheck(context, flag, append=True): 

417 """A configuration test that checks whether a C compiler supports 

418 a particular flag. 

419 

420 Parameters 

421 ---------- 

422 context : 

423 Configuration context. 

424 flag : `str` 

425 Flag to test, e.g., ``-fvisibility-inlines-hidden``. 

426 append : `bool`, optional 

427 Automatically append the flag to ``context.env["CCFLAGS"]`` 

428 if the compiler supports it? 

429 

430 Returns 

431 ------- 

432 result : `bool` 

433 Did the flag work? 

434 """ 

435 context.Message("Checking if C compiler supports " + flag + " flag ") 

436 ccflags = context.env["CCFLAGS"] 

437 context.env.Append(CCFLAGS=flag) 

438 result = context.TryCompile("int main(int argc, char **argv) { return 0; }", ".c") 

439 context.Result(result) 

440 if not append or not result: 

441 context.env.Replace(CCFLAGS=ccflags) 

442 return result 

443 

444 

445def CustomCppFlagCheck(context, flag, append=True): 

446 """A configuration test that checks whether a C++ compiler supports 

447 a particular flag. 

448 

449 Parameters 

450 ---------- 

451 context : 

452 Configuration context. 

453 flag : `str` 

454 Flag to test, e.g., ``-fvisibility-inlines-hidden``. 

455 append : `bool`, optional 

456 Automatically append the flag to ``context.env["CXXFLAGS"]`` 

457 if the compiler supports it? 

458 

459 Returns 

460 ------- 

461 result : `bool` 

462 Did the flag work? 

463 """ 

464 context.Message("Checking if C++ compiler supports " + flag + " flag ") 

465 cxxflags = context.env["CXXFLAGS"] 

466 context.env.Append(CXXFLAGS=flag) 

467 result = context.TryCompile("int main(int argc, char **argv) { return 0; }", ".cc") 

468 context.Result(result) 

469 if not append or not result: 

470 context.env.Replace(CXXFLAGS=cxxflags) 

471 return result 

472 

473 

474def CustomCompileCheck(context, message, source, extension=".cc"): 

475 """A configuration test that checks whether the given source code 

476 compiles. 

477 

478 Parameters 

479 ---------- 

480 context : 

481 Configuration context. 

482 message : `str` 

483 Message displayed on console prior to running the test. 

484 source : `str` 

485 Source code to compile. 

486 extension : `str`, optional 

487 Identifies the language of the source code. Use ".c" for C, and ".cc" 

488 for C++ (the default). 

489 

490 Returns 

491 ------- 

492 result : `bool` 

493 Did the code compile? 

494 """ 

495 context.Message(message) 

496 

497 env = context.env 

498 if env.GetOption("clean") or env.GetOption("help") or env.GetOption("no_exec"): 

499 result = True 

500 else: 

501 result = context.TryCompile(source, extension) 

502 

503 context.Result(result) 

504 

505 return result 

506 

507 

508def CustomLinkCheck(context, message, source, extension=".cc"): 

509 """A configuration test that checks whether the given source code 

510 compiles and links. 

511 

512 Parameters 

513 ---------- 

514 context : 

515 Configuration context. 

516 message : `str` 

517 Message displayed on console prior to running the test. 

518 source : `str` 

519 Source code to compile. 

520 extension : `str`, optional 

521 Identifies the language of the source code. Use ".c" for C, and ".cc" 

522 for C++ (the default). 

523 

524 Returns 

525 ------- 

526 result : `bool` 

527 Did the code compile and link? 

528 """ 

529 context.Message(message) 

530 result = context.TryLink(source, extension) 

531 context.Result(result) 

532 return result 

533 

534 

535class PackageTree: 

536 """A class for loading and managing the dependency tree of a package, 

537 as defined by its configuration module (.cfg) file. 

538 

539 This tree isn't actually stored as a tree; it's flattened into an ordered 

540 dictionary as it is recursively loaded. 

541 

542 The main SCons produced by configure() and available as 

543 `lsst.sconsUtils.env` will contain an instance of this class as 

544 ``env.dependencies``. 

545 

546 Its can be used like a read-only dictionary to check whether an optional 

547 package has been configured; a package that was not found will have a 

548 value of None, while a configured package's value will be its imported 

549 .cfg module. 

550 

551 Parameters 

552 ---------- 

553 primaryName : `str` 

554 The name of the primary package being built. 

555 noCfgFile : `bool`, optional 

556 If True, this package has no .cfg file 

557 

558 Notes 

559 ----- 

560 After ``__init__``, ``self.primary`` will be set to the configuration 

561 module for the primary package, and ``self.packages`` will be an 

562 `OrderedDict` of dependencies (excluding ``self.primary``), ordered 

563 such that configuration can proceed in iteration order. 

564 """ 

565 

566 def __init__(self, primaryName, noCfgFile=False): 

567 self.cfgPath = state.env.cfgPath 

568 self.packages = collections.OrderedDict() 

569 self.customTests = { 

570 "CustomCFlagCheck": CustomCFlagCheck, 

571 "CustomCppFlagCheck": CustomCppFlagCheck, 

572 "CustomCompileCheck": CustomCompileCheck, 

573 "CustomLinkCheck": CustomLinkCheck, 

574 } 

575 self._current = {primaryName} 

576 if noCfgFile: 

577 self.primary = None 

578 return 

579 

580 self.primary = self._tryImport(primaryName) 

581 if self.primary is None: 

582 state.log.fail(f"Failed to load primary package configuration for {primaryName}.") 

583 

584 missingDeps = [] 

585 for dependency in self.primary.dependencies.get("required", ()): 

586 if not self._recurse(dependency): 

587 missingDeps.append(dependency) 

588 if missingDeps: 

589 state.log.fail('Failed to load required dependencies: "%s"' % '", "'.join(missingDeps)) 

590 

591 missingDeps = [] 

592 for dependency in self.primary.dependencies.get("buildRequired", ()): 

593 if not self._recurse(dependency): 

594 missingDeps.append(dependency) 

595 if missingDeps: 

596 state.log.fail('Failed to load required build dependencies: "%s"' % '", "'.join(missingDeps)) 

597 

598 for dependency in self.primary.dependencies.get("optional", ()): 

599 self._recurse(dependency) 

600 

601 for dependency in self.primary.dependencies.get("buildOptional", ()): 

602 self._recurse(dependency) 

603 

604 name = property(lambda self: self.primary.config.name) 

605 

606 def configure(self, env, check=False): 

607 """Configure the entire dependency tree in order. and return an 

608 updated environment.""" 

609 conf = env.Configure(custom_tests=self.customTests) 

610 for name, module in self.packages.items(): 

611 if module is None: 

612 state.log.info(f"Skipping missing optional package {name}.") 

613 continue 

614 if not module.config.configure(conf, packages=self.packages, check=check, build=False): 

615 state.log.fail(f"{name} was found but did not pass configuration checks.") 

616 if self.primary: 

617 self.primary.config.configure(conf, packages=self.packages, check=False, build=True) 

618 env.AppendUnique(SWIGPATH=env["CPPPATH"]) 

619 env.AppendUnique(XSWIGPATH=env["XCPPPATH"]) 

620 # reverse the order of libraries in env.libs, so libraries that 

621 # fulfill a dependency of another appear after it. required by the 

622 # linker to successfully resolve symbols in static libraries. 

623 for target in env.libs: 

624 env.libs[target].reverse() 

625 env = conf.Finish() 

626 return env 

627 

628 def __contains__(self, name): 

629 return name == self.name or name in self.packages 

630 

631 has_key = __contains__ 

632 

633 def __getitem__(self, name): 

634 if name == self.name: 

635 return self.primary 

636 else: 

637 return self.packages[name] 

638 

639 def get(self, name, default=None): 

640 if name == self.name: 

641 return self.primary 

642 else: 

643 return self.packages.get(name) 

644 

645 def keys(self): 

646 k = list(self.packages.keys()) 

647 k.append(self.name) 

648 return k 

649 

650 def _tryImport(self, name): 

651 """Search for and import an individual configuration module from 

652 file.""" 

653 for path in self.cfgPath: 

654 filename = os.path.join(path, name + ".cfg") 

655 if os.path.exists(filename): 

656 try: 

657 # https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly 

658 # Need to specify SourceFileLoader since the files do not 

659 # have a .py extension. 

660 module_name = f"{name}_cfg" 

661 loader = importlib.machinery.SourceFileLoader(module_name, filename) 

662 spec = importlib.util.spec_from_file_location( 

663 module_name, filename, submodule_search_locations=None, loader=loader 

664 ) 

665 module = importlib.util.module_from_spec(spec) 

666 spec.loader.exec_module(module) 

667 except Exception as e: 

668 state.log.warn(f"Error loading configuration {filename} ({e})") 

669 continue 

670 state.log.info(f"Using configuration for package '{name}' at '{filename}'.") 

671 if not hasattr(module, "dependencies") or not isinstance(module.dependencies, dict): 

672 state.log.warn(f"Configuration module for package '{name}' lacks a dependencies dict.") 

673 return None 

674 if not hasattr(module, "config") or not isinstance(module.config, Configuration): 

675 state.log.warn(f"Configuration module for package '{name}' lacks a config object.") 

676 return None 

677 else: 

678 module.config.addCustomTests(self.customTests) 

679 return module 

680 state.log.info(f"Failed to import configuration for optional package '{name}'.") 

681 

682 def _recurse(self, name): 

683 """Recursively load a dependency. 

684 

685 Parameters 

686 ---------- 

687 name : `str` 

688 Name of dependent package. 

689 

690 Returns 

691 ------- 

692 loaded : `bool` 

693 Was the dependency loaded? 

694 """ 

695 if name in self._current: 

696 state.log.fail(f"Detected recursive dependency involving package '{name}'") 

697 else: 

698 self._current.add(name) 

699 if name in self.packages: 

700 self._current.remove(name) 

701 return self.packages[name] is not None 

702 module = self._tryImport(name) 

703 if module is None: 

704 self.packages[name] = None 

705 self._current.remove(name) 

706 return False 

707 for dependency in module.dependencies.get("required", ()): 

708 if not self._recurse(dependency): 

709 # We can't configure this package because a required 

710 # dependency wasn't found. But this package might itself be 

711 # optional, so we don't die yet. 

712 self.packages[name] = None 

713 self._current.remove(name) 

714 state.log.warn( 

715 f"Could not load all dependencies for package '{name}' (missing {dependency})." 

716 ) 

717 return False 

718 for dependency in module.dependencies.get("optional", ()): 

719 self._recurse(dependency) 

720 # This comes last to ensure the ordering puts all dependencies first. 

721 self.packages[name] = module 

722 self._current.remove(name) 

723 return True 

724 

725 

726def getLibs(env, categories="main"): 

727 """Get the libraries the package should be linked with. 

728 

729 Parameters 

730 ---------- 

731 categories : `str` 

732 A string containing whitespace-delimited categories. Standard 

733 categories are "main", "python", and "test". Default is "main". 

734 A special virtual category "self" can be provided, returning 

735 the results of targets="main" with the ``env["packageName"]`` removed. 

736 

737 Returns 

738 ------- 

739 libs : `list` 

740 Libraries to use. 

741 

742 Notes 

743 ----- 

744 Typically, main libraries will be linked with ``LIBS=getLibs("self")``, 

745 Python modules will be linked with ``LIBS=getLibs("main python")`` and 

746 C++-coded test programs will be linked with ``LIBS=getLibs("main test")``. 

747 """ 

748 libs = [] 

749 removeSelf = False 

750 for category in categories.split(): 

751 if category == "self": 

752 category = "main" 

753 removeSelf = True 

754 for lib in env.libs[category]: 

755 if lib not in libs: 

756 libs.append(lib) 

757 if removeSelf: 

758 try: 

759 libs.remove(env["packageName"]) 

760 except ValueError: 

761 pass 

762 return libs 

763 

764 

765SConsEnvironment.getLibs = getLibs