Coverage for python/lsst/sconsUtils/builders.py: 6%

452 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"""Extra builders and methods to be injected into the SConsEnvironment 

23class. 

24""" 

25 

26__all__ = ("DoxygenBuilder", "filesToTag") 

27 

28import csv 

29import fnmatch 

30import os 

31import re 

32import shlex 

33from stat import ST_MODE 

34 

35import SCons.Script 

36from SCons.Script.SConscript import SConsEnvironment 

37 

38from . import state 

39from .installation import determineVersion, getFingerprint 

40from .utils import is_within_tree, memberOf, needShebangRewrite, whichPython 

41 

42 

43@memberOf(SConsEnvironment) 

44def SharedLibraryIncomplete(self, target, source, **keywords): 

45 """Like SharedLibrary, but don't insist that all symbols are resolved.""" 

46 myenv = self.Clone() 

47 if myenv["PLATFORM"] == "darwin": 

48 myenv["SHLINKFLAGS"] += ["-undefined", "dynamic_lookup", "-headerpad_max_install_names"] 

49 return myenv.SharedLibrary(target, source, **keywords) 

50 

51 

52@memberOf(SConsEnvironment) 

53def Pybind11LoadableModule(self, target, source, **keywords): 

54 """Like LoadableModule, but don't insist that all symbols are resolved, and 

55 set some pybind11-specific flags. 

56 """ 

57 myenv = self.Clone() 

58 myenv.Append(CCFLAGS=["-fvisibility=hidden"]) 

59 if myenv["PLATFORM"] == "darwin": 

60 myenv.Append(LDMODULEFLAGS=["-undefined", "dynamic_lookup", "-headerpad_max_install_names"]) 

61 return myenv.LoadableModule(target, source, **keywords) 

62 

63 

64@memberOf(SConsEnvironment) 

65def SourcesForSharedLibrary(self, files): 

66 """Prepare the list of files to be passed to a SharedLibrary constructor. 

67 

68 Parameters 

69 ---------- 

70 files : 

71 List of files to be processed. 

72 

73 Returns 

74 ------- 

75 objs : `list` 

76 Object files. 

77 

78 Notes 

79 ----- 

80 In particular, ensure that any files listed in ``env.NoOptFiles`` (set by 

81 the command line option ``noOptFile="file1 file2"``) are built without 

82 optimisation and files listed in ``env.optFiles`` are built with 

83 optimisation. 

84 

85 The usage pattern in an SConscript file is: 

86 

87 .. code-block:: python 

88 

89 ccFiles = env.SourcesForSharedLibrary(Glob("../src/*/*.cc")) 

90 env.SharedLibrary('afw', ccFiles, LIBS=env.getLibs("self"))) 

91 

92 This is automatically used by 

93 `lsst.sconsUtils.scripts.BasicSConscript.lib()`. 

94 """ 

95 

96 files = [SCons.Script.File(file) for file in files] 

97 

98 if not (self.get("optFiles") or self.get("noOptFiles")): 

99 objs = [self.SharedObject(ccFile) for ccFile in sorted(state.env.Flatten(files), key=str)] 

100 return objs 

101 

102 if self.get("optFiles"): 

103 optFiles = self["optFiles"].replace(".", r"\.") # it'll be used in an RE 

104 optFiles = SCons.Script.Split(optFiles.replace(",", " ")) 

105 optFilesRe = "/(%s)$" % "|".join(optFiles) 

106 else: 

107 optFilesRe = None 

108 

109 if self.get("noOptFiles"): 

110 noOptFiles = self["noOptFiles"].replace(".", r"\.") # it'll be used in an RE 

111 noOptFiles = SCons.Script.Split(noOptFiles.replace(",", " ")) 

112 noOptFilesRe = "/(%s)$" % "|".join(noOptFiles) 

113 else: 

114 noOptFilesRe = None 

115 

116 if self.get("opt"): 

117 opt = int(self["opt"]) 

118 else: 

119 opt = 0 

120 

121 if opt == 0: 

122 opt = 3 

123 

124 CCFLAGS_OPT = re.sub(r"-O(\d|s)\s*", f"-O{opt} ", " ".join(self["CCFLAGS"])) 

125 CCFLAGS_NOOPT = re.sub(r"-O(\d|s)\s*", "-O0 ", " ".join(self["CCFLAGS"])) # remove -O flags from CCFLAGS 

126 

127 objs = [] 

