Coverage for python/lsst/sconsUtils/utils.py: 52%

115 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-26 19:18 +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"""Internal utilities for sconsUtils.""" 

23 

24from __future__ import annotations 

25 

26__all__ = ( 

27 "Log", 

28 "_has_OSX_SIP", 

29 "conda_compilers", 

30 "get_conda_prefix", 

31 "is_within_tree", 

32 "libraryLoaderEnvironment", 

33 "libraryPathPassThrough", 

34 "memberOf", 

35 "needShebangRewrite", 

36 "runExternal", 

37 "whichPython", 

38) 

39 

40import os 

41import platform 

42import subprocess 

43import sys 

44import warnings 

45 

46import SCons.Script 

47 

48 

49class Log: 

50 """A dead-simple logger for all messages. 

51 

52 Centralizes decisions about whether to throw exceptions or print 

53 user-friendly messages (the traceback variable) and whether to print 

54 extra debug info (the verbose variable). These are set from command-line 

55 options in `lsst.sconsUtils.state`. 

56 """ 

57 

58 def __init__(self): 

59 self.traceback = False 

60 self.verbose = True 

61 

62 def info(self, message): 

63 if self.verbose: 

64 print(message) 

65 

66 def warn(self, message): 

67 if self.traceback: 67 ↛ 68line 67 didn't jump to line 68 because the condition on line 67 was never true

68 warnings.warn(message, stacklevel=2) 

69 else: 

70 print(message, file=sys.stderr) 

71 

72 def fail(self, message): 

73 if self.traceback: 73 ↛ 74line 73 didn't jump to line 74 because the condition on line 73 was never true

74 raise RuntimeError(message) 

75 else: 

76 if message: 76 ↛ 78line 76 didn't jump to line 78 because the condition on line 76 was always true

77 print(message, file=sys.stderr) 

78 SCons.Script.Exit(1) 

79 

80 def flush(self): 

81 sys.stderr.flush() 

82 

83 

84def _has_OSX_SIP(): 

85 """Internal function indicating that the OS has System 

86 Integrity Protection. 

87 

88 Returns 

89 ------- 

90 hasSIP : `bool` 

91 `True` if SIP is present in this operating system version. 

92 """ 

93 hasSIP = False 

94 os_platform = SCons.Platform.platform_default() 

95 # SIP is enabled on OS X >=10.11 equivalent to darwin >= 15 

96 if os_platform == "darwin": 96 ↛ 97line 96 didn't jump to line 97 because the condition on line 96 was never true

97 release_str = platform.release() 

98 release_major = int(release_str.split(".")[0]) 

99 if release_major >= 15: 

100 hasSIP = True 

101 return hasSIP 

102 

103 

104def libraryPathPassThrough(): 

105 """Name of library path environment variable to be passed throughself. 

106 

107 Returns 

108 ------- 

109 library : `str` 

110 Name of library path environment variable. `None` if no pass through 

111 is required. 

112 """ 

113 if _has_OSX_SIP(): 113 ↛ 114line 113 didn't jump to line 114 because the condition on line 113 was never true

114 return "DYLD_LIBRARY_PATH" 

115 return None 

116 

117 

118# Cache variable for whichPython() function 

119_pythonPath = None 

120 

121 

122def whichPython(): 

123 """Path of Python executable to use. 

124 

125 Returns 

126 ------- 

127 pythonPath : `str` 

128 Full path to the Python executable as determined 

129 from the PATH. Does not return the full path of the Python running 

130 SCons. Caches result and assumes the PATH does not change between 

131 calls. Runs the "python" command and asks where it is rather than 

132 scanning the PATH. 

133 """ 

134 global _pythonPath 

135 if _pythonPath is None: 

136 _pythonPath = runExternal( 

137 ["python", "-c", "import sys; print(sys.executable)"], fatal=True, msg="Error getting python path" 

138 ) 

139 return _pythonPath 

140 

141 

142def needShebangRewrite(): 

143 """Is shebang rewriting required? 

144 

145 Returns 

146 ------- 

147 rewrite : `bool` 

148 Returns True if the shebang lines of executables should be rewritten. 

149 """ 

150 return _has_OSX_SIP() 

151 

152 

153def libraryLoaderEnvironment(): 

154 """Calculate library loader path environment string to be prepended to 

155 external commands. 

156 

157 Returns 

158 ------- 

159 loader : `str` 

160 If we have an macOS with System Integrity Protection enabled or similar 

161 we need to pass through both DYLD_LIBRARY_PATH and LSST_LIBRARY_PATH 

162 to the external command: DYLD_LIBRARY_PATH for Python code 

163 LSST_LIBRARY_PATH for shell scripts 

164 

165 If both are already defined then pass them each through. 

166 If only one is defined, then set both to the defined env variable 

167 If neither is defined then pass through nothing. 

168 """ 

169 libpathstr = "" 

170 lib_pass_through_var = libraryPathPassThrough() 

171 aux_pass_through_var = "LSST_LIBRARY_PATH" 

172 if lib_pass_through_var is not None: 172 ↛ 173line 172 didn't jump to line 173 because the condition on line 172 was never true

173 for varname in (lib_pass_through_var, aux_pass_through_var): 

174 if varname in os.environ: 

175 libpathstr += f'{varname}="{os.environ[varname]}" ' 

176 

177 if aux_pass_through_var in os.environ and lib_pass_through_var not in os.environ: 

178 libpathstr += f'{lib_pass_through_var}="{os.environ[aux_pass_through_var]}" ' 

179 

180 if lib_pass_through_var in os.environ and aux_pass_through_var not in os.environ: 

181 libpathstr += f'{aux_pass_through_var}="{os.environ[lib_pass_through_var]}" ' 

