Coverage for python/lsst/sconsUtils/pkgconfig.py: 99%

392 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"""pkg-config support for sconsUtils. 

23 

24This module knows how to construct the ``PKG_CONFIG_PATH`` search path 

25sconsUtils uses for every pkg-config invocation, and how to run a 

26pkg-config implementation, preferably ``pkgconf``, itself. It is 

27deliberately free of any SCons import so that it can be unit tested with 

28plain ``pytest`` and reused outside of an SCons build. 

29""" 

30 

31from __future__ import annotations 

32 

33__all__ = ( 

34 "GENERATED_SHIM_SUBDIR", 

35 "MODULE_PREFIX", 

36 "TEMPLATE_SUFFIX", 

37 "VERSION_TOKEN", 

38 "CyclicDependencyError", 

39 "PkgConfig", 

40 "PkgConfigDependencies", 

41 "PkgConfigError", 

42 "ResolvedDependencies", 

43 "SyntheticConfiguration", 

44 "apply_to_env", 

45 "build_search_path", 

46 "cfg_path", 

47 "check_single_format", 

48 "find_executable", 

49 "main", 

50 "module_name", 

51 "output_path", 

52 "remove_generated_pc", 

53 "resolve", 

54 "static_shim_dir", 

55 "synthesize_cfg_module", 

56 "template_path", 

57 "write_pc_from_template", 

58 "write_shims", 

59) 

60 

61import argparse 

62import dataclasses 

63import glob 

64import os 

65import re 

66import shlex 

67import shutil 

68import subprocess 

69import sys 

70import types 

71from collections.abc import Mapping, Sequence 

72from typing import Any 

73 

74#: Prefix applied to an EUPS product name to get its pkg-config module name. 

75MODULE_PREFIX = "lsst_" 

76 

77#: Suffix of a pkg-config template file, relative to a package's build root. 

78TEMPLATE_SUFFIX = ".pc.in" 

79 

80#: Token substituted with the real version string in a template file. 

81VERSION_TOKEN = "@VERSION@" 

82 

83#: Subdirectory, relative to a build root, holding configure-time shims. 

84GENERATED_SHIM_SUBDIR = os.path.join(".sconf_temp", "pkgconfig") 

85 

86#: Names of the pkg-config implementations looked for on ``PATH``, in order 

87#: of preference within a directory. conda-forge provides ``pkgconf``, and 

88#: not every build of it also installs a ``pkg-config`` link. 

89_EXECUTABLE_NAMES = ("pkgconf", "pkg-config") 

90 

91# Matches the same `<name>_DIR` / `<name>_DIR_EXTRA` environment variables 

92# that `state.py` scans when building the EUPS configuration search path. 

93_DIR_VAR_RE = re.compile(r"^(?P<name>\w+)_DIR(?P<extra>_EXTRA)?$") 

94 

95#: Compiler and linker options whose argument is a separate token, such as 

96#: ``-framework Accelerate``. This is the list SCons's ``ParseFlags`` keeps 

97#: together, plus the linker options pkg-config files are known to use. 

98_OPTIONS_WITH_ARGUMENT = frozenset( 

99 { 

100 "--param", 

101 "-D", 

102 "-U", 

103 "-Xlinker", 

104 "-Xpreprocessor", 

105 "-arch", 

106 "-framework", 

107 "-idirafter", 

108 "-imacros", 

109 "-include", 

110 "-iquote", 

111 "-isysroot", 

112 "-isystem", 

113 "-rpath", 

114 "-weak_framework", 

115 } 

116) 

117 

118 

119class PkgConfigError(RuntimeError): 

120 """Raised when invoking pkg-config fails or is misconfigured.""" 

121 

122 

123class CyclicDependencyError(PkgConfigError): 

124 """Raised when `PkgConfig.closure` finds a cycle in ``Requires``. 

125 

126 The exception message lists the modules on the cycle, in path order, 

127 e.g. ``"a -> b -> a"``. 

128 """ 

129 

130 

131def module_name(package_name: str) -> str: 

132 """Return the pkg-config module name for an EUPS package. 

133 

134 Parameters 

135 ---------- 

136 package_name : `str` 

137 The EUPS product name, e.g. ``"afw"``. 

138 

139 Returns 

140 ------- 

141 name : `str` 

142 The pkg-config module name, e.g. ``"lsst_afw"``. 

143 """ 

144 return MODULE_PREFIX + package_name 

145 

146 

147def template_path(build_root: str, package_name: str) -> str: 

148 """Return the path of a package's pkg-config template file. 

149 

150 Parameters 

151 ---------- 

152 build_root : `str` 

153 Absolute path to the root of the package currently being built. 

154 package_name : `str` 

155 The EUPS product name, e.g. ``"afw"``. 

156 

157 Returns 

158 ------- 

159 path : `str` 

160 The path of the template, e.g. ``"<build_root>/lsst_afw.pc.in"``. 

161 """ 

162 return os.path.join(build_root, module_name(package_name) + TEMPLATE_SUFFIX) 

163 

164 

165def cfg_path(build_root: str, package_name: str) -> str: 

166 """Return the path of a package's legacy ``ups/<name>.cfg`` file. 

167 

168 Parameters 

169 ---------- 

170 build_root : `str` 

171 Absolute path to the root of the package currently being built. 

172 package_name : `str` 

173 The EUPS product name, e.g. ``"afw"``. 

174 

175 Returns 

176 ------- 

177 path : `str` 

178 The path of the ``.cfg`` file, e.g. ``"<build_root>/ups/afw.cfg"``. 

179 """ 

180 return os.path.join(build_root, "ups", package_name + ".cfg") 

181 

182 

183def output_path(build_root: str, package_name: str) -> str: 

184 """Return the path of a package's generated ``.pc`` file. 

185 

186 Parameters 

187 ---------- 

188 build_root : `str` 

189 Absolute path to the root of the package currently being built. 

190 package_name : `str` 

191 The EUPS product name, e.g. ``"afw"``. 

192 

193 Returns 

194 ------- 

195 path : `str` 

196 The path of the generated file, e.g. 

197 ``"<build_root>/lib/pkgconfig/lsst_afw.pc"``. 

198 """ 

199 return os.path.join(build_root, "lib", "pkgconfig", module_name(package_name) + ".pc") 

200 

201 

202def check_single_format(build_root: str, package_name: str) -> None: 

203 """Check that a package uses at most one dependency-description format. 

204 

205 Parameters 

206 ---------- 

207 build_root : `str` 

208 Absolute path to the root of the package currently being built. 

209 package_name : `str` 

210 The EUPS product name, e.g. ``"afw"``. 

211 

212 Raises 

213 ------ 

214 PkgConfigError 

215 Raised if both `template_path` and `cfg_path` exist for 

216 `package_name`, naming both paths. Nothing is raised if zero or 

217 one of the two files exists. 

218 """ 

