From 846518d598325c08e6c98dc2d30f1cbeee0e730b Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Tue, 4 May 2021 11:29:40 -0600 Subject: Fix checker-spotted issues in Environment apply_tools If tools is a list, it is looped over, calling Tool on each; that call overwrote the loop variable - since Tool() doesn't return any value anyway just eliminate the assignment. EnvironmentTests had some asserts comparing with self, which is pointless. Tried to determine what this should be to be meaningful. Also quieted one test which got a default action string, unit tests normally just print a row of dots and here it was putting out text which interrupted the flow of dots. Signed-off-by: Mats Wichmann --- CHANGES.txt | 2 ++ SCons/Environment.py | 13 +++++++------ SCons/EnvironmentTests.py | 40 +++++++++++++++++++++------------------- 3 files changed, 30 insertions(+), 25 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 6a817ba..71921f5 100755 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -98,6 +98,8 @@ 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: fix checker-spotted issues in Environment (apply_tools) + and EnvironmentTests (asserts comparing with self) From Dillan Mills: - Add support for the (TARGET,SOURCE,TARGETS,SOURCES,CHANGED_TARGETS,CHANGED_SOURCES}.relpath property. diff --git a/SCons/Environment.py b/SCons/Environment.py index 8a31b33..a324a82 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): + if is_List(tool) or is_Tuple(tool): toolname = tool[0] - toolargs = tool[1] # should be a dict of kw args - tool = env.Tool(toolname, **toolargs) + toolargs = tool[1] # should be a dict of kw args + env.Tool(toolname, **toolargs) else: 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) diff --git a/SCons/EnvironmentTests.py b/SCons/EnvironmentTests.py index 7155969..73a788b 100644 --- a/SCons/EnvironmentTests.py +++ b/SCons/EnvironmentTests.py @@ -1004,9 +1004,9 @@ class BaseTestCase(unittest.TestCase,TestEnvironmentFixture): e1.Replace(BUILDERS = {'b' : b1}) bw = e1.b - assert bw.env is e1 + assert bw.env == e1 bw.env = e2 - assert bw.env is e2 + assert bw.env == e2 assert bw.builder is b1 bw.builder = b2 @@ -1790,9 +1790,10 @@ 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 @@ -1802,27 +1803,26 @@ def exists(env): 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 + 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') @@ -1836,16 +1836,14 @@ def exists(env): 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 @@ -2880,10 +2878,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() -- cgit v0.12 From 91aa64d0d5d7803d9fe13e12554988253456da76 Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Sun, 23 May 2021 11:41:29 -0600 Subject: Update env.Tool behavior and doc Review comments suggested for consistency env.Tool should also return the Tool instance. Signed-off-by: Mats Wichmann --- CHANGES.txt | 6 ++++-- SCons/Environment.py | 11 ++++++----- SCons/Environment.xml | 34 ++++++++++++++++++++-------------- SCons/EnvironmentTests.py | 4 +++- doc/generated/functions.gen | 38 ++++++++++++++++++++++---------------- 5 files changed, 55 insertions(+), 38 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 71921f5..864095b 100755 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -98,8 +98,10 @@ 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: fix checker-spotted issues in Environment (apply_tools) - and EnvironmentTests (asserts comparing with self) + - 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/SCons/Environment.py b/SCons/Environment.py index a324a82..2f2c8b2 100644 --- a/SCons/Environment.py +++ b/SCons/Environment.py @@ -109,11 +109,11 @@ def apply_tools(env, tools, toolpath): # Filter out null tools from the list. for tool in [_f for _f in tools if _f]: if is_List(tool) or is_Tuple(tool): - toolname = tool[0] - toolargs = tool[1] # should be a dict of kw args - env.Tool(toolname, **toolargs) + # 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. The warning can optionally be turned off, @@ -1869,7 +1869,7 @@ 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, **kw) -> SCons.Tool.Tool: if is_String(tool): tool = self.subst(tool) if toolpath is None: @@ -1877,6 +1877,7 @@ class Base(SubstitutionEnvironment): toolpath = list(map(self._find_toolpath_dir, toolpath)) tool = SCons.Tool.Tool(tool, toolpath, **kw) 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..66a2c1a 100644 --- a/SCons/Environment.xml +++ b/SCons/Environment.xml @@ -3222,24 +3222,31 @@ source_nodes = env.subst('$EXPAND_TO_NODELIST', conv=lambda x: x) -Runs the tool identified by +Locates and possibly runs the tool identified by name, which is searched for in standard locations and any paths specified by the optional -toolpath, -to update a &consenv; with &consvars; +toolpath. +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 kwargs are passed on to the tool module's generate function. +Returns a callable tool object. -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 env +and the value of tool 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. +Prior to &SCons; 4.2, &f-env-Tool; returned +None @@ -3252,11 +3259,10 @@ env.Tool('opengl', toolpath=['build/tools']) -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 tools keyword argument, or it can be called directly, @@ -3273,10 +3279,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 diff --git a/SCons/EnvironmentTests.py b/SCons/EnvironmentTests.py index 73a788b..553b5e8 100644 --- a/SCons/EnvironmentTests.py +++ b/SCons/EnvironmentTests.py @@ -2500,9 +2500,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 diff --git a/doc/generated/functions.gen b/doc/generated/functions.gen index 1af4bae..a43ed1a 100644 --- a/doc/generated/functions.gen +++ b/doc/generated/functions.gen @@ -13,8 +13,8 @@ - Action(action, [cmd/str/fun, [var, ...]] [option=value, ...]) - env.Action(action, [cmd/str/fun, [var, ...]] [option=value, ...]) + Action(action, [output, [var, ...]] [key=value, ...]) + env.Action(action, [output, [var, ...]] [key=value, ...]) A factory function to create an Action object for the specified @@ -4248,24 +4248,31 @@ Tag('file2.txt', DOC) Tool(name, [toolpath, **kwargs]) env.Tool(name, [toolpath, **kwargs]) -Runs the tool identified by +Locates and possibly runs the tool identified by name, which is searched for in standard locations and any paths specified by the optional -toolpath, -to update a &consenv; with &consvars; +toolpath. +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 kwargs are passed on to the tool module's generate function. +Returns a callable tool object. -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 env +and the tool 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. +Prior to &SCons; 4.2, &f-env-Tool; returned +None @@ -4278,11 +4285,10 @@ env.Tool('opengl', toolpath=['build/tools']) -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 tools keyword argument, or it can be called directly, @@ -4299,10 +4305,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 -- cgit v0.12 From ef0b9aae9604f07104d6daf11e94bd844b7cf39f Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Mon, 24 May 2021 07:34:48 -0600 Subject: Tweak env.Tool documentation for clarity Review comments pointed out some issues with the exsiting change proposal, rearranged and reworded some things. Signed-off-by: Mats Wichmann --- SCons/Environment.py | 4 ++-- SCons/Environment.xml | 47 +++++++++++++++++++++++++++++------------------ SCons/Tool/__init__.py | 4 ++-- 3 files changed, 33 insertions(+), 22 deletions(-) diff --git a/SCons/Environment.py b/SCons/Environment.py index 2f2c8b2..4868e75 100644 --- a/SCons/Environment.py +++ b/SCons/Environment.py @@ -1869,13 +1869,13 @@ 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) -> SCons.Tool.Tool: + 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 diff --git a/SCons/Environment.xml b/SCons/Environment.xml index 66a2c1a..79af6bc 100644 --- a/SCons/Environment.xml +++ b/SCons/Environment.xml @@ -3222,31 +3222,34 @@ source_nodes = env.subst('$EXPAND_TO_NODELIST', conv=lambda x: x) -Locates and possibly runs the tool identified by -name, which is -searched for in standard locations and any -paths specified by the optional -toolpath. -When run, the tool +Locates the tool specification module name +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 +toolpath parameter. +The standard locations are &SCons;' own internal +path for tools plus the toolpath, if any (see the +Tools section in the manual page +for more details). +Any additional keyword arguments +kwargs are passed +to the tool module's generate function +during tool object construction. + + + +When called, the tool object updates a &consenv; with &consvars; and arranges any other initialization needed to use the mechanisms that tool describes. -Any additional keyword arguments -kwargs are passed -on to the tool module's generate function. -Returns a callable tool object. -When called as &f-env-Tool;, -the tool module is called to update env +When the &f-env-Tool; form is used, +the tool object is automatically called to update env and the value of tool 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. -Prior to &SCons; 4.2, &f-env-Tool; returned -None @@ -3259,14 +3262,16 @@ env.Tool('opengl', toolpath=['build/tools']) -When called as a global function &f-Tool;, +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. The tool object can be passed to an &f-link-Environment; or &f-link-Clone; call as part of the tools 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;. @@ -3284,6 +3289,12 @@ msvctool(env) # adds 'msvc' to the TOOLS variable gltool = Tool('opengl', toolpath = ['tools']) gltool(env) # adds 'opengl' to the TOOLS variable + + +Changed in &SCons; 4.2: &f-env-Tool; now returns +the tool object, previously it did not return +(i.e. returned None). + 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 -- cgit v0.12 From 69dcebbd2deb8cb0fbb37be550362a1f1aa78666 Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Sat, 5 Jun 2021 06:33:19 -0600 Subject: Reduce pylint complaints about Util Fix up UniqueList - remves a Py2-era method and correct args on others; add a __repr__ which does the uniquing. Add "we know what we're doing" pylint comments on apparent redefinitions of builtins and globals that the type tests and type converters do. Add some more pylint comments on "local" (rather than top of file) imports. Remove WindowsError reference (necessitated changing some tool code as well) - partial fix for #3939, WinodwsError is no longer distinct Simplified semi-deepcopy stuff (and quieted complaints) Add class docstrings and fixup some docstrings. AddMethod examples had reversed arguments - now rendered as a doctest, and actually works. Fixed up other examples to (mostly) be doctest as well. Signed-off-by: Mats Wichmann --- CHANGES.txt | 1 + SCons/Tool/MSCommon/common.py | 2 +- SCons/Tool/MSCommon/netframework.py | 2 +- SCons/Tool/MSCommon/sdk.py | 2 +- SCons/Tool/MSCommon/vc.py | 6 +- SCons/Tool/MSCommon/vs.py | 2 +- SCons/Tool/intelc.py | 8 +- SCons/Util.py | 1132 ++++++++++++++++++++--------------- SCons/UtilTests.py | 100 +++- 9 files changed, 714 insertions(+), 541 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 6a817ba..7709a9a 100755 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -98,6 +98,7 @@ 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. From Dillan Mills: - Add support for the (TARGET,SOURCE,TARGETS,SOURCES,CHANGED_TARGETS,CHANGED_SOURCES}.relpath property. 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/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/Util.py b/SCons/Util.py index 4e575d5..54cd786 100644 --- a/SCons/Util.py +++ b/SCons/Util.py @@ -31,8 +31,15 @@ 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 +# Note: Util module cannot import other bits of SCons globally without getting +# into import loops. Both the below modules import SCons.Util early on. +# Thus the local imports, which are annotated for pylint to show we mean it. +# import SCons.Warnings +# from SCons.Errors import UserError + PYPY = hasattr(sys, 'pypy_translation_info') # this string will be hashed if a Node refers to a file that doesn't exist @@ -46,50 +53,56 @@ def dictify(keys, values, result=None): 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 + +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,31 +113,18 @@ 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 @@ -155,38 +155,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 + """Return undecorated construction variable string. + + 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)) + 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: @@ -204,15 +211,16 @@ class DisplayEngine: 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 +243,16 @@ 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 +IDX = lambda N: bool(N) # unicode line drawing chars: BOX_HORIZ = chr(0x2500) # '─' @@ -257,25 +265,36 @@ 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. +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 +338,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 +369,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 +404,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 +414,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( + obj, isinstance=isinstance, DictTypes=DictTypes +): # pylint: disable=redefined-outer-name,redefined-builtin return isinstance(obj, DictTypes) -def is_List(obj, isinstance=isinstance, ListTypes=ListTypes): + +def is_List( + obj, isinstance=isinstance, ListTypes=ListTypes +): # pylint: disable=redefined-outer-name,redefined-builtin return isinstance(obj, ListTypes) -def is_Sequence(obj, isinstance=isinstance, SequenceTypes=SequenceTypes): + +def is_Sequence( + obj, isinstance=isinstance, SequenceTypes=SequenceTypes +): # pylint: disable=redefined-outer-name,redefined-builtin return isinstance(obj, SequenceTypes) -def is_Tuple(obj, isinstance=isinstance, tuple=tuple): + +def is_Tuple( + obj, isinstance=isinstance, tuple=tuple +): # pylint: disable=redefined-builtin return isinstance(obj, tuple) -def is_String(obj, isinstance=isinstance, StringTypes=StringTypes): + +def is_String( + obj, isinstance=isinstance, StringTypes=StringTypes +): # pylint: disable=redefined-outer-name,redefined-builtin return isinstance(obj, StringTypes) -def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes): + +def is_Scalar( + obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes +): # pylint: disable=redefined-outer-name,redefined-builtin + # 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 +465,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( + obj, + isinstance=isinstance, + StringTypes=StringTypes, + SequenceTypes=SequenceTypes, + do_flatten=do_flatten, +): # pylint: disable=redefined-outer-name,redefined-builtin """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 +503,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( + sequence, + isinstance=isinstance, + StringTypes=StringTypes, + SequenceTypes=SequenceTypes, + do_flatten=do_flatten, +): # pylint: disable=redefined-outer-name,redefined-builtin """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 +528,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 +589,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 +607,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. + + 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:: - proxyObj = Proxy(objA), + proxy_obj = Proxy(obj_a) - Then, if in the future, you do something like this + Then, if in the future, you do something like this:: - x = proxyObj.var1, + x = proxy_obj.var1 - since Proxy does not have a 'var1' attribute (but presumably objA does), - the request actually is equivalent to saying + since the :class:`Proxy` class does not have a :attr:`var1` attribute + (but presumably `objA` does), the request actually is equivalent to saying:: - x = objA.var1 + 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: + 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 +676,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 +695,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 +706,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 +716,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 +724,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) @@ -673,54 +752,39 @@ try: can_read_reg = 1 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 - -# 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 - -try: - WinError = WindowsError -except NameError: - WinError = PlainWindowsError - - 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 + RegOpenKeyEx = winreg.OpenKeyEx + RegEnumKey = winreg.EnumKey + RegEnumValue = winreg.EnumValue + RegQueryValueEx = winreg.QueryValueEx + RegError = winreg.error + 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: + """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. + + 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:: + 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') """ @@ -738,10 +802,10 @@ else: HKEY_USERS = None def RegGetValue(root, key): - raise WinError + raise OSError def RegOpenKeyEx(root, key): - raise WinError + raise OSError if sys.platform == 'win32': @@ -768,8 +832,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): @@ -800,8 +864,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,7 +878,7 @@ elif os.name == 'os2': else: - def WhereIs(file, path=None, pathext=None, reject=None): + def WhereIs(file, path=None, pathext=None, reject=None): # pylint: disable=unused-argument import stat if path is None: try: @@ -827,8 +891,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 +910,39 @@ 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. +def PrependPath( + oldpath, newpath, sep=os.pathsep, delete_existing=True, canonicalize=None +): + """Prepends `newpath` path elements to `oldpath`. - Example: - Old Path: "/foo/bar:/foo" - New Path: "/biz/boom:/foo" - Result: "/biz/boom:/foo:/foo/bar" + 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 0, then adding a path that exists will - not move it to the beginning; it will stay where it is in the - list. + 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. - If canonicalize is not None, it is applied to each element of - newpath before use. + >>> 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 +993,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) + +def AppendPath( + oldpath, newpath, sep=os.pathsep, delete_existing=True, canonicalize=None +): + """Appends `newpath` path elements to `oldpath`. - If delete_existing is 0, then adding a path that exists + 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 +1079,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: @@ -1049,24 +1129,25 @@ display = DisplayEngine() def Split(arg): 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 - + that will be issued on the command line. Like :class:`UserList`, + but the argument passed to :meth:`__init__` 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 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 + which allows us to Do the Right Thing with :func:`Append` and + :func:`Prepend`, as well as with pure Python `foo = env['VAR'] + 'arg1 + arg2'` regardless of whether a user adds a list or a string to a command-line construction variable. Side effect: spaces will be stripped from individual string @@ -1074,8 +1155,8 @@ class CLVar(UserList): spaces inside a list argument. """ - 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 +1174,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,19 +1210,21 @@ 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): # pylint: disable=unused-argument + return False + else: def case_sensitive_suffixes(s1, s2): - return (os.path.normcase(s1) != os.path.normcase(s2)) + 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 + """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)) @@ -1164,14 +1248,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 +1272,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 +1307,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 +1341,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 = {} @@ -1303,132 +1384,168 @@ class LogicalLines: 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 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) - def sort(self, *args, **kwds): + super().reverse() + + 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. - """ + """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 +1577,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 +1618,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 +1687,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. + + Args: + hash_format: Hash format to use. - :param hash_format: Hash format to use. - :return: hashlib object. + 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 +1737,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 +1760,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.""" + + global _MD5_WARNING_SHOWN - if not _md5_warning_shown: - import SCons.Warnings + 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 +1863,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 +1872,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 +1880,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 +1912,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) -- cgit v0.12 From 027af36c7b8285a3890989c5e97885a05f8fa1eb Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Mon, 7 Jun 2021 12:06:19 -0600 Subject: Fix test for gdc shared libs Fixes #3952 Signed-off-by: Mats Wichmann --- test/D/SharedObjects/Common/common.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/test/D/SharedObjects/Common/common.py b/test/D/SharedObjects/Common/common.py index 1bb2d50..7ec82ea 100644 --- a/test/D/SharedObjects/Common/common.py +++ b/test/D/SharedObjects/Common/common.py @@ -30,7 +30,7 @@ import TestSCons from SCons.Environment import Base from os.path import abspath, dirname -from subprocess import check_output +import subprocess import sys sys.path.insert(1, abspath(dirname(__file__) + '/../../Support')) @@ -45,8 +45,10 @@ 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] + cp = subprocess.run(('gdc', '--version'), capture_output=True) + # gdc (GCC) 11.1.1 20210531 (Red Hat 11.1.1-3)\nCopyright (C)... + # want this:^^^^^^ + version = cp.stdout.decode().splitlines()[0].split()[2] major, minor, debug = [int(x) for x in version.split('.')] 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') -- cgit v0.12 From a3385ecbe7b0e695b6138ba7ba4f3b037fba884a Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Tue, 8 Jun 2021 07:08:03 -0600 Subject: PR #3954 - make gdc test changes work more broadly Use a subprocess construct that works even for older pythons. Use a regex to match version string to account for different style. Signed-off-by: Mats Wichmann --- test/D/SharedObjects/Common/common.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/test/D/SharedObjects/Common/common.py b/test/D/SharedObjects/Common/common.py index 7ec82ea..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 -from os.path import abspath, dirname +import re import subprocess +from os.path import abspath, dirname import sys sys.path.insert(1, abspath(dirname(__file__) + '/../../Support')) @@ -45,11 +46,17 @@ def testForTool(tool): test.skip_test("Required executable for tool '{0}' not found, skipping test.\n".format(tool)) if tool == 'gdc': - cp = subprocess.run(('gdc', '--version'), capture_output=True) + 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)... - # want this:^^^^^^ - version = cp.stdout.decode().splitlines()[0].split()[2] - major, minor, debug = [int(x) for x in version.split('.')] + # 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') -- cgit v0.12 From 72df8c50486f86e31a434636ae7c17836a89f662 Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Tue, 8 Jun 2021 06:43:52 -0600 Subject: PR #3953: quiet sider complaints Also remove a bit of syntax that was not introduced until Py3.8 - the use of a / as an argument in a function signature. Signed-off-by: Mats Wichmann --- SCons/Util.py | 40 ++++++++++++++++++++++++---------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/SCons/Util.py b/SCons/Util.py index 54cd786..629accc 100644 --- a/SCons/Util.py +++ b/SCons/Util.py @@ -126,7 +126,7 @@ class NodeList(UserList): """ def __bool__(self): - return len(self.data) != 0 + return bool(self.data) def __str__(self): return ' '.join(map(str, self.data)) @@ -252,7 +252,12 @@ def render_tree(root, child_func, prune=0, margin=[0], visited=None): return retval -IDX = lambda N: bool(N) +def IDX(n): + """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) # '─' @@ -745,11 +750,11 @@ 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 except ImportError: @@ -758,16 +763,16 @@ except ImportError: RegError = _NoError if can_read_reg: - HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT + 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 + HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER + HKEY_USERS = hkey_mod.HKEY_USERS - RegOpenKeyEx = winreg.OpenKeyEx - RegEnumKey = winreg.EnumKey - RegEnumValue = winreg.EnumValue + RegOpenKeyEx = winreg.OpenKeyEx + RegEnumKey = winreg.EnumKey + RegEnumValue = winreg.EnumValue RegQueryValueEx = winreg.QueryValueEx - RegError = winreg.error + RegError = winreg.error def RegGetValue(root, key): """Returns a registry value without having to open the key first. @@ -791,10 +796,12 @@ if can_read_reg: # 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 @@ -1230,14 +1237,14 @@ def adjustixes(fname, pre, suf, ensure_suffix=False): # 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 @@ -1497,7 +1504,8 @@ class UniqueList(UserList): self.__make_unique() super().reverse() - def sort(self, /, *args, **kwds): + # TODO: Py3.8: def sort(self, /, *args, **kwds): + def sort(self, *args, **kwds): self.__make_unique() return super().sort(*args, **kwds) -- cgit v0.12 From 69da0a96542d6e529dbb0eef3cdc4e1a439037ae Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Tue, 8 Jun 2021 07:33:44 -0600 Subject: PR #3942: retstore two checks per PR review Signed-off-by: Mats Wichmann --- SCons/EnvironmentTests.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/SCons/EnvironmentTests.py b/SCons/EnvironmentTests.py index 553b5e8..78f6ac2 100644 --- a/SCons/EnvironmentTests.py +++ b/SCons/EnvironmentTests.py @@ -994,19 +994,18 @@ 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 == e1 + assert bw.env is e1 bw.env = e2 - assert bw.env == e2 + assert bw.env is e2 assert bw.builder is b1 bw.builder = b2 @@ -1800,7 +1799,7 @@ def exists(env): 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 == env1 @@ -1809,7 +1808,7 @@ def exists(env): assert env1 != env2 assert env1 == env1copy - env3 = env1.Clone(XXX = 'x3', ZZZ = 'z3') + env3 = env1.Clone(XXX='x3', ZZZ='z3') assert env3 != env1 assert env3.Dictionary('XXX') == 'x3' assert env1.Dictionary('XXX') == 'x' @@ -1832,7 +1831,7 @@ 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()}) -- cgit v0.12 From 273d676853b5373412614ae3d3e85422b5dfcbe7 Mon Sep 17 00:00:00 2001 From: William Deegan Date: Tue, 8 Jun 2021 21:05:29 -0700 Subject: Address comments in PR --- SCons/Util.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/SCons/Util.py b/SCons/Util.py index 629accc..b2c3057 100644 --- a/SCons/Util.py +++ b/SCons/Util.py @@ -36,9 +36,10 @@ from types import MethodType, FunctionType # 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. -# import SCons.Warnings -# from SCons.Errors import UserError + PYPY = hasattr(sys, 'pypy_translation_info') @@ -87,6 +88,8 @@ def containsOnly(s, pat) -> bool: 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. @@ -515,7 +518,7 @@ def flatten_sequence( StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten, -): # pylint: disable=redefined-outer-name,redefined-builtin +) -> list: # pylint: disable=redefined-outer-name,redefined-builtin """Flatten a sequence to a non-nested list. Same as :func:`flatten`, but it does not handle the single scalar case. @@ -665,7 +668,8 @@ class Proxy: Inherit from this class to create a Proxy. - Note that, with new-style classes, this does *not* work transparently + + 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 -- cgit v0.12 From 0da6da254c08eb9003213c27473c9bc6ad981b35 Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Wed, 9 Jun 2021 10:48:06 -0600 Subject: [PR #3953] a few more Util tweaks [ci skip] Return types on a few more funcs Use a __doc__ assignment for funcs that have per-platform implementations. Cygwin get_native_path now uses subprocess for its call. doctest examples added to CLVar docstring. Signed-off-by: Mats Wichmann --- SCons/Util.py | 167 +++++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 106 insertions(+), 61 deletions(-) diff --git a/SCons/Util.py b/SCons/Util.py index b2c3057..fd09d37 100644 --- a/SCons/Util.py +++ b/SCons/Util.py @@ -33,6 +33,7 @@ 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. @@ -48,7 +49,7 @@ 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) -> list: if result is None: result = {} result.update(dict(zip(keys, values))) @@ -166,13 +167,13 @@ class NodeList(UserList): _get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$') -def get_environment_var(varstr): +def get_environment_var(varstr) -> Optional[str]: """Return undecorated construction variable string. - 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. + 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)) @@ -213,6 +214,7 @@ 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. @@ -255,7 +257,7 @@ def render_tree(root, child_func, prune=0, margin=[0], visited=None): return retval -def IDX(n): +def IDX(n) -> bool: """Generate in index into strings from the tree legends. These are always a choice between two, so bool works fine. @@ -273,6 +275,7 @@ BOX_VERT_RIGHT = chr(0x251c) # '├' BOX_HORIZ_DOWN = chr(0x252c) # '┬' +# TODO: W0102: Dangerous default value [] as argument (dangerous-default-value) def print_tree( root, child_func, @@ -431,39 +434,39 @@ StringTypes = (str, UserString) # Empirically, it is faster to check explicitly for str than for basestring. BaseStringTypes = str -def is_Dict( +def is_Dict( # pylint: disable=redefined-outer-name,redefined-builtin obj, isinstance=isinstance, DictTypes=DictTypes -): # pylint: disable=redefined-outer-name,redefined-builtin +) -> bool: return isinstance(obj, DictTypes) -def is_List( +def is_List( # pylint: disable=redefined-outer-name,redefined-builtin obj, isinstance=isinstance, ListTypes=ListTypes -): # pylint: disable=redefined-outer-name,redefined-builtin +) -> bool: return isinstance(obj, ListTypes) -def is_Sequence( +def is_Sequence( # pylint: disable=redefined-outer-name,redefined-builtin obj, isinstance=isinstance, SequenceTypes=SequenceTypes -): # pylint: disable=redefined-outer-name,redefined-builtin +) -> bool: return isinstance(obj, SequenceTypes) -def is_Tuple( +def is_Tuple( # pylint: disable=redefined-builtin obj, isinstance=isinstance, tuple=tuple -): # pylint: disable=redefined-builtin +) -> bool: return isinstance(obj, tuple) -def is_String( +def is_String( # pylint: disable=redefined-outer-name,redefined-builtin obj, isinstance=isinstance, StringTypes=StringTypes -): # pylint: disable=redefined-outer-name,redefined-builtin +) -> bool: return isinstance(obj, StringTypes) -def is_Scalar( +def is_Scalar( # pylint: disable=redefined-outer-name,redefined-builtin obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes -): # pylint: disable=redefined-outer-name,redefined-builtin +) -> bool: # Profiling shows that there is an impressive speed-up of 2x # when explicitly checking for strings instead of just not @@ -488,13 +491,13 @@ def do_flatten( do_flatten(item, result) -def flatten( +def flatten( # pylint: disable=redefined-outer-name,redefined-builtin obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten, -): # pylint: disable=redefined-outer-name,redefined-builtin +) -> list: """Flatten a sequence to a non-nested list. Converts either a single scalar or a nested sequence to a non-nested list. @@ -512,13 +515,13 @@ def flatten( return result -def flatten_sequence( +def flatten_sequence( # pylint: disable=redefined-outer-name,redefined-builtin sequence, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten, -) -> list: # pylint: disable=redefined-outer-name,redefined-builtin +) -> list: """Flatten a sequence to a non-nested list. Same as :func:`flatten`, but it does not handle the single scalar case. @@ -668,7 +671,6 @@ class Proxy: Inherit from this class to create a Proxy. - 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 @@ -779,7 +781,7 @@ if can_read_reg: RegError = winreg.error def RegGetValue(root, key): - """Returns a registry value without having to open the key first. + 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. @@ -818,9 +820,10 @@ else: def RegOpenKeyEx(root, key): 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'] @@ -857,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'] @@ -889,8 +892,9 @@ elif os.name == 'os2': else: - def WhereIs(file, path=None, pathext=None, reject=None): # pylint: disable=unused-argument - 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'] @@ -921,9 +925,23 @@ else: continue return None +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 @@ -1009,7 +1027,7 @@ def PrependPath( 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 @@ -1123,21 +1141,39 @@ 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 @@ -1148,22 +1184,32 @@ def Split(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 :class:`UserList`, - but the argument passed to :meth:`__init__` 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 adding a string, - which allows us to Do the Right Thing with :func:`Append` and - :func:`Prepend`, as well as with pure 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, initlist=None): @@ -1221,15 +1267,15 @@ 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): # pylint: disable=unused-argument + def case_sensitive_suffixes(s1, s2) -> bool: # pylint: disable=unused-argument return False else: - def case_sensitive_suffixes(s1, 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): +def adjustixes(fname, pre, suf, ensure_suffix=False) -> str: """Adjust filename prefixes and suffixes as needed. Add `prefix` to `fname` if specified. @@ -1387,8 +1433,7 @@ 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): @@ -1402,8 +1447,8 @@ class UniqueList(UserList): """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 time. + 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) @@ -1546,7 +1591,7 @@ class Unbuffered: def __getattr__(self, attr): return getattr(self.file, attr) -def make_path_relative(path): +def make_path_relative(path) -> str: """Converts an absolute path name to a relative pathname.""" if os.path.isabs(path): -- cgit v0.12 From cb8e6921bce54ab8a5f05ccd6605b9b74d2b7902 Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Wed, 9 Jun 2021 11:27:14 -0600 Subject: [PR #3953] wrong return type on dictify() [ci skip] Signed-off-by: Mats Wichmann --- SCons/Util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SCons/Util.py b/SCons/Util.py index fd09d37..5f521b3 100644 --- a/SCons/Util.py +++ b/SCons/Util.py @@ -49,7 +49,7 @@ PYPY = hasattr(sys, 'pypy_translation_info') NOFILE = "SCONS_MAGIC_MISSING_FILE_STRING" # unused? -def dictify(keys, values, result=None) -> list: +def dictify(keys, values, result=None) -> dict: if result is None: result = {} result.update(dict(zip(keys, values))) -- cgit v0.12 From 3a3a5fabdae99d87639c3b3cdf67aaa86135d55f Mon Sep 17 00:00:00 2001 From: William Deegan Date: Fri, 11 Jun 2021 13:20:03 -0700 Subject: added affect_signature to _concat to have it take care of adding if needed. Updated _LIBDIRFLAGS and _CPPINCFLAGS to use --- SCons/Defaults.py | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/SCons/Defaults.py b/SCons/Defaults.py index 95a2e52..9b74bf6 100644 --- a/SCons/Defaults.py +++ b/SCons/Defaults.py @@ -348,21 +348,31 @@ Touch = ActionFactory(touch_func, # Internal utility functions -def _concat(prefix, iter, suffix, env, f=lambda x: x, target=None, source=None): +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 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 - return _concat_ixes(prefix, iter, suffix, env) + if not affect_signature: + value = ['$('] + else: + value = [] + value += _concat_ixes(prefix, iter, suffix, env) + + if not affect_signature: + value += ["$)"] + + return value def _concat_ixes(prefix, iter, suffix, env): @@ -606,8 +616,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, -- cgit v0.12 From 4ff3a437e7abb98ef88afc33b72bfdb3a5cedb14 Mon Sep 17 00:00:00 2001 From: William Deegan Date: Fri, 11 Jun 2021 14:54:30 -0700 Subject: fix variable rename --- SCons/Defaults.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SCons/Defaults.py b/SCons/Defaults.py index 9b74bf6..4f826e5 100644 --- a/SCons/Defaults.py +++ b/SCons/Defaults.py @@ -361,13 +361,13 @@ def _concat(prefix, items_iter, suffix, env, f=lambda x: x, target=None, source= l = f(SCons.PathList.PathList(items_iter).subst_path(env, target, source)) if l is not None: - iter = l + items_iter = l if not affect_signature: value = ['$('] else: value = [] - value += _concat_ixes(prefix, iter, suffix, env) + value += _concat_ixes(prefix, items_iter, suffix, env) if not affect_signature: value += ["$)"] -- cgit v0.12 From e803b9ca867bee42004e62335afd91a3f7e9812e Mon Sep 17 00:00:00 2001 From: William Deegan Date: Sat, 12 Jun 2021 11:33:01 -0700 Subject: Address some pylint issues --- SCons/Defaults.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/SCons/Defaults.py b/SCons/Defaults.py index 4f826e5..7530b46 100644 --- a/SCons/Defaults.py +++ b/SCons/Defaults.py @@ -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,10 +347,10 @@ Touch = ActionFactory(touch_func, # Internal utility functions - +# 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. @@ -373,11 +373,12 @@ def _concat(prefix, items_iter, suffix, env, f=lambda x: x, target=None, source= value += ["$)"] return value +# pylint: enable-msg=too-many-arguments -def _concat_ixes(prefix, iter, suffix, env): +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. @@ -389,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 -- cgit v0.12 From e10c954fa34f67528f0bbe6e7d91179cd83769ab Mon Sep 17 00:00:00 2001 From: William Deegan Date: Sat, 12 Jun 2021 12:22:08 -0700 Subject: Added test of new functionality for _concat's new affect_signature flag --- SCons/EnvironmentTests.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/SCons/EnvironmentTests.py b/SCons/EnvironmentTests.py index 78f6ac2..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): @@ -1488,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.""" -- cgit v0.12 From ccddda156a4ba8d01c21cf229cecf6b9686e4ed6 Mon Sep 17 00:00:00 2001 From: William Deegan Date: Sat, 12 Jun 2021 12:22:42 -0700 Subject: Updated tools to use _concat's new affect_signature flag --- SCons/Defaults.py | 2 +- SCons/Tool/FortranCommon.py | 16 ++++++++-------- SCons/Tool/mingw.py | 2 +- SCons/Tool/swig.py | 2 +- test/_CPPINCFLAGS.py | 6 ++---- 5 files changed, 13 insertions(+), 15 deletions(-) diff --git a/SCons/Defaults.py b/SCons/Defaults.py index 7530b46..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 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/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..1df0ad0 100644 --- a/SCons/Tool/swig.py +++ b/SCons/Tool/swig.py @@ -203,7 +203,7 @@ def generate(env): env['SWIGPATH'] = [] env['SWIGINCPREFIX'] = '-I' env['SWIGINCSUFFIX'] = '' - env['_SWIGINCFLAGS'] = '$( ${_concat(SWIGINCPREFIX, SWIGPATH, SWIGINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' + 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): 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 -- cgit v0.12 From 985c194b41d279099caf505e3ea7776b3bd605da Mon Sep 17 00:00:00 2001 From: William Deegan Date: Sat, 12 Jun 2021 12:29:17 -0700 Subject: Update _concat doc, and add blurb to CHANGES.txt and RELEASE.txt --- CHANGES.txt | 3 +++ RELEASE.txt | 3 +++ SCons/Defaults.xml | 7 ++++--- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 7715f26..c73f345 100755 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -29,6 +29,9 @@ RELEASE VERSION/DATE TO BE FILLED IN LATER - Fix versioned shared library naming for MacOS platform. (Previously was libxyz.dylib.1.2.3, has been fixed to libxyz.1.2.3.dylib. Additionally the sonamed symlink had the same issue, that is now resolved as well) + - 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 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.xml b/SCons/Defaults.xml index 33d219b..34fd371 100644 --- a/SCons/Defaults.xml +++ b/SCons/Defaults.xml @@ -30,12 +30,13 @@ 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. +for variable interpolation, an optional function that will be +called to transform the list before concatenation, affect_signature which will wrap non-empty returned value with + $( and $) to indicate the contents should not affect the signature of the generated command line. -env['_CPPINCFLAGS'] = '$( ${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs)} $)', +env['_CPPINCFLAGS'] = '${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs, affect_signature=False)}', -- cgit v0.12 From b9ac13dde74de190a0d762acfc4c083cc47b087c Mon Sep 17 00:00:00 2001 From: William Deegan Date: Sat, 12 Jun 2021 14:00:43 -0700 Subject: reformat swig.py to fix sider complaint --- SCons/Tool/swig.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/SCons/Tool/swig.py b/SCons/Tool/swig.py index 1df0ad0..4f7c5e1 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, affect_signature=False)}' - 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']) -- cgit v0.12 From c1f2572ddb18d9b5512be1d2ccc807afc5ff6efb Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Sun, 13 Jun 2021 08:34:49 -0600 Subject: Fix an incorrect return-type annotation An earlier change added "-> str" to get_max_drift_csig's function sig. However, it can also return None, so the proper annotation is "-> Optional[str]". Also sorted the file inclusions. Signed-off-by: Mats Wichmann --- SCons/Node/FS.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) 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 -- cgit v0.12 From 76c47082b927ea9dffdfc1ee4d38efbcef058ad1 Mon Sep 17 00:00:00 2001 From: William Deegan Date: Sun, 13 Jun 2021 16:01:33 -0700 Subject: [ci skip] updated docs per mwichmann's feedback --- SCons/Defaults.xml | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/SCons/Defaults.xml b/SCons/Defaults.xml index 34fd371..2d6ba10 100644 --- a/SCons/Defaults.xml +++ b/SCons/Defaults.xml @@ -25,19 +25,23 @@ See its __doc__ string for a discussion of the format. - -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, an optional function that will be -called to transform the list before concatenation, affect_signature which will wrap non-empty returned value with - $( and $) to indicate the contents should not affect the signature of the generated command line. - - - -env['_CPPINCFLAGS'] = '${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs, affect_signature=False)}', - + + 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 affect_signature flag which will wrap non-empty returned value with $( and $) to indicate the contents + should not affect the signature of the generated command line. + + + + env['_CPPINCFLAGS'] = '${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE, affect_signature=False)}' + -- cgit v0.12 From 669f1c8dfc0e7aaf1fce9dd8ae3877bfc9ea24d0 Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Mon, 21 Jun 2021 09:00:35 -0600 Subject: Update pointers to irc to use libera [ci skip] Signed-off-by: Mats Wichmann --- .codecov.yml | 2 +- .travis.yml | 2 +- README-package.rst | 2 +- README.rst | 2 +- 4 files changed, 4 insertions(+), 4 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/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 -- cgit v0.12 From a2540944c38009b567ae290dad0130c0381dcfaf Mon Sep 17 00:00:00 2001 From: William Deegan Date: Mon, 21 Jun 2021 13:45:11 -0700 Subject: Address PR feedback --- SCons/Tool/linkCommon/SharedLibrary.py | 4 ++-- SCons/Tool/swig.py | 4 ++-- test/SWIG/SWIGOUTDIR.py | 6 ++---- test/SWIG/generated_swigfile.py | 23 ++++++----------------- 4 files changed, 12 insertions(+), 25 deletions(-) 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/swig.py b/SCons/Tool/swig.py index 4f7c5e1..ff0c80d 100644 --- a/SCons/Tool/swig.py +++ b/SCons/Tool/swig.py @@ -204,8 +204,8 @@ def generate(env): env['SWIGPATH'] = [] env['SWIGINCPREFIX'] = '-I' env['SWIGINCSUFFIX'] = '' - env[ - '_SWIGINCFLAGS'] = '${_concat(SWIGINCPREFIX, SWIGPATH, SWIGINCSUFFIX, __env__, RDirs, TARGET, SOURCE, affect_signature=False)}' + 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): 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() -- cgit v0.12 From 91298e4ad06f51768550edf167d2bbc806c05c48 Mon Sep 17 00:00:00 2001 From: William Deegan Date: Mon, 21 Jun 2021 14:21:35 -0700 Subject: [ci skip] Add some docbook formatting --- SCons/Defaults.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SCons/Defaults.xml b/SCons/Defaults.xml index 2d6ba10..27b0882 100644 --- a/SCons/Defaults.xml +++ b/SCons/Defaults.xml @@ -35,7 +35,7 @@ See its __doc__ string for a discussion of the format. 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 affect_signature flag which will wrap non-empty returned value with $( and $) to indicate the contents + 8) optional affect_signature flag which will wrap non-empty returned value with $( and $) to indicate the contents should not affect the signature of the generated command line. -- cgit v0.12 From 464ed9ce052ee5681586ed13bf0867ed54646204 Mon Sep 17 00:00:00 2001 From: Mats Wichmann Date: Fri, 2 Jul 2021 09:03:43 -0600 Subject: Update manpage for ParseConfig [skip appveyor] The ParseConfig manpage entry (and userguide entry) does not talk about the requirements for the function passed to ParseConfig - usually this isn't used as the default of using MergeFlags is fine, but it should be mentioned. Signed-off-by: Mats Wichmann --- SCons/Environment.xml | 73 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 45 insertions(+), 28 deletions(-) diff --git a/SCons/Environment.xml b/SCons/Environment.xml index 79af6bc..c2aab51 100644 --- a/SCons/Environment.xml +++ b/SCons/Environment.xml @@ -2168,12 +2168,12 @@ env.MergeShellPaths({'INCLUDE': ['c:/inc1', 'c:/inc2']}, prepend=0) -Merges the specified +Merges values from arg -values to the construction environment's construction variables. -If the +into &consvars; in the current &consenv;. +If arg -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 -unique=0 +unique=False to allow duplicate values to be added. When eliminating duplicate values, -any construction variables that end with +any &consvars; that end with the string PATH keep the left-most unique value. -All other construction variables keep +All other &consvars; keep the right-most unique value. @@ -2330,38 +2330,55 @@ NoClean(env.Program('hello', 'hello.c')) -Calls the specified -function -to modify the environment as specified by the output of -command. -The default -function -is -&f-link-env-MergeFlags;, -which expects the output of a typical -*-config -command -(for example, -gtk-config) -and adds the options -to the appropriate construction variables. +Updates the current &consenv; with the values extracted +from the output from running external command, +by calling a helper function function +which understands +the output of command. +command may be a string +or a list of strings representing the command and +its arguments. +If function +is not given, +&f-link-env-MergeFlags; is used. By default, duplicate values are not added to any construction variables; you can specify -unique=0 -to allow duplicate -values to be added. +unique=False +to allow duplicate values to be added. +If &f-env-MergeFlags; is used, +it expects a response in the style of a +*-config +command typical of the POSIX programming environment +(for example, +gtk-config) +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. + + + +If &f-env-MergeFlags; cannot interpret the results of +command, +you can suppply a custom +function to do so. +function +must accept three arguments: +the &consenv; to modify, the string returned +by running command, +and the optional +unique flag. @@ -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.) -- cgit v0.12 From 561149742ed54cd23c09145324a873c0acbafedc Mon Sep 17 00:00:00 2001 From: greenbender Date: Thu, 8 Jul 2021 18:28:04 +1000 Subject: Install tool fix scons_copytree recursion When called recursively the dirs_exist_ok parameter is passed in the wrong position. This may modify the value of ignore_dangling_symlinks and causes dirs_exist_ok to take on the default value of False. The install will 'silently' fail if the destination directory exists when this happens, and there can obviously be unintended side effects if ignore_dangling_symlinks is changed. The fix simply fixes the arguments in the recursive call, and also uses keyword arguments. --- SCons/Tool/install.py | 11 +++++--- test/Install/rec-sub-dir.py | 66 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 3 deletions(-) create mode 100644 test/Install/rec-sub-dir.py 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/test/Install/rec-sub-dir.py b/test/Install/rec-sub-dir.py new file mode 100644 index 0000000..6400a64 --- /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: -- cgit v0.12 From 95b9f12b46567c80352481c99403cbc64a371404 Mon Sep 17 00:00:00 2001 From: greenbender Date: Thu, 8 Jul 2021 18:51:50 +1000 Subject: Update CHANGES.txt --- CHANGES.txt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGES.txt b/CHANGES.txt index c73f345..ab4cf8d 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 directorys (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. -- cgit v0.12 From 7b1d4905b6323622baf610ff818645571e5ffd09 Mon Sep 17 00:00:00 2001 From: greenbender Date: Fri, 9 Jul 2021 09:22:48 +1000 Subject: Fix typo --- CHANGES.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGES.txt b/CHANGES.txt index ab4cf8d..33cc7ce 100755 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -12,7 +12,7 @@ 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 directorys (and their subdirectories) when the + silently failing to copy directories (and their subdirectories) when the directory already exists in the target. From Joseph Brill: -- cgit v0.12 From c6f8783001ded503a7d473ff15713c53a92b9fe8 Mon Sep 17 00:00:00 2001 From: greenbender Date: Fri, 9 Jul 2021 17:45:23 +1000 Subject: linting --- test/Install/rec-sub-dir.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Install/rec-sub-dir.py b/test/Install/rec-sub-dir.py index 6400a64..0a11928 100644 --- a/test/Install/rec-sub-dir.py +++ b/test/Install/rec-sub-dir.py @@ -47,7 +47,7 @@ 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) +""" % (os.sep, os.sep, os.sep) test.run(arguments=["-Q"], stdout=expect) test.must_exist(test.workpath('a', 'b', 'c')) -- cgit v0.12