182 

183 return libpathstr 

184 

185 

186def runExternal(cmd, fatal=False, msg=None): 

187 """Safe wrapper for running external programs, reading stdout, and 

188 sanitizing error messages. 

189 

190 Parameters 

191 ---------- 

192 cmd : `str` or `list` or `tuple` 

193 Command to execute. Shell usage is disabled if a sequence is given. 

194 Shell is used if a single command string is given. 

195 fatal : `bool`, optional 

196 Control whether command failure is fatal or not. 

197 msg : `str` 

198 Message to report on command failure. 

199 

200 Returns 

201 ------- 

202 output : `str` 

203 Entire program output is returned, not just a single line. 

204 

205 Raises 

206 ------ 

207 RuntimeError 

208 If the command fails and ``fatal`` is `True`. 

209 """ 

210 if msg is None: 

211 try: 

212 msg = f"Error running {cmd.split()[0]}" 

213 except Exception: 

214 msg = "Error running external command" 

215 

216 # Run with shell unless given a list of options 

217 shell = True 

218 if isinstance(cmd, list | tuple): 

219 shell = False 

220 

221 try: 

222 retval = subprocess.run(cmd, shell=shell, capture_output=True, check=True) 

223 except subprocess.CalledProcessError as e: 

224 if fatal: 

225 raise RuntimeError(f"{msg}: {e.stderr.decode()}") from e 

226 else: 

227 from . import state # can't import at module scope due to circular dependency 

228 

229 state.log.warn(f"{msg}: {e.stderr}") 

230 return retval.stdout.decode().strip() 

231 

232 

233def memberOf(cls, name=None): 

234 """A Python decorator that injects functions into a class. 

235 

236 Parameters 

237 ---------- 

238 cls : `type` 

239 Class in which to inject this method. 

240 name : `str`, optional 

241 Name of the method. Will be determined from function name if not 

242 define. 

243 

244 Notes 

245 ----- 

246 For example: 

247 

248 .. code-block:: python 

249 

250 class test_class: 

251 pass 

252 

253 @memberOf(test_class): 

254 def test_method(self): 

255 print("test_method!") 

256 

257 ...will cause ``test_method`` to appear as as if it were defined within 

258 ``test_class``. 

259 

260 The function or method will still be added to the module scope as well, 

261 replacing any existing module-scope function with that name; this appears 

262 to be unavoidable. 

263 """ 

264 if isinstance(cls, type): 264 ↛ 267line 264 didn't jump to line 267 because the condition on line 264 was always true

265 classes = (cls,) 

266 else: 

267 classes = tuple(cls) 

268 kw = {"name": name} 

269 

270 def nested(member): 

271 if kw["name"] is None: 271 ↛ 273line 271 didn't jump to line 273 because the condition on line 271 was always true

272 kw["name"] = member.__name__ 

273 for scope in classes: 

274 setattr(scope, kw["name"], member) 

275 return member 

276 

277 return nested 

278 

279 

280def get_conda_prefix() -> str | None: 

281 """Returns a copy of the current conda prefix, if available.""" 

282 _conda_prefix = os.environ.get("CONDA_PREFIX") 

283 if os.environ.get("CONDA_BUILD", "0") == "1": 283 ↛ 287line 283 didn't jump to line 287 because the condition on line 283 was never true

284 # when running conda-build, the right prefix to use is PREFIX 

285 # however, this appears to be absent in some builds - but we 

286 # already set the fallback 

287 if "PREFIX" in os.environ: 

288 _conda_prefix = os.environ["PREFIX"] 

289 return _conda_prefix 

290 

291 

292def use_conda_compilers(): 

293 """Returns True if we should use conda compilers""" 

294 if "SCONSUTILS_AVOID_CONDA_COMPILERS" in os.environ: 294 ↛ 295line 294 didn't jump to line 295 because the condition on line 294 was never true

295 return False 

296 if "CONDA_BUILD_SYSROOT" in os.environ or "CONDA_PREFIX" in os.environ: 296 ↛ 298line 296 didn't jump to line 298 because the condition on line 296 was always true

297 return True 

298 if os.environ.get("CONDA_BUILD", "0") == "1": 

299 return True 

300 return False 

301 

302 

303def conda_compilers() -> tuple[str, str]: 

304 """Return the C and C++ compilers to use with conda compilers. 

305 

306 The compiler activation scripts of conda-forge ``compilers`` 

307 before version 2 export ``CC`` and ``CXX``. 

308 From version 2 the compilers are installed under their plain 

309 names with no activation script, so fall back to those. 

310 

311 Returns 

312 ------- 

313 cc : `str` 

314 C compiler. 

315 cxx : `str` 

316 C++ compiler. 

317 """ 

318 if sys.platform == "darwin": 

319 default_cc, default_cxx = "clang", "clang++" 

320 else: 

321 default_cc, default_cxx = "gcc", "g++" 

322 return os.environ.get("CC", default_cc), os.environ.get("CXX", default_cxx) 

323 

324 

325def is_within_tree(path: str, root: str) -> bool: 

326 """Check that a given path is within the root directory. 

327 

328 Parameters 

329 ---------- 

330 path : `str` 

331 Path to check. 

332 root : `str` 

333 Root of the directory structure. 

334 

335 Returns 

336 ------- 

337 `True` if the *resolved* path is inside the resolved root directory. 

338 """ 

339 root_real = os.path.realpath(root) 

340 path_real = os.path.realpath(path) 

341 try: 

342 return os.path.commonpath([path_real, root_real]) == root_real 

343 except ValueError: 

344 # Can happen on Windows if drives differ, etc. 

345 return False