219 template = template_path(build_root, package_name) 

220 cfg = cfg_path(build_root, package_name) 

221 if os.path.exists(template) and os.path.exists(cfg): 

222 raise PkgConfigError( 

223 f"Package {package_name!r} has both a pkg-config template ({template}) and a " 

224 f"legacy configuration file ({cfg}); a package must use only one of the two formats." 

225 ) 

226 

227 

228def write_pc_from_template(template: str, output: str, version: str) -> bool: 

229 """Write a ``.pc`` file from a template, substituting the version. 

230 

231 Parameters 

232 ---------- 

233 template : `str` 

234 Path of the template file to read. Every occurrence of 

235 `VERSION_TOKEN` is replaced with `version`; no other substitution 

236 is performed. 

237 output : `str` 

238 Path of the ``.pc`` file to write. Its parent directory is 

239 created if it does not already exist. 

240 version : `str` 

241 The version string to substitute for `VERSION_TOKEN`. 

242 

243 Returns 

244 ------- 

245 wrote : `bool` 

246 `True` if `output` was written or overwritten, `False` if its 

247 content already matched the substituted template and it was left 

248 untouched. 

249 

250 Raises 

251 ------ 

252 PkgConfigError 

253 Raised if `VERSION_TOKEN` does not appear anywhere in `template`, 

254 naming `template`. 

255 """ 

256 with open(template) as f: 

257 contents = f.read() 

258 if VERSION_TOKEN not in contents: 

259 raise PkgConfigError(f"Template {template} does not contain the {VERSION_TOKEN} token") 

260 new_contents = contents.replace(VERSION_TOKEN, version) 

261 

262 if os.path.exists(output): 

263 with open(output) as f: 

264 existing_contents = f.read() 

265 if existing_contents == new_contents: 

266 return False 

267 

268 os.makedirs(os.path.dirname(output), exist_ok=True) 

269 with open(output, "w") as f: 

270 f.write(new_contents) 

271 return True 

272 

273 

274def remove_generated_pc(build_root: str, package_name: str) -> bool: 

275 """Remove a package's generated ``.pc`` file, as ``scons --clean`` does. 

276 

277 Parameters 

278 ---------- 

279 build_root : `str` 

280 Absolute path to the root of the package currently being built. 

281 package_name : `str` 

282 The EUPS product name, e.g. ``"afw"``. 

283 

284 Returns 

285 ------- 

286 removed : `bool` 

287 `True` if `output_path` existed and was removed, `False` if there 

288 was nothing to remove. When the file is removed and its 

289 ``lib/pkgconfig`` directory is left empty, that directory is 

290 removed too; ``lib/`` itself is never touched. 

291 

292 Notes 

293 ----- 

294 Only this one file is removed, rather than every ``*.pc`` file in the 

295 tree, so that ``.pc`` files tracked in a package's repository (such as 

296 sconsUtils's own static shims) survive a clean. 

297 """ 

298 output = output_path(build_root, package_name) 

299 if not os.path.exists(output): 

300 return False 

301 os.remove(output) 

302 directory = os.path.dirname(output) 

303 if not os.listdir(directory): 

304 os.rmdir(directory) 

305 return True 

306 

307 

308def _dedup_preserve_order(entries: list[str]) -> list[str]: 

309 """Remove duplicate entries, keeping the first occurrence of each.""" 

310 seen: set[str] = set() 

311 result: list[str] = [] 

312 for entry in entries: 

313 if entry in seen: 

314 continue 

315 seen.add(entry) 

316 result.append(entry) 

317 return result 

318 

319 

320def build_search_path(build_root: str, environ: Mapping[str, str]) -> list[str]: 

321 """Build the ``PKG_CONFIG_PATH`` search path sconsUtils uses. 

322 

323 Parameters 

324 ---------- 

325 build_root : `str` 

326 Absolute path to the root of the package currently being built. 

327 environ : `~collections.abc.Mapping` [`str`, `str`] 

328 Environment variables to scan, in the style of `os.environ`. 

329 

330 Returns 

331 ------- 

332 search_path : `list` [`str`] 

333 Directories to search, in priority order, with duplicates removed 

334 (the first occurrence of a given directory wins). The order is: 

335 

336 1. ``<build_root>/lib/pkgconfig``, so the package being built finds 

337 its own freshly written file. 

338 2. ``<value>/lib/pkgconfig`` for every environment variable matching 

339 ``^\\w+_DIR$`` whose directory exists, in the same way ``cfgPath`` 

340 is built today in `state.py`. 

341 3. `static_shim_dir`, the static shims, when it exists. 

342 4. ``<build_root>/.sconf_temp/pkgconfig``, the configure-time 

343 generated shims. 

344 5. Whatever ``PKG_CONFIG_PATH`` the user already had. 

345 """ 

346 search_path: list[str] = [os.path.join(build_root, "lib", "pkgconfig")] 

347 

348 for key, value in environ.items(): 

349 match = _DIR_VAR_RE.match(key) 

350 if not match or match.group("extra"): 

351 continue 

352 candidate = os.path.join(value, "lib", "pkgconfig") 

353 if os.path.isdir(candidate): 

354 search_path.append(candidate) 

355 

356 static_dir = static_shim_dir() 

357 if static_dir is not None: 

358 search_path.append(static_dir) 

359 

360 search_path.append(os.path.join(build_root, GENERATED_SHIM_SUBDIR)) 

361 

362 existing = environ.get("PKG_CONFIG_PATH") 

363 if existing: 

364 search_path.extend(existing.split(os.pathsep)) 

365 

366 return _dedup_preserve_order(search_path) 

367 

368 

369def find_executable(environ: Mapping[str, str] | None = None) -> str: 

370 """Find the pkg-config implementation to run. 

371 

372 Parameters 

373 ---------- 

374 environ : `~collections.abc.Mapping` [`str`, `str`], optional 

375 Environment variables to consult, in the style of `os.environ`, 

376 which is the default. 

377 

378 Returns 

379 ------- 

380 executable : `str` 

381 Path of the executable. This is ``$PKG_CONFIG`` if that is set, 

382 as for other build tools. Otherwise it is the first ``pkgconf`` or 

383 ``pkg-config`` on ``PATH``, preferring ``pkgconf`` within a 

384 directory, so that an earlier directory always wins. 

385 

386 Raises 

387 ------ 

388 PkgConfigError 

389 Raised if ``$PKG_CONFIG`` is set but cannot be found, or if it is 

390 unset and neither name is on ``PATH``. 

391 """ 

392 if environ is None: 

393 environ = os.environ 

394 path = environ.get("PATH", os.defpath) 

395 requested = environ.get("PKG_CONFIG") 

396 if requested: 

397 executable = shutil.which(requested, path=path) 

398 if executable is None: 

