"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "SCons/Scanner/__init__.py" between
scons-4.2.0.tar.gz and SCons-4.3.0.tar.gz

About: SCons is a software construction tool (a Python script and a set of modules as a superior alternative to the classic "Make" build tool).

__init__.py  (scons-4.2.0):__init__.py  (SCons-4.3.0)
skipping to change at line 29 skipping to change at line 29
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # 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.
"""The Scanner package for the SCons software construction utility.""" """The Scanner package for the SCons software construction utility."""
import re import re
import SCons.Node.FS import SCons.Node.FS
import SCons.PathList
import SCons.Util import SCons.Util
class _Null: class _Null:
pass pass
# This is used instead of None as a default argument value so None can be # This is used instead of None as a default argument value so None can be
# used as an actual argument value. # used as an actual argument value.
_null = _Null _null = _Null
def Scanner(function, *args, **kw): def Scanner(function, *args, **kwargs):
"""Factory function to create a Scanner Object. """Factory function to create a Scanner Object.
Creates the appropriate Scanner based on the type of "function". Creates the appropriate Scanner based on the type of "function".
TODO: Deprecate this some day. We've moved the functionality TODO: Deprecate this some day. We've moved the functionality
inside the Base class and really don't need this factory function inside the ScannerBase class and really don't need this factory function
any more. It was, however, used by some of our Tool modules, so any more. It was, however, used by some of our Tool modules, so
the call probably ended up in various people's custom modules the call probably ended up in various people's custom modules
patterned on SCons code. patterned on SCons code.
""" """
if SCons.Util.is_Dict(function): if SCons.Util.is_Dict(function):
return Selector(function, *args, **kw) return Selector(function, *args, **kwargs)
else:
return Base(function, *args, **kw) return ScannerBase(function, *args, **kwargs)
class FindPathDirs: class FindPathDirs:
"""Class to bind a specific E{*}PATH variable name to a function that """Class to bind a specific E{*}PATH variable name to a function that
will return all of the E{*}path directories. will return all of the E{*}path directories.
""" """
def __init__(self, variable): def __init__(self, variable):
self.variable = variable self.variable = variable
def __call__(self, env, dir=None, target=None, source=None, argument=None): def __call__(self, env, dir=None, target=None, source=None, argument=None):
import SCons.PathList
try: try:
path = env[self.variable] path = env[self.variable]
except KeyError: except KeyError:
return () return ()
dir = dir or env.fs._cwd dir = dir or env.fs._cwd
path = SCons.PathList.PathList(path).subst_path(env, target, source) path = SCons.PathList.PathList(path).subst_path(env, target, source)
return tuple(dir.Rfindalldirs(path)) return tuple(dir.Rfindalldirs(path))
class Base: class ScannerBase:
"""Base class for dependency scanners. """Base class for dependency scanners.
This implements straightforward, single-pass scanning of a single file. Implements straightforward, single-pass scanning of a single file.
A Scanner is usually set up with a scanner function (and optionally
a path function), but can also be a kind of dispatcher which
passes control to other Scanners.
A scanner function takes three arguments: a Node to scan for
dependecies, the construction environment to use, and an optional
tuple of paths (as generated by the optional path function).
It must return a list containing the Nodes for all the direct
dependencies of the file.
The optional path function is called to return paths that can be
searched for implicit dependency files. It takes five arguments:
a construction environment, a Node for the directory containing
the SConscript file that defined the primary target, a list of
target nodes, a list of source nodes, and the optional argument
for this instance.
Examples::
s = Scanner(my_scanner_function)
s = Scanner(function=my_scanner_function)
s = Scanner(function=my_scanner_function, argument='foo')
Args:
function: either a scanner function taking two or three arguments
and returning a list of File Nodes; or a mapping of keys to
other Scanner objects.
name: an optional name for identifying this scanner object
(defaults to "NONE").
argument: an optional argument that will be passed to both
*function* and *path_function*.
skeys: an optional list argument that can be used
to determine if this scanner can be used for a given Node.
In the case of File nodes, for example, the *skeys*
would be file suffixes.
path_function: an optional function which returns a tuple
of the directories that can be searched for implicit
dependency files. May also return a callable which
is called with no args and returns the tuple (supporting
Bindable class).
node_class: optional class of Nodes which this scan will return.
If not specified, defaults to :class:`SCons.Node.FS.Base`.
If *node_class* is ``None``, then this scanner will not enforce
any Node conversion and will return the raw results from *function*.
node_factory: optional factory function to be called to
translate the raw results returned by *function*
into the expected *node_class* objects.
scan_check: optional function to be called to first check whether
this node really needs to be scanned.
recursive: optional specifier of whether this scanner should be
invoked recursively on all of the implicit dependencies it returns
(for example `#include` lines in C source files, which may refer
to header files which should themselves be scanned).
May be a callable, which will be called to filter
the list of nodes found to select a subset for recursive
scanning (the canonical example being only recursively
scanning subdirectories within a directory). The default
is to not do recursive scanning.
""" """
def __init__( def __init__(
self, self,
function, function,
name="NONE", name="NONE",
argument=_null, argument=_null,
skeys=_null, skeys=_null,
path_function=None, path_function=None,
# Node.FS.Base so that, by default, it's okay for a # Node.FS.Base so that, by default, it's okay for a
# scanner to return a Dir, File or Entry. # scanner to return a Dir, File or Entry.
node_class=SCons.Node.FS.Base, node_class=SCons.Node.FS.Base,
node_factory=None, node_factory=None,
scan_check=None, scan_check=None,
recursive=None, recursive=None,
): ):
"""Construct a new scanner object given a scanner function. """Construct a new scanner object given a scanner function."""
The scanner function's first argument will be a Node that should
be scanned for dependencies, the second argument will be an
Environment object, the third argument will be the tuple of paths
returned by the path_function, and the fourth argument will be
the value passed into 'argument', and the returned list should
contain the Nodes for all the direct dependencies of the file.
Examples:
s = Scanner(my_scanner_function)
s = Scanner(function = my_scanner_function)
s = Scanner(function = my_scanner_function, argument = 'foo')
Args:
function: a scanner function taking two or three arguments
and returning a list of strings.
name: a name for identifying this scanner object.
argument: an optional argument that, if specified, will be
passed to both the scanner function and the path_function.
skeys: an optional list argument that can be used
to determine which scanner should be used for a given
Node. In the case of File nodes, for example, the 'skeys'
would be file suffixes.
path_function: a function that takes four or five arguments
(a construction environment, Node for the directory
containing the SConscript file that defined the primary
target, list of target nodes, list of source nodes, and
optional argument for this instance) and returns a tuple
of the directories that can be searched for implicit
dependency files. May also return a callable() which
is called with no args and returns the tuple (supporting
Bindable class).
node_class: the class of Nodes which this scan will return.
If node_class is None, then this scanner will not enforce
any Node conversion and will return the raw results from
the underlying scanner function.
node_factory: the factory function to be called to
translate the raw results returned by the scanner function
into the expected node_class objects.
scan_check: a function to be called to first check whether
this node really needs to be scanned.
recursive: specifies that this scanner should be invoked
recursively on all of the implicit dependencies it returns
(the canonical example being #include lines in C source
files). May be a callable, which will be called to filter
the list of nodes found to select a subset for recursive
scanning (the canonical example being only recursively
scanning subdirectories within a directory).
"""
# Note: this class could easily work with scanner functions that take # Note: this class could easily work with scanner functions that take
# something other than a filename as an argument (e.g. a database # something other than a filename as an argument (e.g. a database
# node) and a dependencies list that aren't file names. All that # node) and a dependencies list that aren't file names. All that
# would need to be changed is the documentation. # would need to be changed is the documentation.
self.function = function self.function = function
self.path_function = path_function self.path_function = path_function
self.name = name self.name = name
self.argument = argument self.argument = argument
skipping to change at line 181 skipping to change at line 191
if callable(recursive): if callable(recursive):
self.recurse_nodes = recursive self.recurse_nodes = recursive
elif recursive: elif recursive:
self.recurse_nodes = self._recurse_all_nodes self.recurse_nodes = self._recurse_all_nodes
else: else:
self.recurse_nodes = self._recurse_no_nodes self.recurse_nodes = self._recurse_no_nodes
def path(self, env, dir=None, target=None, source=None): def path(self, env, dir=None, target=None, source=None):
if not self.path_function: if not self.path_function:
return () return ()
if self.argument is not _null: if self.argument is not _null:
return self.path_function(env, dir, target, source, self.argument) return self.path_function(env, dir, target, source, self.argument)
else:
return self.path_function(env, dir, target, source)
def __call__(self, node, env, path=()): return self.path_function(env, dir, target, source)
def __call__(self, node, env, path=()) -> list:
"""Scans a single object. """Scans a single object.
Args: Args:
node: the node that will be passed to the scanner function node: the node that will be passed to the scanner function
env: the environment that will be passed to the scanner function. env: the environment that will be passed to the scanner function.
path: tuple of paths from the `path_function`
Returns: Returns:
A list of direct dependency nodes for the specified node. A list of direct dependency nodes for the specified node.
""" """
if self.scan_check and not self.scan_check(node, env): if self.scan_check and not self.scan_check(node, env):
return [] return []
self = self.select(node) # here we may morph into a different Scanner instance:
self = self.select(node) # pylint: disable=self-cls-assignment
if self.argument is not _null: if self.argument is not _null:
node_list = self.function(node, env, path, self.argument) node_list = self.function(node, env, path, self.argument)
else: else:
node_list = self.function(node, env, path) node_list = self.function(node, env, path)
kw = {} kw = {}
if hasattr(node, 'dir'): if hasattr(node, 'dir'):
kw['directory'] = node.dir kw['directory'] = node.dir
node_factory = env.get_factory(self.node_factory) conv = env.get_factory(self.node_factory)
nodes = [] cls = self.node_class
for l in node_list: nl = [conv(n, **kw) if cls and not isinstance(n, cls) else n for n in no
if self.node_class and not isinstance(l, self.node_class): de_list]
l = node_factory(l, **kw) return nl
nodes.append(l)
return nodes
def __eq__(self, other): def __eq__(self, other):
try: try:
return self.__dict__ == other.__dict__ return self.__dict__ == other.__dict__
except AttributeError: except AttributeError:
# other probably doesn't have a __dict__ # other probably doesn't have a __dict__
return self.__dict__ == other return self.__dict__ == other
def __hash__(self): def __hash__(self):
return id(self) return id(self)
skipping to change at line 250 skipping to change at line 260
def select(self, node): def select(self, node):
if SCons.Util.is_Dict(self.function): if SCons.Util.is_Dict(self.function):
key = node.scanner_key() key = node.scanner_key()
try: try:
return self.function[key] return self.function[key]
except KeyError: except KeyError:
return None return None
else: else:
return self return self
def _recurse_all_nodes(self, nodes): @staticmethod
def _recurse_all_nodes(nodes):
return nodes return nodes
def _recurse_no_nodes(self, nodes): @staticmethod
def _recurse_no_nodes(nodes):
return [] return []
# recurse_nodes = _recurse_no_nodes # recurse_nodes = _recurse_no_nodes
def add_scanner(self, skey, scanner): def add_scanner(self, skey, scanner):
self.function[skey] = scanner self.function[skey] = scanner
self.add_skey(skey) self.add_skey(skey)
class Selector(Base): # keep the old name for a while in case external users are using.
# there are no more internal uses of this class by the name "Base"
Base = ScannerBase
class Selector(ScannerBase):
""" """
A class for selecting a more specific scanner based on the A class for selecting a more specific scanner based on the
scanner_key() (suffix) for a specific Node. :func:`scanner_key` (suffix) for a specific Node.
TODO: This functionality has been moved into the inner workings of TODO: This functionality has been moved into the inner workings of
the Base class, and this class will be deprecated at some point. the ScannerBase class, and this class will be deprecated at some point.
(It was never exposed directly as part of the public interface, (It was never exposed directly as part of the public interface,
although it is used by the Scanner() factory function that was although it is used by the :func:`Scanner` factory function that was
used by various Tool modules and therefore was likely a template used by various Tool modules and therefore was likely a template
for custom modules that may be out there.) for custom modules that may be out there.)
""" """
def __init__(self, dict, *args, **kw): def __init__(self, mapping, *args, **kwargs):
Base.__init__(self, None, *args, **kw) super().__init__(None, *args, **kwargs)
self.dict = dict self.mapping = mapping
self.skeys = list(dict.keys()) self.skeys = list(mapping.keys())
def __call__(self, node, env, path=()): def __call__(self, node, env, path=()):
return self.select(node)(node, env, path) return self.select(node)(node, env, path)
def select(self, node): def select(self, node):
try: try:
return self.dict[node.scanner_key()] return self.mapping[node.scanner_key()]
except KeyError: except KeyError:
return None return None
def add_scanner(self, skey, scanner): def add_scanner(self, skey, scanner):
self.dict[skey] = scanner self.mapping[skey] = scanner
self.add_skey(skey) self.add_skey(skey)
class Current(Base): class Current(ScannerBase):
""" """
A class for scanning files that are source files (have no builder) A class for scanning files that are source files (have no builder)
or are derived files and are current (which implies that they exist, or are derived files and are current (which implies that they exist,
either locally or in a repository). either locally or in a repository).
""" """
def __init__(self, *args, **kw): def __init__(self, *args, **kwargs):
def current_check(node, env): def current_check(node, env):
return not node.has_builder() or node.is_up_to_date() return not node.has_builder() or node.is_up_to_date()
kw['scan_check'] = current_check
Base.__init__(self, *args, **kw) kwargs['scan_check'] = current_check
super().__init__(*args, **kwargs)
class Classic(Current): class Classic(Current):
""" """
A Scanner subclass to contain the common logic for classic CPP-style A Scanner subclass to contain the common logic for classic CPP-style
include scanning, but which can be customized to use different include scanning, but which can be customized to use different
regular expressions to find the includes. regular expressions to find the includes.
Note that in order for this to work "out of the box" (without Note that in order for this to work "out of the box" (without
overriding the find_include() and sort_key() methods), the regular overriding the :meth:`find_include` and :meth:`sort_key1` methods),
expression passed to the constructor must return the name of the the regular expression passed to the constructor must return the
include file in group 0. name of the include file in group 0.
""" """
def __init__(self, name, suffixes, path_variable, regex, *args, **kw): def __init__(self, name, suffixes, path_variable, regex, *args, **kwargs):
self.cre = re.compile(regex, re.M) self.cre = re.compile(regex, re.M)
def _scan(node, _, path=(), self=self): def _scan(node, _, path=(), self=self):
node = node.rfile() node = node.rfile()
if not node.exists(): if not node.exists():
return [] return []
return self.scan(node, path) return self.scan(node, path)
kw['function'] = _scan kwargs['function'] = _scan
kw['path_function'] = FindPathDirs(path_variable) kwargs['path_function'] = FindPathDirs(path_variable)
# Allow recursive to propagate if child class specifies. # Allow recursive to propagate if child class specifies.
# In this case resource scanner needs to specify a filter on which files # In this case resource scanner needs to specify a filter on which files
# get recursively processed. Previously was hardcoded to 1 instead of # get recursively processed. Previously was hardcoded to 1 instead of
# defaulted to 1. # defaulted to 1.
kw['recursive'] = kw.get('recursive', 1) kwargs['recursive'] = kwargs.get('recursive', True)
kw['skeys'] = suffixes kwargs['skeys'] = suffixes
kw['name'] = name kwargs['name'] = name
Current.__init__(self, *args, **kw) super().__init__(*args, **kwargs)
def find_include(self, include, source_dir, path): @staticmethod
def find_include(include, source_dir, path):
n = SCons.Node.FS.find_file(include, (source_dir,) + tuple(path)) n = SCons.Node.FS.find_file(include, (source_dir,) + tuple(path))
return n, include return n, include
def sort_key(self, include): @staticmethod
def sort_key(include):
return SCons.Node.FS._my_normcase(include) return SCons.Node.FS._my_normcase(include)
def find_include_names(self, node): def find_include_names(self, node):
return self.cre.findall(node.get_text_contents()) return self.cre.findall(node.get_text_contents())
def scan(self, node, path=()): def scan(self, node, path=()):
# cache the includes list in node so we only scan it once: # cache the includes list in node so we only scan it once:
if node.includes is not None: if node.includes is not None:
includes = node.includes includes = node.includes
else: else:
includes = self.find_include_names(node) includes = self.find_include_names(node)
# Intern the names of the include files. Saves some memory # Intern the names of the include files. Saves some memory
# if the same header is included many times. # if the same header is included many times.
node.includes = list(map(SCons.Util.silent_intern, includes)) node.includes = list(map(SCons.Util.silent_intern, includes))
# This is a hand-coded DSU (decorate-sort-undecorate, or # This is a hand-coded DSU (decorate-sort-undecorate, or
skipping to change at line 375 skipping to change at line 392
# us keep the sort order constant regardless of whether the file # us keep the sort order constant regardless of whether the file
# is actually found in a Repository or locally. # is actually found in a Repository or locally.
nodes = [] nodes = []
source_dir = node.get_dir() source_dir = node.get_dir()
if callable(path): if callable(path):
path = path() path = path()
for include in includes: for include in includes:
n, i = self.find_include(include, source_dir, path) n, i = self.find_include(include, source_dir, path)
if n is None: if n is None:
SCons.Warnings.warn(SCons.Warnings.DependencyWarning, SCons.Warnings.warn(
"No dependency generated for file: %s (inclu SCons.Warnings.DependencyWarning,
ded from: %s) -- file not found" % (i, node)) "No dependency generated for file: %s "
"(included from: %s) -- file not found" % (i, node),
)
else: else:
nodes.append((self.sort_key(include), n)) nodes.append((self.sort_key(include), n))
return [pair[1] for pair in sorted(nodes)] return [pair[1] for pair in sorted(nodes)]
class ClassicCPP(Classic): class ClassicCPP(Classic):
""" """
A Classic Scanner subclass which takes into account the type of A Classic Scanner subclass which takes into account the type of
bracketing used to include the file, and uses classic CPP rules bracketing used to include the file, and uses classic CPP rules
for searching for the files based on the bracketing. for searching for the files based on the bracketing.
skipping to change at line 400 skipping to change at line 420
the contained filename in group 1. the contained filename in group 1.
""" """
def find_include(self, include, source_dir, path): def find_include(self, include, source_dir, path):
include = list(map(SCons.Util.to_str, include)) include = list(map(SCons.Util.to_str, include))
if include[0] == '"': if include[0] == '"':
paths = (source_dir,) + tuple(path) paths = (source_dir,) + tuple(path)
else: else:
paths = tuple(path) + (source_dir,) paths = tuple(path) + (source_dir,)
n = SCons.Node.FS.find_file(include[1], paths) n = SCons.Node.FS.find_file(include[1], paths)
i = SCons.Util.silent_intern(include[1]) i = SCons.Util.silent_intern(include[1])
return n, i return n, i
def sort_key(self, include): def sort_key(self, include):
return SCons.Node.FS._my_normcase(' '.join(include)) return SCons.Node.FS._my_normcase(' '.join(include))
# Local Variables: # Local Variables:
# tab-width:4 # tab-width:4
# indent-tabs-mode:nil # indent-tabs-mode:nil
# End: # End:
 End of changes. 38 change blocks. 
113 lines changed or deleted 132 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)