128 for ccFile in files: 

129 if optFilesRe and re.search(optFilesRe, ccFile.abspath): 

130 obj = self.SharedObject(ccFile, CCFLAGS=CCFLAGS_OPT) 

131 elif noOptFilesRe and re.search(noOptFilesRe, ccFile.abspath): 

132 obj = self.SharedObject(ccFile, CCFLAGS=CCFLAGS_NOOPT) 

133 else: 

134 obj = self.SharedObject(ccFile) 

135 objs.append(obj) 

136 

137 objs = sorted(state.env.Flatten(objs), key=str) 

138 return objs 

139 

140 

141def filesToTag(root=None, fileRegex=None, ignoreDirs=None): 

142 """Return a list of files that need to be scanned for tags, starting at 

143 directory root. 

144 

145 Parameters 

146 ---------- 

147 root : `str`, optional 

148 Directory root to search. 

149 fileRegex : `str`, optional 

150 Matching regular expression for files. 

151 ignoreDirs : `list` 

152 List of directories to ignore when searching. 

153 

154 Returns 

155 ------- 

156 files : `list` 

157 List of matching files. 

158 

159 Notes 

160 ----- 

161 These tags are for advanced Emacs users, and should not be confused with 

162 SVN tags or Doxygen tags. 

163 

164 Files are chosen if they match fileRegex; toplevel directories in list 

165 ignoreDirs are ignored. 

166 This routine won't do anything unless you specified a "TAGS" target. 

167 """ 

168 

169 if root is None: 

170 root = "." 

171 if fileRegex is None: 

172 fileRegex = r"^[a-zA-Z0-9_].*\.(cc|h(pp)?|py)$" 

173 if ignoreDirs is None: 

174 ignoreDirs = ["examples", "tests"] 

175 

176 if "TAGS" not in SCons.Script.COMMAND_LINE_TARGETS: 

177 return [] 

178 

179 files = [] 

180 for dirpath, dirnames, filenames in os.walk(root): 

181 if dirpath == ".": 

182 dirnames[:] = [d for d in dirnames if not re.search(r"^(%s)$" % "|".join(ignoreDirs), d)] 

183 

184 dirnames[:] = [d for d in dirnames if not re.search(r"^(\.svn)$", d)] # ignore .svn tree 

185 # 

186 # List of possible files to tag, but there's some cleanup required 

187 # for machine-generated files 

188 # 

189 candidates = [f for f in filenames if re.search(fileRegex, f)] 

190 # 

191 # Remove files generated by swig 

192 # 

193 for swigFile in [f for f in filenames if f.endswith(".i")]: 

194 name = os.path.splitext(swigFile)[0] 

195 candidates = [f for f in candidates if not re.search(rf"{name}(_wrap\.cc?|\.py)$", f)] 

196 

197 files += [os.path.join(dirpath, f) for f in candidates] 

198 

199 return files 

200 

201 

202@memberOf(SConsEnvironment) 

203def BuildETags(env, root=None, fileRegex=None, ignoreDirs=None): 

204 """Build Emacs tags (see man etags for more information). 

205 

206 Parameters 

207 ---------- 

208 env : `SCons.Environment` 

209 Environment to use to run ``etags`` command. 

210 root : `str`, optional 

211 Directory to begin search. 

212 fileRegex : `str` 

213 Regular expression to match files. 

214 ignoreDirs : `list` 

215 List of directories to ignore. 

216 

217 Notes 

218 ----- 

219 Files are chosen if they match fileRegex; toplevel directories in list 

220 ignoreDirs are ignored. This routine won't do anything unless you 

221 specified a "TAGS" target.""" 

222 

223 toTag = filesToTag(root, fileRegex, ignoreDirs) 

224 if toTag: 

225 return env.Command("TAGS", toTag, "etags -o $TARGET $SOURCES") 

226 

227 

228@memberOf(SConsEnvironment) 

229def CleanTree(self, filePatterns, dirPatterns="", directory=".", verbose=False): 

230 """Remove files matching the argument list starting at directory 

231 when scons is invoked with -c/--clean and no explicit targets are listed. 

232 

233 Parameters 

234 ---------- 

235 filePatterns : `str` 

236 Glob to match for files to be deleted. 

237 dirPatterns : `str`, optional 

238 Specification of directories to be removed. 

239 directory : `str`, optional 

240 Directory to clean. 

241 verbose : `bool`, optional 

242 If `True` print each filename after deleting it. 

243 

244 Notes 

245 ----- 

246 Can be run as: 

247 

248 .. code-block:: python 

249 

250 env.CleanTree(r"*~ core") 

251 """ 

