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

441 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-26 11:16 -0800

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": 59 ↛ 61line 59 didn't jump to line 61 because the condition on line 59 was always true

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")): 98 ↛ 102line 98 didn't jump to line 102 because the condition on line 98 was always true

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: 169 ↛ 171line 169 didn't jump to line 171 because the condition on line 169 was always true

170 root = "." 

171 if fileRegex is None: 171 ↛ 173line 171 didn't jump to line 173 because the condition on line 171 was always true

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

173 if ignoreDirs is None: 173 ↛ 176line 173 didn't jump to line 176 because the condition on line 173 was always true

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

175 

176 if "TAGS" not in SCons.Script.COMMAND_LINE_TARGETS: 176 ↛ 179line 176 didn't jump to line 179 because the condition on line 176 was always true

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 files += [os.path.join(dirpath, f) for f in candidates] 

192 

193 return files 

194 

195 

196@memberOf(SConsEnvironment) 

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

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

199 

200 Parameters 

201 ---------- 

202 env : `SCons.Environment` 

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

204 root : `str`, optional 

205 Directory to begin search. 

206 fileRegex : `str` 

207 Regular expression to match files. 

208 ignoreDirs : `list` 

209 List of directories to ignore. 

210 

211 Notes 

212 ----- 

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

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

215 specified a "TAGS" target.""" 

216 

217 toTag = filesToTag(root, fileRegex, ignoreDirs) 

218 if toTag: 218 ↛ 219line 218 didn't jump to line 219 because the condition on line 218 was never true

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

220 

221 

222@memberOf(SConsEnvironment) 

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

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

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

226 

227 Parameters 

228 ---------- 

229 filePatterns : `str` 

230 Glob to match for files to be deleted. 

231 dirPatterns : `str`, optional 

232 Specification of directories to be removed. 

233 directory : `str`, optional 

234 Directory to clean. 

235 verbose : `bool`, optional 

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

237 

238 Notes 

239 ----- 

240 Can be run as: 

241 

242 .. code-block:: python 

243 

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

245 """ 

246 

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

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

249 # or directories. 

250 expr = "" 

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

252 if expr != "": 

253 expr += " -o " 

254 # Quote unquoted * and [ 

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

256 if filesOnly: 

257 expr += " -type f" 

258 else: 

259 expr += " -type d -prune" 

260 

261 command = "find " + directory 

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

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

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

265 if filesOnly: 

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

267 else: 

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

269 if verbose: 269 ↛ 270line 269 didn't jump to line 270 because the condition on line 269 was never true

270 command += " -print" 

271 return command 

272 

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

274 

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

276 # clean copy. 

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

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

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

280 

281 if dirPatterns != "": 281 ↛ 286line 281 didn't jump to line 286 because the condition on line 281 was always true

282 action += " ; " 

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

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

285 # "scons -c install" 

286 if "clean" in SCons.Script.COMMAND_LINE_TARGETS: 286 ↛ 287line 286 didn't jump to line 287 because the condition on line 286 was never true

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

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

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

290 

291 

292@memberOf(SConsEnvironment) 

293def ProductDir(env, product): 

294 """Return the product directory. 

295 

296 Parameters 

297 ---------- 

298 product : `str` 

299 The EUPS product name. 

300 

301 Returns 

302 ------- 

303 dir : `str` 

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

305 """ 

306 from . import eupsForScons 

307 

308 global _productDirs 

309 try: 

310 _productDirs # noqa: B018 

311 except Exception: 

312 try: 

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

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

315 _productDirs = None 

316 if _productDirs: 

317 pdir = _productDirs.get(product) 

318 else: 

319 pdir = eupsForScons.productDir(product) 

320 if pdir == "none": 

321 pdir = None 

322 return pdir 

323 

324 

325class DoxygenBuilder: 

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

327 

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

