Coverage for python/lsst/sconsUtils/installation.py: 28%

234 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-26 19:26 +0000

1# This file is part of sconsUtils. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This program is free software: you can redistribute it and/or modify 

10# it under the terms of the GNU General Public License as published by 

11# the Free Software Foundation, either version 3 of the License, or 

12# (at your option) any later version. 

13# 

14# This program is distributed in the hope that it will be useful, 

15# but WITHOUT ANY WARRANTY; without even the implied warranty of 

16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

17# GNU General Public License for more details. 

18# 

19# You should have received a copy of the GNU General Public License 

20# along with this program. If not, see <https://www.gnu.org/licenses/>. 

21 

22"""Builders and path setup for installation targets.""" 

23 

24__all__ = ( 

25 "DirectoryInstaller", 

26 "SConsUtilsEnvironment", 

27 "determineVersion", 

28 "getFingerprint", 

29 "makeProductPath", 

30 "setPrefix", 

31) 

32 

33import glob 

34import os.path 

35import re 

36import shutil 

37 

38import SCons.Script 

39from SCons.Script.SConscript import SConsEnvironment 

40 

41from . import state 

42from .utils import is_within_tree, memberOf 

43from .vcs import git, hg, svn 

44 

45 

46class SConsUtilsEnvironment(SConsEnvironment): 

47 """Dummy class to make visible the methods injected into the SCons 

48 parent environment. 

49 """ 

50 

51 

52def makeProductPath(env, pathFormat): 

53 """Return a path to use as the installation directory for a product. 

54 

55 Parameters 

56 ---------- 

57 env : `SCons.Environment` 

58 The SCons environment. 

59 pathFormat : `str` 

60 The format string to process. 

61 

62 Returns 

63 ------- 

64 formatted : `str` 

65 Formatted path string. 

66 """ 

67 pathFormat = re.sub(r"%(\w)", r"%(\1)s", pathFormat) 

68 

69 eupsPath = os.environ["PWD"] 

70 if "eupsPath" in env and env["eupsPath"]: 

71 eupsPath = env["eupsPath"] 

72 

73 return pathFormat % { 

74 "P": eupsPath, 

75 "f": env["eupsFlavor"], 

76 "p": env["eupsProduct"], 

77 "v": env["version"], 

78 "c": os.environ["PWD"], 

79 } 

80 

81 

82def determineVersion(env, versionString): 

83 """Set a version ID from env, or a version control ID string 

84 (``$name$`` or ``$HeadURL$``). 

85 

86 Parameters 

87 ---------- 

88 env : `SCons.Environment` 

89 The SCons environment. 

90 versionString : `str` 

91 The string containining version information to search if the 

92 version can not be found in the environment. 

93 

94 Returns 

95 ------- 

96 version : `str` 

97 The version. 

98 """ 

99 version = "unknown" 

100 if "version" in env: 

101 version = env["version"] 

102 elif not versionString: 102 ↛ 103line 102 didn't jump to line 103 because the condition on line 102 was never true

103 version = "unknown" 

104 elif re.search(r"^[$]Name:\s+", versionString): 104 ↛ 106line 104 didn't jump to line 106 because the condition on line 104 was never true

105 # CVS. Extract the tagname 

106 version = re.search(r"^[$]Name:\s+([^ $]*)", versionString).group(1) 

107 if version == "": 

108 version = "cvs" 

109 elif re.search(r"^[$]HeadURL:\s+", versionString): 109 ↛ 111line 109 didn't jump to line 111 because the condition on line 109 was never true

110 # SVN. Guess the tagname from the last part of the directory 

111 HeadURL = re.search(r"^[$]HeadURL:\s+(.*)", versionString).group(1) 

112 HeadURL = os.path.split(HeadURL)[0] 

113 version = svn.guessVersionName(HeadURL) 

114 elif versionString.lower() in ("hg", "mercurial"): 114 ↛ 116line 114 didn't jump to line 116 because the condition on line 114 was never true

115 # Mercurial (hg). 

116 version = hg.guessVersionName() 

117 elif versionString.lower() in ("git",): 117 ↛ 120line 117 didn't jump to line 120 because the condition on line 117 was always true

118 # git. 

119 version = git.guessVersionName() 

120 return version.replace("/", "_") 

121 

122 