252 

253 def genFindCommand(patterns, directory, verbose, filesOnly): 

254 # Generate find command to clean up (find-glob) patterns, either files 

255 # or directories. 

256 expr = "" 

257 for pattern in SCons.Script.Split(patterns): 

258 if expr != "": 

259 expr += " -o " 

260 # Quote unquoted * and [ 

261 expr += "-name %s" % re.sub(r"(^|[^\\])([\[*])", r"\1\\\2", pattern) 

262 if filesOnly: 

263 expr += " -type f" 

264 else: 

265 expr += " -type d -prune" 

266 

267 command = "find " + directory 

268 # Don't look into .svn or .git directories to save time. 

269 command += r" \( -name .svn -prune -o -name .git -prune -o -name \* \) " 

270 command += r" \( " + expr + r" \)" 

271 if filesOnly: 

272 command += r" -exec rm -f {} \;" 

273 else: 

274 command += r" -exec rm -rf {} \;" 

275 if verbose: 

276 command += " -print" 

277 return command 

278 

279 action = genFindCommand(filePatterns, directory, verbose, filesOnly=True) 

280 

281 # Clean up scons files --- users want to be able to say scons -c and get a 

282 # clean copy. 

283 # We can't delete .sconsign.dblite if we use "scons clean" instead of 

284 # "scons --clean", so the former is no longer supported. 

285 action += " ; rm -rf .sconf_temp .sconsign.dblite .sconsign.tmp config.log" 

286 

287 if dirPatterns != "": 

288 action += " ; " 

289 action += genFindCommand(dirPatterns, directory, verbose, filesOnly=False) 

290 # Do we actually want to clean up? We don't if the command is e.g. 

291 # "scons -c install" 

292 if "clean" in SCons.Script.COMMAND_LINE_TARGETS: 

293 state.log.fail("'scons clean' is no longer supported; please use 'scons --clean'.") 

294 elif not SCons.Script.COMMAND_LINE_TARGETS and self.GetOption("clean"): 

295 self.Execute(self.Action([action])) 

296 

297 

298@memberOf(SConsEnvironment) 

299def ProductDir(env, product): 

300 """Return the product directory. 

301 

302 Parameters 

303 ---------- 

304 product : `str` 

305 The EUPS product name. 

306 

307 Returns 

308 ------- 

309 dir : `str` 

310 The product directory. `None` if the product is not known. 

311 """ 

312 from . import eupsForScons 

313 

314 global _productDirs 

315 try: 

316 _productDirs # noqa: B018 

317 except Exception: 

318 try: 

319 _productDirs = eupsForScons.productDir(eupsenv=eupsForScons.getEups()) 

320 except TypeError: # old version of eups (pre r18588) 

321 _productDirs = None 

322 if _productDirs: 

323 pdir = _productDirs.get(product) 

324 else: 

325 pdir = eupsForScons.productDir(product) 

326 if pdir == "none": 

327 pdir = None 

328 return pdir 

329 

330 

331class DoxygenBuilder: 

332 """A callable to be used as an SCons Action to run Doxygen. 

333 

334 This should only be used by the env.Doxygen pseudo-builder method. 

335 """ 

336 

337 def __init__(self, **kw): 

338 self.__dict__.update(kw) 

339 self.results = [] 

340 self.sources = [] 

341 self.targets = [] 

342 self.useTags = [SCons.Script.File(item).abspath for item in self.useTags] 

343 self.inputs = [SCons.Script.Entry(item).abspath for item in self.inputs] 

344 self.excludes = [SCons.Script.Entry(item).abspath for item in self.excludes] 

345 self.outputPaths = [SCons.Script.Dir(item) for item in self.outputs] 

346 

347 def __call__(self, env, config): 

348 self.findSources() 

349 self.findTargets() 

350 inConfigNode = SCons.Script.File(config) 

351 outConfigName, ext = os.path.splitext(inConfigNode.abspath) 

352 outConfigNode = SCons.Script.File(outConfigName) 

353 if self.makeTag: 

354 tagNode = SCons.Script.File(self.makeTag) 

355 self.makeTag = tagNode.abspath 

356 self.targets.append(tagNode) 