329 """ 

330 

331 def __init__(self, **kw): 

332 self.__dict__.update(kw) 

333 self.results = [] 

334 self.sources = [] 

335 self.targets = [] 

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

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

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

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

340 

341 def __call__(self, env, config): 

342 self.findSources() 

343 self.findTargets() 

344 inConfigNode = SCons.Script.File(config) 

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

346 outConfigNode = SCons.Script.File(outConfigName) 

347 if self.makeTag: 

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

349 self.makeTag = tagNode.abspath 

350 self.targets.append(tagNode) 

351 config = env.Command( 

352 target=outConfigNode, 

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

354 action=self.buildConfig, 

355 ) 

356 env.AlwaysBuild(config) 

357 doc = env.Command( 

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

359 ) 

360 for path in self.outputPaths: 

361 env.Clean(doc, path) 

362 env.Depends(doc, config) 

363 self.results.extend(config) 

364 self.results.extend(doc) 

365 return self.results 

366 

367 def findSources(self): 

368 for path in self.inputs: 

369 if os.path.isdir(path): 

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

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

372 dirs[:] = [] 

373 continue 

374 if not self.recursive: 

375 dirs[:] = [] 

376 else: 

377 toKeep = [] 

378 for relDir in dirs: 

379 if relDir.startswith("."): 

380 continue 

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

382 if absDir not in self.excludes: 

383 toKeep.append(relDir) 

384 dirs[:] = toKeep 

385 for relFile in files: 

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

387 if absFile in self.excludes: 

388 continue 

389 for pattern in self.patterns: 

390 if fnmatch.fnmatch(relFile, pattern): 

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

392 break 

393 elif os.path.isfile(path): 

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

395 

396 def findTargets(self): 

397 for item in self.outputs: 

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

399 

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

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

402 

403 # Need a routine to quote paths that contain spaces 

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

405 # a double quote for doxygen.conf 

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

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

408 # the final quoted entry. 

409 def _quote_path(path): 

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

411 return f'"{path}"' 

412 return path 

413 

414 def _quote_paths(pathList): 

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

416 

417 docPaths = [] 

418 incFiles = [] 

419 for incPath in self.includes: 

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

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

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

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

424 if docPaths: 

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

426 for incFile in incFiles: 

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

428 

429 for tagPath in self.useTags: 

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

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

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

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

434 if self.projectName is not None: 

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

436 if self.projectNumber is not None: 

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

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

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

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

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

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

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

444 try: 

445 allOutputs.remove(output.lower()) 

446 except Exception: 

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

448 state.log.finish() 

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

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

451 for output in allOutputs: 

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

453 if self.makeTag is not None: 

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

455 # 

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

457 # 

458 if len(source) > 0: 

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

460 outConfigFile.write(inConfigFile.read()) 

461 

462 outConfigFile.close() 

463 

464 

465@memberOf(SConsEnvironment) 

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

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

468 

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

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

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

472 GENERATE_XX options (and possibly others) to an existing 

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

474 the proto-config file. 

475 

476 Parameters 

477 ---------- 

478 config : `str` 

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

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

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

482 generated by this method. 

483 **kwargs 

484 Keyword arguments. 

485 

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

487 as the INPUT setting for Doxygen. This list 

488 will be turned into absolute paths by SCons, 

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

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

491 the builder will also examine those 

492 directories to find which source files the 

493 Doxygen output actually depends on. 

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

495 FILE_PATTERNS Doxygen setting. This will be 

496 passed directly to Doxygen, but it is also 

497 used to determine which source files should 

498 be considered dependencies. 

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

500 recursively (used for the Doxygen RECURSIVE 

501 setting). 

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

503 be used as output directories. 

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

505 to be ignored by Doxygen (the Doxygen 

506 EXCLUDE setting). Hidden directories are 

507 automatically ignored. 

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

509 include. These will automatically be 

510 separated into paths and files to fill in 

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

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

513 will be assumed that the html directory for 

514 each tag file is in an "html" subdirectory 

515 in the same directory as the tag file. 

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

517 to be generated. 

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

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

520 

521 Notes 

522 ----- 

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

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

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

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

527 """ 

528 

529 inputs = [ 

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

531 ] 

532 defaults = { 

533 "inputs": inputs, 

534 "recursive": True, 

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

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

537 "excludes": [], 

538 "includes": [], 

539 "useTags": [], 

540 "makeTag": None, 

541 "projectName": None, 

542 "projectNumber": None, 

543 } 