123def getFingerprint(versionString): 

124 """Return a unique fingerprint for a version (e.g. an SHA1); 

125 

126 Parameters 

127 ---------- 

128 versionString : `str` 

129 A string that might contain version information. 

130 

131 Returns 

132 ------- 

133 fingerprint : `str` 

134 Unique fingerprint of this version. `None` if unavailable. 

135 """ 

136 if versionString.lower() in ("hg", "mercurial"): 136 ↛ 137line 136 didn't jump to line 137 because the condition on line 136 was never true

137 fingerprint = hg.guessFingerprint() 

138 elif versionString.lower() in ("git",): 138 ↛ 141line 138 didn't jump to line 141 because the condition on line 138 was always true

139 fingerprint = git.guessFingerprint() 

140 else: 

141 fingerprint = None 

142 

143 return fingerprint 

144 

145 

146def setPrefix(env, versionString, eupsProductPath=None): 

147 """Set a prefix based on the EUPS_PATH, the product name, and a 

148 version string from CVS or SVN. 

149 

150 Parameters 

151 ---------- 

152 env : `SCons.Environment` 

153 Environment to search. 

154 versionString : `str` 

155 String that might contain version information. 

156 eupsProductPath : `str`, optional 

157 Path to the EUPS product. 

158 

159 Returns 

160 ------- 

161 prefix : `str` 

162 Prefix to use. 

163 """ 

164 try: 

165 env["version"] = determineVersion(env, versionString) 

166 except RuntimeError as err: 

167 env["version"] = "unknown" 

168 if (env.installing or env.declaring) and not env["force"]: 

169 state.log.fail( 

170 f"{err}\nFound problem with version number; update or specify force=True to proceed" 

171 ) 

172 

173 if state.env["no_eups"]: 173 ↛ 174line 173 didn't jump to line 174 because the condition on line 173 was never true

174 if "prefix" in env and env["prefix"]: 

175 return env["prefix"] 

176 else: 

177 return "/usr/local" 

178 

179 if eupsProductPath: 179 ↛ 180line 179 didn't jump to line 180 because the condition on line 179 was never true

180 eupsPrefix = makeProductPath(env, eupsProductPath) 

181 elif "eupsPath" in env and env["eupsPath"]: 181 ↛ 184line 181 didn't jump to line 184 because the condition on line 181 was always true

182 eupsPrefix = env["eupsPath"] 

183 else: 

184 state.log.fail("Unable to determine eupsPrefix from eupsProductPath or eupsPath") 

185 flavor = env["eupsFlavor"] 

186 if not re.search("/" + flavor + "$", eupsPrefix): 186 ↛ 193line 186 didn't jump to line 193 because the condition on line 186 was always true

187 eupsPrefix = os.path.join(eupsPrefix, flavor) 

188 prodPath = env["eupsProduct"] 

189 if "eupsProductPath" in env and env["eupsProductPath"]: 189 ↛ 190line 189 didn't jump to line 190 because the condition on line 189 was never true

190 prodPath = env["eupsProductPath"] 

191 eupsPrefix = os.path.join(eupsPrefix, prodPath, env["version"]) 

192 else: 

193 eupsPrefix = None 

194 if "prefix" in env: 194 ↛ 195line 194 didn't jump to line 195 because the condition on line 194 was never true

195 if env["version"] != "unknown" and eupsPrefix and eupsPrefix != env["prefix"]: 

196 state.log.warn(f"Ignoring prefix {eupsPrefix} from EUPS_PATH") 

197 return makeProductPath(env, env["prefix"]) 

198 elif "eupsPath" in env and env["eupsPath"]: 198 ↛ 201line 198 didn't jump to line 201 because the condition on line 198 was always true

199 prefix = eupsPrefix 

200 else: 

201 prefix = "/usr/local" 

202 return prefix 

203 

204 

205@memberOf(SConsEnvironment) 

206def Declare(self, products=None): 

207 """Create current and declare targets for products. 

208 

209 Parameters 

210 ---------- 

211 products : `list` of `tuple`, optional 

212 A list of ``(product, version)`` tuples. If ``product`` is `None` 

213 it's taken to be ``self['eupsProduct']``; if version is `None` it's 

214 taken to be ``self['version']``. 

215 

216 Returns 

217 ------- 

218 acts : `list` 

219 Commands to execute. 

220 """ 