357 config = env.Command( 

358 target=outConfigNode, 

359 source=inConfigNode if os.path.exists(config) else None, 

360 action=self.buildConfig, 

361 ) 

362 env.AlwaysBuild(config) 

363 doc = env.Command( 

364 target=self.targets, source=self.sources, action=f"doxygen {shlex.quote(outConfigNode.abspath)}" 

365 ) 

366 for path in self.outputPaths: 

367 env.Clean(doc, path) 

368 env.Depends(doc, config) 

369 self.results.extend(config) 

370 self.results.extend(doc) 

371 return self.results 

372 

373 def findSources(self): 

374 for path in self.inputs: 

375 if os.path.isdir(path): 

376 for root, dirs, files in os.walk(path): 

377 if os.path.abspath(root) in self.excludes: 

378 dirs[:] = [] 

379 continue 

380 if not self.recursive: 

381 dirs[:] = [] 

382 else: 

383 toKeep = [] 

384 for relDir in dirs: 

385 if relDir.startswith("."): 

386 continue 

387 absDir = os.path.abspath(os.path.join(root, relDir)) 

388 if absDir not in self.excludes: 

389 toKeep.append(relDir) 

390 dirs[:] = toKeep 

391 if self.excludeSwig: 

392 for relFile in files: 

393 base, ext = os.path.splitext(relFile) 

394 if ext == ".i": 

395 self.excludes.append(os.path.join(root, base + ".py")) 

396 self.excludes.append(os.path.join(root, base + "_wrap.cc")) 

397 for relFile in files: 

398 absFile = os.path.abspath(os.path.join(root, relFile)) 

399 if absFile in self.excludes: 

400 continue 

401 for pattern in self.patterns: 

402 if fnmatch.fnmatch(relFile, pattern): 

403 self.sources.append(SCons.Script.File(absFile)) 

404 break 

405 elif os.path.isfile(path): 

406 self.sources.append(SCons.Script.File(path)) 

407 

408 def findTargets(self): 

409 for item in self.outputs: 

410 self.targets.append(SCons.Script.Dir(item)) 

411 

412 def buildConfig(self, target, source, env): 

413 outConfigFile = open(target[0].abspath, "w") 

414 

415 # Need a routine to quote paths that contain spaces 

416 # but can not use shlex.quote because it has to be 

417 # a double quote for doxygen.conf 

418 # Do not quote a string if it is already quoted 

419 # Also have a version that quotes each item in a sequence and generates 

420 # the final quoted entry. 

421 def _quote_path(path): 

422 if " " in path and not path.startswith('"') and not path.endswith('"'): 

423 return f'"{path}"' 

424 return path 

425 

426 def _quote_paths(pathList): 

427 return " ".join(_quote_path(p) for p in pathList) 

428 

429 docPaths = [] 

430 incFiles = [] 

431 for incPath in self.includes: 

432 docDir, incFile = os.path.split(incPath) 

433 docPaths.append(f'"{docDir}"') 

434 incFiles.append(f'"{incFile}"') 

435 self.sources.append(SCons.Script.File(incPath)) 

436 if docPaths: 

437 outConfigFile.write(f"@INCLUDE_PATH = {_quote_paths(docPaths)}\n") 

438 for incFile in incFiles: 

439 outConfigFile.write(f"@INCLUDE = {_quote_path(incFile)}\n") 

440 

441 for tagPath in self.useTags: 

442 docDir, tagFile = os.path.split(tagPath) 

443 htmlDir = os.path.join(docDir, "html") 

444 outConfigFile.write(f'TAGFILES += "{tagPath}={htmlDir}"\n') 

445 self.sources.append(SCons.Script.Dir(docDir)) 

446 if self.projectName is not None: 

447 outConfigFile.write(f"PROJECT_NAME = {self.projectName}\n") 

448 if self.projectNumber is not None: 

449 outConfigFile.write(f"PROJECT_NUMBER = {self.projectNumber}\n") 

450 outConfigFile.write(f"INPUT = {_quote_paths(self.inputs)}\n") 

451 outConfigFile.write(f"EXCLUDE = {_quote_paths(self.excludes)}\n") 

452 outConfigFile.write(f"FILE_PATTERNS = {' '.join(self.patterns)}\n") 

453 outConfigFile.write("RECURSIVE = YES\n" if self.recursive else "RECURSIVE = NO\n") 

454 allOutputs = {"html", "latex", "man", "rtf", "xml"} 