399 raise PkgConfigError(f"PKG_CONFIG={requested} was not found") 

400 return executable 

401 for directory in path.split(os.pathsep): 

402 for name in _EXECUTABLE_NAMES: 

403 executable = shutil.which(name, path=directory) 

404 if executable is not None: 

405 return executable 

406 raise PkgConfigError(f"neither {' nor '.join(_EXECUTABLE_NAMES)} was found on PATH") 

407 

408 

409class PkgConfig: 

410 """A runner for a pkg-config implementation such as ``pkgconf``. 

411 

412 Parameters 

413 ---------- 

414 search_path : `~collections.abc.Sequence` [`str`] 

415 Directories to place on ``PKG_CONFIG_PATH``, in priority order. 

416 conda_prefix : `str` or `None` 

417 The active conda prefix, as returned by 

418 `lsst.sconsUtils.utils.get_conda_prefix`. Every invocation passes 

419 this as ``--define-variable=conda_prefix=<conda_prefix>``. Builds 

420 without a conda environment are unsupported, so `None` is rejected. 

421 executable : `str`, optional 

422 Path to the executable. Defaults to the one `find_executable` 

423 returns. 

424 

425 Raises 

426 ------ 

427 PkgConfigError 

428 Raised if `executable` is not given and `find_executable` fails, or 

429 if `conda_prefix` is `None`. 

430 

431 Notes 

432 ----- 

433 The result of every invocation is cached for the lifetime of the 

434 instance, because resolving several packages with overlapping closures 

435 repeats the same per-module queries. An instance must therefore not be 

436 reused once a ``.pc`` file it may already have read has changed. 

437 """ 

438 

439 def __init__( 

440 self, 

441 search_path: Sequence[str], 

442 conda_prefix: str | None, 

443 executable: str | None = None, 

444 ) -> None: 

445 if conda_prefix is None: 

446 raise PkgConfigError("sconsUtils requires a conda environment; CONDA_PREFIX is not set") 

447 if executable is None: 

448 executable = find_executable() 

449 self.executable: str = executable 

450 self._search_path = list(search_path) 

451 self._conda_prefix = conda_prefix 

452 # pkg-config's own default search path; queried on first use by 

453 # _default_search_path(). 

454 self._default_path: list[str] | None = None 

455 # Completed invocations, keyed by their arguments; see _invoke(). 

456 self._results: dict[tuple[str, ...], subprocess.CompletedProcess[str]] = {} 

457 

458 def _invoke(self, *args: str) -> subprocess.CompletedProcess[str]: 

459 """Run the executable with `args` and return the completed process. 

460 

461 The ``--define-variable=conda_prefix=...`` argument is always 

462 prepended. This never raises on a non-zero exit status; callers 

463 decide how to interpret the result. The executable is run only the 

464 first time a given `args` is seen; later calls return the cached 

465 result. 

466 """ 

467 if args in self._results: 

468 return self._results[args] 

469 env = dict(os.environ) 

470 env["PKG_CONFIG_PATH"] = os.pathsep.join(self._search_path) 

471 env["PKG_CONFIG_ALLOW_SYSTEM_CFLAGS"] = "1" 

472 env["PKG_CONFIG_ALLOW_SYSTEM_LIBS"] = "1" 

473 command = [ 

474 self.executable, 

475 f"--define-variable=conda_prefix={self._conda_prefix}", 

476 *args, 

477 ] 

478 result = subprocess.run( 

479 command, 

480 env=env, 

481 capture_output=True, 

482 text=True, 

483 ) 

484 self._results[args] = result 

485 return result 

486 

487 def run(self, *args: str) -> str: 

488 """Run the executable with the given arguments and return its output. 

489 

490 Parameters 

491 ---------- 

492 *args : `str` 

493 Arguments to pass to the executable, after the 

494 ``--define-variable=conda_prefix=...`` argument that is always 

495 prepended. 

496 

497 Returns 

498 ------- 

499 stdout : `str` 

500 The standard output of the command, as text. 

501 

502 Raises 

503 ------ 

504 PkgConfigError 

505 Raised if the executable exits with a non-zero status. The 

506 exception message includes the command's standard error. 

507 """ 

508 result = self._invoke(*args) 

509 if result.returncode != 0: 

510 raise PkgConfigError( 

511 f"{os.path.basename(self.executable)} {' '.join(args)} failed with exit status " 

512 f"{result.returncode}: {result.stderr.strip()}" 

513 ) 

514 return result.stdout 

515 

516 def exists(self, module: str) -> bool: 

517 """Return whether `module` can be found on the search path. 

518 

519 Parameters 

520 ---------- 

521 module : `str` 

522 The pkg-config module name to look up. 

523 

524 Returns 

525 ------- 

526 exists : `bool` 

527 `True` if the module exists, `False` otherwise. This never 

528 raises, even if `module` cannot be found. 

529 """ 

530 return self._invoke("--exists", module).returncode == 0 

531 

532 def missing_reason(self, module: str) -> str | None: 

533 """Return why `module` cannot be used, or `None` if it exists. 

534 

535 Parameters 

536 ---------- 

537 module : `str` 

538 The pkg-config module name to look up. 

539 

540 Returns 

541 ------- 

542 reason : `str` or `None` 

543 `None` if `exists` would be `True`, otherwise pkg-config's own 

544 explanation, which names the module that is actually missing: 

545 `module` itself, or one of the modules in its ``Requires``. 

546 """ 

547 result = self._invoke("--print-errors", "--exists", module) 

548 if result.returncode == 0: 

549 return None 

550 return result.stderr.strip() or f"{module} was not found" 

551 

552 def present(self, module: str) -> bool: 

553 """Return whether a ``.pc`` file for `module` is on the search path. 

554 

555 Unlike `exists`, this is `True` even if the ``Requires`` of 

556 `module` cannot be satisfied, so that a broken module can be told 

557 apart from a missing one. 

558 

559 Parameters 

560 ---------- 

561 module : `str` 

562 The pkg-config module name to look up. 

563 

564 Returns 

565 ------- 

566 present : `bool` 

567 `True` if a ``<module>.pc`` file exists in a directory of the 

568 search path or of pkg-config's own default search path, `False` 

569 otherwise. This never raises. 

570 

571 Notes 

572 ----- 

573 This looks for the file itself rather than asking pkg-config, 

574 because no pkg-config query reliably succeeds for a module whose 

575 ``Requires`` are missing: pkg-config 0.29.2 still answers 

576 ``--modversion`` for one, but pkgconf does not. 

577 """ 

578 filename = module + ".pc" 

579 if any(os.path.isfile(os.path.join(d, filename)) for d in self._search_path): 

580 return True 

581 return any(os.path.isfile(os.path.join(d, filename)) for d in self._default_search_path()) 

582 

583 def _default_search_path(self) -> list[str]: 