221 

222 if "undeclare" in SCons.Script.COMMAND_LINE_TARGETS and not self.GetOption("silent"): 222 ↛ 223line 222 didn't jump to line 223 because the condition on line 222 was never true

223 state.log.warn("'scons undeclare' is deprecated; please use 'scons declare -c' instead") 

224 

225 acts = [] 

226 if ( 226 ↛ 232line 226 didn't jump to line 232 because the condition on line 226 was never true

227 "declare" in SCons.Script.COMMAND_LINE_TARGETS 

228 or "undeclare" in SCons.Script.COMMAND_LINE_TARGETS 

229 or ("install" in SCons.Script.COMMAND_LINE_TARGETS and self.GetOption("clean")) 

230 or "current" in SCons.Script.COMMAND_LINE_TARGETS 

231 ): 

232 current = [] 

233 declare = [] 

234 undeclare = [] 

235 

236 if not products: 

237 products = [None] 

238 

239 for prod in products: 

240 if not prod or isinstance(prod, str): # i.e. no version 

241 product = prod 

242 

243 if "version" in self: 

244 version = self["version"] 

245 else: 

246 version = None 

247 else: 

248 product, version = prod 

249 

250 if not product: 

251 product = self["eupsProduct"] 

252 

253 if "EUPS_DIR" in os.environ: 

254 self["ENV"]["PATH"] += os.pathsep + f"{os.environ['EUPS_DIR']}/bin" 

255 self["ENV"]["EUPS_LOCK_PID"] = os.environ.get("EUPS_LOCK_PID", "-1") 

256 if "undeclare" in SCons.Script.COMMAND_LINE_TARGETS or self.GetOption("clean"): 

257 if version: 

258 command = f"eups undeclare --flavor {self['eupsFlavor']} {product} {version}" 

259 if ( 

260 "current" in SCons.Script.COMMAND_LINE_TARGETS 

261 and "declare" not in SCons.Script.COMMAND_LINE_TARGETS 

262 ): 

263 command += " --current" 

264 

265 if self.GetOption("clean"): 

266 self.Execute(command) 

267 else: 

268 undeclare += [command] 

269 else: 

270 state.log.warn("I don't know your version; not undeclaring to eups") 

271 else: 

272 command = "eups declare --force --flavor {} --root {}".format( 

273 self["eupsFlavor"], 

274 self["prefix"], 

275 ) 

276 

277 if "eupsPath" in self: 

278 command += f" -Z {self['eupsPath']}" 

279 

280 if version: 

281 command += f" {product} {version}" 

282 

283 current += [command + " --current"] 

284 

285 if self.GetOption("tag"): 

286 command += f" --tag={self.GetOption('tag')}" 

287 

288 declare += [command] 

289 

290 if current: 

291 acts += self.Command("current", "", action=current) 

292 if declare: 

293 if "current" in SCons.Script.COMMAND_LINE_TARGETS: 

294 acts += self.Command("declare", "", action="") # current will declare it for us 

295 else: 

296 acts += self.Command("declare", "", action=declare) 

297 if undeclare: 

298 acts += self.Command("undeclare", "", action=undeclare) 

299 

300 return acts 

301 

302 

303class DirectoryInstaller: 

304 """SCons Action callable to recursively install a directory. 

305 

306 This is separate from the InstallDir function to allow the 

307 directory-walking to happen when installation is actually invoked, 

308 rather than when the SConscripts are parsed. This still does not ensure 

309 that all necessary files are built as prerequisites to installing, but 

310 if one explicitly marks the install targets as dependent on the build 

311 targets, that should be enough. 

312 

313 Parameters 

314 ---------- 

315 ignoreRegex : `str` 

316 Regular expression to use to ignore files and directories. 

317 recursive : `bool` 

318 Control whether to recurse through directories. 

319 """ 

320 

321 def __init__(self, ignoreRegex, recursive): 

322 self.ignoreRegex = re.compile(ignoreRegex) 

323 self.recursive = recursive 

324 

325 def __call__(self, target, source, env): 

326 prefix = os.path.abspath(os.path.join(target[0].abspath, "..")) 

327 destpath = os.path.join(target[0].abspath) 

328 if not os.path.isdir(destpath): 