455 for output, path in zip(self.outputs, self.outputPaths, strict=True): 

456 try: 

457 allOutputs.remove(output.lower()) 

458 except Exception: 

459 state.log.fail(f"Unknown Doxygen output format '{output}'.") 

460 state.log.finish() 

461 outConfigFile.write(f"GENERATE_{output.upper()} = YES\n") 

462 outConfigFile.write(f"{output.upper()}_OUTPUT = {_quote_path(path.abspath)}\n") 

463 for output in allOutputs: 

464 outConfigFile.write(f"GENERATE_{output.upper()} = NO\n") 

465 if self.makeTag is not None: 

466 outConfigFile.write(f"GENERATE_TAGFILE = {_quote_path(self.makeTag)}\n") 

467 # 

468 # Append the local overrides (usually doxygen.conf.in) 

469 # 

470 if len(source) > 0: 

471 with open(source[0].abspath) as inConfigFile: 

472 outConfigFile.write(inConfigFile.read()) 

473 

474 outConfigFile.close() 

475 

476 

477@memberOf(SConsEnvironment) 

478def Doxygen(self, config, **kwargs): 

479 """Generate a Doxygen config file and run Doxygen on it. 

480 

481 Rather than parse a complete Doxygen config file for SCons sources 

482 and targets, this Doxygen builder builds a Doxygen config file, 

483 adding INPUT, FILE_PATTERNS, RECURSIVE, EXCLUDE, XX_OUTPUT and 

484 GENERATE_XX options (and possibly others) to an existing 

485 proto-config file. Generated settings will override those in 

486 the proto-config file. 

487 

488 Parameters 

489 ---------- 

490 config : `str` 

491 A Doxygen config file, usually with the extension .conf.in; a new file 

492 with the ``.in`` removed will be generated and passed to Doxygen. 

493 Settings in the original config file will be overridden by those 

494 generated by this method. 

495 **kwargs 

496 Keyword arguments. 

497 

498 - ``inputs`` : A sequence of folders or files to be passed 

499 as the INPUT setting for Doxygen. This list 

500 will be turned into absolute paths by SCons, 

501 so the ``#folder`` syntax will work. 

502 Otherwise, the list is passed in as-is, but 

503 the builder will also examine those 

504 directories to find which source files the 

505 Doxygen output actually depends on. 

506 - ``patterns`` : A sequence of glob patterns for the 

507 FILE_PATTERNS Doxygen setting. This will be 

508 passed directly to Doxygen, but it is also 

509 used to determine which source files should 

510 be considered dependencies. 

511 - ``recursive`` : Whether the inputs should be searched 

512 recursively (used for the Doxygen RECURSIVE 

513 setting). 

514 - ``outputs`` : A sequence of output formats which will also 

515 be used as output directories. 

516 - ``exclude`` : A sequence of folders or files (not globs) 

517 to be ignored by Doxygen (the Doxygen 

518 EXCLUDE setting). Hidden directories are 

519 automatically ignored. 

520 - ``includes`` : A sequence of Doxygen config files to 

521 include. These will automatically be 

522 separated into paths and files to fill in 

523 the ``@INCLUDE_PATH`` and ``@INCLUDE`` settings. 

524 - ``useTags`` : A sequence of Doxygen tag files to use. It 

525 will be assumed that the html directory for 

526 each tag file is in an "html" subdirectory 

527 in the same directory as the tag file. 

528 - ``makeTag`` A string indicating the name of a tag file 

529 to be generated. 

530 - ``projectName`` : Sets the Doxygen PROJECT_NAME setting. 

531 - ``projectNumber`` : Sets the Doxygen PROJECT_NUMBER setting. 

532 - ``excludeSwig`` : If True (default), looks for SWIG .i files 

533 in the input directories and adds Python 

534 and C++ files generated by SWIG to the 

535 list of files to exclude. For this to work, 

536 the SWIG-generated filenames must be the 

537 default ones ("module.i" generates "module.py" 

538 and "moduleLib_wrap.cc"). 

539 

540 Notes 

541 ----- 

542 When building documentation from a clean source tree, generated source 

543 files (like headers generated with M4) will not be included among the 

544 dependencies, because they aren't present when we walk the input folders. 

545 The workaround is just to build the docs after building the source. 

546 """ 

547 

548 inputs = [ 

549 d for d in ["#doc", "#include", "#python", "#src"] if os.path.exists(SCons.Script.Entry(d).abspath) 

550 ] 