584 """Return the directories pkg-config searches after 

585 ``PKG_CONFIG_PATH``. 

586 

587 This is ``PKG_CONFIG_LIBDIR`` if that is set, since it replaces the 

588 compiled-in default, and otherwise the default as reported by 

589 ``--variable=pc_path pkg-config``, which both pkgconf and 

590 pkg-config support. The result is computed once and cached; it is 

591 empty if the query fails. 

592 """ 

593 if self._default_path is None: 

594 value = os.environ.get("PKG_CONFIG_LIBDIR") 

595 if value is None: 

596 result = self._invoke("--variable=pc_path", "pkg-config") 

597 value = result.stdout.strip() if result.returncode == 0 else "" 

598 self._default_path = [d for d in value.split(os.pathsep) if d] 

599 return self._default_path 

600 

601 def modversion(self, module: str) -> str: 

602 """Return the version of `module`. 

603 

604 Parameters 

605 ---------- 

606 module : `str` 

607 The pkg-config module name to look up. 

608 

609 Returns 

610 ------- 

611 version : `str` 

612 The module's version, as reported by ``pkg-config 

613 --modversion``. 

614 """ 

615 return self.run("--modversion", module).strip() 

616 

617 def variable(self, module: str, name: str) -> str | None: 

618 """Return the value of a pkg-config variable. 

619 

620 Parameters 

621 ---------- 

622 module : `str` 

623 The pkg-config module name to look up. 

624 name : `str` 

625 The name of the variable. 

626 

627 Returns 

628 ------- 

629 value : `str` or `None` 

630 The variable's value, or `None` if it is unset or empty. 

631 """ 

632 value = self.run(f"--variable={name}", module).strip() 

633 return value or None 

634 

635 def requires(self, module: str) -> list[str]: 

636 """Return the modules `module` directly requires. 

637 

638 Parameters 

639 ---------- 

640 module : `str` 

641 The pkg-config module name to look up. 

642 

643 Returns 

644 ------- 

645 requires : `list` [`str`] 

646 The module names listed in `module`'s ``Requires`` field, in 

647 order, with any version constraint (e.g. ``"foo >= 1.2"``) 

648 stripped down to just the module name. 

649 """ 

650 requires = [] 

651 for line in self.run("--print-requires", module).splitlines(): 

652 line = line.strip() 

653 if not line: 

654 continue 

655 requires.append(line.split()[0]) 

656 return requires 

657 

658 def closure(self, modules: Sequence[str]) -> list[str]: 

659 """Return the transitive closure of `modules` under ``Requires``. 

660 

661 Parameters 

662 ---------- 

663 modules : `~collections.abc.Sequence` [`str`] 

664 The pkg-config module names to start from. 

665 

666 Returns 

667 ------- 

668 closure : `list` [`str`] 

669 Every module reachable from `modules`, depth-first, in 

670 first-visit order, with each module appearing only once. 

671 

672 Raises 

673 ------ 

674 CyclicDependencyError 

675 Raised if a cycle is found in the ``Requires`` graph. The 

676 exception message lists the modules on the cycle, in path 

677 order (e.g. ``"a -> b -> a"``). 

678 PkgConfigError 

679 Raised if a module cannot be queried. pkgconf 2 refuses every 

680 query about a module on a cycle, so with it a cycle is 

681 reported this way instead. 

682 """ 

683 result: list[str] = [] 

684 visited: set[str] = set() 

685 

686 def visit(module: str, path: list[str]) -> None: 

687 if module in path: 

688 cycle = path[path.index(module) :] + [module] 

689 raise CyclicDependencyError(" -> ".join(cycle)) 

690 if module in visited: 

691 return 

692 visited.add(module) 

693 result.append(module) 

694 for dependency in self.requires(module): 

695 visit(dependency, path + [module]) 

696 

697 for module in modules: 

698 visit(module, []) 

699 return result 

700 

701 def cflags_only_I(self, modules: Sequence[str]) -> list[str]: 

702 """Return the ``-I`` include directories for `modules`. 

703 

704 Parameters 

705 ---------- 

706 modules : `~collections.abc.Sequence` [`str`] 

707 The pkg-config module names to query. 

708 

709 Returns 

710 ------- 

711 directories : `list` [`str`] 

712 Include directories, in pkg-config's order, with the ``-I`` 

713 prefix stripped. 

714 """ 

715 return self._split_flags("--cflags-only-I", modules, "-I") 

716 

717 def cflags_only_other(self, modules: Sequence[str]) -> list[str]: 

718 """Return the non-``-I`` compiler flags for `modules`. 

719 

720 Parameters 

721 ---------- 

722 modules : `~collections.abc.Sequence` [`str`] 

723 The pkg-config module names to query. 

724 

725 Returns 

726 ------- 

727 flags : `list` [`str`] 

728 Compiler flags other than ``-I``, in pkg-config's order. 

729 """ 

730 return self._split_flags("--cflags-only-other", modules) 

731 

732 def libs_only_L(self, modules: Sequence[str]) -> list[str]: 

733 """Return the ``-L`` library directories for `modules`. 

734 

735 Parameters 

736 ---------- 

737 modules : `~collections.abc.Sequence` [`str`] 

738 The pkg-config module names to query. 

739 

740 Returns 

741 ------- 

742 directories : `list` [`str`] 

743 Library search directories, in pkg-config's order, with the 

744 ``-L`` prefix stripped. 

745 """ 

746 return self._split_flags("--libs-only-L", modules, "-L") 

747 

748 def libs_only_l(self, modules: Sequence[str]) -> list[str]: 

749 """Return the ``-l`` library names for `modules`. 

750 

751 Parameters 

752 ---------- 

753 modules : `~collections.abc.Sequence` [`str`] 

754 The pkg-config module names to query. 

755 

756 Returns 

757 ------- 

758 names : `list` [`str`] 

759 Library names, in pkg-config's order, with the ``-l`` prefix 

760 stripped. 

761 """ 

762 return self._split_flags("--libs-only-l", modules, "-l") 

763 

764 def libs_only_other(self, modules: Sequence[str]) -> list[str]: 

765 """Return the non-``-L``/``-l`` linker flags for `modules`. 

766 

767 Parameters 

768 ---------- 

769 modules : `~collections.abc.Sequence` [`str`] 

770 The pkg-config module names to query. 

771 

772 Returns 

773 ------- 

774 flags : `list` [`str`] 

775 Linker flags other than ``-L`` and ``-l``, in pkg-config's 

776 order. 

777 """ 

778 return self._split_flags("--libs-only-other", modules) 

779 

780 def _split_flags(self, query: str, modules: Sequence[str], prefix: str | None = None) -> list[str]: 

