summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorWilliam Deegan <bill@baddogconsulting.com>2021-07-09 19:05:28 (GMT)
committerGitHub <noreply@github.com>2021-07-09 19:05:28 (GMT)
commit0b866fcf04156d1cd9101017f59a10b327ae94df (patch)
treeaf178afb84b498730491559cb80756d4260519b5
parent6c08f310bbbb21bf304862cd541858e2aa793dda (diff)
parent7486756e18f068f6df6c31c73771d86be87c1186 (diff)
downloadSCons-0b866fcf04156d1cd9101017f59a10b327ae94df.zip
SCons-0b866fcf04156d1cd9101017f59a10b327ae94df.tar.gz
SCons-0b866fcf04156d1cd9101017f59a10b327ae94df.tar.bz2
Merge branch 'master' into ninja-generation
-rw-r--r--.codecov.yml2
-rw-r--r--.travis.yml2
-rwxr-xr-xCHANGES.txt14
-rwxr-xr-xREADME-package.rst2
-rwxr-xr-xREADME.rst2
-rwxr-xr-xRELEASE.txt3
-rw-r--r--SCons/Defaults.py49
-rw-r--r--SCons/Defaults.xml29
-rw-r--r--SCons/Environment.py22
-rw-r--r--SCons/Environment.xml130
-rw-r--r--SCons/EnvironmentTests.py56
-rw-r--r--SCons/Node/FS.py11
-rw-r--r--SCons/Tool/FortranCommon.py16
-rw-r--r--SCons/Tool/MSCommon/common.py2
-rw-r--r--SCons/Tool/MSCommon/netframework.py2
-rw-r--r--SCons/Tool/MSCommon/sdk.py2
-rw-r--r--SCons/Tool/MSCommon/vc.py6
-rw-r--r--SCons/Tool/MSCommon/vs.py2
-rw-r--r--SCons/Tool/__init__.py4
-rw-r--r--SCons/Tool/install.py11
-rw-r--r--SCons/Tool/intelc.py8
-rw-r--r--SCons/Tool/linkCommon/SharedLibrary.py4
-rw-r--r--SCons/Tool/mingw.py2
-rw-r--r--SCons/Tool/swig.py24
-rw-r--r--SCons/Util.py1269
-rw-r--r--SCons/UtilTests.py100
-rw-r--r--doc/generated/functions.gen34
-rw-r--r--test/D/SharedObjects/Common/common.py17
-rw-r--r--test/Install/rec-sub-dir.py66
-rw-r--r--test/SWIG/SWIGOUTDIR.py6
-rw-r--r--test/SWIG/generated_swigfile.py23
-rw-r--r--test/_CPPINCFLAGS.py6
32 files changed, 1153 insertions, 773 deletions
diff --git a/.codecov.yml b/.codecov.yml
index 375b10f..512670b 100644
--- a/.codecov.yml
+++ b/.codecov.yml
@@ -19,7 +19,7 @@ coverage:
notify:
irc:
default:
- server: "chat.freenode.net#scons"
+ server: "irc.libera.chat#scons"
branches: master
threshold: null
message: "Coverage {{changed}} for {{owner}}/{{repo}}" # customize the message
diff --git a/.travis.yml b/.travis.yml
index 054945d..7b93019 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,7 @@
dist: xenial
language: python
-# Used: travis encrypt "chat.freenode.net#scons" --add notifications.irc
+# Used: travis encrypt "irc.libera.chat#scons" --add notifications.irc
notifications:
irc:
secure: TTb+41Bj1qIUc6vj+kDqBME8H3lqXdAe1RWAjjz5hL7bzFah6qCBHNJn4DwzqYs6+Pwuwp+6wFy8hgmQttJnXve4h6GtjtvlWprDqxaC7RkFqMWFDBzDalgbB54Bi4+TTZmSJ1K/duI3LrDaN873nyn+2GBnj+3TiNtgURp1fsJMpPxXJzAsoC8UthEsbx0Zkoal/WF+IfsT2q1yQRmAwB9r/drbahx/FfL16r1QjDbI9y1fKvN5J3PirLUvxtHfuH1r8zq1vlLew2fvldgVRtFv7+Lsk2waG/eiRpMf94V5JWP1rNreV/i4AUbZaTLb3bkrhtvTjSKhvx69Ydm+ygXdRgWOD/KRgqpLNAfA+t/a2J1R++89svQI4dPBpQjlfua1elcDCFddeIslgnjDUPO23Y0o7tHAy8sWkwhTcZH1Wm42uJP6Z6tHTH6+dMLvvZpkq4RUKUcrXvoUvCsVlWMGjcsBX+AEQSFGDJnLtLehO9x0QbgVga/IRKjgpDWgQDZgro3AkGg/zzVj5uFRUoU+rbmEXq9feh5i3HfExAvA3UoEtnQ6uadDyWqtQcLRFmPSWDU82CO+sanGdFL0jBjigE8ubPObzxEAz3Fg1xk56OYBkAdEd+2KEzeO1nqJmrhsnc3c/3+b1cBvaL5ozW4XB4XcWsOi268SoiBrcBo=
diff --git a/CHANGES.txt b/CHANGES.txt
index 2b0de50..fd316d3 100755
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -9,6 +9,12 @@ NOTE: The 4.2.0 Release of SCons will drop Python 3.5 Support
RELEASE VERSION/DATE TO BE FILLED IN LATER
+ From Byron Platt:
+ - Fix Install() issue when copytree recursion gives bad arguments that can
+ lead to install side-effects including keeping dangling symlinks and
+ silently failing to copy directories (and their subdirectories) when the
+ directory already exists in the target.
+
From Joseph Brill:
- Internal MSVS update: Remove unnecessary calls to find all installed versions of msvc
when constructing the installed visual studios list.
@@ -30,6 +36,9 @@ RELEASE VERSION/DATE TO BE FILLED IN LATER
has been fixed to libxyz.1.2.3.dylib. Additionally the sonamed symlink had the same issue,
that is now resolved as well)
- Add experimental ninja builder. (Contributed by MongoDB, Daniel Moody and many others).
+ - Fix #3955 - _LIBDIRFLAGS leaving $( and $) in *COMSTR output. Added affect_signature flag to
+ _concat function. If set to False, it will prepend and append $( and $). That way the various
+ Environment variables can use that rather than "$( _concat(...) $)".
From David H:
- Fix Issue #3906 - `IMPLICIT_COMMAND_DEPENDENCIES` was not properly disabled when
@@ -99,6 +108,11 @@ RELEASE VERSION/DATE TO BE FILLED IN LATER
SetOption equivalents to --hash-chunksize, --implicit-deps-unchanged
and --implicit-deps-changed are enabled.
- Add tests for SetOption failing on disallowed options and value types.
+ - Maintenance: eliminate lots of checker complaints about Util.py.
+ - Maintenance: fix checker-spotted issues in Environment (apply_tools)
+ and EnvironmentTests (asserts comparing with self).
+ For consistency, env.Tool() now returns a tool object the same way
+ Tool() has done.
From Dillan Mills:
- Add support for the (TARGET,SOURCE,TARGETS,SOURCES,CHANGED_TARGETS,CHANGED_SOURCES}.relpath property.
diff --git a/README-package.rst b/README-package.rst
index 4aaea1c..bc0e7ef 100755
--- a/README-package.rst
+++ b/README-package.rst
@@ -2,7 +2,7 @@ SCons - a software construction tool
####################################
.. image:: https://img.shields.io/badge/IRC-scons-blue.svg
- :target: http://webchat.freenode.net/?channels=%23scons&uio=d4
+ :target: https://web.libera.chat/#scons
:alt: IRC
.. image:: https://img.shields.io/sourceforge/dm/scons.svg
diff --git a/README.rst b/README.rst
index 219151c..cc14a01 100755
--- a/README.rst
+++ b/README.rst
@@ -2,7 +2,7 @@ SCons - a software construction tool
####################################
.. image:: https://img.shields.io/badge/IRC-scons-blue.svg
- :target: http://webchat.freenode.net/?channels=%23scons&uio=d4
+ :target: https://web.libera.chat/#scons
:alt: IRC
.. image:: https://img.shields.io/sourceforge/dm/scons.svg
diff --git a/RELEASE.txt b/RELEASE.txt
index f5c1af3..e6e870b 100755
--- a/RELEASE.txt
+++ b/RELEASE.txt
@@ -14,6 +14,9 @@ NEW FUNCTIONALITY
Fixes #396
- Added --experimental flag, to enable various experimental features/tools. You can specify
'all', 'none', or any combination of available experimental features.
+ - Added affect_signature flag to _concat function. If set to False, it will prepend and append $( and $).
+ That way the various Environment variables can use that rather than "$( _concat(...) $)".
+
DEPRECATED FUNCTIONALITY
------------------------
diff --git a/SCons/Defaults.py b/SCons/Defaults.py
index 95a2e52..3edfe7b 100644
--- a/SCons/Defaults.py
+++ b/SCons/Defaults.py
@@ -42,9 +42,9 @@ import SCons.Builder
import SCons.CacheDir
import SCons.Environment
import SCons.PathList
+import SCons.Scanner.Dir
import SCons.Subst
import SCons.Tool
-import SCons.Scanner.Dir
# A placeholder for a default Environment (for fetching source files
# from source code management systems and the like). This must be
@@ -94,13 +94,13 @@ def DefaultEnvironment(*args, **kw):
def StaticObjectEmitter(target, source, env):
for tgt in target:
tgt.attributes.shared = None
- return (target, source)
+ return target, source
def SharedObjectEmitter(target, source, env):
for tgt in target:
tgt.attributes.shared = 1
- return (target, source)
+ return target, source
def SharedFlagChecker(source, target, env):
@@ -291,7 +291,7 @@ def delete_func(dest, must_exist=0):
continue
# os.path.isdir returns True when entry is a link to a dir
if os.path.isdir(entry) and not os.path.islink(entry):
- shutil.rmtree(entry, 1)
+ shutil.rmtree(entry, True)
continue
os.unlink(entry)
@@ -312,7 +312,7 @@ def mkdir_func(dest):
Mkdir = ActionFactory(mkdir_func,
- lambda dir: 'Mkdir(%s)' % get_paths_str(dir))
+ lambda _dir: 'Mkdir(%s)' % get_paths_str(_dir))
def move_func(dest, src):
@@ -347,27 +347,38 @@ Touch = ActionFactory(touch_func,
# Internal utility functions
-
-def _concat(prefix, iter, suffix, env, f=lambda x: x, target=None, source=None):
+# pylint: disable-msg=too-many-arguments
+def _concat(prefix, items_iter, suffix, env, f=lambda x: x, target=None, source=None, affect_signature=True):
"""
- Creates a new list from 'iter' by first interpolating each element
+ Creates a new list from 'items_iter' by first interpolating each element
in the list using the 'env' dictionary and then calling f on the
list, and finally calling _concat_ixes to concatenate 'prefix' and
'suffix' onto each element of the list.
"""
- if not iter:
- return iter
- l = f(SCons.PathList.PathList(iter).subst_path(env, target, source))
+ if not items_iter:
+ return items_iter
+
+ l = f(SCons.PathList.PathList(items_iter).subst_path(env, target, source))
if l is not None:
- iter = l
+ items_iter = l
- return _concat_ixes(prefix, iter, suffix, env)
+ if not affect_signature:
+ value = ['$(']
+ else:
+ value = []
+ value += _concat_ixes(prefix, items_iter, suffix, env)
+ if not affect_signature:
+ value += ["$)"]
-def _concat_ixes(prefix, iter, suffix, env):
+ return value
+# pylint: enable-msg=too-many-arguments
+
+
+def _concat_ixes(prefix, items_iter, suffix, env):
"""
- Creates a new list from 'iter' by concatenating the 'prefix' and
+ Creates a new list from 'items_iter' by concatenating the 'prefix' and
'suffix' arguments onto each element of the list. A trailing space
on 'prefix' or leading space on 'suffix' will cause them to be put
into separate list elements rather than being concatenated.
@@ -379,7 +390,7 @@ def _concat_ixes(prefix, iter, suffix, env):
prefix = str(env.subst(prefix, SCons.Subst.SUBST_RAW))
suffix = str(env.subst(suffix, SCons.Subst.SUBST_RAW))
- for x in SCons.Util.flatten(iter):
+ for x in SCons.Util.flatten(items_iter):
if isinstance(x, SCons.Node.FS.File):
result.append(x)
continue
@@ -606,8 +617,10 @@ ConstructionEnvironment = {
'_defines': _defines,
'_stripixes': _stripixes,
'_LIBFLAGS': '${_concat(LIBLINKPREFIX, LIBS, LIBLINKSUFFIX, __env__)}',
- '_LIBDIRFLAGS': '$( ${_concat(LIBDIRPREFIX, LIBPATH, LIBDIRSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)',
- '_CPPINCFLAGS': '$( ${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)',
+
+ '_LIBDIRFLAGS': '${_concat(LIBDIRPREFIX, LIBPATH, LIBDIRSUFFIX, __env__, RDirs, TARGET, SOURCE, affect_signature=False)}',
+ '_CPPINCFLAGS': '${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE, affect_signature=False)}',
+
'_CPPDEFFLAGS': '${_defines(CPPDEFPREFIX, CPPDEFINES, CPPDEFSUFFIX, __env__, TARGET, SOURCE)}',
'__libversionflags': __libversionflags,
diff --git a/SCons/Defaults.xml b/SCons/Defaults.xml
index 33d219b..27b0882 100644
--- a/SCons/Defaults.xml
+++ b/SCons/Defaults.xml
@@ -25,18 +25,23 @@ See its __doc__ string for a discussion of the format.
<cvar name ="_concat">
<summary>
-<para>
-A function used to produce variables like &cv-link-_CPPINCFLAGS;. It takes
-four or five
-arguments: a prefix to concatenate onto each element, a list of
-elements, a suffix to concatenate onto each element, an environment
-for variable interpolation, and an optional function that will be
-called to transform the list before concatenation.
-</para>
-
-<example_commands>
-env['_CPPINCFLAGS'] = '$( ${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs)} $)',
-</example_commands>
+ <para>
+ A function used to produce variables like &cv-link-_CPPINCFLAGS;. It takes
+ four mandatory arguments, and up to 4 additional optional arguments:
+ 1) a prefix to concatenate onto each element,
+ 2) a list of elements,
+ 3) a suffix to concatenate onto each element,
+ 4) an environment for variable interpolation,
+ 5) an optional function that will be called to transform the list before concatenation,
+ 6) an optionally specified target (Can use TARGET),
+ 7) an optionally specified source (Can use SOURCE),
+ 8) optional <parameter>affect_signature</parameter> flag which will wrap non-empty returned value with $( and $) to indicate the contents
+ should not affect the signature of the generated command line.
+ </para>
+
+ <example_commands>
+ env['_CPPINCFLAGS'] = '${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE, affect_signature=False)}'
+ </example_commands>
</summary>
</cvar>
diff --git a/SCons/Environment.py b/SCons/Environment.py
index 8a31b33..4868e75 100644
--- a/SCons/Environment.py
+++ b/SCons/Environment.py
@@ -100,22 +100,23 @@ AliasBuilder = SCons.Builder.Builder(
def apply_tools(env, tools, toolpath):
# Store the toolpath in the Environment.
+ # This is expected to work even if no tools are given, so do this first.
if toolpath is not None:
env['toolpath'] = toolpath
-
if not tools:
return
+
# Filter out null tools from the list.
for tool in [_f for _f in tools if _f]:
- if is_List(tool) or isinstance(tool, tuple):
- toolname = tool[0]
- toolargs = tool[1] # should be a dict of kw args
- tool = env.Tool(toolname, **toolargs)
+ if is_List(tool) or is_Tuple(tool):
+ # toolargs should be a dict of kw args
+ toolname, toolargs, *rest = tool
+ _ = env.Tool(toolname, **toolargs)
else:
- env.Tool(tool)
+ _ = env.Tool(tool)
# These names are (or will be) controlled by SCons; users should never
-# set or override them. This warning can optionally be turned off,
+# set or override them. The warning can optionally be turned off,
# but scons will still ignore the illegal variable names even if it's off.
reserved_construction_var_names = [
'CHANGED_SOURCES',
@@ -132,7 +133,7 @@ future_reserved_construction_var_names = [
#'HOST_OS',
#'HOST_ARCH',
#'HOST_CPU',
- ]
+]
def copy_non_reserved_keywords(dict):
result = semi_deepcopy(dict)
@@ -1868,14 +1869,15 @@ class Base(SubstitutionEnvironment):
def _find_toolpath_dir(self, tp):
return self.fs.Dir(self.subst(tp)).srcnode().get_abspath()
- def Tool(self, tool, toolpath=None, **kw):
+ def Tool(self, tool, toolpath=None, **kwargs) -> SCons.Tool.Tool:
if is_String(tool):
tool = self.subst(tool)
if toolpath is None:
toolpath = self.get('toolpath', [])
toolpath = list(map(self._find_toolpath_dir, toolpath))
- tool = SCons.Tool.Tool(tool, toolpath, **kw)
+ tool = SCons.Tool.Tool(tool, toolpath, **kwargs)
tool(self)
+ return tool
def WhereIs(self, prog, path=None, pathext=None, reject=None):
"""Find prog in the path. """
diff --git a/SCons/Environment.xml b/SCons/Environment.xml
index 27e7302..c2aab51 100644
--- a/SCons/Environment.xml
+++ b/SCons/Environment.xml
@@ -2168,12 +2168,12 @@ env.MergeShellPaths({'INCLUDE': ['c:/inc1', 'c:/inc2']}, prepend=0)
</arguments>
<summary>
<para>
-Merges the specified
+Merges values from
<parameter>arg</parameter>
-values to the construction environment's construction variables.
-If the
+into &consvars; in the current &consenv;.
+If
<parameter>arg</parameter>
-argument is not a dictionary,
+is not a dictionary,
it is converted to one by calling
&f-link-env-ParseFlags;
on the argument
@@ -2191,15 +2191,15 @@ not as separate arguments to
By default,
duplicate values are eliminated;
you can, however, specify
-<literal>unique=0</literal>
+<literal>unique=False</literal>
to allow duplicate
values to be added.
When eliminating duplicate values,
-any construction variables that end with
+any &consvars; that end with
the string
<literal>PATH</literal>
keep the left-most unique value.
-All other construction variables keep
+All other &consvars; keep
the right-most unique value.
</para>
@@ -2330,38 +2330,55 @@ NoClean(env.Program('hello', 'hello.c'))
</arguments>
<summary>
<para>
-Calls the specified
-<parameter>function</parameter>
-to modify the environment as specified by the output of
-<parameter>command</parameter>.
-The default
-<parameter>function</parameter>
-is
-&f-link-env-MergeFlags;,
-which expects the output of a typical
-<application>*-config</application>
-command
-(for example,
-<application>gtk-config</application>)
-and adds the options
-to the appropriate construction variables.
+Updates the current &consenv; with the values extracted
+from the output from running external <parameter>command</parameter>,
+by calling a helper function <parameter>function</parameter>
+which understands
+the output of <parameter>command</parameter>.
+<parameter>command</parameter> may be a string
+or a list of strings representing the command and
+its arguments.
+If <parameter>function</parameter>
+is not given,
+&f-link-env-MergeFlags; is used.
By default,
duplicate values are not
added to any construction variables;
you can specify
-<literal>unique=0</literal>
-to allow duplicate
-values to be added.
+<parameter>unique=False</parameter>
+to allow duplicate values to be added.
</para>
<para>
+If &f-env-MergeFlags; is used,
+it expects a response in the style of a
+<command>*-config</command>
+command typical of the POSIX programming environment
+(for example,
+<application>gtk-config</application>)
+and adds the options
+to the appropriate construction variables.
Interpreted options
and the construction variables they affect
are as specified for the
&f-link-env-ParseFlags;
-method (which this method calls).
+method (which
+&f-env-MergeFlags; calls).
See that method's description
-for a table of options and construction variables.
+for a table of options and corresponding construction variables.
+</para>
+
+<para>
+If &f-env-MergeFlags; cannot interpret the results of
+<parameter>command</parameter>,
+you can suppply a custom
+<parameter>function</parameter> to do so.
+<parameter>function</parameter>
+must accept three arguments:
+the &consenv; to modify, the string returned
+by running <parameter>command</parameter>,
+and the optional
+<parameter>unique</parameter> flag.
</para>
</summary>
</scons_function>
@@ -2452,7 +2469,7 @@ before merging them into the construction environment.
&f-env-MergeFlags;
will call this method if its argument is not a dictionary,
so it is usually not necessary to call
-&f-link-env-ParseFlags;
+&f-env-ParseFlags;
directly unless you want to manipulate the values.)
</para>
@@ -3222,22 +3239,32 @@ source_nodes = env.subst('$EXPAND_TO_NODELIST', conv=lambda x: x)
<summary>
<para>
-Runs the tool identified by
-<parameter>name</parameter>, which is
-searched for in standard locations and any
-paths specified by the optional
-<parameter>toolpath</parameter>,
-to update a &consenv; with &consvars;
-needed to use the mechanisms that tool describes.
+Locates the tool specification module <parameter>name</parameter>
+and returns a callable tool object for that tool.
+The tool module is searched for in standard locations
+and in any paths specified by the optional
+<parameter>toolpath</parameter> parameter.
+The standard locations are &SCons;' own internal
+path for tools plus the toolpath, if any (see the
+<emphasis role="bold">Tools</emphasis> section in the manual page
+for more details).
Any additional keyword arguments
<parameter>kwargs</parameter> are passed
-on to the tool module's <function>generate</function> function.
+to the tool module's <function>generate</function> function
+during tool object construction.
</para>
<para>
-When called as a &consenv; method,
-the tool module is called to update the
-&consenv; and the name of the tool is
+When called, the tool object
+updates a &consenv; with &consvars; and arranges
+any other initialization
+needed to use the mechanisms that tool describes.
+</para>
+
+<para>
+When the &f-env-Tool; form is used,
+the tool object is automatically called to update <varname>env</varname>
+and the value of <parameter>tool</parameter> is
appended to the &cv-link-TOOLS;
&consvar; in that environment.
</para>
@@ -3252,15 +3279,16 @@ env.Tool('opengl', toolpath=['build/tools'])
</example_commands>
<para>
-When called as a global function,
-returns a callable tool object;
-the tool is not called at this time,
+When the global function &f-Tool; form is used,
+the tool object is constructed but not called,
as it lacks the context of an environment to update.
-This tool object can be passed to an
+The tool object can be passed to an
&f-link-Environment; or &f-link-Clone; call
as part of the <parameter>tools</parameter> keyword argument,
+in which case the tool is applied to the environment being constructed,
or it can be called directly,
-passing a &consenv; to update as the argument.
+in which case a &consenv; to update must be
+passed as the argument.
Either approach will also update the
&cv-TOOLS; &consvar;.
</para>
@@ -3273,11 +3301,17 @@ Examples:
env = Environment(tools=[Tool('msvc')])
env = Environment()
-t = Tool('msvc')
-t(env) # adds 'msvc' to the TOOLS variable
-u = Tool('opengl', toolpath = ['tools'])
-u(env) # adds 'opengl' to the TOOLS variable
+msvctool = Tool('msvc')
+msvctool(env) # adds 'msvc' to the TOOLS variable
+gltool = Tool('opengl', toolpath = ['tools'])
+gltool(env) # adds 'opengl' to the TOOLS variable
</example_commands>
+
+<para>
+<emphasis>Changed in &SCons; 4.2: &f-env-Tool; now returns
+the tool object, previously it did not return
+(i.e. returned <constant>None</constant>).</emphasis>
+</para>
</summary>
</scons_function>
diff --git a/SCons/EnvironmentTests.py b/SCons/EnvironmentTests.py
index 7155969..2ed897a 100644
--- a/SCons/EnvironmentTests.py
+++ b/SCons/EnvironmentTests.py
@@ -143,7 +143,7 @@ class DummyNode:
return self
def test_tool( env ):
- env['_F77INCFLAGS'] = '$( ${_concat(INCPREFIX, F77PATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
+ env['_F77INCFLAGS'] = '${_concat(INCPREFIX, F77PATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE, affect_signature=False)}'
class TestEnvironmentFixture:
def TestEnvironment(self, *args, **kw):
@@ -994,14 +994,13 @@ class BaseTestCase(unittest.TestCase,TestEnvironmentFixture):
assert called_it['source'] is None, called_it
def test_BuilderWrapper_attributes(self):
- """Test getting and setting of BuilderWrapper attributes
- """
+ """Test getting and setting of BuilderWrapper attributes."""
b1 = Builder()
b2 = Builder()
e1 = Environment()
e2 = Environment()
- e1.Replace(BUILDERS = {'b' : b1})
+ e1.Replace(BUILDERS={'b': b1})
bw = e1.b
assert bw.env is e1
@@ -1489,6 +1488,9 @@ def exists(env):
assert x == 'prea bsuf', x
x = s("${_concat(PRE, LIST, SUF, __env__)}")
assert x == 'preasuf prebsuf', x
+ x = s("${_concat(PRE, LIST, SUF, __env__,affect_signature=False)}", raw=True)
+ assert x == '$( preasuf prebsuf $)', x
+
def test_concat_nested(self):
"""Test _concat() on a nested substitution strings."""
@@ -1790,39 +1792,39 @@ def exists(env):
assert result == ['bar'], result
def test_Clone(self):
- """Test construction environment copying
+ """Test construction environment cloning.
- Update the copy independently afterwards and check that
+ The clone should compare equal if there are no overrides.
+ Update the clone independently afterwards and check that
the original remains intact (that is, no dangling
references point to objects in the copied environment).
Clone the original with some construction variable
updates and check that the original remains intact
and the copy has the updated values.
"""
- env1 = self.TestEnvironment(XXX = 'x', YYY = 'y')
+ env1 = self.TestEnvironment(XXX='x', YYY='y')
env2 = env1.Clone()
env1copy = env1.Clone()
- assert env1copy == env1copy
- assert env2 == env2
+ assert env1copy == env1
+ assert env2 == env1
env2.Replace(YYY = 'yyy')
- assert env2 == env2
assert env1 != env2
assert env1 == env1copy
- env3 = env1.Clone(XXX = 'x3', ZZZ = 'z3')
- assert env3 == env3
+ env3 = env1.Clone(XXX='x3', ZZZ='z3')
+ assert env3 != env1
assert env3.Dictionary('XXX') == 'x3'
+ assert env1.Dictionary('XXX') == 'x'
assert env3.Dictionary('YYY') == 'y'
assert env3.Dictionary('ZZZ') == 'z3'
assert env1 == env1copy
- # Ensure that lists and dictionaries are
- # deep copied, but not instances.
+ # Ensure that lists and dictionaries are deep copied, but not instances
class TestA:
pass
- env1 = self.TestEnvironment(XXX=TestA(), YYY = [ 1, 2, 3 ],
- ZZZ = { 1:2, 3:4 })
- env2=env1.Clone()
+
+ env1 = self.TestEnvironment(XXX=TestA(), YYY=[1, 2, 3], ZZZ={1: 2, 3: 4})
+ env2 = env1.Clone()
env2.Dictionary('YYY').append(4)
env2.Dictionary('ZZZ')[5] = 6
assert env1.Dictionary('XXX') is env2.Dictionary('XXX')
@@ -1832,20 +1834,18 @@ def exists(env):
assert 5 not in env1.Dictionary('ZZZ')
#
- env1 = self.TestEnvironment(BUILDERS = {'b1' : Builder()})
+ env1 = self.TestEnvironment(BUILDERS={'b1': Builder()})
assert hasattr(env1, 'b1'), "env1.b1 was not set"
assert env1.b1.object == env1, "b1.object doesn't point to env1"
env2 = env1.Clone(BUILDERS = {'b2' : Builder()})
- assert env2 is env2
- assert env2 == env2
+ assert env2 != env1
assert hasattr(env1, 'b1'), "b1 was mistakenly cleared from env1"
assert env1.b1.object == env1, "b1.object was changed"
assert not hasattr(env2, 'b1'), "b1 was not cleared from env2"
assert hasattr(env2, 'b2'), "env2.b2 was not set"
assert env2.b2.object == env2, "b2.object doesn't point to env2"
- # Ensure that specifying new tools in a copied environment
- # works.
+ # Ensure that specifying new tools in a copied environment works.
def foo(env): env['FOO'] = 1
def bar(env): env['BAR'] = 2
def baz(env): env['BAZ'] = 3
@@ -2502,9 +2502,11 @@ f5: \
exc_caught = None
try:
- env.Tool('does_not_exist')
+ tool = env.Tool('does_not_exist')
except SCons.Errors.UserError:
exc_caught = 1
+ else:
+ assert isinstance(tool, SCons.Tool.Tool)
assert exc_caught, "did not catch expected UserError"
exc_caught = None
@@ -2880,10 +2882,14 @@ def generate(env):
def testFunc(env, target, source):
assert str(target[0]) == 'foo.out'
- assert 'foo1.in' in list(map(str, source)) and 'foo2.in' in list(map(str, source)), list(map(str, source))
+ srcs = list(map(str, source))
+ assert 'foo1.in' in srcs and 'foo2.in' in srcs, srcs
return 0
+
+ # avoid spurious output from action
+ act = env.Action(testFunc, cmdstr=None)
t = env.Command(target='foo.out', source=['foo1.in','foo2.in'],
- action=testFunc)[0]
+ action=act)[0]
assert t.builder is not None
assert t.builder.action.__class__.__name__ == 'FunctionAction'
t.build()
diff --git a/SCons/Node/FS.py b/SCons/Node/FS.py
index 909e5b6..5f05a86 100644
--- a/SCons/Node/FS.py
+++ b/SCons/Node/FS.py
@@ -30,28 +30,29 @@ This holds a "default_fs" variable that should be initialized with an FS
that can be used by scripts or modules looking for the canonical default.
"""
+import codecs
import fnmatch
+import importlib.util
import os
import re
import shutil
import stat
import sys
import time
-import codecs
from itertools import chain
-import importlib.util
+from typing import Optional
import SCons.Action
import SCons.Debug
-from SCons.Debug import logInstanceCreation, Trace
import SCons.Errors
import SCons.Memoize
import SCons.Node
import SCons.Node.Alias
import SCons.Subst
import SCons.Util
-from SCons.Util import hash_signature, hash_file_signature, hash_collect
import SCons.Warnings
+from SCons.Debug import logInstanceCreation, Trace
+from SCons.Util import hash_signature, hash_file_signature, hash_collect
print_duplicate = 0
@@ -3207,7 +3208,7 @@ class File(Base):
# SIGNATURE SUBSYSTEM
#
- def get_max_drift_csig(self) -> str:
+ def get_max_drift_csig(self) -> Optional[str]:
"""
Returns the content signature currently stored for this node
if it's been unmodified longer than the max_drift value, or the
diff --git a/SCons/Tool/FortranCommon.py b/SCons/Tool/FortranCommon.py
index 16b75e2..a73de5d 100644
--- a/SCons/Tool/FortranCommon.py
+++ b/SCons/Tool/FortranCommon.py
@@ -1,9 +1,3 @@
-"""SCons.Tool.FortranCommon
-
-Stuff for processing Fortran, common to all fortran dialects.
-
-"""
-
# MIT License
#
# Copyright The SCons Foundation
@@ -25,7 +19,12 @@ Stuff for processing Fortran, common to all fortran dialects.
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+"""SCons.Tool.FortranCommon
+
+Stuff for processing Fortran, common to all fortran dialects.
+
+"""
import re
import os.path
@@ -35,6 +34,7 @@ import SCons.Scanner.Fortran
import SCons.Tool
import SCons.Util
+
def isfortran(env, source):
"""Return 1 if any of code in source has fortran files in it, 0
otherwise."""
@@ -147,7 +147,7 @@ def DialectAddToEnv(env, dialect, suffixes, ppsuffixes, support_module = 0):
if 'INC%sSUFFIX' % dialect not in env:
env['INC%sSUFFIX' % dialect] = '$INCSUFFIX'
- env['_%sINCFLAGS' % dialect] = '$( ${_concat(INC%sPREFIX, %sPATH, INC%sSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' % (dialect, dialect, dialect)
+ env['_%sINCFLAGS' % dialect] = '${_concat(INC%sPREFIX, %sPATH, INC%sSUFFIX, __env__, RDirs, TARGET, SOURCE, affect_signature=False)}' % (dialect, dialect, dialect)
if support_module == 1:
env['%sCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
diff --git a/SCons/Tool/MSCommon/common.py b/SCons/Tool/MSCommon/common.py
index 81004df..9d01835 100644
--- a/SCons/Tool/MSCommon/common.py
+++ b/SCons/Tool/MSCommon/common.py
@@ -163,7 +163,7 @@ def has_reg(value):
try:
SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, value)
ret = True
- except SCons.Util.WinError:
+ except OSError:
ret = False
return ret
diff --git a/SCons/Tool/MSCommon/netframework.py b/SCons/Tool/MSCommon/netframework.py
index b40576a..5e2c33a 100644
--- a/SCons/Tool/MSCommon/netframework.py
+++ b/SCons/Tool/MSCommon/netframework.py
@@ -41,7 +41,7 @@ def find_framework_root():
try:
froot = read_reg(_FRAMEWORKDIR_HKEY_ROOT)
debug("Found framework install root in registry: {}".format(froot))
- except SCons.Util.WinError as e:
+ except OSError:
debug("Could not read reg key {}".format(_FRAMEWORKDIR_HKEY_ROOT))
return None
diff --git a/SCons/Tool/MSCommon/sdk.py b/SCons/Tool/MSCommon/sdk.py
index b76fbdd..439a7ad 100644
--- a/SCons/Tool/MSCommon/sdk.py
+++ b/SCons/Tool/MSCommon/sdk.py
@@ -78,7 +78,7 @@ class SDKDefinition:
try:
sdk_dir = read_reg(hkey)
- except SCons.Util.WinError as e:
+ except OSError:
debug('find_sdk_dir(): no SDK registry key {}'.format(repr(hkey)))
return None
diff --git a/SCons/Tool/MSCommon/vc.py b/SCons/Tool/MSCommon/vc.py
index 87a1064..66a081f 100644
--- a/SCons/Tool/MSCommon/vc.py
+++ b/SCons/Tool/MSCommon/vc.py
@@ -447,7 +447,7 @@ def find_vc_pdir(env, msvc_version):
comps = find_vc_pdir_vswhere(msvc_version, env)
if not comps:
debug('no VC found for version {}'.format(repr(msvc_version)))
- raise SCons.Util.WinError
+ raise OSError
debug('VC found: {}'.format(repr(msvc_version)))
return comps
else:
@@ -455,13 +455,13 @@ def find_vc_pdir(env, msvc_version):
try:
# ordinarily at win64, try Wow6432Node first.
comps = common.read_reg(root + 'Wow6432Node\\' + key, hkroot)
- except SCons.Util.WinError as e:
+ except OSError:
# at Microsoft Visual Studio for Python 2.7, value is not in Wow6432Node
pass
if not comps:
# not Win64, or Microsoft Visual Studio for Python 2.7
comps = common.read_reg(root + key, hkroot)
- except SCons.Util.WinError as e:
+ except OSError:
debug('no VC registry key {}'.format(repr(key)))
else:
debug('found VC in registry: {}'.format(comps))
diff --git a/SCons/Tool/MSCommon/vs.py b/SCons/Tool/MSCommon/vs.py
index cc8946f..7be7049 100644
--- a/SCons/Tool/MSCommon/vs.py
+++ b/SCons/Tool/MSCommon/vs.py
@@ -82,7 +82,7 @@ class VisualStudio:
key = root + key
try:
comps = read_reg(key)
- except SCons.Util.WinError as e:
+ except OSError:
debug('no VS registry key {}'.format(repr(key)))
else:
debug('found VS in registry: {}'.format(comps))
diff --git a/SCons/Tool/__init__.py b/SCons/Tool/__init__.py
index 63f6a59..e78e953 100644
--- a/SCons/Tool/__init__.py
+++ b/SCons/Tool/__init__.py
@@ -107,7 +107,7 @@ TOOL_ALIASES = {
class Tool:
- def __init__(self, name, toolpath=None, **kw):
+ def __init__(self, name, toolpath=None, **kwargs):
if toolpath is None:
toolpath = []
@@ -115,7 +115,7 @@ class Tool:
self.name = TOOL_ALIASES.get(name, name)
self.toolpath = toolpath + DefaultToolpath
# remember these so we can merge them into the call
- self.init_kw = kw
+ self.init_kw = kwargs
module = self._tool_module()
self.generate = module.generate
diff --git a/SCons/Tool/install.py b/SCons/Tool/install.py
index 59b4a52..97dd846 100644
--- a/SCons/Tool/install.py
+++ b/SCons/Tool/install.py
@@ -122,12 +122,17 @@ def scons_copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,
continue
# otherwise let the copy occurs. copy2 will raise an error
if os.path.isdir(srcname):
- scons_copytree(srcname, dstname, symlinks, ignore,
- copy_function, dirs_exist_ok)
+ scons_copytree(srcname, dstname, symlinks=symlinks,
+ ignore=ignore, copy_function=copy_function,
+ ignore_dangling_symlinks=ignore_dangling_symlinks,
+ dirs_exist_ok=dirs_exist_ok)
else:
copy_function(srcname, dstname)
elif os.path.isdir(srcname):
- scons_copytree(srcname, dstname, symlinks, ignore, copy_function, dirs_exist_ok)
+ scons_copytree(srcname, dstname, symlinks=symlinks,
+ ignore=ignore, copy_function=copy_function,
+ ignore_dangling_symlinks=ignore_dangling_symlinks,
+ dirs_exist_ok=dirs_exist_ok)
else:
# Will raise a SpecialFileError for unsupported file types
copy_function(srcname, dstname)
diff --git a/SCons/Tool/intelc.py b/SCons/Tool/intelc.py
index 0d07c72..ac6fa60 100644
--- a/SCons/Tool/intelc.py
+++ b/SCons/Tool/intelc.py
@@ -175,9 +175,7 @@ def get_intel_registry_value(valuename, version=None, abi=None):
except SCons.Util.RegError:
raise MissingRegistryError("%s was not found in the registry, for Intel compiler version %s, abi='%s'"%(K, version,abi))
- except SCons.Util.RegError:
- raise MissingRegistryError("%s was not found in the registry, for Intel compiler version %s, abi='%s'"%(K, version,abi))
- except SCons.Util.WinError:
+ except (SCons.Util.RegError, OSError):
raise MissingRegistryError("%s was not found in the registry, for Intel compiler version %s, abi='%s'"%(K, version,abi))
# Get the value:
@@ -201,7 +199,7 @@ def get_all_compiler_versions():
try:
k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
keyname)
- except SCons.Util.WinError:
+ except OSError:
# For version 13 or later, check for default instance UUID
if is_win64:
keyname = 'Software\\WoW6432Node\\Intel\\Suites'
@@ -210,7 +208,7 @@ def get_all_compiler_versions():
try:
k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
keyname)
- except SCons.Util.WinError:
+ except OSError:
return []
i = 0
versions = []
diff --git a/SCons/Tool/linkCommon/SharedLibrary.py b/SCons/Tool/linkCommon/SharedLibrary.py
index 6a12dd4..d18aa6b 100644
--- a/SCons/Tool/linkCommon/SharedLibrary.py
+++ b/SCons/Tool/linkCommon/SharedLibrary.py
@@ -208,11 +208,11 @@ def setup_shared_lib_logic(env):
env["SHLIBEMITTER"] = [lib_emitter, shlib_symlink_emitter]
# If it's already set, then don't overwrite.
- env["SHLIBPREFIX"] = env.get('SHLIBPREFIX',"lib")
+ env["SHLIBPREFIX"] = env.get('SHLIBPREFIX', "lib")
env["_SHLIBSUFFIX"] = "${SHLIBSUFFIX}${_SHLIBVERSION}"
env["SHLINKFLAGS"] = CLVar("$LINKFLAGS -shared")
env["SHLINKCOM"] = "$SHLINK -o $TARGET $SHLINKFLAGS $__SHLIBVERSIONFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS"
- env["SHLINKCOMSTR"] = "$SHLINKCOM"
+
env["SHLINK"] = "$LINK"
diff --git a/SCons/Tool/mingw.py b/SCons/Tool/mingw.py
index 2df3c3b..0d2bd6d 100644
--- a/SCons/Tool/mingw.py
+++ b/SCons/Tool/mingw.py
@@ -180,7 +180,7 @@ def generate(env):
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
env['RC'] = 'windres'
env['RCFLAGS'] = SCons.Util.CLVar('')
- env['RCINCFLAGS'] = '$( ${_concat(RCINCPREFIX, CPPPATH, RCINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
+ env['RCINCFLAGS'] = '${_concat(RCINCPREFIX, CPPPATH, RCINCSUFFIX, __env__, RDirs, TARGET, SOURCE, affect_signature=False)}'
env['RCINCPREFIX'] = '--include-dir '
env['RCINCSUFFIX'] = ''
env['RCCOM'] = '$RC $_CPPDEFFLAGS $RCINCFLAGS ${RCINCPREFIX} ${SOURCE.dir} $RCFLAGS -i $SOURCE -o $TARGET'
diff --git a/SCons/Tool/swig.py b/SCons/Tool/swig.py
index fa9d93b..ff0c80d 100644
--- a/SCons/Tool/swig.py
+++ b/SCons/Tool/swig.py
@@ -29,15 +29,15 @@ selection method.
"""
import os.path
-import sys
import re
import subprocess
+import sys
import SCons.Action
import SCons.Defaults
+import SCons.Node
import SCons.Tool
import SCons.Util
-import SCons.Node
import SCons.Warnings
verbose = False
@@ -194,17 +194,19 @@ def generate(env):
if 'SWIG' not in env:
env['SWIG'] = env.Detect(swigs) or swigs[0]
- env['SWIGVERSION'] = _get_swig_version(env, env['SWIG'])
- env['SWIGFLAGS'] = SCons.Util.CLVar('')
+
+ env['SWIGVERSION'] = _get_swig_version(env, env['SWIG'])
+ env['SWIGFLAGS'] = SCons.Util.CLVar('')
env['SWIGDIRECTORSUFFIX'] = '_wrap.h'
- env['SWIGCFILESUFFIX'] = '_wrap$CFILESUFFIX'
+ env['SWIGCFILESUFFIX'] = '_wrap$CFILESUFFIX'
env['SWIGCXXFILESUFFIX'] = '_wrap$CXXFILESUFFIX'
- env['_SWIGOUTDIR'] = r'${"-outdir \"%s\"" % SWIGOUTDIR}'
- env['SWIGPATH'] = []
- env['SWIGINCPREFIX'] = '-I'
- env['SWIGINCSUFFIX'] = ''
- env['_SWIGINCFLAGS'] = '$( ${_concat(SWIGINCPREFIX, SWIGPATH, SWIGINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
- env['SWIGCOM'] = '$SWIG -o $TARGET ${_SWIGOUTDIR} ${_SWIGINCFLAGS} $SWIGFLAGS $SOURCES'
+ env['_SWIGOUTDIR'] = r'${"-outdir \"%s\"" % SWIGOUTDIR}'
+ env['SWIGPATH'] = []
+ env['SWIGINCPREFIX'] = '-I'
+ env['SWIGINCSUFFIX'] = ''
+ env['_SWIGINCFLAGS'] = '${_concat(SWIGINCPREFIX, SWIGPATH, SWIGINCSUFFIX,' \
+ '__env__, RDirs, TARGET, SOURCE, affect_signature=False)}'
+ env['SWIGCOM'] = '$SWIG -o $TARGET ${_SWIGOUTDIR} ${_SWIGINCFLAGS} $SWIGFLAGS $SOURCES'
def exists(env):
swig = env.get('SWIG') or env.Detect(['swig'])
diff --git a/SCons/Util.py b/SCons/Util.py
index 4e575d5..5f521b3 100644
--- a/SCons/Util.py
+++ b/SCons/Util.py
@@ -31,7 +31,16 @@ import re
import sys
from collections import UserDict, UserList, UserString, OrderedDict
from collections.abc import MappingView
+from contextlib import suppress
from types import MethodType, FunctionType
+from typing import Optional, Union
+
+# Note: Util module cannot import other bits of SCons globally without getting
+# into import loops. Both the below modules import SCons.Util early on.
+# --> SCons.Warnings
+# --> SCons.Errors
+# Thus the local imports, which are annotated for pylint to show we mean it.
+
PYPY = hasattr(sys, 'pypy_translation_info')
@@ -40,56 +49,64 @@ PYPY = hasattr(sys, 'pypy_translation_info')
NOFILE = "SCONS_MAGIC_MISSING_FILE_STRING"
# unused?
-def dictify(keys, values, result=None):
+def dictify(keys, values, result=None) -> dict:
if result is None:
result = {}
result.update(dict(zip(keys, values)))
return result
-_altsep = os.altsep
-if _altsep is None and sys.platform == 'win32':
+_ALTSEP = os.altsep
+if _ALTSEP is None and sys.platform == 'win32':
# My ActivePython 2.0.1 doesn't set os.altsep! What gives?
- _altsep = '/'
-if _altsep:
+ _ALTSEP = '/'
+if _ALTSEP:
def rightmost_separator(path, sep):
- return max(path.rfind(sep), path.rfind(_altsep))
+ return max(path.rfind(sep), path.rfind(_ALTSEP))
else:
def rightmost_separator(path, sep):
return path.rfind(sep)
# First two from the Python Cookbook, just for completeness.
# (Yeah, yeah, YAGNI...)
-def containsAny(str, set):
- """Check whether sequence str contains ANY of the items in set."""
- for c in set:
- if c in str: return 1
- return 0
-
-def containsAll(str, set):
- """Check whether sequence str contains ALL of the items in set."""
- for c in set:
- if c not in str: return 0
- return 1
-
-def containsOnly(str, set):
- """Check whether sequence str contains ONLY items in set."""
- for c in str:
- if c not in set: return 0
- return 1
-
-def splitext(path):
- """Same as os.path.splitext() but faster."""
+def containsAny(s, pat) -> bool:
+ """Check whether string `s` contains ANY of the items in `pat`."""
+ for c in pat:
+ if c in s:
+ return True
+ return False
+
+def containsAll(s, pat) -> bool:
+ """Check whether string `s` contains ALL of the items in `pat`."""
+ for c in pat:
+ if c not in s:
+ return False
+ return True
+
+def containsOnly(s, pat) -> bool:
+ """Check whether string `s` contains ONLY items in `pat`."""
+ for c in s:
+ if c not in pat:
+ return False
+ return True
+
+
+# TODO: Verify this method is STILL faster than os.path.splitext
+def splitext(path) -> tuple:
+ """Split `path` into a (root, ext) pair.
+
+ Same as :mod:`os.path.splitext` but faster.
+ """
sep = rightmost_separator(path, os.sep)
dot = path.rfind('.')
# An ext is only real if it has at least one non-digit char
if dot > sep and not containsOnly(path[dot:], "0123456789."):
- return path[:dot],path[dot:]
- else:
- return path,""
+ return path[:dot], path[dot:]
+
+ return path, ""
+
+def updrive(path) -> str:
+ """Make the drive letter (if any) upper case.
-def updrive(path):
- """
- Make the drive letter (if any) upper case.
This is useful because Windows is inconsistent on the case
of the drive letter, which can cause inconsistencies when
calculating command signatures.
@@ -100,33 +117,20 @@ def updrive(path):
return path
class NodeList(UserList):
- """This class is almost exactly like a regular list of Nodes
+ """A list of Nodes with special attribute retrieval.
+
+ This class is almost exactly like a regular list of Nodes
(actually it can hold any object), with one important difference.
If you try to get an attribute from this list, it will return that
attribute from every item in the list. For example:
- >>> someList = NodeList([ ' foo ', ' bar ' ])
+ >>> someList = NodeList([' foo ', ' bar '])
>>> someList.strip()
- [ 'foo', 'bar' ]
+ ['foo', 'bar']
"""
-# def __init__(self, initlist=None):
-# self.data = []
-# # print("TYPE:%s"%type(initlist))
-# if initlist is not None:
-# # XXX should this accept an arbitrary sequence?
-# if type(initlist) == type(self.data):
-# self.data[:] = initlist
-# elif isinstance(initlist, (UserList, NodeList)):
-# self.data[:] = initlist.data[:]
-# elif isinstance(initlist, Iterable):
-# self.data = list(initlist)
-# else:
-# self.data = [ initlist,]
-
-
def __bool__(self):
- return len(self.data) != 0
+ return bool(self.data)
def __str__(self):
return ' '.join(map(str, self.data))
@@ -155,38 +159,45 @@ class NodeList(UserList):
# Expand the slice object using range()
# limited by number of items in self.data
indices = index.indices(len(self.data))
- return self.__class__([self[x] for x in
- range(*indices)])
- else:
- # Return one item of the tart
- return self.data[index]
+ return self.__class__([self[x] for x in range(*indices)])
+
+ # Return one item of the tart
+ return self.data[index]
_get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$')
-def get_environment_var(varstr):
- """Given a string, first determine if it looks like a reference
- to a single environment variable, like "$FOO" or "${FOO}".
- If so, return that variable with no decorations ("FOO").
- If not, return None."""
- mo=_get_env_var.match(to_String(varstr))
+def get_environment_var(varstr) -> Optional[str]:
+ """Return undecorated construction variable string.
+
+ Determine if `varstr` looks like a reference
+ to a single environment variable, like `"$FOO"` or `"${FOO}"`.
+ If so, return that variable with no decorations, like `"FOO"`.
+ If not, return `None`.
+ """
+
+ mo = _get_env_var.match(to_String(varstr))
if mo:
var = mo.group(1)
if var[0] == '{':
return var[1:-1]
- else:
- return var
- else:
- return None
+ return var
+
+ return None
class DisplayEngine:
+ """A callable class used to display SCons messages."""
+
print_it = True
def __call__(self, text, append_newline=1):
if not self.print_it:
return
- if append_newline: text = text + '\n'
+
+ if append_newline:
+ text = text + '\n'
+
try:
sys.stdout.write(str(text))
except IOError:
@@ -203,16 +214,18 @@ class DisplayEngine:
self.print_it = mode
+# TODO: W0102: Dangerous default value [] as argument (dangerous-default-value)
def render_tree(root, child_func, prune=0, margin=[0], visited=None):
- """
- Render a tree of nodes into an ASCII tree view.
-
- :Parameters:
- - `root`: the root node of the tree
- - `child_func`: the function called to get the children of a node
- - `prune`: don't visit the same node twice
- - `margin`: the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe.
- - `visited`: a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune.
+ """Render a tree of nodes into an ASCII tree view.
+
+ Args:
+ root: the root node of the tree
+ child_func: the function called to get the children of a node
+ prune: don't visit the same node twice
+ margin: the format of the left margin to use for children of `root`.
+ 1 results in a pipe, and 0 results in no pipe.
+ visited: a dictionary of visited nodes in the current branch if
+ `prune` is 0, or in the whole tree if `prune` is 1.
"""
rname = str(root)
@@ -235,16 +248,21 @@ def render_tree(root, child_func, prune=0, margin=[0], visited=None):
retval = retval + "+-" + rname + "\n"
if not prune:
visited = copy.copy(visited)
- visited[rname] = 1
+ visited[rname] = True
- for i in range(len(children)):
+ for i, child in enumerate(children):
margin.append(i < len(children)-1)
- retval = retval + render_tree(children[i], child_func, prune, margin, visited)
+ retval = retval + render_tree(child, child_func, prune, margin, visited)
margin.pop()
return retval
-IDX = lambda N: N and 1 or 0
+def IDX(n) -> bool:
+ """Generate in index into strings from the tree legends.
+
+ These are always a choice between two, so bool works fine.
+ """
+ return bool(n)
# unicode line drawing chars:
BOX_HORIZ = chr(0x2500) # '─'
@@ -257,25 +275,37 @@ BOX_VERT_RIGHT = chr(0x251c) # '├'
BOX_HORIZ_DOWN = chr(0x252c) # '┬'
-def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None, lastChild=False, singleLineDraw=False):
- """
- Print a tree of nodes. This is like render_tree, except it prints
- lines directly instead of creating a string representation in memory,
- so that huge trees can be printed.
-
- :Parameters:
- - `root` - the root node of the tree
- - `child_func` - the function called to get the children of a node
- - `prune` - don't visit the same node twice
- - `showtags` - print status information to the left of each node line
- - `margin` - the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe.
- - `visited` - a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune.
- - `singleLineDraw` - use line-drawing characters rather than ASCII.
+# TODO: W0102: Dangerous default value [] as argument (dangerous-default-value)
+def print_tree(
+ root,
+ child_func,
+ prune=0,
+ showtags=False,
+ margin=[0],
+ visited=None,
+ lastChild=False,
+ singleLineDraw=False,
+):
+ """Print a tree of nodes.
+
+ This is like func:`render_tree`, except it prints lines directly instead
+ of creating a string representation in memory, so that huge trees can
+ be handled.
+
+ Args:
+ root: the root node of the tree
+ child_func: the function called to get the children of a node
+ prune: don't visit the same node twice
+ showtags: print status information to the left of each node line
+ margin: the format of the left margin to use for children of `root`.
+ 1 results in a pipe, and 0 results in no pipe.
+ visited: a dictionary of visited nodes in the current branch if
+ prune` is 0, or in the whole tree if `prune` is 1.
+ singleLineDraw: use line-drawing characters rather than ASCII.
"""
rname = str(root)
-
# Initialize 'visited' dict, if required
if visited is None:
visited = {}
@@ -319,14 +349,11 @@ def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None,
def MMM(m):
if singleLineDraw:
return [" ", BOX_VERT + " "][m]
- else:
- return [" ", "| "][m]
- margins = list(map(MMM, margin[:-1]))
+ return [" ", "| "][m]
+ margins = list(map(MMM, margin[:-1]))
children = child_func(root)
-
-
cross = "+-"
if singleLineDraw:
cross = BOX_VERT_RIGHT + BOX_HORIZ # sign used to point to the leaf.
@@ -353,15 +380,26 @@ def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None,
# if this item has children:
if children:
- margin.append(1) # Initialize margin with 1 for vertical bar.
+ margin.append(1) # Initialize margin with 1 for vertical bar.
idx = IDX(showtags)
- _child = 0 # Initialize this for the first child.
+ _child = 0 # Initialize this for the first child.
for C in children[:-1]:
- _child = _child + 1 # number the children
- print_tree(C, child_func, prune, idx, margin, visited, (len(children) - _child) <= 0 ,singleLineDraw)
- margin[-1] = 0 # margins are with space (index 0) because we arrived to the last child.
- print_tree(children[-1], child_func, prune, idx, margin, visited, True ,singleLineDraw) # for this call child and nr of children needs to be set 0, to signal the second phase.
- margin.pop() # destroy the last margin added
+ _child = _child + 1 # number the children
+ print_tree(
+ C,
+ child_func,
+ prune,
+ idx,
+ margin,
+ visited,
+ (len(children) - _child) <= 0,
+ singleLineDraw,
+ )
+ # margins are with space (index 0) because we arrived to the last child.
+ margin[-1] = 0
+ # for this call child and nr of children needs to be set 0, to signal the second phase.
+ print_tree(children[-1], child_func, prune, idx, margin, visited, True, singleLineDraw)
+ margin.pop() # destroy the last margin added
# Functions for deciding if things are like various types, mainly to
@@ -377,6 +415,9 @@ def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None,
# the global functions and constants used by these functions. This
# transforms accesses to global variable into local variables
# accesses (i.e. LOAD_FAST instead of LOAD_GLOBAL).
+# Since checkers dislike this, it's now annotated for pylint to flag
+# (mostly for other readers of this code) we're doing this intentionally.
+# TODO: PY3 check these are still valid choices for all of these funcs.
DictTypes = (dict, UserDict)
ListTypes = (list, UserList)
@@ -384,31 +425,49 @@ ListTypes = (list, UserList)
# Handle getting dictionary views.
SequenceTypes = (list, tuple, UserList, MappingView)
-# TODO: PY3 check this benchmarking is still correct.
# Note that profiling data shows a speed-up when comparing
# explicitly with str instead of simply comparing
# with basestring. (at least on Python 2.5.1)
+# TODO: PY3 check this benchmarking is still correct.
StringTypes = (str, UserString)
# Empirically, it is faster to check explicitly for str than for basestring.
BaseStringTypes = str
-def is_Dict(obj, isinstance=isinstance, DictTypes=DictTypes):
+def is_Dict( # pylint: disable=redefined-outer-name,redefined-builtin
+ obj, isinstance=isinstance, DictTypes=DictTypes
+) -> bool:
return isinstance(obj, DictTypes)
-def is_List(obj, isinstance=isinstance, ListTypes=ListTypes):
+
+def is_List( # pylint: disable=redefined-outer-name,redefined-builtin
+ obj, isinstance=isinstance, ListTypes=ListTypes
+) -> bool:
return isinstance(obj, ListTypes)
-def is_Sequence(obj, isinstance=isinstance, SequenceTypes=SequenceTypes):
+
+def is_Sequence( # pylint: disable=redefined-outer-name,redefined-builtin
+ obj, isinstance=isinstance, SequenceTypes=SequenceTypes
+) -> bool:
return isinstance(obj, SequenceTypes)
-def is_Tuple(obj, isinstance=isinstance, tuple=tuple):
+
+def is_Tuple( # pylint: disable=redefined-builtin
+ obj, isinstance=isinstance, tuple=tuple
+) -> bool:
return isinstance(obj, tuple)
-def is_String(obj, isinstance=isinstance, StringTypes=StringTypes):
+
+def is_String( # pylint: disable=redefined-outer-name,redefined-builtin
+ obj, isinstance=isinstance, StringTypes=StringTypes
+) -> bool:
return isinstance(obj, StringTypes)
-def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes):
+
+def is_Scalar( # pylint: disable=redefined-outer-name,redefined-builtin
+ obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes
+) -> bool:
+
# Profiling shows that there is an impressive speed-up of 2x
# when explicitly checking for strings instead of just not
# sequence when the argument (i.e. obj) is already a string.
@@ -417,21 +476,33 @@ def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes
# assumes that the obj argument is a string most of the time.
return isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes)
-def do_flatten(sequence, result, isinstance=isinstance,
- StringTypes=StringTypes, SequenceTypes=SequenceTypes):
+
+def do_flatten(
+ sequence,
+ result,
+ isinstance=isinstance,
+ StringTypes=StringTypes,
+ SequenceTypes=SequenceTypes,
+): # pylint: disable=redefined-outer-name,redefined-builtin
for item in sequence:
if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
result.append(item)
else:
do_flatten(item, result)
-def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
- SequenceTypes=SequenceTypes, do_flatten=do_flatten):
+
+def flatten( # pylint: disable=redefined-outer-name,redefined-builtin
+ obj,
+ isinstance=isinstance,
+ StringTypes=StringTypes,
+ SequenceTypes=SequenceTypes,
+ do_flatten=do_flatten,
+) -> list:
"""Flatten a sequence to a non-nested list.
- Flatten() converts either a single scalar or a nested sequence
- to a non-nested list. Note that flatten() considers strings
- to be scalars instead of sequences like Python would.
+ Converts either a single scalar or a nested sequence to a non-nested list.
+ Note that :func:`flatten` considers strings
+ to be scalars instead of sequences like pure Python would.
"""
if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes):
return [obj]
@@ -443,13 +514,19 @@ def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
do_flatten(item, result)
return result
-def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes,
- SequenceTypes=SequenceTypes, do_flatten=do_flatten):
+
+def flatten_sequence( # pylint: disable=redefined-outer-name,redefined-builtin
+ sequence,
+ isinstance=isinstance,
+ StringTypes=StringTypes,
+ SequenceTypes=SequenceTypes,
+ do_flatten=do_flatten,
+) -> list:
"""Flatten a sequence to a non-nested list.
- Same as flatten(), but it does not handle the single scalar
- case. This is slightly more efficient when one knows that
- the sequence to flatten can not be a scalar.
+ Same as :func:`flatten`, but it does not handle the single scalar case.
+ This is slightly more efficient when one knows that the sequence
+ to flatten can not be a scalar.
"""
result = []
for item in sequence:
@@ -462,41 +539,58 @@ def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes,
# Generic convert-to-string functions. The wrapper
# to_String_for_signature() will use a for_signature() method if the
# specified object has one.
-#
+def to_String( # pylint: disable=redefined-outer-name,redefined-builtin
+ obj,
+ isinstance=isinstance,
+ str=str,
+ UserString=UserString,
+ BaseStringTypes=BaseStringTypes,
+) -> str:
+ """Return a string version of obj."""
-def to_String(s,
- isinstance=isinstance, str=str,
- UserString=UserString, BaseStringTypes=BaseStringTypes):
- if isinstance(s, BaseStringTypes):
+ if isinstance(obj, BaseStringTypes):
# Early out when already a string!
- return s
- elif isinstance(s, UserString):
- # s.data can only be a regular string. Please see the UserString initializer.
- return s.data
- else:
- return str(s)
+ return obj
+
+ if isinstance(obj, UserString):
+ # obj.data can only be a regular string. Please see the UserString initializer.
+ return obj.data
+ return str(obj)
-def to_String_for_subst(s,
- isinstance=isinstance, str=str, to_String=to_String,
- BaseStringTypes=BaseStringTypes, SequenceTypes=SequenceTypes,
- UserString=UserString):
+def to_String_for_subst( # pylint: disable=redefined-outer-name,redefined-builtin
+ obj,
+ isinstance=isinstance,
+ str=str,
+ BaseStringTypes=BaseStringTypes,
+ SequenceTypes=SequenceTypes,
+ UserString=UserString,
+) -> str:
+ """Return a string version of obj for subst usage."""
# Note that the test cases are sorted by order of probability.
- if isinstance(s, BaseStringTypes):
- return s
- elif isinstance(s, SequenceTypes):
- return ' '.join([to_String_for_subst(e) for e in s])
- elif isinstance(s, UserString):
- # s.data can only a regular string. Please see the UserString initializer.
- return s.data
- else:
- return str(s)
+ if isinstance(obj, BaseStringTypes):
+ return obj
+
+ if isinstance(obj, SequenceTypes):
+ return ' '.join([to_String_for_subst(e) for e in obj])
+
+ if isinstance(obj, UserString):
+ # obj.data can only a regular string. Please see the UserString initializer.
+ return obj.data
+ return str(obj)
+
+def to_String_for_signature( # pylint: disable=redefined-outer-name,redefined-builtin
+ obj, to_String_for_subst=to_String_for_subst, AttributeError=AttributeError
+) -> str:
+ """Return a string version of obj for signature usage.
+
+ Like :func:`to_String_for_subst` but has special handling for
+ scons objects that have a :meth:`for_signature` method, and for dicts.
+ """
-def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst,
- AttributeError=AttributeError):
try:
f = obj.for_signature
except AttributeError:
@@ -506,8 +600,7 @@ def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst,
# which was undefined until py3.6 (where it's by insertion order) was not wise.
# TODO: Change code when floor is raised to PY36
return pprint.pformat(obj, width=1000000)
- else:
- return to_String_for_subst(obj)
+ return to_String_for_subst(obj)
else:
return f()
@@ -525,71 +618,65 @@ def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst,
# The dispatch table approach used here is a direct rip-off from the
# normal Python copy module.
-_semi_deepcopy_dispatch = d = {}
-
-def semi_deepcopy_dict(x, exclude = [] ):
- copy = {}
- for key, val in x.items():
- # The regular Python copy.deepcopy() also deepcopies the key,
- # as follows:
- #
- # copy[semi_deepcopy(key)] = semi_deepcopy(val)
- #
- # Doesn't seem like we need to, but we'll comment it just in case.
- if key not in exclude:
- copy[key] = semi_deepcopy(val)
- return copy
-d[dict] = semi_deepcopy_dict
-
-def _semi_deepcopy_list(x):
- return list(map(semi_deepcopy, x))
-d[list] = _semi_deepcopy_list
-
-def _semi_deepcopy_tuple(x):
- return tuple(map(semi_deepcopy, x))
-d[tuple] = _semi_deepcopy_tuple
-
-def semi_deepcopy(x):
- copier = _semi_deepcopy_dispatch.get(type(x))
+def semi_deepcopy_dict(obj, exclude=None) -> dict:
+ if exclude is None:
+ exclude = []
+ return {k: semi_deepcopy(v) for k, v in obj.items() if k not in exclude}
+
+def _semi_deepcopy_list(obj) -> list:
+ return [semi_deepcopy(item) for item in obj]
+
+def _semi_deepcopy_tuple(obj) -> tuple:
+ return tuple(map(semi_deepcopy, obj))
+
+_semi_deepcopy_dispatch = {
+ dict: semi_deepcopy_dict,
+ list: _semi_deepcopy_list,
+ tuple: _semi_deepcopy_tuple,
+}
+
+def semi_deepcopy(obj):
+ copier = _semi_deepcopy_dispatch.get(type(obj))
if copier:
- return copier(x)
- else:
- if hasattr(x, '__semi_deepcopy__') and callable(x.__semi_deepcopy__):
- return x.__semi_deepcopy__()
- elif isinstance(x, UserDict):
- return x.__class__(semi_deepcopy_dict(x))
- elif isinstance(x, UserList):
- return x.__class__(_semi_deepcopy_list(x))
+ return copier(obj)
- return x
+ if hasattr(obj, '__semi_deepcopy__') and callable(obj.__semi_deepcopy__):
+ return obj.__semi_deepcopy__()
+
+ if isinstance(obj, UserDict):
+ return obj.__class__(semi_deepcopy_dict(obj))
+
+ if isinstance(obj, UserList):
+ return obj.__class__(_semi_deepcopy_list(obj))
+
+ return obj
class Proxy:
- """A simple generic Proxy class, forwarding all calls to
- subject. So, for the benefit of the python newbie, what does
- this really mean? Well, it means that you can take an object, let's
- call it 'objA', and wrap it in this Proxy class, with a statement
- like this
+ """A simple generic Proxy class, forwarding all calls to subject.
- proxyObj = Proxy(objA),
+ This means you can take an object, let's call it `'obj_a`,
+ and wrap it in this Proxy class, with a statement like this::
- Then, if in the future, you do something like this
+ proxy_obj = Proxy(obj_a)
- x = proxyObj.var1,
+ Then, if in the future, you do something like this::
- since Proxy does not have a 'var1' attribute (but presumably objA does),
- the request actually is equivalent to saying
+ x = proxy_obj.var1
- x = objA.var1
+ since the :class:`Proxy` class does not have a :attr:`var1` attribute
+ (but presumably `objA` does), the request actually is equivalent to saying::
+
+ x = obj_a.var1
Inherit from this class to create a Proxy.
- Note that, with new-style classes, this does *not* work transparently
- for Proxy subclasses that use special .__*__() method names, because
- those names are now bound to the class, not the individual instances.
- You now need to know in advance which .__*__() method names you want
- to pass on to the underlying Proxy object, and specifically delegate
- their calls like this:
+ With Python 3.5+ this does *not* work transparently
+ for :class:`Proxy` subclasses that use special .__*__() method names,
+ because those names are now bound to the class, not the individual
+ instances. You now need to know in advance which special method names you
+ want to pass on to the underlying Proxy object, and specifically delegate
+ their calls like this::
class Foo(Proxy):
__str__ = Delegate('__str__')
@@ -600,8 +687,11 @@ class Proxy:
self._subject = subject
def __getattr__(self, name):
- """Retrieve an attribute from the wrapped object. If the named
- attribute doesn't exist, AttributeError is raised"""
+ """Retrieve an attribute from the wrapped object.
+
+ Raises:
+ AttributeError: if attribute `name` doesn't exist.
+ """
return getattr(self._subject, name)
def get(self):
@@ -616,7 +706,7 @@ class Proxy:
class Delegate:
"""A Python Descriptor class that delegates attribute fetches
- to an underlying wrapped subject of a Proxy. Typical use:
+ to an underlying wrapped subject of a Proxy. Typical use::
class Foo(Proxy):
__str__ = Delegate('__str__')
@@ -627,8 +717,8 @@ class Delegate:
def __get__(self, obj, cls):
if isinstance(obj, cls):
return getattr(obj._subject, self.attribute)
- else:
- return self
+
+ return self
class MethodWrapper:
@@ -637,7 +727,7 @@ class MethodWrapper:
As part of creating this MethodWrapper object an attribute with the
specified name (by default, the name of the supplied method) is added
to the underlying object. When that new "method" is called, our
- __call__() method adds the object as the first argument, simulating
+ :meth:`__call__` method adds the object as the first argument, simulating
the Python behavior of supplying "self" on method calls.
We hang on to the name by which the method was added to the underlying
@@ -645,10 +735,10 @@ class MethodWrapper:
a new underlying object being copied (without which we wouldn't need
to save that info).
"""
- def __init__(self, object, method, name=None):
+ def __init__(self, obj, method, name=None):
if name is None:
name = method.__name__
- self.object = object
+ self.object = obj
self.method = method
self.name = name
setattr(self.object, name, self)
@@ -666,71 +756,58 @@ class MethodWrapper:
# attempt to load the windows registry module:
-can_read_reg = 0
+can_read_reg = False
try:
import winreg
- can_read_reg = 1
+ can_read_reg = True
hkey_mod = winreg
- RegOpenKeyEx = winreg.OpenKeyEx
- RegEnumKey = winreg.EnumKey
- RegEnumValue = winreg.EnumValue
- RegQueryValueEx = winreg.QueryValueEx
- RegError = winreg.error
-
except ImportError:
class _NoError(Exception):
pass
RegError = _NoError
+if can_read_reg:
+ HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT
+ HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE
+ HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER
+ HKEY_USERS = hkey_mod.HKEY_USERS
-# Make sure we have a definition of WindowsError so we can
-# run platform-independent tests of Windows functionality on
-# platforms other than Windows. (WindowsError is, in fact, an
-# OSError subclass on Windows.)
-
-class PlainWindowsError(OSError):
- pass
+ RegOpenKeyEx = winreg.OpenKeyEx
+ RegEnumKey = winreg.EnumKey
+ RegEnumValue = winreg.EnumValue
+ RegQueryValueEx = winreg.QueryValueEx
+ RegError = winreg.error
-try:
- WinError = WindowsError
-except NameError:
- WinError = PlainWindowsError
+ def RegGetValue(root, key):
+ r"""Returns a registry value without having to open the key first.
+ Only available on Windows platforms with a version of Python that
+ can read the registry.
-if can_read_reg:
- HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT
- HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE
- HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER
- HKEY_USERS = hkey_mod.HKEY_USERS
+ Returns the same thing as :func:`RegQueryValueEx`, except you just
+ specify the entire path to the value, and don't have to bother
+ opening the key first. So, instead of::
- def RegGetValue(root, key):
- r"""This utility function returns a value in the registry
- without having to open the key first. Only available on
- Windows platforms with a version of Python that can read the
- registry. Returns the same thing as
- SCons.Util.RegQueryValueEx, except you just specify the entire
- path to the value, and don't have to bother opening the key
- first. So:
-
- Instead of:
k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Windows\CurrentVersion')
- out = SCons.Util.RegQueryValueEx(k,
- 'ProgramFilesDir')
+ out = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir')
+
+ You can write::
- You can write:
out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir')
"""
# I would use os.path.split here, but it's not a filesystem
# path...
p = key.rfind('\\') + 1
- keyp = key[:p-1] # -1 to omit trailing slash
+ keyp = key[: p - 1] # -1 to omit trailing slash
val = key[p:]
k = RegOpenKeyEx(root, keyp)
- return RegQueryValueEx(k,val)
+ return RegQueryValueEx(k, val)
+
+
else:
HKEY_CLASSES_ROOT = None
HKEY_LOCAL_MACHINE = None
@@ -738,14 +815,15 @@ else:
HKEY_USERS = None
def RegGetValue(root, key):
- raise WinError
+ raise OSError
def RegOpenKeyEx(root, key):
- raise WinError
+ raise OSError
+
if sys.platform == 'win32':
- def WhereIs(file, path=None, pathext=None, reject=None):
+ def WhereIs(file, path=None, pathext=None, reject=None) -> Optional[str]:
if path is None:
try:
path = os.environ['PATH']
@@ -768,8 +846,8 @@ if sys.platform == 'win32':
reject = []
if not is_List(reject) and not is_Tuple(reject):
reject = [reject]
- for dir in path:
- f = os.path.join(dir, file)
+ for p in path:
+ f = os.path.join(p, file)
for ext in pathext:
fext = f + ext
if os.path.isfile(fext):
@@ -782,7 +860,7 @@ if sys.platform == 'win32':
elif os.name == 'os2':
- def WhereIs(file, path=None, pathext=None, reject=None):
+ def WhereIs(file, path=None, pathext=None, reject=None) -> Optional[str]:
if path is None:
try:
path = os.environ['PATH']
@@ -800,8 +878,8 @@ elif os.name == 'os2':
reject = []
if not is_List(reject) and not is_Tuple(reject):
reject = [reject]
- for dir in path:
- f = os.path.join(dir, file)
+ for p in path:
+ f = os.path.join(p, file)
for ext in pathext:
fext = f + ext
if os.path.isfile(fext):
@@ -814,8 +892,9 @@ elif os.name == 'os2':
else:
- def WhereIs(file, path=None, pathext=None, reject=None):
- import stat
+ def WhereIs(file, path=None, pathext=None, reject=None) -> Optional[str]:
+ import stat # pylint: disable=import-outside-toplevel
+
if path is None:
try:
path = os.environ['PATH']
@@ -827,8 +906,8 @@ else:
reject = []
if not is_List(reject) and not is_Tuple(reject):
reject = [reject]
- for d in path:
- f = os.path.join(d, file)
+ for p in path:
+ f = os.path.join(p, file)
if os.path.isfile(f):
try:
st = os.stat(f)
@@ -846,35 +925,53 @@ else:
continue
return None
-def PrependPath(oldpath, newpath, sep = os.pathsep,
- delete_existing=1, canonicalize=None):
- """This prepends newpath elements to the given oldpath. Will only
- add any particular path once (leaving the first one it encounters
- and ignoring the rest, to preserve path order), and will
- os.path.normpath and os.path.normcase all paths to help assure
- this. This can also handle the case where the given old path
- variable is a list instead of a string, in which case a list will
- be returned instead of a string.
-
- Example:
- Old Path: "/foo/bar:/foo"
- New Path: "/biz/boom:/foo"
- Result: "/biz/boom:/foo:/foo/bar"
-
- If delete_existing is 0, then adding a path that exists will
- not move it to the beginning; it will stay where it is in the
- list.
-
- If canonicalize is not None, it is applied to each element of
- newpath before use.
+WhereIs.__doc__ = """\
+Return the path to an executable that matches `file`.
+
+Searches the given `path` for `file`, respecting any filename
+extensions `pathext` (on the Windows platform only), and
+returns the full path to the matching command. If no
+command is found, return ``None``.
+
+If `path` is not specified, :attr:`os.environ[PATH]` is used.
+If `pathext` is not specified, :attr:`os.environ[PATHEXT]`
+is used. Will not select any path name or names in the optional
+`reject` list.
+"""
+
+def PrependPath(
+ oldpath, newpath, sep=os.pathsep, delete_existing=True, canonicalize=None
+) -> Union[list, str]:
+ """Prepends `newpath` path elements to `oldpath`.
+
+ Will only add any particular path once (leaving the first one it
+ encounters and ignoring the rest, to preserve path order), and will
+ :mod:`os.path.normpath` and :mod:`os.path.normcase` all paths to help
+ assure this. This can also handle the case where `oldpath`
+ is a list instead of a string, in which case a list will be returned
+ instead of a string. For example:
+
+ >>> p = PrependPath("/foo/bar:/foo", "/biz/boom:/foo")
+ >>> print(p)
+ /biz/boom:/foo:/foo/bar
+
+ If `delete_existing` is ``False``, then adding a path that exists will
+ not move it to the beginning; it will stay where it is in the list.
+
+ >>> p = PrependPath("/foo/bar:/foo", "/biz/boom:/foo", delete_existing=False)
+ >>> print(p)
+ /biz/boom:/foo/bar:/foo
+
+ If `canonicalize` is not ``None``, it is applied to each element of
+ `newpath` before use.
"""
orig = oldpath
- is_list = 1
+ is_list = True
paths = orig
if not is_List(orig) and not is_Tuple(orig):
paths = paths.split(sep)
- is_list = 0
+ is_list = False
if is_String(newpath):
newpaths = newpath.split(sep)
@@ -925,42 +1022,47 @@ def PrependPath(oldpath, newpath, sep = os.pathsep,
if is_list:
return paths
- else:
- return sep.join(paths)
-
-def AppendPath(oldpath, newpath, sep = os.pathsep,
- delete_existing=1, canonicalize=None):
- """This appends new path elements to the given old path. Will
- only add any particular path once (leaving the last one it
- encounters and ignoring the rest, to preserve path order), and
- will os.path.normpath and os.path.normcase all paths to help
- assure this. This can also handle the case where the given old
- path variable is a list instead of a string, in which case a list
- will be returned instead of a string.
- Example:
- Old Path: "/foo/bar:/foo"
- New Path: "/biz/boom:/foo"
- Result: "/foo/bar:/biz/boom:/foo"
+ return sep.join(paths)
- If delete_existing is 0, then adding a path that exists
+def AppendPath(
+ oldpath, newpath, sep=os.pathsep, delete_existing=True, canonicalize=None
+) -> Union[list, str]:
+ """Appends `newpath` path elements to `oldpath`.
+
+ Will only add any particular path once (leaving the last one it
+ encounters and ignoring the rest, to preserve path order), and will
+ :mod:`os.path.normpath` and :mod:`os.path.normcase` all paths to help
+ assure this. This can also handle the case where `oldpath`
+ is a list instead of a string, in which case a list will be returned
+ instead of a string. For example:
+
+ >>> p = AppendPath("/foo/bar:/foo", "/biz/boom:/foo")
+ >>> print(p)
+ /foo/bar:/biz/boom:/foo
+
+ If `delete_existing` is ``False``, then adding a path that exists
will not move it to the end; it will stay where it is in the list.
- If canonicalize is not None, it is applied to each element of
- newpath before use.
+ >>> p = AppendPath("/foo/bar:/foo", "/biz/boom:/foo", delete_existing=False)
+ >>> print(p)
+ /foo/bar:/foo:/biz/boom
+
+ If `canonicalize` is not ``None``, it is applied to each element of
+ `newpath` before use.
"""
orig = oldpath
- is_list = 1
+ is_list = True
paths = orig
if not is_List(orig) and not is_Tuple(orig):
paths = paths.split(sep)
- is_list = 0
+ is_list = False
if is_String(newpath):
newpaths = newpath.split(sep)
elif not is_List(newpath) and not is_Tuple(newpath):
- newpaths = [ newpath ] # might be a Dir
+ newpaths = [newpath] # might be a Dir
else:
newpaths = newpath
@@ -1006,22 +1108,29 @@ def AppendPath(oldpath, newpath, sep = os.pathsep,
if is_list:
return paths
- else:
- return sep.join(paths)
+
+ return sep.join(paths)
def AddPathIfNotExists(env_dict, key, path, sep=os.pathsep):
- """This function will take 'key' out of the dictionary
- 'env_dict', then add the path 'path' to that key if it is not
- already there. This treats the value of env_dict[key] as if it
- has a similar format to the PATH variable...a list of paths
- separated by tokens. The 'path' will get added to the list if it
- is not already there."""
+ """Add a path element to a construction variable.
+
+ `key` is looked up in `env_dict`, and `path` is added to it if it
+ is not already present. `env_dict[key]` is assumed to be in the
+ format of a PATH variable: a list of paths separated by `sep` tokens.
+ Example:
+
+ >>> env = {'PATH': '/bin:/usr/bin:/usr/local/bin'}
+ >>> AddPathIfNotExists(env, 'PATH', '/opt/bin')
+ >>> print(env['PATH'])
+ /opt/bin:/bin:/usr/bin:/usr/local/bin
+ """
+
try:
- is_list = 1
+ is_list = True
paths = env_dict[key]
if not is_List(env_dict[key]):
paths = paths.split(sep)
- is_list = 0
+ is_list = False
if os.path.normcase(path) not in list(map(os.path.normcase, paths)):
paths = [ path ] + paths
if is_list:
@@ -1032,50 +1141,79 @@ def AddPathIfNotExists(env_dict, key, path, sep=os.pathsep):
env_dict[key] = path
if sys.platform == 'cygwin':
- def get_native_path(path):
- """Transforms an absolute path into a native path for the system. In
- Cygwin, this converts from a Cygwin path to a Windows one."""
- with os.popen('cygpath -w ' + path) as p:
- npath = p.read().replace('\n', '')
- return npath
+ import subprocess # pylint: disable=import-outside-toplevel
+
+ def get_native_path(path) -> str:
+ cp = subprocess.run(('cygpath', '-w', path), check=False, stdout=subprocess.PIPE)
+ return cp.stdout.decode().replace('\n', '')
else:
- def get_native_path(path):
- """Transforms an absolute path into a native path for the system.
- Non-Cygwin version, just leave the path alone."""
+ def get_native_path(path) -> str:
return path
+get_native_path.__doc__ = """\
+Transform an absolute path into a native path for the system.
+
+In Cygwin, this converts from a Cygwin path to a Windows path,
+without regard to whether `path` refers to an existing file
+system object. For other platforms, `path` is unchanged.
+"""
+
+
display = DisplayEngine()
-def Split(arg):
+def Split(arg) -> list:
+ """Returns a list of file names or other objects.
+
+ If `arg` is a string, it will be split on strings of white-space
+ characters within the string. If `arg` is already a list, the list
+ will be returned untouched. If `arg` is any other type of object,
+ it will be returned as a list containing just the object.
+
+ >>> print(Split(" this is a string "))
+ ['this', 'is', 'a', 'string']
+ >>> print(Split(["stringlist", " preserving ", " spaces "]))
+ ['stringlist', ' preserving ', ' spaces ']
+ """
if is_List(arg) or is_Tuple(arg):
return arg
- elif is_String(arg):
+
+ if is_String(arg):
return arg.split()
- else:
- return [arg]
+
+ return [arg]
class CLVar(UserList):
- """A class for command-line construction variables.
-
- Forces the use of a list of strings, matching individual arguments
- that will be issued on the command line. Like UserList,
- but the argument passed to __init__ will be processed by the
- Split function, which includes special handling for string types -
- they will be split into a list of words, not coereced directly
- to a list. The same happens if adding a string,
- which allows us to Do the Right Thing with Append() and
- Prepend() (as well as straight Python foo = env['VAR'] + 'arg1
- arg2') regardless of whether a user adds a list or a string to a
- command-line construction variable.
+ """A container for command-line construction variables.
+
+ Forces the use of a list of strings intended as command-line
+ arguments. Like :class:`collections.UserList`, but the argument
+ passed to the initializter will be processed by the :func:`Split`
+ function, which includes special handling for string types: they
+ will be split into a list of words, not coereced directly to a list.
+ The same happens if a string is added to a :class:`CLVar`,
+ which allows doing the right thing with both
+ :func:`Append`/:func:`Prepend` methods,
+ as well as with pure Python addition, regardless of whether adding
+ a list or a string to a construction variable.
Side effect: spaces will be stripped from individual string
arguments. If you need spaces preserved, pass strings containing
spaces inside a list argument.
+
+ >>> u = UserList("--some --opts and args")
+ >>> print(len(u), repr(u))
+ 22 ['-', '-', 's', 'o', 'm', 'e', ' ', '-', '-', 'o', 'p', 't', 's', ' ', 'a', 'n', 'd', ' ', 'a', 'r', 'g', 's']
+ >>> c = CLVar("--some --opts and args")
+ >>> print(len(c), repr(c))
+ 4 ['--some', '--opts', 'and', 'args']
+ >>> c += " strips spaces "
+ >>> print(len(c), repr(c))
+ 6 ['--some', '--opts', 'and', 'args', 'strips', 'spaces']
"""
- def __init__(self, seq=[]):
- super().__init__(Split(seq))
+ def __init__(self, initlist=None):
+ super().__init__(Split(initlist))
def __add__(self, other):
return super().__add__(CLVar(other))
@@ -1093,7 +1231,8 @@ class CLVar(UserList):
class Selector(OrderedDict):
"""A callable ordered dictionary that maps file suffixes to
dictionary values. We preserve the order in which items are added
- so that get_suffix() calls always return the first suffix added."""
+ so that :func:`get_suffix` calls always return the first suffix added.
+ """
def __call__(self, env, source, ext=None):
if ext is None:
try:
@@ -1128,32 +1267,34 @@ class Selector(OrderedDict):
if sys.platform == 'cygwin':
# On Cygwin, os.path.normcase() lies, so just report back the
# fact that the underlying Windows OS is case-insensitive.
- def case_sensitive_suffixes(s1, s2):
- return 0
+ def case_sensitive_suffixes(s1, s2) -> bool: # pylint: disable=unused-argument
+ return False
+
else:
- def case_sensitive_suffixes(s1, s2):
- return (os.path.normcase(s1) != os.path.normcase(s2))
+ def case_sensitive_suffixes(s1, s2) -> bool:
+ return os.path.normcase(s1) != os.path.normcase(s2)
-def adjustixes(fname, pre, suf, ensure_suffix=False):
- """
- Add prefix to file if specified.
- Add suffix to file if specified and if ensure_suffix = True
+def adjustixes(fname, pre, suf, ensure_suffix=False) -> str:
+ """Adjust filename prefixes and suffixes as needed.
+ Add `prefix` to `fname` if specified.
+ Add `suffix` to `fname` if specified and if `ensure_suffix` is ``True``
"""
+
if pre:
path, fn = os.path.split(os.path.normpath(fname))
# Handle the odd case where the filename = the prefix.
# In that case, we still want to add the prefix to the file
- if fn[:len(pre)] != pre or fn == pre:
+ if not fn.startswith(pre) or fn == pre:
fname = os.path.join(path, pre + fn)
# Only append a suffix if the suffix we're going to add isn't already
# there, and if either we've been asked to ensure the specific suffix
# is present or there's no suffix on it at all.
# Also handle the odd case where the filename = the suffix.
# in that case we still want to append the suffix
- if suf and fname[-len(suf):] != suf and \
+ if suf and not fname.endswith(suf) and \
(ensure_suffix or not splitext(fname)[1]):
fname = fname + suf
return fname
@@ -1164,14 +1305,20 @@ def adjustixes(fname, pre, suf, ensure_suffix=False):
# https://code.activestate.com/recipes/52560
# ASPN: Python Cookbook: Remove duplicates from a sequence
# (Also in the printed Python Cookbook.)
+# Updated. This algorithm is used by some scanners and tools.
-def unique(s):
- """Return a list of the elements in s, but without duplicates.
+def unique(seq):
+ """Return a list of the elements in seq without duplicates, ignoring order.
- For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
- unique("abcabc") some permutation of ["a", "b", "c"], and
- unique(([1, 2], [2, 3], [1, 2])) some permutation of
- [[2, 3], [1, 2]].
+ >>> mylist = unique([1, 2, 3, 1, 2, 3])
+ >>> print(sorted(mylist))
+ [1, 2, 3]
+ >>> mylist = unique("abcabc")
+ >>> print(sorted(mylist))
+ ['a', 'b', 'c']
+ >>> mylist = unique(([1, 2], [2, 3], [1, 2]))
+ >>> print(sorted(mylist))
+ [[1, 2], [2, 3]]
For best speed, all sequence elements should be hashable. Then
unique() will usually work in linear time.
@@ -1182,41 +1329,33 @@ def unique(s):
usually work in O(N*log2(N)) time.
If that's not possible either, the sequence elements must support
- equality-testing. Then unique() will usually work in quadratic
- time.
+ equality-testing. Then unique() will usually work in quadratic time.
"""
- n = len(s)
- if n == 0:
+ if not seq:
return []
# Try using a dict first, as that's the fastest and will usually
# work. If it doesn't work, it will usually fail quickly, so it
# usually doesn't cost much to *try* it. It requires that all the
# sequence elements be hashable, and support equality comparison.
- u = {}
- try:
- for x in s:
- u[x] = 1
- except TypeError:
- pass # move on to the next method
- else:
- return list(u.keys())
- del u
+ # TODO: should be even faster: return(list(set(seq)))
+ with suppress(TypeError):
+ return list(dict.fromkeys(seq))
- # We can't hash all the elements. Second fastest is to sort,
- # which brings the equal elements together; then duplicates are
- # easy to weed out in a single pass.
+ # We couldn't hash all the elements (got a TypeError).
+ # Next fastest is to sort, which brings the equal elements together;
+ # then duplicates are easy to weed out in a single pass.
# NOTE: Python's list.sort() was designed to be efficient in the
# presence of many duplicate elements. This isn't true of all
# sort functions in all languages or libraries, so this approach
# is more effective in Python than it may be elsewhere.
+ n = len(seq)
try:
- t = sorted(s)
+ t = sorted(seq)
except TypeError:
pass # move on to the next method
else:
- assert n > 0
last = t[0]
lasti = i = 1
while i < n:
@@ -1225,11 +1364,10 @@ def unique(s):
lasti = lasti + 1
i = i + 1
return t[:lasti]
- del t
# Brute force is all that's left.
u = []
- for x in s:
+ for x in seq:
if x not in u:
u.append(x)
return u
@@ -1260,7 +1398,7 @@ def uniquer(seq, idfun=None):
# A more efficient implementation of Alex's uniquer(), this avoids the
# idfun() argument and function-call overhead by assuming that all
-# items in the sequence are hashable.
+# items in the sequence are hashable. Order-preserving.
def uniquer_hashables(seq):
seen = {}
@@ -1295,140 +1433,176 @@ def logical_lines(physical_lines, joiner=''.join):
class LogicalLines:
""" Wrapper class for the logical_lines method.
- Allows us to read all "logical" lines at once from a
- given file object.
+ Allows us to read all "logical" lines at once from a given file object.
"""
def __init__(self, fileobj):
self.fileobj = fileobj
def readlines(self):
- result = [l for l in logical_lines(self.fileobj)]
- return result
+ return list(logical_lines(self.fileobj))
class UniqueList(UserList):
- def __init__(self, seq = []):
- UserList.__init__(self, seq)
+ """A list which maintains uniqueness.
+
+ Uniquing is lazy: rather than being assured on list changes, it is fixed
+ up on access by those methods which need to act on a uniqe list to be
+ correct. That means things like "in" don't have to eat the uniquing time.
+ """
+ def __init__(self, initlist=None):
+ super().__init__(initlist)
self.unique = True
+
def __make_unique(self):
if not self.unique:
self.data = uniquer_hashables(self.data)
self.unique = True
+
+ def __repr__(self):
+ self.__make_unique()
+ return super().__repr__()
+
def __lt__(self, other):
self.__make_unique()
- return UserList.__lt__(self, other)
+ return super().__lt__(other)
+
def __le__(self, other):
self.__make_unique()
- return UserList.__le__(self, other)
+ return super().__le__(other)
+
def __eq__(self, other):
self.__make_unique()
- return UserList.__eq__(self, other)
+ return super().__eq__(other)
+
def __ne__(self, other):
self.__make_unique()
- return UserList.__ne__(self, other)
+ return super().__ne__(other)
+
def __gt__(self, other):
self.__make_unique()
- return UserList.__gt__(self, other)
+ return super().__gt__(other)
+
def __ge__(self, other):
self.__make_unique()
- return UserList.__ge__(self, other)
- def __cmp__(self, other):
- self.__make_unique()
- return UserList.__cmp__(self, other)
+ return super().__ge__(other)
+
+ # __contains__ doesn't need to worry about uniquing, inherit
+
def __len__(self):
self.__make_unique()
- return UserList.__len__(self)
+ return super().__len__()
+
def __getitem__(self, i):
self.__make_unique()
- return UserList.__getitem__(self, i)
+ return super().__getitem__(i)
+
def __setitem__(self, i, item):
- UserList.__setitem__(self, i, item)
+ super().__setitem__(i, item)
self.unique = False
+
+ # __delitem__ doesn't need to worry about uniquing, inherit
+
def __add__(self, other):
- result = UserList.__add__(self, other)
+ result = super().__add__(other)
result.unique = False
return result
+
def __radd__(self, other):
- result = UserList.__radd__(self, other)
+ result = super().__radd__(other)
result.unique = False
return result
+
def __iadd__(self, other):
- result = UserList.__iadd__(self, other)
+ result = super().__iadd__(other)
result.unique = False
return result
+
def __mul__(self, other):
- result = UserList.__mul__(self, other)
+ result = super().__mul__(other)
result.unique = False
return result
+
def __rmul__(self, other):
- result = UserList.__rmul__(self, other)
+ result = super().__rmul__(other)
result.unique = False
return result
+
def __imul__(self, other):
- result = UserList.__imul__(self, other)
+ result = super().__imul__(other)
result.unique = False
return result
+
def append(self, item):
- UserList.append(self, item)
+ super().append(item)
self.unique = False
- def insert(self, i):
- UserList.insert(self, i)
+
+ def insert(self, i, item):
+ super().insert(i, item)
self.unique = False
+
def count(self, item):
self.__make_unique()
- return UserList.count(self, item)
- def index(self, item):
+ return super().count(item)
+
+ def index(self, item, *args):
self.__make_unique()
- return UserList.index(self, item)
+ return super().index(item, *args)
+
def reverse(self):
self.__make_unique()
- UserList.reverse(self)
+ super().reverse()
+
+ # TODO: Py3.8: def sort(self, /, *args, **kwds):
def sort(self, *args, **kwds):
self.__make_unique()
- return UserList.sort(self, *args, **kwds)
+ return super().sort(*args, **kwds)
+
def extend(self, other):
- UserList.extend(self, other)
+ super().extend(other)
self.unique = False
class Unbuffered:
- """
- A proxy class that wraps a file object, flushing after every write,
- and delegating everything else to the wrapped object.
+ """A proxy that wraps a file object, flushing after every write.
+
+ Delegates everything else to the wrapped object.
"""
def __init__(self, file):
self.file = file
- self.softspace = 0 ## backward compatibility; not supported in Py3k
+
def write(self, arg):
- try:
+ # Stdout might be connected to a pipe that has been closed
+ # by now. The most likely reason for the pipe being closed
+ # is that the user has press ctrl-c. It this is the case,
+ # then SCons is currently shutdown. We therefore ignore
+ # IOError's here so that SCons can continue and shutdown
+ # properly so that the .sconsign is correctly written
+ # before SCons exits.
+ with suppress(IOError):
self.file.write(arg)
self.file.flush()
- except IOError:
- # Stdout might be connected to a pipe that has been closed
- # by now. The most likely reason for the pipe being closed
- # is that the user has press ctrl-c. It this is the case,
- # then SCons is currently shutdown. We therefore ignore
- # IOError's here so that SCons can continue and shutdown
- # properly so that the .sconsign is correctly written
- # before SCons exits.
- pass
+
+ def writelines(self, arg):
+ with suppress(IOError):
+ self.file.writelines(arg)
+ self.file.flush()
+
def __getattr__(self, attr):
return getattr(self.file, attr)
-def make_path_relative(path):
- """ makes an absolute path name to a relative pathname.
- """
+def make_path_relative(path) -> str:
+ """Converts an absolute path name to a relative pathname."""
+
if os.path.isabs(path):
- drive_s,path = os.path.splitdrive(path)
+ drive_s, path = os.path.splitdrive(path)
- import re
if not drive_s:
- path=re.compile("/*(.*)").findall(path)[0]
+ path=re.compile(r"/*(.*)").findall(path)[0]
else:
path=path[1:]
- assert( not os.path.isabs( path ) ), path
+ assert not os.path.isabs(path), path
return path
@@ -1460,18 +1634,23 @@ def AddMethod(obj, function, name=None):
construction environments; it is preferred to use env.AddMethod
to add to an individual environment.
- Example::
-
- class A:
- ...
- a = A()
- def f(self, x, y):
- self.z = x + y
- AddMethod(f, A, "add")
- a.add(2, 4)
- print(a.z)
- AddMethod(lambda self, i: self.l[i], a, "listIndex")
- print(a.listIndex(5))
+ >>> class A:
+ ... ...
+
+ >>> a = A()
+
+ >>> def f(self, x, y):
+ ... self.z = x + y
+
+ >>> AddMethod(A, f, "add")
+ >>> a.add(2, 4)
+ >>> print(a.z)
+ 6
+ >>> a.data = ['a', 'b', 'c', 'd', 'e', 'f']
+ >>> AddMethod(a, lambda self, i: self.data[i], "listIndex")
+ >>> print(a.listIndex(3))
+ d
+
"""
if name is None:
name = function.__name__
@@ -1496,58 +1675,63 @@ def AddMethod(obj, function, name=None):
# Default hash function and format. SCons-internal.
-_hash_function = None
-_hash_format = None
+ALLOWED_HASH_FORMATS = ['md5', 'sha1', 'sha256']
+_HASH_FUNCTION = None
+_HASH_FORMAT = None
def get_hash_format():
- """
- Retrieves the hash format or None if not overridden. A return value of None
+ """Retrieves the hash format or ``None`` if not overridden.
+
+ A return value of ``None``
does not guarantee that MD5 is being used; instead, it means that the
- default precedence order documented in SCons.Util.set_hash_format is
- respected.
+ default precedence order documented in :func:`SCons.Util.set_hash_format`
+ is respected.
"""
- return _hash_format
+ return _HASH_FORMAT
def set_hash_format(hash_format):
- """
- Sets the default hash format used by SCons. If hash_format is None or
+ """Sets the default hash format used by SCons.
+
+ If `hash_format` is ``None`` or
an empty string, the default is determined by this function.
Currently the default behavior is to use the first available format of
the following options: MD5, SHA1, SHA256.
"""
- global _hash_format, _hash_function
+ global _HASH_FORMAT, _HASH_FUNCTION
- _hash_format = hash_format
+ _HASH_FORMAT = hash_format
if hash_format:
hash_format_lower = hash_format.lower()
- allowed_hash_formats = ['md5', 'sha1', 'sha256']
- if hash_format_lower not in allowed_hash_formats:
- from SCons.Errors import UserError
+ if hash_format_lower not in ALLOWED_HASH_FORMATS:
+ from SCons.Errors import UserError # pylint: disable=import-outside-toplevel
+
raise UserError('Hash format "%s" is not supported by SCons. Only '
'the following hash formats are supported: %s' %
(hash_format_lower,
- ', '.join(allowed_hash_formats)))
+ ', '.join(ALLOWED_HASH_FORMATS)))
+
+ _HASH_FUNCTION = getattr(hashlib, hash_format_lower, None)
+ if _HASH_FUNCTION is None:
+ from SCons.Errors import UserError # pylint: disable=import-outside-toplevel
- _hash_function = getattr(hashlib, hash_format_lower, None)
- if _hash_function is None:
- from SCons.Errors import UserError
raise UserError(
- 'Hash format "%s" is not available in your Python '
- 'interpreter.' % hash_format_lower)
+ 'Hash format "%s" is not available in your Python interpreter.'
+ % hash_format_lower
+ )
else:
# Set the default hash format based on what is available, defaulting
# to md5 for backwards compatibility.
- choices = ['md5', 'sha1', 'sha256']
- for choice in choices:
- _hash_function = getattr(hashlib, choice, None)
- if _hash_function is not None:
+ for choice in ALLOWED_HASH_FORMATS:
+ _HASH_FUNCTION = getattr(hashlib, choice, None)
+ if _HASH_FUNCTION is not None:
break
else:
# This is not expected to happen in practice.
- from SCons.Errors import UserError
+ from SCons.Errors import UserError # pylint: disable=import-outside-toplevel
+
raise UserError(
'Your Python interpreter does not have MD5, SHA1, or SHA256. '
'SCons requires at least one.')
@@ -1560,34 +1744,42 @@ set_hash_format(None)
def _get_hash_object(hash_format):
- """
- Allocates a hash object using the requested hash format.
+ """Allocates a hash object using the requested hash format.
- :param hash_format: Hash format to use.
- :return: hashlib object.
+ Args:
+ hash_format: Hash format to use.
+
+ Returns:
+ hashlib object.
"""
if hash_format is None:
- if _hash_function is None:
- from SCons.Errors import UserError
+ if _HASH_FUNCTION is None:
+ from SCons.Errors import UserError # pylint: disable=import-outside-toplevel
+
raise UserError('There is no default hash function. Did you call '
'a hashing function before SCons was initialized?')
- return _hash_function()
- elif not hasattr(hashlib, hash_format):
- from SCons.Errors import UserError
+ return _HASH_FUNCTION()
+
+ if not hasattr(hashlib, hash_format):
+ from SCons.Errors import UserError # pylint: disable=import-outside-toplevel
+
raise UserError(
'Hash format "%s" is not available in your Python interpreter.' %
hash_format)
- else:
- return getattr(hashlib, hash_format)()
+
+ return getattr(hashlib, hash_format)()
def hash_signature(s, hash_format=None):
"""
Generate hash signature of a string
- :param s: either string or bytes. Normally should be bytes
- :param hash_format: Specify to override default hash format
- :return: String of hex digits representing the signature
+ Args:
+ s: either string or bytes. Normally should be bytes
+ hash_format: Specify to override default hash format
+
+ Returns:
+ String of hex digits representing the signature
"""
m = _get_hash_object(hash_format)
try:
@@ -1602,11 +1794,15 @@ def hash_file_signature(fname, chunksize=65536, hash_format=None):
"""
Generate the md5 signature of a file
- :param fname: file to hash
- :param chunksize: chunk size to read
- :param hash_format: Specify to override default hash format
- :return: String of Hex digits representing the signature
+ Args:
+ fname: file to hash
+ chunksize: chunk size to read
+ hash_format: Specify to override default hash format
+
+ Returns:
+ String of Hex digits representing the signature
"""
+
m = _get_hash_object(hash_format)
with open(fname, "rb") as f:
while True:
@@ -1621,60 +1817,60 @@ def hash_collect(signatures, hash_format=None):
"""
Collects a list of signatures into an aggregate signature.
- :param signatures: a list of signatures
- :param hash_format: Specify to override default hash format
- :return: - the aggregate signature
+ Args:
+ signatures: a list of signatures
+ hash_format: Specify to override default hash format
+
+ Returns:
+ the aggregate signature
"""
+
if len(signatures) == 1:
return signatures[0]
- else:
- return hash_signature(', '.join(signatures), hash_format)
+
+ return hash_signature(', '.join(signatures), hash_format)
-_md5_warning_shown = False
+_MD5_WARNING_SHOWN = False
def _show_md5_warning(function_name):
- """
- Shows a deprecation warning for various MD5 functions.
- """
- global _md5_warning_shown
+ """Shows a deprecation warning for various MD5 functions."""
- if not _md5_warning_shown:
- import SCons.Warnings
+ global _MD5_WARNING_SHOWN
+
+ if not _MD5_WARNING_SHOWN:
+ import SCons.Warnings # pylint: disable=import-outside-toplevel
SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning,
"Function %s is deprecated" % function_name)
- _md5_warning_shown = True
+ _MD5_WARNING_SHOWN = True
def MD5signature(s):
- """
- Deprecated. Use hash_signature instead.
- """
+ """Deprecated. Use :func:`hash_signature` instead."""
+
_show_md5_warning("MD5signature")
return hash_signature(s)
def MD5filesignature(fname, chunksize=65536):
- """
- Deprecated. Use hash_file_signature instead.
- """
+ """Deprecated. Use :func:`hash_file_signature` instead."""
+
_show_md5_warning("MD5filesignature")
return hash_file_signature(fname, chunksize)
def MD5collect(signatures):
- """
- Deprecated. Use hash_collect instead.
- """
+ """Deprecated. Use :func:`hash_collect` instead."""
+
_show_md5_warning("MD5collect")
return hash_collect(signatures)
def silent_intern(x):
"""
- Perform sys.intern() on the passed argument and return the result.
- If the input is ineligible the original argument is
+ Perform :mod:`sys.intern` on the passed argument and return the result.
+ If the input is ineligible for interning the original argument is
returned and no exception is thrown.
"""
try:
@@ -1724,7 +1920,7 @@ class NullSeq(Null):
return self
-def to_bytes(s):
+def to_bytes(s) -> bytes:
if s is None:
return b'None'
if isinstance(s, (bytes, bytearray)):
@@ -1733,7 +1929,7 @@ def to_bytes(s):
return bytes(s, 'utf-8')
-def to_str(s):
+def to_str(s) -> str:
if s is None:
return 'None'
if is_String(s):
@@ -1741,30 +1937,28 @@ def to_str(s):
return str(s, 'utf-8')
-def cmp(a, b):
- """
- Define cmp because it's no longer available in python3
- Works under python 2 as well
- """
+def cmp(a, b) -> bool:
+ """A cmp function because one is no longer available in python3."""
return (a > b) - (a < b)
-def get_env_bool(env, name, default=False):
+def get_env_bool(env, name, default=False) -> bool:
"""Convert a construction variable to bool.
- If the value of *name* in *env* is 'true', 'yes', 'y', 'on' (case
+ If the value of `name` in `env` is 'true', 'yes', 'y', 'on' (case
insensitive) or anything convertible to int that yields non-zero then
- return True; if 'false', 'no', 'n', 'off' (case insensitive)
- or a number that converts to integer zero return False.
- Otherwise, return *default*.
+ return ``True``; if 'false', 'no', 'n', 'off' (case insensitive)
+ or a number that converts to integer zero return ``False``.
+ Otherwise, return `default`.
Args:
env: construction environment, or any dict-like object
name: name of the variable
- default: value to return if *name* not in *env* or cannot
+ default: value to return if `name` not in `env` or cannot
be converted (default: False)
+
Returns:
- bool: the "truthiness" of *name*
+ the "truthiness" of `name`
"""
try:
var = env[name]
@@ -1775,21 +1969,24 @@ def get_env_bool(env, name, default=False):
except ValueError:
if str(var).lower() in ('true', 'yes', 'y', 'on'):
return True
- elif str(var).lower() in ('false', 'no', 'n', 'off'):
+
+ if str(var).lower() in ('false', 'no', 'n', 'off'):
return False
- else:
- return default
+
+ return default
-def get_os_env_bool(name, default=False):
+def get_os_env_bool(name, default=False) -> bool:
"""Convert an environment variable to bool.
Conversion is the same as for :func:`get_env_bool`.
"""
return get_env_bool(os.environ, name, default)
+
def print_time():
"""Hack to return a value from Main if can't import Main."""
+ # pylint: disable=redefined-outer-name,import-outside-toplevel
from SCons.Script.Main import print_time
return print_time
diff --git a/SCons/UtilTests.py b/SCons/UtilTests.py
index 8e39a16..6cdc2ee 100644
--- a/SCons/UtilTests.py
+++ b/SCons/UtilTests.py
@@ -32,10 +32,44 @@ import TestCmd
import SCons.Errors
import SCons.compat
-from SCons.Util import hash_signature, get_os_env_bool, get_env_bool, flatten, to_bytes, to_String, render_tree, to_str, \
- is_Dict, is_String, is_List, splitext, print_tree, is_Tuple, silent_intern, get_native_path, get_environment_var, \
- display, containsAny, containsAll, containsOnly, WhereIs, Selector, adjustixes, Proxy, AddPathIfNotExists, \
- PrependPath, NodeList, AppendPath, LogicalLines, hash_collect
+from SCons.Util import (
+ AddPathIfNotExists,
+ AppendPath,
+ CLVar,
+ LogicalLines,
+ NodeList,
+ PrependPath,
+ Proxy,
+ Selector,
+ WhereIs,
+ adjustixes,
+ containsAll,
+ containsAny,
+ containsOnly,
+ dictify,
+ display,
+ flatten,
+ get_env_bool,
+ get_environment_var,
+ get_native_path,
+ get_os_env_bool,
+ hash_collect,
+ hash_signature,
+ is_Dict,
+ is_List,
+ is_String,
+ is_Tuple,
+ print_tree,
+ render_tree,
+ silent_intern,
+ splitext,
+ to_String,
+ to_bytes,
+ to_str,
+)
+
+# These Util classes have no unit tests. Some don't make sense to test?
+# DisplayEngine, Delegate, MethodWrapper, UniqueList, Unbuffered, Null, NullSeq
class OutBuffer:
@@ -49,13 +83,13 @@ class OutBuffer:
class dictifyTestCase(unittest.TestCase):
def test_dictify(self):
"""Test the dictify() function"""
- r = SCons.Util.dictify(['a', 'b', 'c'], [1, 2, 3])
+ r = dictify(['a', 'b', 'c'], [1, 2, 3])
assert r == {'a': 1, 'b': 2, 'c': 3}, r
r = {}
- SCons.Util.dictify(['a'], [1], r)
- SCons.Util.dictify(['b'], [2], r)
- SCons.Util.dictify(['c'], [3], r)
+ dictify(['a'], [1], r)
+ dictify(['b'], [2], r)
+ dictify(['c'], [3], r)
assert r == {'a': 1, 'b': 2, 'c': 3}, r
@@ -552,115 +586,115 @@ class UtilTestCase(unittest.TestCase):
"""Test the command-line construction variable class"""
# input to CLVar is a string - should be split
- f = SCons.Util.CLVar('aa bb')
+ f = CLVar('aa bb')
r = f + 'cc dd'
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', 'cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + ' cc dd'
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', 'cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + ['cc dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', 'cc dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + [' cc dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', ' cc dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + ['cc', 'dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', 'cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + [' cc', 'dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', ' cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
# input to CLVar is a list of one string, should not be split
- f = SCons.Util.CLVar(['aa bb'])
+ f = CLVar(['aa bb'])
r = f + 'cc dd'
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa bb', 'cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + ' cc dd'
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa bb', 'cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + ['cc dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa bb', 'cc dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + [' cc dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa bb', ' cc dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + ['cc', 'dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa bb', 'cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + [' cc', 'dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa bb', ' cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
# input to CLVar is a list of strings
- f = SCons.Util.CLVar(['aa', 'bb'])
+ f = CLVar(['aa', 'bb'])
r = f + 'cc dd'
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', 'cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + ' cc dd'
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', 'cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + ['cc dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', 'cc dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + [' cc dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', ' cc dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + ['cc', 'dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', 'cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
r = f + [' cc', 'dd']
- assert isinstance(r, SCons.Util.CLVar), type(r)
+ assert isinstance(r, CLVar), type(r)
assert r.data == ['aa', 'bb', ' cc', 'dd'], r.data
assert str(r) == 'aa bb cc dd', str(r)
# make sure inplace adding a string works as well (issue 2399)
# UserList would convert the string to a list of chars
- f = SCons.Util.CLVar(['aa', 'bb'])
+ f = CLVar(['aa', 'bb'])
f += 'cc dd'
- assert isinstance(f, SCons.Util.CLVar), type(f)
+ assert isinstance(f, CLVar), type(f)
assert f.data == ['aa', 'bb', 'cc', 'dd'], f.data
assert str(f) == 'aa bb cc dd', str(f)
- f = SCons.Util.CLVar(['aa', 'bb'])
+ f = CLVar(['aa', 'bb'])
f += ' cc dd'
- assert isinstance(f, SCons.Util.CLVar), type(f)
+ assert isinstance(f, CLVar), type(f)
assert f.data == ['aa', 'bb', 'cc', 'dd'], f.data
assert str(f) == 'aa bb cc dd', str(f)
diff --git a/doc/generated/functions.gen b/doc/generated/functions.gen
index fe2f516..5554802 100644
--- a/doc/generated/functions.gen
+++ b/doc/generated/functions.gen
@@ -4282,24 +4282,31 @@ Tag('file2.txt', DOC)
<term><function>Tool</function>(<parameter>name, [toolpath, **kwargs]</parameter>)</term>
<term><replaceable>env</replaceable>.<methodname>Tool</methodname>(<parameter>name, [toolpath, **kwargs]</parameter>)</term>
<listitem><para>
-Runs the tool identified by
+Locates and possibly runs the tool identified by
<parameter>name</parameter>, which is
searched for in standard locations and any
paths specified by the optional
-<parameter>toolpath</parameter>,
-to update a &consenv; with &consvars;
+<parameter>toolpath</parameter>.
+When run, the tool
+updates a &consenv; with &consvars; and arranges
+any other initialization
needed to use the mechanisms that tool describes.
Any additional keyword arguments
<parameter>kwargs</parameter> are passed
on to the tool module's <function>generate</function> function.
+Returns a callable tool object.
</para>
<para>
-When called as a &consenv; method,
-the tool module is called to update the
-&consenv; and the name of the tool is
+When called as &f-env-Tool;,
+the tool module is called to update <varname>env</varname>
+and the <parameter>tool</parameter> is
appended to the &cv-link-TOOLS;
&consvar; in that environment.
+In this form, there is usually no need to save
+the returned tool object, since it is of no further use.
+<emphasis>Prior to &SCons; 4.2, &f-env-Tool; returned
+<constant>None</constant></emphasis>
</para>
<para>
@@ -4312,11 +4319,10 @@ env.Tool('opengl', toolpath=['build/tools'])
</example_commands>
<para>
-When called as a global function,
-returns a callable tool object;
-the tool is not called at this time,
+When called as a global function &f-Tool;,
+the tool object is constructed but not called,
as it lacks the context of an environment to update.
-This tool object can be passed to an
+The tool object can be passed to an
&f-link-Environment; or &f-link-Clone; call
as part of the <parameter>tools</parameter> keyword argument,
or it can be called directly,
@@ -4333,10 +4339,10 @@ Examples:
env = Environment(tools=[Tool('msvc')])
env = Environment()
-t = Tool('msvc')
-t(env) # adds 'msvc' to the TOOLS variable
-u = Tool('opengl', toolpath = ['tools'])
-u(env) # adds 'opengl' to the TOOLS variable
+msvctool = Tool('msvc')
+msvctool(env) # adds 'msvc' to the TOOLS variable
+gltool = Tool('opengl', toolpath = ['tools'])
+gltool(env) # adds 'opengl' to the TOOLS variable
</example_commands>
</listitem>
</varlistentry>
diff --git a/test/D/SharedObjects/Common/common.py b/test/D/SharedObjects/Common/common.py
index 1bb2d50..6a75e34 100644
--- a/test/D/SharedObjects/Common/common.py
+++ b/test/D/SharedObjects/Common/common.py
@@ -29,8 +29,9 @@ import TestSCons
from SCons.Environment import Base
+import re
+import subprocess
from os.path import abspath, dirname
-from subprocess import check_output
import sys
sys.path.insert(1, abspath(dirname(__file__) + '/../../Support'))
@@ -45,9 +46,17 @@ def testForTool(tool):
test.skip_test("Required executable for tool '{0}' not found, skipping test.\n".format(tool))
if tool == 'gdc':
- result = check_output(('gdc', '--version'))
- version = result.decode().splitlines()[0].split()[3]
- major, minor, debug = [int(x) for x in version.split('.')]
+ cp = subprocess.run(('gdc', '--version'), stdout=subprocess.PIPE)
+ # different version strings possible, i.e.:
+ # gdc (GCC) 11.1.1 20210531 (Red Hat 11.1.1-3)\nCopyright (C)...
+ # gdc (Ubuntu 10.2.0-5ubuntu1~20.04) 10.20.0\nCopyright (C)...
+ vstr = cp.stdout.decode().splitlines()[0]
+ match = re.search(r'[0-9]+(\.[0-9]+)+', vstr)
+ if match:
+ version = match.group(0)
+ major, minor, debug = [int(x) for x in version.split('.')]
+ else:
+ major = 0
if (major < 6) or (major == 6 and minor < 3):
test.skip_test('gdc prior to version 6.0.0 does not support shared libraries.\n')
diff --git a/test/Install/rec-sub-dir.py b/test/Install/rec-sub-dir.py
new file mode 100644
index 0000000..0a11928
--- /dev/null
+++ b/test/Install/rec-sub-dir.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# MIT Licenxe
+#
+# Copyright The SCons Foundation
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+"""
+Test using Install() on directory that contains existing subdirectories
+causing copytree recursion where the directory already exists.
+"""
+
+import os.path
+
+import TestSCons
+
+test = TestSCons.TestSCons()
+
+test.write('SConstruct', """\
+DefaultEnvironment(tools=[])
+Execute(Mkdir('a/b/c'))
+Execute(Mkdir('b/c/d'))
+Install('z', 'a')
+Install('z/a', 'b')
+""")
+
+expect="""\
+Mkdir("a/b/c")
+Mkdir("b/c/d")
+Install directory: "a" as "z%sa"
+Install directory: "b" as "z%sa%sb"
+""" % (os.sep, os.sep, os.sep)
+test.run(arguments=["-Q"], stdout=expect)
+
+test.must_exist(test.workpath('a', 'b', 'c'))
+test.must_exist(test.workpath('b', 'c', 'd'))
+test.must_exist(test.workpath('z', 'a', 'b', 'c', 'd'))
+
+# this run used to fail on Windows with an OS error before the copytree fix
+test.run(arguments=["-Q"])
+
+test.pass_test()
+
+# Local Variables:
+# tab-width:4
+# indent-tabs-mode:nil
+# End:
+# vim: set expandtab tabstop=4 shiftwidth=4:
diff --git a/test/SWIG/SWIGOUTDIR.py b/test/SWIG/SWIGOUTDIR.py
index 10b1575..6b600d7 100644
--- a/test/SWIG/SWIGOUTDIR.py
+++ b/test/SWIG/SWIGOUTDIR.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python
+# MIT License
#
-# __COPYRIGHT__
+# Copyright The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -20,9 +21,6 @@
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-
-__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify that use of the $SWIGOUTDIR variable causes SCons to recognize
diff --git a/test/SWIG/generated_swigfile.py b/test/SWIG/generated_swigfile.py
index 145349b..8d2a2c9 100644
--- a/test/SWIG/generated_swigfile.py
+++ b/test/SWIG/generated_swigfile.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python
+# MIT License
#
-# __COPYRIGHT__
+# Copyright The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -20,9 +21,6 @@
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-
-__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify that SCons realizes the -noproxy option means no .py file will
@@ -38,14 +36,8 @@ import TestSCons
if sys.platform == 'win32':
_dll = '.dll'
else:
- _dll = '.so'
+ _dll = '.so'
-# swig-python expects specific filenames.
-# the platform specific suffix won't necessarily work.
-if sys.platform == 'win32':
- _dll = '.dll'
-else:
- _dll = '.so'
test = TestSCons.TestSCons()
@@ -54,12 +46,11 @@ if not swig:
test.skip_test('Can not find installed "swig", skipping test.\n')
python, python_include, python_libpath, python_lib = \
- test.get_platform_python_info(python_h_required=True)
+ test.get_platform_python_info(python_h_required=True)
# handle testing on other platforms:
ldmodule_prefix = '_'
-
test.write('SConstruct', """
foo = Environment(CPPPATH=[r'%(python_include)s'],
SWIG=[r'%(swig)s'],
@@ -69,7 +60,6 @@ python_interface = foo.Command( 'test_py_swig.i', Value(1), 'echo %%module test_
python_c_file = foo.CFile( target='python_swig_test',source=python_interface, SWIGFLAGS = '-python -c++' )
java_interface = foo.Command( 'test_java_swig.i', Value(1),'echo %%module test_java_swig > test_java_swig.i' )
java_c_file = foo.CFile( target='java_swig_test' ,source=java_interface, SWIGFLAGS = '-java -c++' )
-
""" % locals())
expected_stdout = """\
@@ -78,12 +68,11 @@ echo %%module test_java_swig > test_java_swig.i
echo %%module test_py_swig > test_py_swig.i
%(swig)s -o python_swig_test_wrap.cc -python -c++ test_py_swig.i
""" % locals()
-test.run(arguments = '.',stdout=test.wrap_stdout(expected_stdout))
-
+test.run(arguments='.', stdout=test.wrap_stdout(expected_stdout))
# If we mistakenly depend on the .py file that SWIG didn't create
# (suppressed by the -noproxy option) then the build won't be up-to-date.
-test.up_to_date(arguments = '.')
+test.up_to_date(arguments='.')
test.pass_test()
diff --git a/test/_CPPINCFLAGS.py b/test/_CPPINCFLAGS.py
index c5096ba..8bb8261 100644
--- a/test/_CPPINCFLAGS.py
+++ b/test/_CPPINCFLAGS.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python
+# MIT License
#
-# __COPYRIGHT__
+# Copyright The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -20,9 +21,6 @@
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-
-__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test that we can expand $_CPPINCFLAGS correctly regardless of whether