551 defaults = { 

552 "inputs": inputs, 

553 "recursive": True, 

554 "patterns": ["*.h", "*.cc", "*.py", "*.dox"], 

555 "outputs": ["html", "xml"], 

556 "excludes": [], 

557 "includes": [], 

558 "useTags": [], 

559 "makeTag": None, 

560 "projectName": None, 

561 "projectNumber": None, 

562 "excludeSwig": True, 

563 } 

564 for k in defaults: 

565 if kwargs.get(k) is None: 

566 kwargs[k] = defaults[k] 

567 builder = DoxygenBuilder(**kwargs) 

568 return builder(self, config) 

569 

570 

571def _get_version_string(versionString): 

572 if versionString is None: 

573 for n in ("git", "hg", "svn"): 

574 if os.path.isdir(f".{n}"): 

575 versionString = n 

576 

577 if not versionString: 

578 versionString = "git" 

579 return versionString 

580 

581 

582def _calcMd5(filename): 

583 try: 

584 import hashlib 

585 

586 md5 = hashlib.md5(open(filename, "rb").read()).hexdigest() 

587 except OSError: 

588 md5 = None 

589 

590 return md5 

591 

592 

593@memberOf(SConsEnvironment) 

594def VersionModule(self, filename, versionString=None): 

595 versionString = _get_version_string(versionString) 

596 oldMd5 = _calcMd5(filename) 

597 

598 def makeVersionModule(target, source, env): 

599 try: 

600 version = determineVersion(state.env, versionString) 

601 except RuntimeError: 

602 version = "unknown" 

603 parts = version.split("+") 

604 

605 names = [] 

606 with open(target[0].abspath, "w") as outFile: 

607 outFile.write("# -------- This file is automatically generated by LSST's sconsUtils -------- #\n") 

608 

609 version_info = None 

610 try: 

611 info = tuple(int(v) for v in parts[0].split(".")) 

612 what = "__version_info__" 

613 names.append(what) 

614 version_info = f"{what}: tuple[int, ...] = {info!r}\n" 

615 except ValueError: 

616 pass 

617 

618 what = "__version__" 

619 outFile.write(f'{what}: str = "{version}"\n') 

620 names.append(what) 

621 

622 what = "__repo_version__" 

623 outFile.write(f'{what}: str = "{parts[0]}"\n') 

624 names.append(what) 

625 

626 what = "__fingerprint__" 

627 outFile.write(f'{what}: str = "{getFingerprint(versionString)}"\n') 

628 names.append(what) 

629 

630 if version_info is not None: 

631 outFile.write(version_info) 

632 

633 if len(parts) > 1: 

634 try: 

635 what = "__rebuild_version__" 

636 outFile.write(f"{what}: int = {int(parts[1])}\n") 

637 names.append(what) 

638 except ValueError: 

639 pass 

640 

641 what = "__dependency_versions__" 

642 names.append(what) 

643 outFile.write(f"{what}: dict[str, str | None] = {{") 

644 if env.dependencies.packages: 

645 outFile.write("\n") 

646 for name, mod in env.dependencies.packages.items(): 

647 if mod is None: 

648 outFile.write(f' "{name}": None,\n') 

649 elif hasattr(mod.config, "version"): 

650 outFile.write(f' "{name}": "{mod.config.version}",\n') 

651 else: 

652 outFile.write(f' "{name}": "unknown",\n') 

653 outFile.write("}\n") 

654 

655 # Write out an entry per line as there can be many names 

656 outFile.write("__all__ = (\n") 

657 for n in sorted(names): 

658 outFile.write(f' "{n}",\n') 

659 outFile.write(")\n") 

660 

661 if _calcMd5(target[0].abspath) != oldMd5: # only print if something's changed 

662 state.log.info(f'makeVersionModule(["{target[0]}"], [])') 

663 

664 result = self.Command(filename, [], self.Action(makeVersionModule, strfunction=lambda *args: None)) 

665 

666 self.AlwaysBuild(result) 

667 return result 

668 

669 

670@memberOf(SConsEnvironment) 

671def PackageInfo(self, pythonDir, versionString=None): 

672 versionString = _get_version_string(versionString) 

673 

674 if not os.path.exists(pythonDir): 

675 return [] 

676 

677 root_path = os.path.realpath(".") 

678 # Some information can come from the pyproject file. 

679 toml_metadata = {} 

680 if os.path.exists("pyproject.toml"): 