329 state.log.info(f"Creating directory {destpath}") 

330 os.makedirs(destpath) 

331 # Store the real path to the product root for comparison with sub 

332 # directories to check soft links. This is the parent directory of 

333 # the source target since this installer is called for the python, 

334 # doc, tests directories and not globally. 

335 source_root = os.path.realpath(os.path.join(source[0].path, "..")) 

336 for root, dirnames, filenames in os.walk(source[0].path, followlinks=True): 

337 if not self.recursive: 

338 dirnames[:] = [] 

339 else: 

340 dirnames[:] = [d for d in dirnames if d != ".svn"] # ignore .svn tree 

341 for dirname in dirnames: 

342 # Ensure that this directory isn't a symlink taking us outside 

343 # the package. 

344 source_path = os.path.join(root, dirname) 

345 if not is_within_tree(source_path, source_root): 

346 state.log.warn( 

347 f"Skipping install of directory {os.path.realpath(source_path)} which links outside " 

348 f"of product tree at {source_root}." 

349 ) 

350 continue 

351 

352 destpath = os.path.join(prefix, root, dirname) 

353 if not os.path.isdir(destpath): 

354 state.log.info(f"Creating directory {destpath}") 

355 os.makedirs(destpath) 

356 for filename in filenames: 

357 if self.ignoreRegex.search(filename): 

358 continue 

359 destpath = os.path.join(prefix, root) 

360 srcpath = os.path.join(root, filename) 

361 if not is_within_tree(srcpath, source_root): 

362 continue 

363 state.log.info(f"Copying {srcpath} to {destpath}") 

364 shutil.copy(srcpath, destpath) 

365 return 0 

366 

367 

368@memberOf(SConsEnvironment) 

369def InstallDir(self, prefix, dir, ignoreRegex=r"(~$|\.pyc$|\.os?$)", recursive=True): 

370 """Install the directory dir into prefix, ignoring certain files. 

371 

372 Parameters 

373 ---------- 

374 prefix : `str` 

375 Prefix to use for installation. 

376 dir : `str` 

377 Directory to install. 

378 ignoreRegex : `str` 

379 Regular expression to control whether a file is ignored. 

380 recursive : `bool` 

381 Recurse into directories? 

382 

383 Returns 

384 ------- 

385 result : `bool` 

386 Was installation successful? 

387 """ 

388 if not self.installing: 388 ↛ 390line 388 didn't jump to line 390 because the condition on line 388 was always true

389 return [] 

390 result = self.Command( 

391 target=os.path.join(self.Dir(prefix).abspath, dir), 

392 source=dir, 

393 action=DirectoryInstaller(ignoreRegex, recursive), 

394 ) 

395 self.AlwaysBuild(result) 

396 return result 

397 

398 

399@memberOf(SConsEnvironment) 

400def InstallEups(env, dest, files=(), presetup=""): 

401 """Install a ups directory, setting absolute versions as appropriate 

402 (unless you're installing from the trunk, in which case no versions 

403 are expanded). 

404 

405 Parameters 

406 ---------- 

407 env : `SCons.Environment` 

408 Environment to use. 

409 dest : `str` 

410 Destination directory. 

411 files : `collections.abc.Sequence`, optional 

412 List of files to install. Any build/table files present in ``./ups`` 

413 are automatically added to this list. 

414 presetup : `dict`, optional 

415 A dictionary with keys product names and values the version that 

416 should be installed into the table files, overriding eups 

417 expandtable's usual behaviour. 

418 

419 Returns 

420 ------- 

421 acts : `list` 

422 Commands to execute. 

423 

424 Notes 

425 ----- 

426 Sample usage: 

427 

428 .. code-block:: python 

429 

430 env.InstallEups( 

431 os.path.join(env["prefix"], "ups"), 

432 presetup={"sconsUtils": env["version"]}, 

433 ) 

434 """ 

435 acts = [] 

436 if not env.installing: 436 ↛ 439line 436 didn't jump to line 439 because the condition on line 436 was always true

437 return acts 

438 

439 if env.GetOption("clean"): 

440 state.log.warn("Removing" + dest) 

441 shutil.rmtree(dest, ignore_errors=True) 

442 else: 

443 presetupStr = [] 

444 for p in presetup: 