781 """Run `query` over `modules` and split the result into tokens. 

782 

783 Parameters 

784 ---------- 

785 query : `str` 

786 The pkg-config flag query to run, e.g. ``"--cflags-only-I"``. 

787 modules : `~collections.abc.Sequence` [`str`] 

788 The pkg-config module names to query. If empty, pkg-config is 

789 not invoked and an empty list is returned. 

790 prefix : `str` or `None`, optional 

791 A two-character prefix (e.g. ``"-I"``) to strip from each 

792 token. If `None`, tokens are returned unchanged. 

793 

794 Returns 

795 ------- 

796 tokens : `list` [`str`] 

797 The split, optionally unprefixed, tokens. Tokens that are 

798 empty once unprefixed, such as a bare ``-I``, are dropped. 

799 """ 

800 if not modules: 

801 return [] 

802 tokens = shlex.split(self.run(query, *modules)) 

803 if prefix is not None: 

804 tokens = [token[len(prefix) :] for token in tokens] 

805 return [token for token in tokens if token] 

806 

807 

808@dataclasses.dataclass 

809class ResolvedDependencies: 

810 """The result of resolving a package's dependencies through pkg-config. 

811 

812 This is a plain description of what the build needs; it holds no SCons 

813 objects, so it can be used both to populate an SCons environment and to 

814 synthesize a legacy configuration. 

815 """ 

816 

817 modules: list[str] 

818 """Transitive closure of the module set, primary module first.""" 

819 

820 cpppath: list[str] 

821 """Include directories belonging to ``lsst_*`` modules in the closure, 

822 normalized with `os.path.realpath`; these are dependency-scanned.""" 

823 

824 xcpppath: list[str] 

825 """All other include directories, normalized with `os.path.realpath`; 

826 these are treated as system headers.""" 

827 

828 ccflags: list[str | tuple[str, str]] 

829 """Compiler flags other than ``-I``. An option whose argument is a 

830 separate token, such as ``-isystem /a``, is a tuple of the two, so that 

831 SCons de-duplicates it as one flag.""" 

832 

833 libpath: list[str] 

834 """Library search directories, with the ``-L`` prefix stripped.""" 

835 

836 linkflags: list[str | tuple[str, str]] 

837 """Linker flags other than ``-L`` and ``-l``, with an option and a 

838 separate argument, such as ``-framework Accelerate``, paired into a 

839 tuple as in `ccflags`.""" 

840 

841 libs: dict[str, list[str]] 

842 """Library names without the ``-l`` prefix, keyed by category 

843 (``"main"``, ``"python"``, ``"test"``).""" 

844 

845 doxygen: dict[str, list[str]] 

846 """Doxygen tag files (``"tags"``) and include files (``"includes"``).""" 

847 

848 versions: dict[str, str] 

849 """Version of every module in the closure, keyed by module name with a 

850 leading `MODULE_PREFIX` stripped.""" 

851 

852 

853def _group_flags(tokens: Sequence[str]) -> list[str | tuple[str, str]]: 

854 """Pair each option in `_OPTIONS_WITH_ARGUMENT` with its argument. 

855 

856 The pair becomes a tuple, as SCons's ``ParseFlags`` does, so that 

857 ``AppendUnique`` treats e.g. ``-framework Accelerate`` as one flag 

858 rather than de-duplicating ``-framework`` on its own. SCons expands a 

859 tuple into its elements on the command line. An option with nothing 

860 after it is kept as a plain string. 

861 """ 

862 grouped: list[str | tuple[str, str]] = [] 

863 tokens = list(tokens) 

864 i = 0 

865 while i < len(tokens): 

866 if tokens[i] in _OPTIONS_WITH_ARGUMENT and i + 1 < len(tokens): 

867 grouped.append((tokens[i], tokens[i + 1])) 

868 i += 2 

869 else: 

870 grouped.append(tokens[i]) 

871 i += 1 

872 return grouped 

873 

874 

875def _strip_module_prefix(module: str) -> str: 

876 """Return `module` with a leading `MODULE_PREFIX` removed, if present.""" 

877 return module[len(MODULE_PREFIX) :] if module.startswith(MODULE_PREFIX) else module 

878 

879 

880def _variable_values(pkgconfig: PkgConfig, modules: Sequence[str], name: str) -> list[str]: 

881 """Return the set values of variable `name` over `modules`, in order.""" 

882 values = [] 

883 for module in modules: 

884 value = pkgconfig.variable(module, name) 

885 if value is not None: 

886 values.append(value) 

887 return values 

888 

889 

890def _library_union(pkgconfig: PkgConfig, modules: Sequence[str], name: str) -> list[str]: 

891 """Return the de-duplicated union of a library-list variable. 

892 

893 Each value is split on whitespace; tokens starting with ``-l`` have 

894 that prefix stripped and any other token is kept unchanged. 

895 """ 

896 libraries = [] 

897 for value in _variable_values(pkgconfig, modules, name): 

898 for token in value.split(): 

899 libraries.append(token[2:] if token.startswith("-l") else token) 

900 return _dedup_preserve_order(libraries) 

901 

902 

903def _route_includes( 

904 pkgconfig: PkgConfig, flag_modules: Sequence[str], modules: Sequence[str], conda_prefix: str 

905) -> tuple[list[str], list[str]]: 

906 """Split the ``-I`` directories of `flag_modules` into internal and 

907 external include paths. 

908 

909 A directory is internal if its realpath equals the realpath of the 

910 ``includedir`` of some ``lsst_*`` module in `modules`, except that 

911 ``<conda_prefix>/include`` is always external. Every other directory 

912 is external. Both returned lists hold realpath'd directories, in 

913 pkg-config's order, with duplicates removed. 

914 """ 

915 lsst_includes = { 

916 os.path.realpath(includedir) 

917 for includedir in _variable_values( 

918 pkgconfig, [m for m in modules if m.startswith(MODULE_PREFIX)], "includedir" 

919 ) 

920 } 

921 conda_include = os.path.realpath(os.path.join(conda_prefix, "include")) 

922 cpppath: list[str] = [] 

923 xcpppath: list[str] = [] 

924 for directory in pkgconfig.cflags_only_I(flag_modules): 

925 resolved = os.path.realpath(directory) 

926 if resolved != conda_include and resolved in lsst_includes: 

927 cpppath.append(resolved) 

928 else: 

929 xcpppath.append(resolved) 

930 return _dedup_preserve_order(cpppath), _dedup_preserve_order(xcpppath) 

931 

932 

933def resolve( 

934 package_name: str, pkgconfig: PkgConfig, conda_prefix: str, include_build_requires: bool = True 

935) -> ResolvedDependencies: 