681 import tomllib 

682 

683 with open("pyproject.toml", "rb") as fd: 

684 toml_metadata = tomllib.load(fd) 

685 

686 toml_project = toml_metadata.get("project", {}) 

687 pythonPackageName = "" 

688 if "name" in toml_project: 

689 pythonPackageName = toml_project["name"] 

690 else: 

691 if os.path.exists(os.path.join(pythonDir, "lsst")): 

692 pythonPackageName = "lsst_" + state.env["packageName"] 

693 else: 

694 pythonPackageName = state.env["packageName"] 

695 pythonPackageName = pythonPackageName.replace("_", "-") 

696 

697 # Documenteer would like to know the project URLs so put them in 

698 # metadata if present. 

699 urls = [] 

700 if "urls" in toml_project: 

701 urls = [f"{label}, {url}" for label, url in toml_project["urls"].items()] 

702 

703 # The directory name is required to use "_" instead of "-" 

704 distDir = os.path.join(pythonDir, f"{pythonPackageName.replace('-', '_')}.dist-info") 

705 filename = os.path.join(distDir, "METADATA") 

706 oldMd5 = _calcMd5(filename) 

707 

708 def makePackageMetadata(target, source, env): 

709 # Create the metadata file. 

710 try: 

711 version = determineVersion(state.env, versionString) 

712 except RuntimeError: 

713 version = "unknown" 

714 

715 os.makedirs(os.path.dirname(target[0].abspath), exist_ok=True) 

716 with open(target[0].abspath, "w") as outFile: 

717 print("Metadata-Version: 1.0", file=outFile) 

718 print(f"Name: {pythonPackageName}", file=outFile) 

719 print(f"Version: {version}", file=outFile) 

720 for url_string in urls: 

721 print(f"Project-URL: {url_string}", file=outFile) 

722 

723 if _calcMd5(target[0].abspath) != oldMd5: # only print if something's changed 

724 state.log.info(f'PackageInfo(["{target[0]}"], [])') 

725 

726 results = [] 

727 results.append( 

728 self.Command(filename, [], self.Action(makePackageMetadata, strfunction=lambda *args: None)) 

729 ) 

730 

731 def makeInstallerFile(target, source, env): 

732 # Write the INSTALLER file. This is purely something to potentially 

733 # tell the end user the tooling that was used to install the files. 

734 with open(target[0].abspath, "w") as outFile: 

735 print("sconsUtils", file=outFile) 

736 

737 filename = os.path.join(distDir, "INSTALLER") 

738 results.append(self.Command(filename, [], self.Action(makeInstallerFile, strfunction=lambda *args: None))) 

739 

740 # Create the entry points file if defined in the pyproject.toml file. 

741 entryPoints = toml_project.get("entry-points", {}) 

742 if entryPoints: 

743 filename = os.path.join(distDir, "entry_points.txt") 

744 oldMd5 = _calcMd5(filename) 

745 

746 def makeEntryPoints(target, source, env): 

747 # Make the entry points file as necessary. 

748 if not entryPoints: 

749 return 

750 os.makedirs(os.path.dirname(target[0].abspath), exist_ok=True) 

751 

752 # Structure of entry points dict is something like: 

753 # "entry-points": { 

754 # "butler.cli": { 

755 # "pipe_base": "lsst.pipe.base.cli:get_cli_subcommands" 

756 # } 

757 # } 

758 # Which becomes a file with: 

759 # [butler.cli] 

760 # pipe_base = lsst.pipe.base.cli:get_cli_subcommands 

761 with open(target[0].abspath, "w") as fd: 

762 for entryGroup in entryPoints: 

763 print(f"[{entryGroup}]", file=fd) 

764 for entryPoint, entryValue in entryPoints[entryGroup].items(): 

765 print(f"{entryPoint} = {entryValue}", file=fd) 

766 

767 if _calcMd5(target[0].abspath) != oldMd5: # only print if something's changed 

768 state.log.info(f'PackageInfo(["{target[0]}"], [])') 

769 

770 if entryPoints: 

771 results.append( 

772 self.Command(filename, [], self.Action(makeEntryPoints, strfunction=lambda *args: None)) 

773 ) 

774 

775 def makeRecordFile(target, source, env): 

776 # Write the RECORD file containing every python file in the package. 

777 # Do not attempt to write hashes and file sizes since these can 

778 # change if the package is not really installed into an EUPS tree. 