544 for k in defaults: 

545 if kwargs.get(k) is None: 

546 kwargs[k] = defaults[k] 

547 builder = DoxygenBuilder(**kwargs) 

548 return builder(self, config) 

549 

550 

551def _get_version_string(versionString): 

552 if versionString is None: 

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

554 if os.path.isdir(f".{n}"): 554 ↛ 555line 554 didn't jump to line 555 because the condition on line 554 was never true

555 versionString = n 

556 

557 if not versionString: 557 ↛ 559line 557 didn't jump to line 559 because the condition on line 557 was always true

558 versionString = "git" 

559 return versionString 

560 

561 

562def _calcMd5(filename): 

563 try: 

564 import hashlib 

565 

566 with open(filename, "rb") as f: 

567 md5 = hashlib.md5(f.read()).hexdigest() 

568 except OSError: 

569 md5 = None 

570 

571 return md5 

572 

573 

574@memberOf(SConsEnvironment) 

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

576 versionString = _get_version_string(versionString) 

577 oldMd5 = _calcMd5(filename) 

578 

579 def makeVersionModule(target, source, env): 

580 try: 

581 version = determineVersion(state.env, versionString) 

582 except RuntimeError: 

583 version = "unknown" 

584 parts = version.split("+") 

585 

586 names = [] 

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

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

589 

590 version_info = None 

591 try: 

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

593 what = "__version_info__" 

594 names.append(what) 

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

596 except ValueError: 

597 pass 

598 

599 what = "__version__" 

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

601 names.append(what) 

602 

603 what = "__repo_version__" 

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

605 names.append(what) 

606 

607 what = "__fingerprint__" 

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

609 names.append(what) 

610 

611 if version_info is not None: 611 ↛ 612line 611 didn't jump to line 612 because the condition on line 611 was never true

612 outFile.write(version_info) 

613 

614 if len(parts) > 1: 614 ↛ 615line 614 didn't jump to line 615 because the condition on line 614 was never true

615 try: 

616 what = "__rebuild_version__" 

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

618 names.append(what) 

619 except ValueError: 

620 pass 

621 

622 what = "__dependency_versions__" 

623 names.append(what) 

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

625 dependencyVersions = env.dependencies.versions 

626 if dependencyVersions: 

627 outFile.write("\n") 

628 for name, depVersion in dependencyVersions.items(): 

629 outFile.write(f" {name!r}: {depVersion!r},\n") 

630 outFile.write("}\n") 

631 

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

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

634 for n in sorted(names): 

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

636 outFile.write(")\n") 

637 

638 if _calcMd5(target[0].abspath) != oldMd5: # only print if something's changed 638 ↛ exitline 638 didn't return from function 'makeVersionModule' because the condition on line 638 was always true

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

640 

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

642 

643 self.AlwaysBuild(result) 

644 return result 

645 

646 

647@memberOf(SConsEnvironment) 

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

649 versionString = _get_version_string(versionString) 

650 

651 if not os.path.exists(pythonDir): 651 ↛ 652line 651 didn't jump to line 652 because the condition on line 651 was never true

652 return [] 

653 

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

655 # Some information can come from the pyproject file. 

656 toml_metadata = {} 

657 if os.path.exists("pyproject.toml"): 657 ↛ 658line 657 didn't jump to line 658 because the condition on line 657 was never true

658 import tomllib 

659 

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

661 toml_metadata = tomllib.load(fd) 

662 

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

664 pythonPackageName = "" 

665 if "name" in toml_project: 665 ↛ 666line 665 didn't jump to line 666 because the condition on line 665 was never true

666 pythonPackageName = toml_project["name"] 

667 else: 

668 if os.path.exists(os.path.join(pythonDir, "lsst")): 668 ↛ 671line 668 didn't jump to line 671 because the condition on line 668 was always true

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

670 else: 

671 pythonPackageName = state.env["packageName"] 

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

673 

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

675 # metadata if present. 

676 urls = [] 