936 """Resolve a package's dependencies through pkg-config. 

937 

938 Parameters 

939 ---------- 

940 package_name : `str` 

941 The EUPS product name of the primary package, e.g. ``"afw"``. 

942 pkgconfig : `PkgConfig` 

943 The runner used for every pkg-config query. 

944 conda_prefix : `str` 

945 The active conda prefix. ``<conda_prefix>/include`` is always 

946 routed to `ResolvedDependencies.xcpppath`. 

947 include_build_requires : `bool`, optional 

948 If `True` (the default), the module set also includes every module 

949 named in the primary module's ``lsst_build_requires`` variable. 

950 

951 Returns 

952 ------- 

953 resolved : `ResolvedDependencies` 

954 The resolved dependencies. Flag queries are run once over the 

955 module set (the primary plus any build requirements), letting 

956 pkg-config expand ``Requires`` itself; per-module variables and 

957 versions are read for every module in the closure. 

958 

959 Raises 

960 ------ 

961 PkgConfigError 

962 Raised if the primary module or any of its build requirements 

963 cannot be used, with pkg-config's explanation, which names the 

964 missing module even when it is one of their ``Requires``. 

965 CyclicDependencyError 

966 Raised if the ``Requires`` graph contains a cycle. 

967 """ 

968 primary = module_name(package_name) 

969 reason = pkgconfig.missing_reason(primary) 

970 if reason is not None: 

971 raise PkgConfigError( 

972 f"pkg-config module {primary} for package {package_name!r} is unusable: {reason}" 

973 ) 

974 module_set = [primary] 

975 if include_build_requires: 

976 for required in (pkgconfig.variable(primary, "lsst_build_requires") or "").split(): 

977 reason = pkgconfig.missing_reason(required) 

978 if reason is not None: 

979 raise PkgConfigError( 

980 f"pkg-config module {required}, listed in lsst_build_requires of {primary}, " 

981 f"is unusable: {reason}" 

982 ) 

983 module_set.append(required) 

984 module_set = _dedup_preserve_order(module_set) 

985 

986 modules = pkgconfig.closure(module_set) 

987 lsst_modules = [m for m in modules if m.startswith(MODULE_PREFIX)] 

988 cpppath, xcpppath = _route_includes(pkgconfig, module_set, modules, conda_prefix) 

989 

990 return ResolvedDependencies( 

991 modules=modules, 

992 cpppath=cpppath, 

993 xcpppath=xcpppath, 

994 ccflags=_group_flags(pkgconfig.cflags_only_other(module_set)), 

995 libpath=_dedup_preserve_order(pkgconfig.libs_only_L(module_set)), 

996 linkflags=_group_flags(pkgconfig.libs_only_other(module_set)), 

997 libs={ 

998 "main": pkgconfig.libs_only_l(module_set), 

999 "python": _library_union(pkgconfig, modules, "lsst_python_libs"), 

1000 "test": _library_union(pkgconfig, modules, "lsst_test_libs"), 

1001 }, 

1002 doxygen={ 

1003 "tags": _variable_values(pkgconfig, [m for m in lsst_modules if m != primary], "doxygen_tag"), 

1004 "includes": _variable_values(pkgconfig, lsst_modules, "doxygen_include"), 

1005 }, 

1006 versions={_strip_module_prefix(m): pkgconfig.modversion(m) for m in modules}, 

1007 ) 

1008 

1009 

1010def apply_to_env(env: Any, resolved: ResolvedDependencies) -> None: 

1011 """Update an SCons environment with a package's resolved dependencies. 

1012 

1013 Parameters 

1014 ---------- 

1015 env : `SCons.Environment.Environment` 

1016 The environment to update. Its ``CPPPATH``, ``XCPPPATH`` and 

1017 ``LIBPATH`` have the resolved directories prepended, and its 

1018 ``CCFLAGS`` and ``LINKFLAGS`` have the resolved flags appended, 

1019 skipping entries already present. Its ``libs`` and ``doxygen`` 

1020 attributes are replaced with copies of the resolved values. 

1021 resolved : `ResolvedDependencies` 

1022 The resolved dependencies, as returned by `resolve`. 

1023 

1024 Notes 

1025 ----- 

1026 Unlike the ``.cfg`` path, the library lists are not reversed, because 

1027 pkg-config already emits a dependent's libraries before those of the 

1028 modules it depends on. 

1029 """ 

1030 env.PrependUnique(CPPPATH=resolved.cpppath, XCPPPATH=resolved.xcpppath, LIBPATH=resolved.libpath) 

1031 env.AppendUnique(CCFLAGS=resolved.ccflags, LINKFLAGS=resolved.linkflags) 

1032 env.libs = {k: list(v) for k, v in resolved.libs.items()} 

1033 env.doxygen = {k: list(v) for k, v in resolved.doxygen.items()} 

1034 

1035 

1036class PkgConfigDependencies: 

1037 """The dependencies of a package configured through pkg-config. 

1038 

1039 This is stored as ``env.dependencies`` in place of a 

1040 `~lsst.sconsUtils.dependencies.PackageTree` when the package being 

1041 built has a pkg-config template. 

1042 

1043 Parameters 

1044 ---------- 

1045 package_name : `str` 

1046 The EUPS product name of the package being built. 

1047 resolved : `ResolvedDependencies` 

1048 The resolved dependencies of that package. 

1049 """ 

1050 

1051 def __init__(self, package_name: str, resolved: ResolvedDependencies) -> None: 

1052 self.name = package_name 

1053 self.resolved = resolved 

1054 

1055 @property 

1056 def versions(self) -> dict[str, str | None]: 

1057 """Version of every module in the dependency closure except the 

1058 package's own, keyed by module name with a leading `MODULE_PREFIX` 

1059 stripped (`dict` [`str`, `str` or `None`]). 

1060 

1061 The package itself is left out, as 

1062 `~lsst.sconsUtils.dependencies.PackageTree.versions` leaves out the 

1063 primary package, so that ``__dependency_versions__`` lists only 

1064 dependencies. 

1065 """ 

1066 return {name: version for name, version in self.resolved.versions.items() if name != self.name} 

1067 

1068 

1069class SyntheticConfiguration: 

1070 """A ``.cfg``-style configuration synthesized from pkg-config. 

1071 

1072 This stands in for the ``config`` object of a ``.cfg`` module when a 

1073 package built through the ``.cfg`` path depends on a package that has 

1074 been converted to a pkg-config template and no longer ships a ``.cfg`` 

1075 file. It provides the attributes and the ``configure`` method that 

1076 `~lsst.sconsUtils.dependencies.PackageTree` uses, without depending on 

1077 `~lsst.sconsUtils.dependencies.Configuration`. 

1078 

1079 Parameters 

1080 ---------- 

1081 name : `str` 

1082 The EUPS product name of the converted package. 

1083 resolved : `ResolvedDependencies` 

1084 The resolved dependencies of that package, as returned by 

1085 `resolve`. These already cover the package's whole closure. 

1086 

1087 Notes 

1088 ----- 

1089 The library lists are stored reversed, because 

1090 `~lsst.sconsUtils.dependencies.PackageTree.configure` reverses every 

1091 library list after configuring all packages; the final order is then 

1092 pkg-config's own, which already places a dependent's libraries before 

1093 those of the modules it depends on. 

1094 """ 