779 all_files = set() 

780 for root, _, files in os.walk(pythonDir, followlinks=True): 

781 if not is_within_tree(root, root_path): 

782 # Soft link outside of tree. 

783 state.log.warn( 

784 f"Found directory in python tree ({root}), that lives outside of this product. " 

785 f"Not adding to Python package metadata." 

786 ) 

787 continue 

788 root = root.removeprefix(pythonDir) 

789 root = root.removeprefix("/") 

790 all_files.update({os.path.join(root, f) for f in files}) 

791 # Ensure that RECORD itself is included in the list. 

792 record_path = target[0].abspath 

793 record_path = record_path.removeprefix(os.path.abspath(pythonDir)).removeprefix("/") 

794 all_files.add(record_path) 

795 

796 # Also force the other metadata files we are writing into the 

797 # file in case the order cannot be guaranteed. 

798 meta_files = ["INSTALLER", "METADATA"] 

799 if entryPoints: 

800 meta_files.append("entry_points.txt") 

801 dist_path, _ = os.path.split(record_path) 

802 for f in meta_files: 

803 all_files.add(os.path.join(dist_path, f)) 

804 

805 # The RECORD file is nominally a CSV file. 

806 # Do not record file sizes or hashes. 

807 rows = [(f, "", "") for f in sorted(all_files)] 

808 with open(target[0].abspath, "w") as outFile: 

809 csv_writer = csv.writer(outFile) 

810 csv_writer.writerows(rows) 

811 

812 filename = os.path.join(distDir, "RECORD") 

813 # This action really needs to run after the previous pkginfo actions 

814 # so that INSTALLER, entry_points.txt and METADATA files are created. 

815 # Additionally, the RECORD target needs to run after "python" so that 

816 # shared libraries are created -- this is configured elsewhere. 

817 results.append(self.Command(filename, [], self.Action(makeRecordFile, strfunction=lambda *args: None))) 

818 

819 self.AlwaysBuild(results) 

820 return results 

821 

822 

823@memberOf(SConsEnvironment) 

824def PythonScripts(self): 

825 # Scripts are defined in the pyproject.toml file. 

826 toml_metadata = {} 

827 if os.path.exists("pyproject.toml"): 

828 import tomllib 

829 

830 with open("pyproject.toml", "rb") as fd: 

831 toml_metadata = tomllib.load(fd) 

832 

833 if not toml_metadata: 

834 return [] 

835 

836 scripts = {} 

837 if "project" in toml_metadata and "scripts" in toml_metadata["project"]: 

838 scripts = toml_metadata["project"]["scripts"] 

839 

840 def makePythonScript(target, source, env): 

841 cmdfile = target[0].abspath 

842 command = os.path.basename(cmdfile) 

843 if command not in scripts: 

844 return 

845 os.makedirs(os.path.dirname(cmdfile), exist_ok=True) 

846 package, func = scripts[command].split(":", maxsplit=1) 

847 python_exe = whichPython() 

848 if needShebangRewrite(): 

849 shebang = python_exe 

850 else: 

851 # Linux has very small shebang limit so always use env. 

852 shebang = f"/usr/bin/env {os.path.basename(python_exe)}" 

853 with open(cmdfile, "w") as fd: 

854 # Follow setuptools convention and always change the shebang. 

855 # Can not add noqa on Linux for long paths so do not add anywhere. 

856 print( 

857 rf"""#!{shebang} 

858import sys 

859from {package} import {func} 

860if __name__ == '__main__': 

861 sys.exit({func}()) 

862""", 

863 file=fd, 

864 ) 

865 

866 # Ensure the bin/ file is executable 

867 oldmode = os.stat(cmdfile)[ST_MODE] & 0o7777 

868 newmode = (oldmode | 0o555) & 0o7777 

869 if newmode != oldmode: 

870 state.log.info(f"Changing mode of {cmdfile} from {oldmode} to {newmode}") 

871 os.chmod(cmdfile, newmode) 

872 

873 results = [] 

874 for cmd in scripts: 

875 filename = f"bin/{cmd}" 

876 

877 # Do not do anything if there is an equivalent target in bin.src 

878 # that shebang would trigger. 

879 if os.path.exists(f"bin.src/{cmd}"): 

880 continue 

881 

882 results.append( 

883 self.Command(filename, [], self.Action(makePythonScript, strfunction=lambda *args: None)) 

884 ) 

885 

886 return results