445 presetupStr += [f"--product {p}={presetup[p]}"] 

446 presetup = " ".join(presetupStr) 

447 

448 env = env.Clone(ENV=os.environ) 

449 # 

450 # Add any build/table/cfg files to the desired files 

451 # 

452 files = [str(f) for f in files] # in case the user used Glob not glob.glob 

453 files += ( 

454 glob.glob(os.path.join("ups", "*.build")) 

455 + glob.glob(os.path.join("ups", "*.table")) 

456 + glob.glob(os.path.join("ups", "*.cfg")) 

457 + glob.glob(os.path.join("ups", "eupspkg*")) 

458 ) 

459 files = list(set(files)) # remove duplicates 

460 

461 buildFiles = [f for f in files if re.search(r"\.build$", f)] 

462 build_obj = env.Install(dest, buildFiles) 

463 acts += build_obj 

464 

465 tableFiles = [f for f in files if re.search(r"\.table$", f)] 

466 table_obj = env.Install(dest, tableFiles) 

467 acts += table_obj 

468 

469 eupspkgFiles = [f for f in files if re.search(r"^eupspkg", f)] 

470 eupspkg_obj = env.Install(dest, eupspkgFiles) 

471 acts += eupspkg_obj 

472 

473 miscFiles = [f for f in files if not re.search(r"\.(build|table)$", f)] 

474 misc_obj = env.Install(dest, miscFiles) 

475 acts += misc_obj 

476 

477 try: 

478 import eups.lock 

479 

480 path = eups.Eups.setEupsPath() 

481 if path: 

482 locks = eups.lock.takeLocks("setup", path, eups.lock.LOCK_SH) # noqa F841 keep locks active 

483 env["ENV"]["EUPS_LOCK_PID"] = os.environ.get("EUPS_LOCK_PID", "-1") 

484 except ImportError: 

485 state.log.warn("Unable to import eups; not locking") 

486 

487 eupsTargets = [] 

488 

489 for i in build_obj: 

490 env.AlwaysBuild(i) 

491 

492 cmd = f"eups expandbuild -i --version {env['version']} " 

493 if "baseversion" in env: 

494 cmd += f" --repoversion {env['baseversion']} " 

495 cmd += str(i) 

496 eupsTargets.extend(env.AddPostAction(build_obj, env.Action(f"{cmd}", cmd))) 

497 

498 for i in table_obj: 

499 env.AlwaysBuild(i) 

500 

501 cmd = "eups expandtable -i -W '^(?!LOCAL:)' " # version doesn't start "LOCAL:" 

502 if presetup: 

503 cmd += presetup + " " 

504 cmd += str(i) 

505 

506 act = env.Command("table", "", env.Action(f"{cmd}", cmd)) 

507 eupsTargets.extend(act) 

508 acts += act 

509 env.Depends(act, i) 

510 

511 # By declaring that all the Eups operations create a file called 

512 # "eups" as a side-effect, even though they don't, SCons knows it 

513 # can't run them in parallel (it thinks of the side-effect file as 

514 # something like a log, and knows you shouldn't be appending to it 

515 # in parallel). When Eups locking is working, we may be able to 

516 # remove this. 

517 env.SideEffect("eups", eupsTargets) 

518 

519 return acts 

520 

521 

522@memberOf(SConsEnvironment) 

523def InstallLSST(self, prefix, dirs, ignoreRegex=None): 

524 """Install directories in the usual LSST way, handling "ups" specially. 

525 

526 Parameters 

527 ---------- 

528 prefix : `str` 

529 Installation prefix. 

530 dirs : `list` 

531 Directories to install. 

532 ignoreRegex : `str` 

533 Regular expression for files and directories to ignore. 

534 

535 Returns 

536 ------- 

537 results : `list` 

538 Commands to execute. 

539 """ 

540 results = [] 

541 for d in dirs: 

542 # if eups is disabled, the .build & .table files will not be "expanded" 

543 if d == "ups" and not state.env["no_eups"]: 

544 t = self.InstallEups(os.path.join(prefix, "ups")) 

545 else: 

546 t = self.InstallDir(prefix, d, ignoreRegex=ignoreRegex) 

547 self.Depends(t, d) 

548 results.extend(t) 

549 self.Alias("install", t) 

550 self.Clean("install", prefix) 

551 return results