1095 

1096 def __init__(self, name: str, resolved: ResolvedDependencies) -> None: 

1097 self.name = name 

1098 self.version = resolved.versions[name] 

1099 self.libs = {target: list(reversed(libs)) for target, libs in resolved.libs.items()} 

1100 self.paths = { 

1101 "CPPPATH": list(resolved.cpppath), 

1102 "XCPPPATH": list(resolved.xcpppath), 

1103 "LIBPATH": list(resolved.libpath), 

1104 } 

1105 self.doxygen = {key: list(value) for key, value in resolved.doxygen.items()} 

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

1107 self._ccflags = list(resolved.ccflags) 

1108 self._linkflags = list(resolved.linkflags) 

1109 

1110 def configure(self, conf: Any, packages: Mapping[str, Any], build: bool = True) -> bool: 

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

1112 

1113 This has the same effect on ``conf.env`` as 

1114 `lsst.sconsUtils.dependencies.Configuration.configure`, and also 

1115 appends the package's compiler and linker flags. 

1116 

1117 Parameters 

1118 ---------- 

1119 conf : `SCons.Configure` 

1120 An SCons Configure context. The SCons Environment ``conf.env`` 

1121 is updated. 

1122 packages : `~collections.abc.Mapping` 

1123 The configuration modules of all dependencies; unused, because 

1124 pkg-config has already flattened the closure. 

1125 build : `bool`, optional 

1126 If True, this is the package currently being built, and its 

1127 Doxygen tag files are not added. 

1128 

1129 Returns 

1130 ------- 

1131 success : `bool` 

1132 Always `True`. 

1133 """ 

1134 # Imported here so that this module stays free of SCons imports; 

1135 # this method is only ever called from inside an SCons build. 

1136 from . import state 

1137 

1138 log = state.log 

1139 assert log is not None, "sconsUtils state has not been initialized" 

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

1141 conf.env.AppendUnique(CCFLAGS=self._ccflags, LINKFLAGS=self._linkflags) 

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

1143 # Synthesized closures overlap, so a shared dependency's files may 

1144 # already be there. 

1145 keys = ["includes"] if build else ["includes", "tags"] 

1146 for key in keys: 

1147 for path in self.doxygen[key]: 

1148 if path not in conf.env.doxygen[key]: 

1149 conf.env.doxygen[key].append(path) 

1150 for target, libs in self.libs.items(): 

1151 if target not in conf.env.libs: 

1152 conf.env.libs[target] = libs.copy() 

1153 log.info(f"Adding '{libs}' libraries to target '{target}'.") 

1154 else: 

1155 for lib in libs: 

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

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

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

1159 return True 

1160 

1161 

1162def synthesize_cfg_module(name: str, pkgconfig: PkgConfig, conda_prefix: str) -> types.SimpleNamespace: 

1163 """Synthesize a ``.cfg`` configuration module from pkg-config. 

1164 

1165 Parameters 

1166 ---------- 

1167 name : `str` 

1168 The EUPS product name of a package with a ``lsst_<name>`` module 

1169 on the pkg-config search path. 

1170 pkgconfig : `PkgConfig` 

1171 The runner used for every pkg-config query. 

1172 conda_prefix : `str` 

1173 The active conda prefix. 

1174 

1175 Returns 

1176 ------- 

1177 module : `types.SimpleNamespace` 

1178 An object with three attributes: 

1179 

1180 ``dependencies`` 

1181 An empty `dict`, because pkg-config has already flattened the 

1182 closure, so there is nothing left for 

1183 `~lsst.sconsUtils.dependencies.PackageTree` to recurse into. 

1184 ``config`` 

1185 A `SyntheticConfiguration` covering the whole closure. The 

1186 package's ``lsst_build_requires`` are not included, because a 

1187 dependency's build-only requirements are never applied to the 

1188 package consuming it. Unlike in `resolve`, the package's own 

1189 ``doxygen_tag`` is included, ahead of those of the modules it 

1190 requires. 

1191 ``provided`` 

1192 The version of every other module in the closure, keyed by 

1193 module name with a leading `MODULE_PREFIX` stripped (`dict` 

1194 [`str`, `str`]), so that they can still be listed as 

1195 dependencies. 

1196 

1197 Raises 

1198 ------ 

1199 PkgConfigError 

1200 Raised if the module is missing or its ``Requires`` cannot be 

1201 satisfied, with pkg-config's own explanation, or if it cannot be 

1202 resolved for another reason; see `resolve`. 

1203 """ 

1204 resolved = resolve(name, pkgconfig, conda_prefix, include_build_requires=False) 

1205 # resolve() leaves out the primary module's own tag file, which only the 

1206 # package being built must do; a dependency's tag file is wanted, as 

1207 # with a .cfg dependency that sets hasDoxygenTag. 

1208 tag = pkgconfig.variable(module_name(name), "doxygen_tag") 

1209 if tag is not None: 

1210 resolved.doxygen["tags"].insert(0, tag) 

1211 provided = {other: version for other, version in resolved.versions.items() if other != name} 

1212 return types.SimpleNamespace( 

1213 dependencies={}, config=SyntheticConfiguration(name, resolved), provided=provided 

1214 ) 

1215 

1216 

1217def _write_if_changed(output: str, contents: str) -> bool: 

1218 """Write `contents` to `output` unless it already has that content. 

1219 

1220 Parameters 

1221 ---------- 

1222 output : `str` 

1223 Path of the file to write. Its parent directory is created if it 

1224 does not already exist. 

1225 contents : `str` 

1226 The full content to write. 

1227 

1228 Returns 

1229 ------- 

1230 wrote : `bool` 

1231 `True` if `output` was written or overwritten, `False` if its 

1232 content already matched `contents` and it was left untouched. 

1233 """ 

1234 if os.path.exists(output): 

1235 with open(output) as f: 

1236 if f.read() == contents: 

1237 return False 

1238 os.makedirs(os.path.dirname(output), exist_ok=True) 

1239 with open(output, "w") as f: 

1240 f.write(contents) 

1241 return True 

1242 

1243 

1244def static_shim_dir() -> str | None: 

1245 """Return the directory of sconsUtils' static pkg-config shims. 

1246 

1247 Returns 

1248 ------- 

1249 directory : `str` or `None` 

1250 The ``pkgconfig_shims`` directory installed alongside this module, 

1251 whether sconsUtils is set up by EUPS or installed with pip, or 

1252 `None` if that directory does not exist. 

1253 """ 

1254 candidate = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pkgconfig_shims") 

1255 if not os.path.isdir(candidate): 1255 ↛ 1256line 1255 didn't jump to line 1256 because the condition on line 1255 was never true

1256 return None 

1257 return candidate 

1258 

1259 

1260class _ShimSkippedError(Exception): 

1261 """Raised by a shim generator that cannot write its shim; the message 

