2
0
mirror of https://gitlab.com/ita1024/waf.git synced 2024-12-11 11:20:21 +01:00
waf/waflib/Node.py

926 lines
23 KiB
Python
Raw Normal View History

2011-09-10 11:13:51 +02:00
#!/usr/bin/env python
# encoding: utf-8
2017-02-11 16:13:37 +01:00
# Thomas Nagy, 2005-2017 (ita)
2011-09-10 11:13:51 +02:00
"""
2016-06-25 12:50:04 +02:00
Node: filesystem structure
2011-09-10 11:13:51 +02:00
#. Each file/folder is represented by exactly one node.
#. Some potential class properties are stored on :py:class:`waflib.Build.BuildContext` : nodes to depend on, etc.
Unused class members can increase the `.wafpickle` file size sensibly.
#. Node objects should never be created directly, use
2016-06-25 12:50:04 +02:00
the methods :py:func:`Node.make_node` or :py:func:`Node.find_node` for the low-level operations
2011-09-10 11:13:51 +02:00
2016-06-25 12:50:04 +02:00
#. The methods :py:func:`Node.find_resource`, :py:func:`Node.find_dir` :py:func:`Node.find_or_declare` must be
2011-09-10 11:13:51 +02:00
used when a build context is present
2016-06-25 12:50:04 +02:00
#. Each instance of :py:class:`waflib.Context.Context` has a unique :py:class:`Node` subclass required for serialization.
(:py:class:`waflib.Node.Nod3`, see the :py:class:`waflib.Context.Context` initializer). A reference to the context
owning a node is held as *self.ctx*
2011-09-10 11:13:51 +02:00
"""
import os, re, sys, shutil
2011-09-10 11:13:51 +02:00
from waflib import Utils, Errors
exclude_regs = '''
**/*~
**/#*#
**/.#*
**/%*%
**/._*
**/CVS
**/CVS/**
**/.cvsignore
**/SCCS
**/SCCS/**
**/vssver.scc
**/.svn
**/.svn/**
**/BitKeeper
**/.git
**/.git/**
**/.gitignore
**/.bzr
**/.bzrignore
**/.bzr/**
**/.hg
**/.hg/**
**/_MTN
**/_MTN/**
**/.arch-ids
**/{arch}
**/_darcs
**/_darcs/**
**/.intlcache
2011-09-10 11:13:51 +02:00
**/.DS_Store'''
"""
Ant patterns for files and folders to exclude while doing the
recursive traversal in :py:meth:`waflib.Node.Node.ant_glob`
"""
class Node(object):
"""
2016-06-25 12:50:04 +02:00
This class is organized in two parts:
2011-09-10 11:13:51 +02:00
* The basic methods meant for filesystem access (compute paths, create folders, etc)
* The methods bound to a :py:class:`waflib.Build.BuildContext` (require ``bld.srcnode`` and ``bld.bldnode``)
"""
2016-06-25 12:50:04 +02:00
2014-07-05 23:02:38 +02:00
dict_class = dict
2016-06-25 12:50:04 +02:00
"""
Subclasses can provide a dict class to enable case insensitivity for example.
"""
2015-12-23 17:50:48 +01:00
__slots__ = ('name', 'parent', 'children', 'cache_abspath', 'cache_isdir')
2011-09-10 11:13:51 +02:00
def __init__(self, name, parent):
2016-06-25 12:50:04 +02:00
"""
2016-06-25 14:49:27 +02:00
.. note:: Use :py:func:`Node.make_node` or :py:func:`Node.find_node` instead of calling this constructor
2016-06-25 12:50:04 +02:00
"""
2011-09-10 11:13:51 +02:00
self.name = name
self.parent = parent
if parent:
if name in parent.children:
raise Errors.WafError('node %s exists in the parent files %r already' % (name, parent))
parent.children[name] = self
def __setstate__(self, data):
2016-06-25 12:50:04 +02:00
"Deserializes node information, used for persistence"
2011-09-10 11:13:51 +02:00
self.name = data[0]
self.parent = data[1]
if data[2] is not None:
# Issue 1480
self.children = self.dict_class(data[2])
2011-09-10 11:13:51 +02:00
def __getstate__(self):
2016-06-25 12:50:04 +02:00
"Serializes node information, used for persistence"
2015-12-23 17:50:48 +01:00
return (self.name, self.parent, getattr(self, 'children', None))
2011-09-10 11:13:51 +02:00
def __str__(self):
2016-06-25 13:27:22 +02:00
"""
String representation (abspath), for debugging purposes
:rtype: string
"""
2016-01-02 01:54:52 +01:00
return self.abspath()
2011-09-10 11:13:51 +02:00
def __repr__(self):
2016-06-25 13:27:22 +02:00
"""
String representation (abspath), for debugging purposes
:rtype: string
"""
2011-09-10 11:13:51 +02:00
return self.abspath()
def __copy__(self):
2016-06-25 13:27:22 +02:00
"""
Provided to prevent nodes from being copied
:raises: :py:class:`waflib.Errors.WafError`
"""
2011-09-10 11:13:51 +02:00
raise Errors.WafError('nodes are not supposed to be copied')
2017-01-21 13:28:06 +01:00
def read(self, flags='r', encoding='latin-1'):
2011-09-10 11:13:51 +02:00
"""
2016-06-25 12:50:04 +02:00
Reads and returns the contents of the file represented by this node, see :py:func:`waflib.Utils.readf`::
2011-09-10 11:13:51 +02:00
def build(bld):
bld.path.find_node('wscript').read()
2016-06-25 12:50:04 +02:00
:param flags: Open mode
:type flags: string
:param encoding: encoding value for Python3
:type encoding: string
:rtype: string or bytes
2011-09-10 11:13:51 +02:00
:return: File contents
"""
return Utils.readf(self.abspath(), flags, encoding)
2011-09-10 11:13:51 +02:00
2017-01-21 13:28:06 +01:00
def write(self, data, flags='w', encoding='latin-1'):
"""
2016-06-25 12:50:04 +02:00
Writes data to the file represented by this node, see :py:func:`waflib.Utils.writef`::
def build(bld):
bld.path.make_node('foo.txt').write('Hello, world!')
:param data: data to write
2016-06-25 12:50:04 +02:00
:type data: string
:param flags: Write mode
2016-06-25 12:50:04 +02:00
:type flags: string
:param encoding: encoding value for Python3
:type encoding: string
"""
Utils.writef(self.abspath(), data, flags, encoding)
def read_json(self, convert=True, encoding='utf-8'):
"""
2016-06-25 12:50:04 +02:00
Reads and parses the contents of this node as JSON (Python 2.6)::
def build(bld):
bld.path.find_node('abc.json').read_json()
Note that this by default automatically decodes unicode strings on Python2, unlike what the Python JSON module does.
:type convert: boolean
:param convert: Prevents decoding of unicode strings on Python2
:type encoding: string
:param encoding: The encoding of the file to read. This default to UTF8 as per the JSON standard
:rtype: object
:return: Parsed file contents
"""
import json # Python 2.6 and up
object_pairs_hook = None
if convert and sys.hexversion < 0x3000000:
try:
_type = unicode
except NameError:
_type = str
def convert(value):
if isinstance(value, list):
return [convert(element) for element in value]
elif isinstance(value, _type):
return str(value)
else:
return value
def object_pairs(pairs):
return dict((str(pair[0]), convert(pair[1])) for pair in pairs)
object_pairs_hook = object_pairs
return json.loads(self.read(encoding=encoding), object_pairs_hook=object_pairs_hook)
def write_json(self, data, pretty=True):
"""
2016-06-25 12:50:04 +02:00
Writes a python object as JSON to disk (Python 2.6) as UTF-8 data (JSON standard)::
def build(bld):
bld.path.find_node('xyz.json').write_json(199)
:type data: object
:param data: The data to write to disk
:type pretty: boolean
:param pretty: Determines if the JSON will be nicely space separated
"""
import json # Python 2.6 and up
indent = 2
separators = (',', ': ')
sort_keys = pretty
newline = os.linesep
if not pretty:
indent = None
separators = (',', ':')
newline = ''
output = json.dumps(data, indent=indent, separators=separators, sort_keys=sort_keys) + newline
self.write(output, encoding='utf-8')
def exists(self):
2016-06-25 12:50:04 +02:00
"""
Returns whether the Node is present on the filesystem
2016-06-25 13:27:22 +02:00
:rtype: bool
2016-06-25 12:50:04 +02:00
"""
return os.path.exists(self.abspath())
def isdir(self):
2016-06-25 12:50:04 +02:00
"""
Returns whether the Node represents a folder
2016-06-25 13:27:22 +02:00
:rtype: bool
2016-06-25 12:50:04 +02:00
"""
return os.path.isdir(self.abspath())
2011-09-10 11:13:51 +02:00
def chmod(self, val):
"""
2016-06-25 12:50:04 +02:00
Changes the file/dir permissions::
2011-09-10 11:13:51 +02:00
def build(bld):
bld.path.chmod(493) # 0755
"""
os.chmod(self.abspath(), val)
def delete(self, evict=True):
2016-06-25 12:50:04 +02:00
"""
Removes the file/folder from the filesystem (equivalent to `rm -rf`), and remove this object from the Node tree.
Do not use this object after calling this method.
"""
2011-09-10 11:13:51 +02:00
try:
try:
2016-05-21 01:15:19 +02:00
if os.path.isdir(self.abspath()):
shutil.rmtree(self.abspath())
else:
os.remove(self.abspath())
2017-02-05 13:00:36 +01:00
except OSError:
if os.path.exists(self.abspath()):
2017-02-05 12:59:01 +01:00
raise
2014-04-20 02:29:27 +02:00
finally:
if evict:
self.evict()
2011-09-10 11:13:51 +02:00
2012-02-12 15:36:57 +01:00
def evict(self):
2016-06-25 13:27:22 +02:00
"""
Removes this node from the Node tree
"""
2012-02-12 15:36:57 +01:00
del self.parent.children[self.name]
2011-09-10 11:13:51 +02:00
def suffix(self):
2016-06-25 13:27:22 +02:00
"""
Returns the file rightmost extension, for example `a.b.c.d .d`
:rtype: string
"""
2011-09-10 11:13:51 +02:00
k = max(0, self.name.rfind('.'))
return self.name[k:]
def height(self):
2016-06-25 12:50:04 +02:00
"""
Returns the depth in the folder hierarchy from the filesystem root or from all the file drives
:returns: filesystem depth
:rtype: integer
"""
2011-09-10 11:13:51 +02:00
d = self
val = -1
while d:
d = d.parent
val += 1
return val
def listdir(self):
2016-06-25 12:50:04 +02:00
"""
Lists the folder contents
:returns: list of file/folder names ordered alphabetically
:rtype: list of string
"""
2011-09-10 11:13:51 +02:00
lst = Utils.listdir(self.abspath())
lst.sort()
return lst
def mkdir(self):
2011-10-04 21:53:06 +02:00
"""
2016-06-25 12:50:04 +02:00
Creates a folder represented by this node. Intermediate folders are created as needed.
:raises: :py:class:`waflib.Errors.WafError` when the folder is missing
2011-10-04 21:53:06 +02:00
"""
if self.isdir():
2011-09-10 11:13:51 +02:00
return
try:
self.parent.mkdir()
2012-02-11 14:43:07 +01:00
except OSError:
2011-09-10 11:13:51 +02:00
pass
if self.name:
try:
os.makedirs(self.abspath())
except OSError:
pass
if not self.isdir():
raise Errors.WafError('Could not create the directory %r' % self)
2011-09-10 11:13:51 +02:00
try:
self.children
2012-02-11 14:43:07 +01:00
except AttributeError:
2014-07-05 23:02:38 +02:00
self.children = self.dict_class()
2011-09-10 11:13:51 +02:00
def find_node(self, lst):
"""
2016-06-25 12:50:04 +02:00
Finds a node on the file system (files or folders), and creates the corresponding Node objects if it exists
2011-09-10 11:13:51 +02:00
2016-06-25 12:50:04 +02:00
:param lst: relative path
2011-09-10 11:13:51 +02:00
:type lst: string or list of string
2016-06-25 12:50:04 +02:00
:returns: The corresponding Node object or None if no entry was found on the filesystem
:rtype: :py:class:´waflib.Node.Node´
2011-09-10 11:13:51 +02:00
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
2011-09-10 11:13:51 +02:00
2017-03-02 20:45:01 +01:00
if lst and lst[0].startswith('\\\\') and not self.parent:
node = self.ctx.root.make_node(lst[0])
node.cache_isdir = True
return node.find_node(lst[1:])
2011-09-10 11:13:51 +02:00
cur = self
for x in lst:
if x == '..':
cur = cur.parent or cur
continue
try:
2012-02-11 14:43:07 +01:00
ch = cur.children
except AttributeError:
2014-07-05 23:02:38 +02:00
cur.children = self.dict_class()
2012-02-11 14:43:07 +01:00
else:
try:
cur = ch[x]
2011-09-10 11:13:51 +02:00
continue
2012-02-11 14:43:07 +01:00
except KeyError:
pass
2011-09-10 11:13:51 +02:00
# optimistic: create the node first then look if it was correct to do so
cur = self.__class__(x, cur)
if not cur.exists():
2012-02-12 15:36:57 +01:00
cur.evict()
2011-09-10 11:13:51 +02:00
return None
if not cur.exists():
cur.evict()
2011-10-04 20:52:02 +02:00
return None
return cur
2011-09-10 11:13:51 +02:00
def make_node(self, lst):
"""
2016-06-25 12:50:04 +02:00
Returns or creates a Node object corresponding to the input path without considering the filesystem.
2011-09-10 11:13:51 +02:00
2016-06-25 12:50:04 +02:00
:param lst: relative path
2011-09-10 11:13:51 +02:00
:type lst: string or list of string
2016-06-25 12:50:04 +02:00
:rtype: :py:class:´waflib.Node.Node´
2011-09-10 11:13:51 +02:00
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
2011-09-10 11:13:51 +02:00
cur = self
for x in lst:
if x == '..':
cur = cur.parent or cur
continue
try:
cur = cur.children[x]
except AttributeError:
2014-07-05 23:02:38 +02:00
cur.children = self.dict_class()
except KeyError:
pass
else:
continue
2011-09-10 11:13:51 +02:00
cur = self.__class__(x, cur)
return cur
def search_node(self, lst):
2011-09-10 11:13:51 +02:00
"""
2016-06-25 12:50:04 +02:00
Returns a Node previously defined in the data structure. The filesystem is not considered.
2011-09-10 11:13:51 +02:00
2016-06-25 12:50:04 +02:00
:param lst: relative path
2011-09-10 11:13:51 +02:00
:type lst: string or list of string
2016-06-25 12:50:04 +02:00
:rtype: :py:class:´waflib.Node.Node´ or None if there is no entry in the Node datastructure
2011-09-10 11:13:51 +02:00
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
2011-09-10 11:13:51 +02:00
cur = self
2012-02-11 14:43:07 +01:00
for x in lst:
if x == '..':
cur = cur.parent or cur
else:
try:
2011-09-10 11:13:51 +02:00
cur = cur.children[x]
2012-02-11 14:43:07 +01:00
except (AttributeError, KeyError):
return None
return cur
2011-09-10 11:13:51 +02:00
def path_from(self, node):
"""
Path of this node seen from the other::
def build(bld):
n1 = bld.path.find_node('foo/bar/xyz.txt')
n2 = bld.path.find_node('foo/stuff/')
2012-12-01 17:36:53 +01:00
n1.path_from(n2) # '../bar/xyz.txt'
2011-09-10 11:13:51 +02:00
:param node: path to use as a reference
:type node: :py:class:`waflib.Node.Node`
2016-12-21 19:50:29 +01:00
:returns: a relative path or an absolute one if that is better
2016-06-25 12:50:04 +02:00
:rtype: string
2011-09-10 11:13:51 +02:00
"""
c1 = self
c2 = node
c1h = c1.height()
c2h = c2.height()
lst = []
up = 0
while c1h > c2h:
lst.append(c1.name)
c1 = c1.parent
c1h -= 1
while c2h > c1h:
up += 1
c2 = c2.parent
c2h -= 1
2016-03-25 14:02:36 +01:00
while not c1 is c2:
2011-09-10 11:13:51 +02:00
lst.append(c1.name)
up += 1
c1 = c1.parent
c2 = c2.parent
if c1.parent:
2016-12-21 19:50:29 +01:00
lst.extend(['..'] * up)
lst.reverse()
return os.sep.join(lst) or '.'
else:
2016-12-21 19:50:29 +01:00
return self.abspath()
2011-09-10 11:13:51 +02:00
def abspath(self):
"""
2016-06-25 12:50:04 +02:00
Returns the absolute path. A cache is kept in the context as ``cache_node_abspath``
:rtype: string
2011-09-10 11:13:51 +02:00
"""
try:
return self.cache_abspath
2012-02-11 14:43:07 +01:00
except AttributeError:
2011-09-10 11:13:51 +02:00
pass
# think twice before touching this (performance + complexity + correctness)
2015-03-08 18:30:57 +01:00
if not self.parent:
val = os.sep
elif not self.parent.name:
val = os.sep + self.name
2011-09-10 11:13:51 +02:00
else:
2015-03-08 18:30:57 +01:00
val = self.parent.abspath() + os.sep + self.name
self.cache_abspath = val
return val
if Utils.is_win32:
def abspath(self):
try:
return self.cache_abspath
except AttributeError:
pass
2011-09-10 11:13:51 +02:00
if not self.parent:
val = ''
elif not self.parent.name:
val = self.name + os.sep
else:
val = self.parent.abspath().rstrip(os.sep) + os.sep + self.name
2015-03-08 18:30:57 +01:00
self.cache_abspath = val
return val
2011-09-10 11:13:51 +02:00
def is_child_of(self, node):
"""
2016-06-25 12:50:04 +02:00
Returns whether the object belongs to a subtree of the input node::
2011-09-10 11:13:51 +02:00
def build(bld):
node = bld.path.find_node('wscript')
node.is_child_of(bld.path) # True
:param node: path to use as a reference
:type node: :py:class:`waflib.Node.Node`
2016-06-25 12:50:04 +02:00
:rtype: bool
2011-09-10 11:13:51 +02:00
"""
p = self
diff = self.height() - node.height()
while diff > 0:
diff -= 1
p = p.parent
2016-03-25 14:02:36 +01:00
return p is node
2011-09-10 11:13:51 +02:00
def ant_iter(self, accept=None, maxdepth=25, pats=[], dir=False, src=True, remove=True):
"""
2016-06-25 12:50:04 +02:00
Recursive method used by :py:meth:`waflib.Node.ant_glob`.
2011-09-10 11:13:51 +02:00
:param accept: function used for accepting/rejecting a node, returns the patterns that can be still accepted in recursion
:type accept: function
:param maxdepth: maximum depth in the filesystem (25)
:type maxdepth: int
:param pats: list of patterns to accept and list of patterns to exclude
:type pats: tuple
:param dir: return folders too (False by default)
:type dir: bool
:param src: return files (True by default)
:type src: bool
:param remove: remove files/folders that do not exist (True by default)
:type remove: bool
2016-06-25 12:50:04 +02:00
:returns: A generator object to iterate from
:rtype: iterator
2011-09-10 11:13:51 +02:00
"""
dircont = self.listdir()
dircont.sort()
try:
lst = set(self.children.keys())
2012-02-11 14:43:07 +01:00
except AttributeError:
2014-07-05 23:02:38 +02:00
self.children = self.dict_class()
2012-02-11 14:43:07 +01:00
else:
2011-09-10 11:13:51 +02:00
if remove:
for x in lst - set(dircont):
2012-02-12 15:36:57 +01:00
self.children[x].evict()
2011-09-10 11:13:51 +02:00
for name in dircont:
npats = accept(name, pats)
if npats and npats[0]:
accepted = [] in npats[0]
node = self.make_node([name])
isdir = node.isdir()
2011-09-10 11:13:51 +02:00
if accepted:
if isdir:
if dir:
yield node
2017-01-15 01:16:44 +01:00
elif src:
yield node
2011-09-10 11:13:51 +02:00
if isdir:
2011-09-10 11:13:51 +02:00
node.cache_isdir = True
if maxdepth:
2011-12-14 09:20:34 +01:00
for k in node.ant_iter(accept=accept, maxdepth=maxdepth - 1, pats=npats, dir=dir, src=src, remove=remove):
2011-09-10 11:13:51 +02:00
yield k
raise StopIteration
def ant_glob(self, *k, **kw):
"""
2016-06-25 12:50:04 +02:00
Finds files across folders:
2011-09-10 11:13:51 +02:00
* ``**/*`` find all files recursively
* ``**/*.class`` find all files ending by .class
* ``..`` find files having two dot characters
For example::
def configure(cfg):
2016-06-25 12:50:04 +02:00
cfg.path.ant_glob('**/*.cpp') # finds all .cpp files
cfg.root.ant_glob('etc/*.txt') # matching from the filesystem root can be slow
2011-09-10 11:13:51 +02:00
cfg.path.ant_glob('*.cpp', excl=['*.c'], src=True, dir=False)
For more information see http://ant.apache.org/manual/dirtasks.html
2016-06-25 12:50:04 +02:00
The nodes that correspond to files and folders that do not exist are garbage-collected.
To prevent this behaviour in particular when running over the build directory, pass ``remove=False``
2011-09-10 11:13:51 +02:00
:param incl: ant patterns or list of patterns to include
:type incl: string or list of strings
:param excl: ant patterns or list of patterns to exclude
:type excl: string or list of strings
:param dir: return folders too (False by default)
:type dir: bool
:param src: return files (True by default)
:type src: bool
:param remove: remove files/folders that do not exist (True by default)
:type remove: bool
:param maxdepth: maximum depth of recursion
:type maxdepth: int
:param ignorecase: ignore case while matching (False by default)
:type ignorecase: bool
2016-06-25 12:50:04 +02:00
:returns: The corresponding Nodes
:type generator: bool
:returns: Whether to evaluate the Nodes lazily, alters the type of the returned value
:rtype: by default, list of :py:class:`waflib.Node.Node` instances
2011-09-10 11:13:51 +02:00
"""
src = kw.get('src', True)
2017-01-15 01:16:44 +01:00
dir = kw.get('dir')
2011-09-10 11:13:51 +02:00
excl = kw.get('excl', exclude_regs)
incl = k and k[0] or kw.get('incl', '**')
2017-01-15 01:16:44 +01:00
reflags = kw.get('ignorecase', re.I)
2011-09-10 11:13:51 +02:00
def to_pat(s):
ret = []
2017-01-15 01:16:44 +01:00
for x in Utils.to_list(s):
2011-09-10 11:13:51 +02:00
x = x.replace('\\', '/').replace('//', '/')
if x.endswith('/'):
x += '**'
accu = []
2017-01-15 01:16:44 +01:00
for k in x.split('/'):
2011-09-10 11:13:51 +02:00
if k == '**':
accu.append(k)
else:
k = k.replace('.', '[.]').replace('*','.*').replace('?', '.').replace('+', '\\+')
k = '^%s$' % k
try:
#print "pattern", k
2017-01-15 01:16:44 +01:00
exp = re.compile(k, flags=reflags)
2011-09-10 11:13:51 +02:00
except Exception as e:
2016-06-05 00:23:57 +02:00
raise Errors.WafError('Invalid pattern: %s' % k, e)
2017-01-15 01:16:44 +01:00
else:
accu.append(exp)
2011-09-10 11:13:51 +02:00
ret.append(accu)
return ret
def filtre(name, nn):
ret = []
for lst in nn:
if not lst:
pass
elif lst[0] == '**':
ret.append(lst)
if len(lst) > 1:
if lst[1].match(name):
ret.append(lst[2:])
else:
ret.append([])
elif lst[0].match(name):
ret.append(lst[1:])
return ret
def accept(name, pats):
nacc = filtre(name, pats[0])
nrej = filtre(name, pats[1])
if [] in nrej:
nacc = []
return [nacc, nrej]
it = self.ant_iter(accept=accept, pats=[to_pat(incl), to_pat(excl)], maxdepth=kw.get('maxdepth', 25), dir=dir, src=src, remove=kw.get('remove', True))
2017-01-15 01:16:44 +01:00
if kw.get('flat'):
# returns relative paths as a space-delimited string
# prefer Node objects whenever possible
return ' '.join(x.path_from(self) for x in it)
elif kw.get('generator'):
return it
return list(it)
2011-09-10 11:13:51 +02:00
2017-01-15 01:16:44 +01:00
# ----------------------------------------------------------------------------
# the methods below require the source/build folders (bld.srcnode/bld.bldnode)
2011-09-10 11:13:51 +02:00
def is_src(self):
"""
2016-06-25 12:50:04 +02:00
Returns True if the node is below the source directory. Note that ``!is_src() is_bld()``
2011-09-10 11:13:51 +02:00
:rtype: bool
"""
cur = self
2016-03-25 14:02:36 +01:00
x = self.ctx.srcnode
y = self.ctx.bldnode
2011-09-10 11:13:51 +02:00
while cur.parent:
2016-03-25 14:02:36 +01:00
if cur is y:
2011-09-10 11:13:51 +02:00
return False
2016-03-25 14:02:36 +01:00
if cur is x:
2011-09-10 11:13:51 +02:00
return True
cur = cur.parent
return False
def is_bld(self):
"""
2016-06-25 12:50:04 +02:00
Returns True if the node is below the build directory. Note that ``!is_bld() is_src()``
2011-09-10 11:13:51 +02:00
:rtype: bool
"""
cur = self
2016-03-25 14:02:36 +01:00
y = self.ctx.bldnode
2011-09-10 11:13:51 +02:00
while cur.parent:
2016-03-25 14:02:36 +01:00
if cur is y:
2011-09-10 11:13:51 +02:00
return True
cur = cur.parent
return False
def get_src(self):
"""
2017-04-01 10:12:17 +02:00
Returns the corresponding Node object in the source directory (or self if already
under the source directory). Use this method only if the purpose is to create
a Node object (this is common with folders but not with files, see ticket 1937)
2011-09-10 11:13:51 +02:00
:rtype: :py:class:`waflib.Node.Node`
"""
cur = self
2016-03-25 14:02:36 +01:00
x = self.ctx.srcnode
y = self.ctx.bldnode
2011-09-10 11:13:51 +02:00
lst = []
while cur.parent:
2016-03-25 14:02:36 +01:00
if cur is y:
2011-09-10 11:13:51 +02:00
lst.reverse()
2016-03-25 14:02:36 +01:00
return x.make_node(lst)
if cur is x:
2011-09-10 11:13:51 +02:00
return self
lst.append(cur.name)
cur = cur.parent
return self
def get_bld(self):
"""
2017-04-01 10:12:17 +02:00
Return the corresponding Node object in the build directory (or self if already
under the build directory). Use this method only if the purpose is to create
a Node object (this is common with folders but not with files, see ticket 1937)
2011-09-10 11:13:51 +02:00
:rtype: :py:class:`waflib.Node.Node`
"""
cur = self
2016-03-25 14:02:36 +01:00
x = self.ctx.srcnode
y = self.ctx.bldnode
2011-09-10 11:13:51 +02:00
lst = []
while cur.parent:
2016-03-25 14:02:36 +01:00
if cur is y:
2011-09-10 11:13:51 +02:00
return self
2016-03-25 14:02:36 +01:00
if cur is x:
2011-09-10 11:13:51 +02:00
lst.reverse()
return self.ctx.bldnode.make_node(lst)
lst.append(cur.name)
cur = cur.parent
2011-10-09 10:54:11 +02:00
# the file is external to the current project, make a fake root in the current build directory
2011-10-09 19:46:34 +02:00
lst.reverse()
if lst and Utils.is_win32 and len(lst[0]) == 2 and lst[0].endswith(':'):
lst[0] = lst[0][0]
2011-10-09 10:54:11 +02:00
return self.ctx.bldnode.make_node(['__root__'] + lst)
2011-09-10 11:13:51 +02:00
def find_resource(self, lst):
"""
2016-06-25 12:50:04 +02:00
Use this method in the build phase to find source files corresponding to the relative path given.
First it looks up the Node data structure to find any declared Node object in the build directory.
If None is found, it then considers the filesystem in the source directory.
2011-09-10 11:13:51 +02:00
2016-06-25 12:50:04 +02:00
:param lst: relative path
2011-09-10 11:13:51 +02:00
:type lst: string or list of string
2016-06-25 12:50:04 +02:00
:returns: the corresponding Node object or None
:rtype: :py:class:`waflib.Node.Node`
2011-09-10 11:13:51 +02:00
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
2011-09-10 11:13:51 +02:00
node = self.get_bld().search_node(lst)
2011-09-10 11:13:51 +02:00
if not node:
node = self.get_src().find_node(lst)
if node and node.isdir():
return None
2011-09-10 11:13:51 +02:00
return node
def find_or_declare(self, lst):
"""
Use this method in the build phase to declare output files which
are meant to be written in the build directory.
2016-06-25 12:50:04 +02:00
This method creates the Node object and its parent folder
as needed.
2011-09-10 11:13:51 +02:00
2016-06-25 12:50:04 +02:00
:param lst: relative path
2011-09-10 11:13:51 +02:00
:type lst: string or list of string
"""
if isinstance(lst, str) and os.path.isabs(lst):
node = self.ctx.root.make_node(lst)
else:
node = self.get_bld().make_node(lst)
2011-09-10 11:13:51 +02:00
node.parent.mkdir()
return node
def find_dir(self, lst):
"""
2016-06-25 12:50:04 +02:00
Searches for a folder on the filesystem (see :py:meth:`waflib.Node.Node.find_node`)
2011-09-10 11:13:51 +02:00
2016-06-25 12:50:04 +02:00
:param lst: relative path
2011-09-10 11:13:51 +02:00
:type lst: string or list of string
2016-06-25 12:50:04 +02:00
:returns: The corresponding Node object or None if there is no such folder
:rtype: :py:class:`waflib.Node.Node`
2011-09-10 11:13:51 +02:00
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
2011-09-10 11:13:51 +02:00
node = self.find_node(lst)
if node and not node.isdir():
2011-09-10 11:13:51 +02:00
return None
return node
# helpers for building things
def change_ext(self, ext, ext_in=None):
"""
2016-06-25 12:50:04 +02:00
Declares a build node with a distinct extension; this is uses :py:meth:`waflib.Node.Node.find_or_declare`
2011-09-10 11:13:51 +02:00
:return: A build node of the same path, but with a different extension
:rtype: :py:class:`waflib.Node.Node`
"""
name = self.name
if ext_in is None:
k = name.rfind('.')
if k >= 0:
name = name[:k] + ext
else:
name = name + ext
else:
name = name[:- len(ext_in)] + ext
return self.parent.find_or_declare([name])
def bldpath(self):
2016-06-25 12:50:04 +02:00
"""
Returns the relative path seen from the build directory ``src/foo.cpp``
:rtype: string
"""
2011-09-10 11:13:51 +02:00
return self.path_from(self.ctx.bldnode)
def srcpath(self):
2016-06-25 12:50:04 +02:00
"""
Returns the relative path seen from the source directory ``../src/foo.cpp``
:rtype: string
"""
2011-09-10 11:13:51 +02:00
return self.path_from(self.ctx.srcnode)
def relpath(self):
2016-06-25 12:50:04 +02:00
"""
If a file in the build directory, returns :py:meth:`waflib.Node.Node.bldpath`,
else returns :py:meth:`waflib.Node.Node.srcpath`
:rtype: string
"""
2011-09-10 11:13:51 +02:00
cur = self
2016-03-25 14:02:36 +01:00
x = self.ctx.bldnode
2011-09-10 11:13:51 +02:00
while cur.parent:
2016-03-25 14:02:36 +01:00
if cur is x:
2011-09-10 11:13:51 +02:00
return self.bldpath()
cur = cur.parent
return self.srcpath()
def bld_dir(self):
2016-06-25 12:50:04 +02:00
"""
Equivalent to self.parent.bldpath()
:rtype: string
"""
2011-09-10 11:13:51 +02:00
return self.parent.bldpath()
def h_file(self):
2016-06-25 12:50:04 +02:00
"""
See :py:func:`waflib.Utils.h_file`
:return: a hash representing the file contents
:rtype: string or bytes
"""
return Utils.h_file(self.abspath())
2011-09-10 11:13:51 +02:00
def get_bld_sig(self):
"""
2016-06-25 12:50:04 +02:00
Returns a signature (see :py:meth:`waflib.Node.Node.h_file`) for the purpose
of build dependency calculation. This method uses a per-context cache.
:return: a hash representing the object contents
:rtype: string or bytes
2011-09-10 11:13:51 +02:00
"""
# previous behaviour can be set by returning self.ctx.node_sigs[self] when a build node
try:
cache = self.ctx.cache_sig
except AttributeError:
cache = self.ctx.cache_sig = {}
try:
ret = cache[self]
except KeyError:
p = self.abspath()
try:
ret = cache[self] = self.h_file()
except EnvironmentError:
if self.isdir():
# allow folders as build nodes, do not use the creation time
st = os.stat(p)
ret = cache[self] = Utils.h_list([p, st.st_ino, st.st_mode])
return ret
raise
return ret
2011-09-10 11:13:51 +02:00
pickle_lock = Utils.threading.Lock()
"""Lock mandatory for thread-safe node serialization"""
class Nod3(Node):
"""Mandatory subclass for thread-safe node serialization"""
pass # do not remove