677 if "urls" in toml_project: 677 ↛ 678line 677 didn't jump to line 678 because the condition on line 677 was never true

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

679 

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

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

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

683 oldMd5 = _calcMd5(filename) 

684 

685 def makePackageMetadata(target, source, env): 

686 # Create the metadata file. 

687 try: 

688 version = determineVersion(state.env, versionString) 

689 except RuntimeError: 

690 version = "unknown" 

691 

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

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

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

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

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

697 for url_string in urls: 

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

699 

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

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

702 

703 results = [] 

704 results.append( 

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

706 ) 

707 

708 def makeInstallerFile(target, source, env): 

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

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

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

712 print("sconsUtils", file=outFile) 

713 

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

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

716 

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

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

719 if entryPoints: 719 ↛ 720line 719 didn't jump to line 720 because the condition on line 719 was never true

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

721 oldMd5 = _calcMd5(filename) 

722 

723 def makeEntryPoints(target, source, env): 

724 # Make the entry points file as necessary. 

725 if not entryPoints: 

726 return 

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

728 

729 # Structure of entry points dict is something like: 

730 # "entry-points": { 

731 # "butler.cli": { 

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

733 # } 

734 # } 

735 # Which becomes a file with: 

736 # [butler.cli] 

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

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

739 for entryGroup in entryPoints: 

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

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

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

743 

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

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

746 

747 if entryPoints: 747 ↛ 748line 747 didn't jump to line 748 because the condition on line 747 was never true

748 results.append( 

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

750 ) 

751 

752 def makeRecordFile(target, source, env): 

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

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

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

756 all_files = set() 

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

758 if not is_within_tree(root, root_path): 

759 # Soft link outside of tree. 

760 state.log.warn( 

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

762 f"Not adding to Python package metadata." 

763 ) 

764 continue 

765 root = root.removeprefix(pythonDir) 

766 root = root.removeprefix("/") 

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

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

769 record_path = target[0].abspath 

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

771 all_files.add(record_path) 

772 

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

774 # file in case the order cannot be guaranteed. 

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

776 if entryPoints: 

777 meta_files.append("entry_points.txt") 

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

779 for f in meta_files: 

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

781 

782 # The RECORD file is nominally a CSV file. 

783 # Do not record file sizes or hashes. 

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

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

786 csv_writer = csv.writer(outFile) 

787 csv_writer.writerows(rows) 

788 

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

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

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

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

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

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

795 

796 self.AlwaysBuild(results) 

797 return results 

798 

799 

800@memberOf(SConsEnvironment) 

801def PythonScripts(self): 

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

803 toml_metadata = {} 

804 if os.path.exists("pyproject.toml"): 804 ↛ 805line 804 didn't jump to line 805 because the condition on line 804 was never true

805 import tomllib 

806 

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

808 toml_metadata = tomllib.load(fd) 

809 

810 if not toml_metadata: 810 ↛ 813line 810 didn't jump to line 813 because the condition on line 810 was always true

811 return [] 

812 

813 scripts = {} 

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

815 scripts = toml_metadata["project"]["scripts"] 

816 

817 def makePythonScript(target, source, env): 

818 cmdfile = target[0].abspath 

819 command = os.path.basename(cmdfile) 

820 if command not in scripts: 

821 return 

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

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

824 python_exe = whichPython() 

825 if needShebangRewrite(): 

826 shebang = python_exe 

827 else: 

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

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

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

831 # Follow setuptools convention and always change the shebang. 

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

833 print( 

834 rf"""#!{shebang} 

835import sys 

836from {package} import {func} 

837if __name__ == '__main__': 

838 sys.exit({func}()) 

839""", 

840 file=fd, 

841 ) 

842 

843 # Ensure the bin/ file is executable 

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

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

846 if newmode != oldmode: 

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

848 os.chmod(cmdfile, newmode) 

849 

850 results = [] 

851 for cmd in scripts: 

852 filename = f"bin/{cmd}" 

853 

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

855 # that shebang would trigger. 

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

857 continue 

858 

859 results.append( 

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

861 ) 

862 

863 return results