1262 says why.""" 

1263 

1264 

1265def _write_numpy_shim(directory: str) -> str: 

1266 """Generate ``numpy.pc`` in `directory` and return its path. 

1267 

1268 Runs the ``python`` found on ``PATH`` once to read both 

1269 ``numpy.__version__`` and ``numpy.get_include()``. If that invocation 

1270 fails, for example because ``numpy`` is not importable, nothing is 

1271 written and `_ShimSkippedError` is raised; an environment without numpy 

1272 simply has no use for the shim. 

1273 """ 

1274 try: 

1275 output = subprocess.check_output( 

1276 [ 

1277 "python", 

1278 "-c", 

1279 "import numpy; print(numpy.__version__); print(numpy.get_include())", 

1280 ], 

1281 text=True, 

1282 stderr=subprocess.DEVNULL, 

1283 ) 

1284 except (subprocess.CalledProcessError, OSError) as err: 

1285 raise _ShimSkippedError(f"numpy is not importable by the python on PATH ({err})") from None 

1286 lines = output.splitlines() 

1287 if len(lines) < 2: 

1288 raise _ShimSkippedError(f"unexpected output from the python on PATH: {output!r}") 

1289 version, include = lines[0].strip(), lines[1].strip() 

1290 contents = f"Name: numpy\nDescription: NumPy C API\nVersion: {version}\nCflags: -I{include}\nLibs:\n" 

1291 output_file = os.path.join(directory, "numpy.pc") 

1292 _write_if_changed(output_file, contents) 

1293 return output_file 

1294 

1295 

1296def _write_starlink_ast_shim(directory: str) -> str: 

1297 """Generate ``starlink_ast.pc`` in `directory` and return its path. 

1298 

1299 Runs the ``ast_link`` script found on ``PATH`` through ``sh``, as 

1300 ``configs/starlink_ast.cfg`` does, to learn the library list. If 

1301 ``ast_link`` cannot be found or fails, nothing is written and 

1302 `_ShimSkippedError` is raised. 

1303 """ 

1304 ast_link = shutil.which("ast_link") 

1305 if ast_link is None: 

1306 raise _ShimSkippedError("ast_link was not found on PATH") 

1307 try: 

1308 libs = subprocess.check_output(["sh", ast_link], text=True) 

1309 except (subprocess.CalledProcessError, OSError) as err: 

1310 raise _ShimSkippedError(f"running {ast_link} failed ({err})") from None 

1311 libs = " ".join(libs.split()) 

1312 contents = ( 

1313 "conda_prefix=${pcfiledir}/../..\n\n" 

1314 "Name: starlink_ast\n" 

1315 "Description: Starlink AST world coordinate system library\n" 

1316 "Version: unknown\n" 

1317 "Cflags: -I${conda_prefix}/include/star\n" 

1318 f"Libs: {libs}\n" 

1319 ) 

1320 output_file = os.path.join(directory, "starlink_ast.pc") 

1321 _write_if_changed(output_file, contents) 

1322 return output_file 

1323 

1324 

1325def write_shims(directory: str, static_dir: str | None = None, skipped: list[str] | None = None) -> list[str]: 

1326 """Write every pkg-config shim sconsUtils knows about into `directory`. 

1327 

1328 Parameters 

1329 ---------- 

1330 directory : `str` 

1331 Directory to write into. Created if it does not already exist. 

1332 static_dir : `str` or `None`, optional 

1333 Directory holding the static shims to copy. Defaults to 

1334 `static_shim_dir`. If that is also `None`, no static shims are 

1335 copied. 

1336 skipped : `list` [`str`] or `None`, optional 

1337 If given, a message is appended to this list for every generated 

1338 shim that could not be written, naming the shim and saying why, 

1339 e.g. because ``numpy`` is not importable. Skipping a shim is not 

1340 an error. 

1341 

1342 Returns 

1343 ------- 

1344 written : `list` [`str`] 

1345 The paths, under `directory`, of every shim that exists there 

1346 after this call: every ``*.pc`` copied from `static_dir`, plus 

1347 ``numpy.pc`` and ``starlink_ast.pc`` if they could be generated. 

1348 This list is returned regardless of whether a given file's 

1349 content actually changed; a file already present with identical 

1350 content is still included, and its modification time is left 

1351 untouched. 

1352 """ 

1353 os.makedirs(directory, exist_ok=True) 

1354 if static_dir is None: 

1355 static_dir = static_shim_dir() 

1356 

1357 written: list[str] = [] 

1358 if static_dir is not None: 

1359 for source in sorted(glob.glob(os.path.join(static_dir, "*.pc"))): 

1360 output_file = os.path.join(directory, os.path.basename(source)) 

1361 with open(source) as f: 

1362 contents = f.read() 

1363 _write_if_changed(output_file, contents) 

1364 written.append(output_file) 

1365 

1366 for name, generator in (("numpy.pc", _write_numpy_shim), ("starlink_ast.pc", _write_starlink_ast_shim)): 

1367 try: 

1368 written.append(generator(directory)) 

1369 except _ShimSkippedError as err: 

1370 if skipped is not None: 1370 ↛ 1366line 1370 didn't jump to line 1366 because the condition on line 1370 was always true

1371 skipped.append(f"Not writing pkg-config shim {name}: {err}") 

1372 

1373 return written 

1374 

1375 

1376def main(argv: Sequence[str] | None = None) -> int: 

1377 """Run the ``sconsUtils-write-pkgconfig-shims`` console script. 

1378 

1379 Parameters 

1380 ---------- 

1381 argv : `~collections.abc.Sequence` [`str`] or `None`, optional 

1382 Command-line arguments, not including the program name. Defaults 

1383 to `sys.argv[1:]`. 

1384 

1385 Returns 

1386 ------- 

1387 status : `int` 

1388 ``0`` on success, or ``1`` if the static shims could not be found, 

1389 in which case nothing is written. A generated shim that cannot be 

1390 written is not an error, but the reason is printed to standard 

1391 error. 

1392 """ 

1393 parser = argparse.ArgumentParser(description="Write sconsUtils' pkg-config shims into a directory.") 

1394 parser.add_argument("directory", help="Directory to write the shims into.") 

1395 args = parser.parse_args(argv) 

1396 static_dir = static_shim_dir() 

1397 if static_dir is None: 

1398 print("sconsUtils' static pkg-config shims are not installed; nothing was written.", file=sys.stderr) 

1399 return 1 

1400 skipped: list[str] = [] 

1401 write_shims(args.directory, static_dir=static_dir, skipped=skipped) 

1402 for message in skipped: 

1403 print(f"{message}.", file=sys.stderr) 

1404 return 0