Coverage for python/lsst/sconsUtils/scripts.py: 7%
289 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 06:33 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 06:33 +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/>.
22"""Convenience functions to do the work of standard LSST SConstruct/SConscript
23files.
24"""
26import glob
27import os.path
28import re
29import shlex
30import shutil
31import warnings
32from stat import ST_MODE
34from SCons.Script import BUILD_TARGETS, Dir, File, GetOption, Glob, SConscript
36from . import dependencies, state, tests, utils
38DEFAULT_TARGETS = ("lib", "python", "shebang", "tests", "examples", "doc")
41def _getFileBase(node):
42 name, ext = os.path.splitext(os.path.basename(str(node)))
43 return name
46class BasicSConstruct:
47 """A scope-only class for SConstruct-replacement convenience functions.
49 The boilerplate for a standard LSST SConstruct file is replaced by two
50 static methods: ``initialize()`` and ``finish()``. The former configures
51 dependencies, sets up package-dependent environment variables, and calls
52 any SConscript files found in subdirectories, while the latter sets up
53 installation paths, default targets, and explicit dependencies.
55 Calling ``BasicSConstruct`` as a function invokes its ``__new__`` method,
56 which calls both `~lsst.sconsUtils.BasicSConstruct.initialize` and
57 `~lsst.sconsUtils.BasicSConstruct.finish`, and should be used when the
58 SConstruct file doesn't need to do anything other than what they provide.
59 When called this way it returns the `~lsst.sconsUtils.env` Environment
60 object rather than a `~lsst.sconsUtils.scripts.BasicSConstruct` instance
61 (which would be useless).
62 """
64 _initializing = False
66 def __new__(
67 cls,
68 packageName,
69 versionString=None,
70 eupsProduct=None,
71 eupsProductPath=None,
72 cleanExt=None,
73 defaultTargets=DEFAULT_TARGETS,
74 subDirList=None,
75 ignoreRegex=None,
76 versionModuleName="python/lsst/%s/version.py",
77 noCfgFile=False,
78 sconscriptOrder=None,
79 disableCc=False,
80 ):
81 cls.initialize(
82 packageName,
83 versionString,
84 eupsProduct,
85 eupsProductPath,
86 cleanExt,
87 versionModuleName,
88 noCfgFile=noCfgFile,
89 sconscriptOrder=sconscriptOrder,
90 disableCc=disableCc,
91 )
92 cls.finish(defaultTargets, subDirList, ignoreRegex)
93 return state.env
95 @classmethod
96 def initialize(
97 cls,
98 packageName,
99 versionString=None,
100 eupsProduct=None,
101 eupsProductPath=None,
102 cleanExt=None,
103 versionModuleName="python/lsst/%s/version.py",
104 noCfgFile=False,
105 sconscriptOrder=None,
106 disableCc=False,
107 ):
108 """Convenience function to replace standard SConstruct boilerplate
109 (step 1).
111 This function:
113 - Calls all SConscript files found in subdirectories.
114 - Configures dependencies.
115 - Sets how the ``--clean`` option works.
117 Parameters
118 ----------
119 packageName : `str`
120 Name of the package being built; must correspond to a .cfg
121 file in ``ups/``.
122 versionString : `str`, optional
123 Version-control system string to be parsed for version information
124 (``$HeadURL$`` for SVN). Defaults to "git" if not set or `None`.
125 eupsProduct : `str`, optional
126 Name of the EUPS product being built. Defaults to and is almost
127 always the name of the package.
128 eupsProductPath : `str`, optional
129 An alternate directory where the package should be installed.
130 cleanExt : `list`, optional
131 Whitespace delimited sequence of globs for files to remove with
132 ``--clean``.
133 versionModuleName : `str`, optional
134 If non-None, builds a ``version.py`` module as this file; ``'%s'``
135 is replaced with the name of the package.
136 noCfgFile : `bool`, optional
137 If True, this package has no .cfg file
138 sconscriptOrder : `list`, optional
139 A sequence of directory names that set the order for processing
140 SConscript files discovered in nested directories. Full
141 directories need not be specified, but paths must begin at the
142 root. For example, ``["lib", "python"]`` will ensure that
143 ``lib/SConscript`` is run before both ``python/foo/SConscript``
144 and ``python/bar/SConscript``. The default order should work for
145 most LSST SCons builds, as it provides the correct ordering for
146 the ``lib``, ``python``, ``tests``, ``examples``, and ``doc``
147 targets. If this argument is provided, it must include the subset
148 of that list that is valid for the package, in that order.
149 disableCC : `bool`, optional
150 Should the C++ compiler check be disabled? Disabling this checks
151 allows a faster startup and permits building on systems that don't
152 meet the requirements for the C++ compiler (e.g., for
153 pure-python packages).
155 Returns
156 -------
157 env : `lsst.sconsUtils.env`
158 A SCons Environment object.
159 """
160 if not disableCc:
161 state._configureCommon()
162 state._saveState()
163 if cls._initializing:
164 state.log.fail("Recursion detected; an SConscript file should not call BasicSConstruct.")
165 cls._initializing = True
166 dependencies.configure(packageName, versionString, eupsProduct, eupsProductPath, noCfgFile)
167 state.env.BuildETags()
168 if cleanExt is None:
169 cleanExt = r"*~ core core.[1-9]* *.so *.os *.o *.pyc *.pkgc"
170 state.env.CleanTree(cleanExt, "__pycache__ .pytest_cache *.dist-info")
171 if versionModuleName is not None:
172 try:
173 versionModuleName = versionModuleName % "/".join(packageName.split("_"))
174 except TypeError:
175 pass
176 state.targets["version"] = state.env.VersionModule(versionModuleName)
177 # Always attempt to write python package info into the python
178 # directory.
179 if os.path.exists("python"):
180 state.targets["pkginfo"] = state.env.PackageInfo("python")
181 # Python script generation does no harm since it will only do anything
182 # if there is a scripts entry in pyproject.toml.
183 state.targets["scripts"] = state.env.PythonScripts()
184 scripts = []
185 for root, dirs, files in os.walk("."):
186 if "SConstruct" in files and root != ".":
187 dirs[:] = []
188 continue
189 dirs[:] = [d for d in dirs if not d.startswith(".")]
190 dirs.sort() # os.walk order is not specified, but we want builds to be deterministic
191 if "SConscript" in files:
192 scripts.append(os.path.join(root, "SConscript"))
193 if sconscriptOrder is None:
194 sconscriptOrder = DEFAULT_TARGETS
196 # directory for shebang target is bin.src
197 sconscriptOrder = [t if t != "shebang" else "bin.src" for t in sconscriptOrder]
199 def key(path):
200 for i, item in enumerate(sconscriptOrder):
201 if path.lstrip("./").startswith(item):
202 return i
203 return len(sconscriptOrder)
205 scripts.sort(key=key)
206 for script in scripts:
207 state.log.info(f"Using SConscript at {script}")
208 SConscript(script)
209 cls._initializing = False
210 return state.env
212 @staticmethod
213 def finish(defaultTargets=DEFAULT_TARGETS, subDirList=None, ignoreRegex=None):
214 """Convenience function to replace standard SConstruct boilerplate
215 (step 2).
217 This function:
219 - Sets up installation paths.
220 - Tells SCons to only do MD5 checks when timestamps have changed.
221 - Sets the "include", "lib", "python", and "tests" targets as the
222 defaults to be built when scons is run with no target arguments.
224 Parameters
225 ----------
226 subDirList : `list`
227 An explicit list of subdirectories that should be installed.
228 By default, all non-hidden subdirectories will be installed.
229 defaultTargets : `list`
230 A sequence of targets (see `lsst.sconsUtils.state.targets`)
231 that should be built when scons is run with no arguments.
232 ignoreRegex : `str`
233 Regular expression that matches files that should not be installed.
235 Returns
236 -------
237 env : `lsst.sconsUtils.env`
238 A SCons Environment.
239 """
240 if ignoreRegex is None:
241 ignoreRegex = r"(~$|\.pyc$|^\.svn$|\.o|\.os$)"
242 if subDirList is None:
243 subDirList = []
244 for path in os.listdir("."):
245 if os.path.isdir(path) and not path.startswith("."):
246 subDirList.append(path)
247 if "bin.src" in subDirList and "shebang" in state.targets and state.targets["shebang"]:
248 # shebang makes a directory that should be installed
249 subDirList += ["bin"]
250 install = state.env.InstallLSST(state.env["prefix"], list(subDirList), ignoreRegex=ignoreRegex)
251 for name, target in state.targets.items():
252 state.env.Requires(install, target)
253 state.env.Alias(name, target)
254 state.env.Requires(state.targets["python"], state.targets["version"])
255 declarer = state.env.Declare()
256 state.env.Requires(declarer, install) # Ensure declaration fires after installation available
258 # shebang should be in the list if bin.src exists but the location
259 # matters so we can not append it afterwards.
260 state.env.Default(
261 [t for t in defaultTargets if os.path.exists(t) or (t == "shebang" and os.path.exists("bin.src"))]
262 )
263 if "version" in state.targets:
264 state.env.Default(state.targets["version"])
265 state.env.Requires(state.targets["tests"], state.targets["version"])
266 if "pkginfo" in state.targets:
267 state.env.Default(state.targets["pkginfo"])
268 state.env.Requires(state.targets["pkginfo"], state.targets["python"])
269 state.env.Requires(state.targets["tests"], state.targets["pkginfo"])
270 if "scripts" in state.targets:
271 state.env.Default(state.targets["scripts"])
272 state.env.Requires(state.targets["tests"], state.targets["scripts"])
274 state.env.Decider("MD5-timestamp") # if timestamps haven't changed, don't do MD5 checks
275 #
276 # Check if any of the tests failed by looking for *.failed files.
277 # Perform this test just before scons exits
278 #
279 # N.b. the test is written in sh not python as then we can use @ to
280 # suppress output
281 #
282 if "tests" in [str(t) for t in BUILD_TARGETS]:
283 testsDir = shlex.quote(os.path.join(os.getcwd(), "tests", ".tests"))
284 checkTestStatus_command = state.env.Command(
285 "checkTestStatus",
286 [],
287 f"""
288 @ if [ -d {testsDir} ]; then \
289 nfail=`find {testsDir} -name "*.failed" | wc -l | sed -e 's/ //g'`; \
290 if [ $$nfail -gt 0 ]; then \
291 echo "Failed test output:" >&2; \
292 for f in `find {testsDir} -name "*.failed"`; do \
293 case "$$f" in \
294 *.xml.failed) \
295 echo "Global pytest output is in $$f" >&2; \
296 ;; \
297 *.failed) \
298 cat $$f >&2; \
299 ;; \
300 esac; \
301 done; \
302 echo "The following tests failed:" >&2;\
303 find {testsDir} -name "*.failed" >&2; \
304 echo "$$nfail tests failed" >&2; exit 1; \
305 fi; \
306 fi; \
307 """,
308 )
310 state.env.Depends(checkTestStatus_command, BUILD_TARGETS) # this is why the check runs last
311 BUILD_TARGETS.extend(checkTestStatus_command)
312 state.env.AlwaysBuild(checkTestStatus_command)
315class BasicSConscript:
316 """A scope-only class for SConscript-replacement convenience functions.
318 All methods of `~lsst.sconsUtils.scripts.BasicSConscript` are static. All
319 of these functions update the `~lsst.sconsUtils.state.targets` dictionary
320 of targets used to set default targets and fix build dependencies; if you
321 build anything without using BasicSConscript methods, be sure to manually
322 add it to the `~lsst.sconsUtils.state.state.targets` `dict`.
323 """
325 @staticmethod
326 def lib(libName=None, src=None, libs="self", noBuildList=None):
327 """Convenience function to replace standard lib/SConscript boilerplate.
329 With no arguments, this will build a shared library with the same name
330 as the package. This uses
331 `lsst.sconsUtils.env.SourcesForSharedLibrary` to support the
332 ``optFiles``/``noOptFiles`` command-line variables.
334 Parameters
335 ----------
336 libName : `str`
337 Name of the shared libray to be built (defaults to
338 ``env["packageName"]``).
339 src : `str` or `~SCons.Script.Glob`
340 Source to compile into the library. Defaults to a 4-directory
341 deep glob of all ``*.cc`` files in ``#src``.
342 libs : `str` or `list`
343 Libraries to link against, either as a string argument to be
344 passed to `lsst.sconsUtils.env.getLibs` or a sequence of actual
345 libraries to pass in.
346 noBuildList : `list`
347 List of source files to exclude from building.
349 Returns
350 -------
351 result : ???
352 ???
353 """
354 if libName is None:
355 libName = state.env["packageName"]
356 if src is None:
357 src = Glob("#src/*.cc") + Glob("#src/*/*.cc") + Glob("#src/*/*/*.cc") + Glob("#src/*/*/*/*.cc")
358 if noBuildList is not None:
359 src = [node for node in src if os.path.basename(str(node)) not in noBuildList]
360 src = state.env.SourcesForSharedLibrary(src)
361 if isinstance(libs, str):
362 libs = state.env.getLibs(libs)
363 elif libs is None:
364 libs = []
365 result = state.env.SharedLibrary(libName, src, LIBS=libs)
366 state.targets["lib"].extend(result)
367 return result
369 @staticmethod
370 def shebang(src=None):
371 """Handles shebang rewriting.
373 With no arguments looks in ``bin.src/`` and copies to ``bin/``
374 If `~lsst.sconsUtils.utils.needShebangRewrite()` is `False` the
375 shebang will not be modified.
377 Only Python files requiring a shebang rewrite should be placed
378 in ``bin.src/``. Do not place executable binaries in this directory.
380 Parameters
381 ----------
382 src : `str` or `~SCons.Script.Glob`, optional
383 Glob to use to search for files.
384 """
385 # check if Python is called on the first line with this expression
386 # This comes from distutils copy_scripts
387 FIRST_LINE_RE = re.compile(r"^#!.*python[0-9.]*([ \t].*)?$")
388 doRewrite = utils.needShebangRewrite()
390 def rewrite_shebang(target, source, env):
391 """Copy source to target, rewriting the shebang"""
392 # Currently just use this python
393 usepython = utils.whichPython()
394 for targ, src in zip(target, source, strict=True):
395 with open(str(src)) as srcfd:
396 with open(str(targ), "w") as outfd:
397 first_line = srcfd.readline()
398 # Always match the first line so we can warn people
399 # if an attempt is being made to rewrite a file that
400 # should not be rewritten
401 match = FIRST_LINE_RE.match(first_line)
402 if match and doRewrite:
403 post_interp = match.group(1) or ""
404 # Paths can be long so ensure that flake8 won't
405 # complain
406 outfd.write(f"#!{usepython}{post_interp} # noqa\n")
407 else:
408 if not match:
409 state.log.warn(
410 f"Could not rewrite shebang of {src}. Please check"
411 " file or move it to bin directory."
412 )
413 outfd.write(first_line)
414 for line in srcfd.readlines():
415 outfd.write(line)
416 # Ensure the bin/ file is executable
417 oldmode = os.stat(str(targ))[ST_MODE] & 0o7777
418 newmode = (oldmode | 0o555) & 0o7777
419 if newmode != oldmode:
420 state.log.info(f"changing mode of {str(targ)} from {oldmode} to {newmode}")
421 os.chmod(str(targ), newmode)
423 if src is None:
424 # Ask the file system rather than SCons. Glob() reports every
425 # entry SCons knows about in a directory, including nodes that no
426 # file corresponds to, and only a file can be rewritten. Sort
427 # for a deterministic build.
428 src = sorted(glob.glob(os.path.join(Dir("#bin.src").abspath, "*")))
429 for s in src:
430 filename = os.path.basename(str(s))
431 # Do not try to rewrite files starting with non-letters
432 if filename != "SConscript" and re.match("[A-Za-z]", filename):
433 result = state.env.Command(
434 target=os.path.join(Dir("#bin").abspath, filename), source=s, action=rewrite_shebang
435 )
436 state.targets["shebang"].extend(result)
438 @staticmethod
439 def python(module=None, src=None, extra=(), libs="main python"):
440 """Convenience function to replace standard ``python/*/SConscript``
441 boilerplate.
443 With no arguments, this will build a pybind11 module with the name
444 determined according to our current pseudo-convention: last part of
445 ``env["packageName"]`` (split by underscores), with an underscore
446 prepended. All .cc files in the same directory will be linked into a
447 single module.
449 Parameters
450 ----------
451 module : `str`, optional
452 Name of the module to build (does not include the file extension).
453 Defaults to ``"_" + env["packageName"].split("_")[-1]``.
454 src : `list`, optional
455 A list of source files to build the module from; defaults to all
456 .cc files in the directory.
457 extra : `list`, optional
458 A list of additional source files to add to ``src``; should only
459 be used if ``src`` is defaulted.
460 libs : `str` or `list`, optional
461 Libraries to link against, either as a string argument to be
462 passed to `lsst.sconsUtils.env.getLibs` or a sequence of actual
463 libraries to pass in.
465 Returns
466 -------
467 result : `lsst.sconsUtils.env.Pybind11LoadableModule`
468 A Pybind11LoadableModule instance.
469 """
470 if module is None:
471 module = "_" + state.env["packageName"].split("_")[-1]
472 if src is None:
473 src = state.env.Glob("*.cc")
474 src.extend(extra)
475 if isinstance(libs, str):
476 libs = state.env.getLibs(libs)
477 elif libs is None:
478 libs = []
479 result = state.env.Pybind11LoadableModule(module, src, LIBS=libs)
480 state.targets["python"].append(result)
481 return result
483 @staticmethod
484 def pybind11(nameList=(), libs="main python", extraSrc=None, addUnderscore=True):
485 """Convenience function to replace standard ``python/*/SConscript``
486 boilerplate.
488 .. note:: Deprecated
490 Use `lsst.sconsUtils.scripts.BasicSConscript.python` for new code
491 with all source compiled into a single module. Will be removed
492 once all LSST code has been converted to use the new approach.
494 Parameters
495 ----------
496 nameList : `collections.abc.Sequence`, optional
497 Sequence of pybind11 modules to be built (does not include the
498 file extensions).
499 libs : `str` or `list`, optional
500 Libraries to link against, either as a string argument to be
501 passed to `lsst.sconsUtils.env.getLibs` or a sequence of actual
502 libraries to pass in.
503 extraSrc : `dict`, optional
504 A dictionary of additional source files that go into the modules.
505 Each key should be an entry in nameList, and each value should be
506 a list of additional C++ source files.
507 addUnderscore : `bool`, optional
508 Add an underscore to each library name (if the source file name
509 does not already start with underscore)? If False the library name
510 is always the same as the source file name
511 **DEPRECATED**: always use `False` for new code.
513 Returns
514 -------
515 result : `lsst.sconsUtils.env.Pybind11LoadableModule`
516 A Pybind11LoadableModule instance.
517 """
518 warnings.warn(
519 "sconsUtils.scripts.pybind11() is deprecated; please use scripts.python() instead",
520 DeprecationWarning,
521 stacklevel=2,
522 )
523 srcList = extraSrc
524 if srcList is None:
525 srcList = {name: [] for name in nameList}
526 for name in nameList:
527 srcList[name].append(name + ".cc")
528 if isinstance(libs, str):
529 libs = state.env.getLibs(libs)
530 elif libs is None:
531 libs = []
532 result = []
533 for name in nameList:
534 # TODO remove this block and the `addUnderscore` argument and
535 # always use pyLibName = name; but we can't do that until all our
536 # pybind11 SConscript files have been converted
537 if addUnderscore:
538 if name.startswith("_"):
539 pyLibName = name
540 else:
541 pyLibName = "_" + name
542 else:
543 pyLibName = name
544 result.extend(state.env.Pybind11LoadableModule(pyLibName, srcList[name], LIBS=libs))
545 state.targets["python"].extend(result)
546 return result
548 @staticmethod
549 def doc(config="doxygen.conf.in", projectName=None, projectNumber=None, **kwargs):
550 """Convenience function to replace standard doc/SConscript
551 boilerplate.
553 With no arguments, this will generate a Doxygen config file and run
554 Doxygen with `lsst.sconsUtils.env.Doxygen`, using the projectName
555 and projectNumber from ``env["packageName"]`` and ``env["version"]``,
556 respectively.
558 This essentially just forwards all arguments (which should be passed as
559 keyword arguments) to `lsst.sconsUtils.env.Doxygen`.
561 Parameters
562 ----------
563 config : `str`, optional
564 Configuration .in file to use.
565 projectName : `str`, optional
566 Project name.
567 projectNumber : `str`, optional
568 Project version number.
569 kwargs
571 Returns
572 -------
573 result : ???
574 ???
575 """
576 if not shutil.which("doxygen"):
577 state.log.warn("doxygen executable not found; skipping documentation build.")
578 return []
579 if projectName is None:
580 projectName = ".".join(["lsst"] + state.env["packageName"].split("_"))
581 if projectNumber is None:
582 projectNumber = state.env["version"]
583 result = state.env.Doxygen(
584 config,
585 projectName=projectName,
586 projectNumber=projectNumber,
587 includes=state.env.doxygen["includes"],
588 useTags=state.env.doxygen["tags"],
589 makeTag=(state.env["packageName"] + ".tag"),
590 **kwargs,
591 )
592 state.targets["doc"].extend(result)
593 return result
595 @staticmethod
596 def tests(
597 pyList=None,
598 ccList=None,
599 swigNameList=None,
600 swigSrc=None,
601 ignoreList=None,
602 noBuildList=None,
603 pySingles=None,
604 args=None,
605 ):
606 """Convenience function to replace standard tests/SConscript
607 boilerplate.
609 With no arguments, will attempt to figure out which files should be
610 run as tests and which are support code (like SWIG modules).
612 Python tests will be marked as dependent on the entire ``#python``
613 directory and any SWIG modules built in the tests directory. This
614 should ensure tests are always run when their results might have
615 changed, but may result in them being re-run more often
616 than necessary.
618 Parameters
619 ----------
620 pyList : `list`, optional
621 A sequence of Python tests to run (including .py extensions).
622 Defaults to a ``*.py`` glob of the tests directory, minus any
623 files corresponding to the SWIG modules in swigFileList.
624 An empty list will enable automated test discovery.
625 ccList : `list`, optional
626 A sequence of C++ unit tests to run (including .cc extensions).
627 Defaults to a ``*.cc`` glob of the tests directory, minus any
628 files that end with ``*_wrap.cc`` and files present in swigSrc.
629 swigNameList : `list`, optional
630 A sequence of SWIG modules to build (NOT including .i extensions).
631 swigSrc : `dict`, optional
632 Additional source files to be compiled into SWIG modules, as a
633 dictionary; each key must be an entry in swigNameList, and each
634 value a list of additional source files.
635 ignoreList : `list`, optional
636 List of ignored tests to be passed to
637 `lsst.sconsUtils.tests.Control` (note that ignored tests will be
638 built, but not run).
639 noBuildList : `list`, optional
640 List of tests that should not even be built.
641 pySingles : `list`, optional
642 A sequence of Python tests to run (including .py extensions)
643 as independent single tests. By default this list is empty
644 and all tests are run in a single pytest call.
645 Items specified here will not appear in the default pyList
646 and should not start with ``test_`` (such that they will not
647 be auto-discoverable by pytest).
648 args : `dict`, optional
649 A dictionary of program arguments for tests, passed directly
650 to `lsst.sconsUtils.tests.Control`.
652 Returns
653 -------
654 result : ???
655 ???
656 """
657 if GetOption("no_tests"):
658 return []
659 if noBuildList is None:
660 noBuildList = []
661 if pySingles is None:
662 pySingles = []
663 if swigNameList is None:
664 swigFileList = Glob("*.i")
665 swigNameList = [_getFileBase(node) for node in swigFileList]
666 else:
667 swigFileList = [File(name + ".i") for name in swigNameList]
668 if swigSrc is None:
669 swigSrc = {}
670 allSwigSrc = set()
671 for name, node in zip(swigNameList, swigFileList, strict=True):
672 src = swigSrc.setdefault(name, [])
673 allSwigSrc.update(str(element) for element in src)
674 src.append(node)
675 if pyList is None:
676 pyList = [
677 node
678 for node in Glob("*.py")
679 if _getFileBase(node) not in swigNameList and os.path.basename(str(node)) not in noBuildList
680 ]
681 # if we got no matches, reset to None so we do not enabled
682 # auto test detection in pytest
683 if not pyList:
684 pyList = None
685 if ccList is None:
686 ccList = [
687 node
688 for node in Glob("*.cc")
689 if (not str(node).endswith("_wrap.cc"))
690 and str(node) not in allSwigSrc
691 and os.path.basename(str(node)) not in noBuildList
692 ]
693 if ignoreList is None:
694 ignoreList = []
696 def s(ll):
697 if ll is None:
698 return ["None"]
699 return [str(i) for i in ll]
701 state.log.info(f"SWIG modules for tests: {s(swigFileList)}")
702 state.log.info(f"Python tests: {s(pyList)}")
703 state.log.info(f"C++ tests: {s(ccList)}")
704 state.log.info(f"Files that will not be built: {noBuildList}")
705 state.log.info(f"Ignored tests: {ignoreList}")
706 control = tests.Control(state.env, ignoreList=ignoreList, args=args, verbose=True)
707 for ccTest in ccList:
708 state.env.Program(ccTest, LIBS=state.env.getLibs("main test"))
709 swigMods = []
710 for name, src in swigSrc.items():
711 swigMods.extend(
712 state.env.SwigLoadableModule("_" + name, src, LIBS=state.env.getLibs("main python"))
713 )
715 # Warn about insisting that a test in pySingles starts with test_ and
716 # therefore might be automatically discovered by pytest. These files
717 # should not be discovered automatically.
718 for node in pySingles:
719 if str(node).startswith("test_"):
720 state.log.warn(
721 f"Warning: {node} should be run independently but can be automatically discovered"
722 )
724 # Ensure that python tests listed in pySingles are not included in
725 # pyList.
726 if pyList is not None:
727 pyList = [str(node) for node in pyList if str(node) not in pySingles]
729 ccList = [control.run(str(node)) for node in ccList]
730 pySingles = [control.run(str(node)) for node in pySingles]
732 # If we tried to discover .py files and found none, do not then
733 # try to use auto test discovery.
734 if pyList is not None:
735 pyList = [control.runPythonTests(pyList)]
736 else:
737 pyList = []
738 pyList.extend(control.runPythonLinter())
740 # Run all pySingles sequentially before other tests. This ensures
741 # that there are no race conditions collecting coverage databases.
742 if pySingles:
743 for i in range(len(pySingles) - 1):
744 state.env.Depends(pySingles[i + 1], pySingles[i])
745 for pyTest in pyList:
746 state.env.Depends(pyTest, pySingles[-1])
748 pyList.extend(pySingles)
749 for pyTest in pyList:
750 state.env.Depends(pyTest, ccList)
751 state.env.Depends(pyTest, swigMods)
752 state.env.Depends(pyTest, state.targets["python"])
753 state.env.Depends(pyTest, state.targets["shebang"])
754 result = ccList + pyList
755 state.targets["tests"].extend(result)
756 return result
758 @staticmethod
759 def examples(ccList=None, swigNameList=None, swigSrc=None):
760 """Convenience function to replace standard examples/SConscript
761 boilerplate.
763 Parameters
764 ----------
765 ccList : `list`, optional
766 A sequence of C++ examples to build (including .cc extensions).
767 Defaults to a ``*.cc`` glob of the examples directory, minus any
768 files that end with ``*_wrap.cc`` and files present in swigSrc.
769 swigNameList : `list`, optional
770 A sequence of SWIG modules to build (NOT including .i extensions).
771 swigSrc : `list`, optional
772 Additional source files to be compiled into SWIG modules, as a
773 dictionary; each key must be an entry in swigNameList, and each
774 value a list of additional source files.
776 Returns
777 -------
778 result : ???
779 ???
780 """
781 if swigNameList is None:
782 swigFileList = Glob("*.i")
783 swigNameList = [_getFileBase(node) for node in swigFileList]
784 else:
785 swigFileList = [File(name) for name in swigNameList]
786 if swigSrc is None:
787 swigSrc = {}
788 allSwigSrc = set()
789 for name, node in zip(swigNameList, swigFileList, strict=True):
790 src = swigSrc.setdefault(name, [])
791 allSwigSrc.update(str(element) for element in src)
792 src.append(node)
793 if ccList is None:
794 ccList = [
795 node
796 for node in Glob("*.cc")
797 if (not str(node).endswith("_wrap.cc")) and str(node) not in allSwigSrc
798 ]
799 state.log.info(f"SWIG modules for examples: {swigFileList}")
800 state.log.info(f"C++ examples: {ccList}")
801 results = []
802 for src in ccList:
803 results.extend(state.env.Program(src, LIBS=state.env.getLibs("main")))
804 for name, src in swigSrc.items():
805 results.extend(
806 state.env.SwigLoadableModule("_" + name, src, LIBS=state.env.getLibs("main python"))
807 )
808 for result in results:
809 state.env.Depends(result, state.targets["lib"])
810 state.targets["examples"].extend(results)
811 return results