jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

970 lines
25KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2018 (ita)
  4. """
  5. Node: filesystem structure
  6. #. Each file/folder is represented by exactly one node.
  7. #. Some potential class properties are stored on :py:class:`waflib.Build.BuildContext` : nodes to depend on, etc.
  8. Unused class members can increase the `.wafpickle` file size sensibly.
  9. #. Node objects should never be created directly, use
  10. the methods :py:func:`Node.make_node` or :py:func:`Node.find_node` for the low-level operations
  11. #. The methods :py:func:`Node.find_resource`, :py:func:`Node.find_dir` :py:func:`Node.find_or_declare` must be
  12. used when a build context is present
  13. #. Each instance of :py:class:`waflib.Context.Context` has a unique :py:class:`Node` subclass required for serialization.
  14. (:py:class:`waflib.Node.Nod3`, see the :py:class:`waflib.Context.Context` initializer). A reference to the context
  15. owning a node is held as *self.ctx*
  16. """
  17. import os, re, sys, shutil
  18. from waflib import Utils, Errors
  19. exclude_regs = '''
  20. **/*~
  21. **/#*#
  22. **/.#*
  23. **/%*%
  24. **/._*
  25. **/*.swp
  26. **/CVS
  27. **/CVS/**
  28. **/.cvsignore
  29. **/SCCS
  30. **/SCCS/**
  31. **/vssver.scc
  32. **/.svn
  33. **/.svn/**
  34. **/BitKeeper
  35. **/.git
  36. **/.git/**
  37. **/.gitignore
  38. **/.bzr
  39. **/.bzrignore
  40. **/.bzr/**
  41. **/.hg
  42. **/.hg/**
  43. **/_MTN
  44. **/_MTN/**
  45. **/.arch-ids
  46. **/{arch}
  47. **/_darcs
  48. **/_darcs/**
  49. **/.intlcache
  50. **/.DS_Store'''
  51. """
  52. Ant patterns for files and folders to exclude while doing the
  53. recursive traversal in :py:meth:`waflib.Node.Node.ant_glob`
  54. """
  55. def ant_matcher(s, ignorecase):
  56. reflags = re.I if ignorecase else 0
  57. ret = []
  58. for x in Utils.to_list(s):
  59. x = x.replace('\\', '/').replace('//', '/')
  60. if x.endswith('/'):
  61. x += '**'
  62. accu = []
  63. for k in x.split('/'):
  64. if k == '**':
  65. accu.append(k)
  66. else:
  67. k = k.replace('.', '[.]').replace('*', '.*').replace('?', '.').replace('+', '\\+')
  68. k = '^%s$' % k
  69. try:
  70. exp = re.compile(k, flags=reflags)
  71. except Exception as e:
  72. raise Errors.WafError('Invalid pattern: %s' % k, e)
  73. else:
  74. accu.append(exp)
  75. ret.append(accu)
  76. return ret
  77. def ant_sub_filter(name, nn):
  78. ret = []
  79. for lst in nn:
  80. if not lst:
  81. pass
  82. elif lst[0] == '**':
  83. ret.append(lst)
  84. if len(lst) > 1:
  85. if lst[1].match(name):
  86. ret.append(lst[2:])
  87. else:
  88. ret.append([])
  89. elif lst[0].match(name):
  90. ret.append(lst[1:])
  91. return ret
  92. def ant_sub_matcher(name, pats):
  93. nacc = ant_sub_filter(name, pats[0])
  94. nrej = ant_sub_filter(name, pats[1])
  95. if [] in nrej:
  96. nacc = []
  97. return [nacc, nrej]
  98. class Node(object):
  99. """
  100. This class is organized in two parts:
  101. * The basic methods meant for filesystem access (compute paths, create folders, etc)
  102. * The methods bound to a :py:class:`waflib.Build.BuildContext` (require ``bld.srcnode`` and ``bld.bldnode``)
  103. """
  104. dict_class = dict
  105. """
  106. Subclasses can provide a dict class to enable case insensitivity for example.
  107. """
  108. __slots__ = ('name', 'parent', 'children', 'cache_abspath', 'cache_isdir')
  109. def __init__(self, name, parent):
  110. """
  111. .. note:: Use :py:func:`Node.make_node` or :py:func:`Node.find_node` instead of calling this constructor
  112. """
  113. self.name = name
  114. self.parent = parent
  115. if parent:
  116. if name in parent.children:
  117. raise Errors.WafError('node %s exists in the parent files %r already' % (name, parent))
  118. parent.children[name] = self
  119. def __setstate__(self, data):
  120. "Deserializes node information, used for persistence"
  121. self.name = data[0]
  122. self.parent = data[1]
  123. if data[2] is not None:
  124. # Issue 1480
  125. self.children = self.dict_class(data[2])
  126. def __getstate__(self):
  127. "Serializes node information, used for persistence"
  128. return (self.name, self.parent, getattr(self, 'children', None))
  129. def __str__(self):
  130. """
  131. String representation (abspath), for debugging purposes
  132. :rtype: string
  133. """
  134. return self.abspath()
  135. def __repr__(self):
  136. """
  137. String representation (abspath), for debugging purposes
  138. :rtype: string
  139. """
  140. return self.abspath()
  141. def __copy__(self):
  142. """
  143. Provided to prevent nodes from being copied
  144. :raises: :py:class:`waflib.Errors.WafError`
  145. """
  146. raise Errors.WafError('nodes are not supposed to be copied')
  147. def read(self, flags='r', encoding='latin-1'):
  148. """
  149. Reads and returns the contents of the file represented by this node, see :py:func:`waflib.Utils.readf`::
  150. def build(bld):
  151. bld.path.find_node('wscript').read()
  152. :param flags: Open mode
  153. :type flags: string
  154. :param encoding: encoding value for Python3
  155. :type encoding: string
  156. :rtype: string or bytes
  157. :return: File contents
  158. """
  159. return Utils.readf(self.abspath(), flags, encoding)
  160. def write(self, data, flags='w', encoding='latin-1'):
  161. """
  162. Writes data to the file represented by this node, see :py:func:`waflib.Utils.writef`::
  163. def build(bld):
  164. bld.path.make_node('foo.txt').write('Hello, world!')
  165. :param data: data to write
  166. :type data: string
  167. :param flags: Write mode
  168. :type flags: string
  169. :param encoding: encoding value for Python3
  170. :type encoding: string
  171. """
  172. Utils.writef(self.abspath(), data, flags, encoding)
  173. def read_json(self, convert=True, encoding='utf-8'):
  174. """
  175. Reads and parses the contents of this node as JSON (Python ≥ 2.6)::
  176. def build(bld):
  177. bld.path.find_node('abc.json').read_json()
  178. Note that this by default automatically decodes unicode strings on Python2, unlike what the Python JSON module does.
  179. :type convert: boolean
  180. :param convert: Prevents decoding of unicode strings on Python2
  181. :type encoding: string
  182. :param encoding: The encoding of the file to read. This default to UTF8 as per the JSON standard
  183. :rtype: object
  184. :return: Parsed file contents
  185. """
  186. import json # Python 2.6 and up
  187. object_pairs_hook = None
  188. if convert and sys.hexversion < 0x3000000:
  189. try:
  190. _type = unicode
  191. except NameError:
  192. _type = str
  193. def convert(value):
  194. if isinstance(value, list):
  195. return [convert(element) for element in value]
  196. elif isinstance(value, _type):
  197. return str(value)
  198. else:
  199. return value
  200. def object_pairs(pairs):
  201. return dict((str(pair[0]), convert(pair[1])) for pair in pairs)
  202. object_pairs_hook = object_pairs
  203. return json.loads(self.read(encoding=encoding), object_pairs_hook=object_pairs_hook)
  204. def write_json(self, data, pretty=True):
  205. """
  206. Writes a python object as JSON to disk (Python ≥ 2.6) as UTF-8 data (JSON standard)::
  207. def build(bld):
  208. bld.path.find_node('xyz.json').write_json(199)
  209. :type data: object
  210. :param data: The data to write to disk
  211. :type pretty: boolean
  212. :param pretty: Determines if the JSON will be nicely space separated
  213. """
  214. import json # Python 2.6 and up
  215. indent = 2
  216. separators = (',', ': ')
  217. sort_keys = pretty
  218. newline = os.linesep
  219. if not pretty:
  220. indent = None
  221. separators = (',', ':')
  222. newline = ''
  223. output = json.dumps(data, indent=indent, separators=separators, sort_keys=sort_keys) + newline
  224. self.write(output, encoding='utf-8')
  225. def exists(self):
  226. """
  227. Returns whether the Node is present on the filesystem
  228. :rtype: bool
  229. """
  230. return os.path.exists(self.abspath())
  231. def isdir(self):
  232. """
  233. Returns whether the Node represents a folder
  234. :rtype: bool
  235. """
  236. return os.path.isdir(self.abspath())
  237. def chmod(self, val):
  238. """
  239. Changes the file/dir permissions::
  240. def build(bld):
  241. bld.path.chmod(493) # 0755
  242. """
  243. os.chmod(self.abspath(), val)
  244. def delete(self, evict=True):
  245. """
  246. Removes the file/folder from the filesystem (equivalent to `rm -rf`), and remove this object from the Node tree.
  247. Do not use this object after calling this method.
  248. """
  249. try:
  250. try:
  251. if os.path.isdir(self.abspath()):
  252. shutil.rmtree(self.abspath())
  253. else:
  254. os.remove(self.abspath())
  255. except OSError:
  256. if os.path.exists(self.abspath()):
  257. raise
  258. finally:
  259. if evict:
  260. self.evict()
  261. def evict(self):
  262. """
  263. Removes this node from the Node tree
  264. """
  265. del self.parent.children[self.name]
  266. def suffix(self):
  267. """
  268. Returns the file rightmost extension, for example `a.b.c.d → .d`
  269. :rtype: string
  270. """
  271. k = max(0, self.name.rfind('.'))
  272. return self.name[k:]
  273. def height(self):
  274. """
  275. Returns the depth in the folder hierarchy from the filesystem root or from all the file drives
  276. :returns: filesystem depth
  277. :rtype: integer
  278. """
  279. d = self
  280. val = -1
  281. while d:
  282. d = d.parent
  283. val += 1
  284. return val
  285. def listdir(self):
  286. """
  287. Lists the folder contents
  288. :returns: list of file/folder names ordered alphabetically
  289. :rtype: list of string
  290. """
  291. lst = Utils.listdir(self.abspath())
  292. lst.sort()
  293. return lst
  294. def mkdir(self):
  295. """
  296. Creates a folder represented by this node. Intermediate folders are created as needed.
  297. :raises: :py:class:`waflib.Errors.WafError` when the folder is missing
  298. """
  299. if self.isdir():
  300. return
  301. try:
  302. self.parent.mkdir()
  303. except OSError:
  304. pass
  305. if self.name:
  306. try:
  307. os.makedirs(self.abspath())
  308. except OSError:
  309. pass
  310. if not self.isdir():
  311. raise Errors.WafError('Could not create the directory %r' % self)
  312. try:
  313. self.children
  314. except AttributeError:
  315. self.children = self.dict_class()
  316. def find_node(self, lst):
  317. """
  318. Finds a node on the file system (files or folders), and creates the corresponding Node objects if it exists
  319. :param lst: relative path
  320. :type lst: string or list of string
  321. :returns: The corresponding Node object or None if no entry was found on the filesystem
  322. :rtype: :py:class:´waflib.Node.Node´
  323. """
  324. if isinstance(lst, str):
  325. lst = [x for x in Utils.split_path(lst) if x and x != '.']
  326. if lst and lst[0].startswith('\\\\') and not self.parent:
  327. node = self.ctx.root.make_node(lst[0])
  328. node.cache_isdir = True
  329. return node.find_node(lst[1:])
  330. cur = self
  331. for x in lst:
  332. if x == '..':
  333. cur = cur.parent or cur
  334. continue
  335. try:
  336. ch = cur.children
  337. except AttributeError:
  338. cur.children = self.dict_class()
  339. else:
  340. try:
  341. cur = ch[x]
  342. continue
  343. except KeyError:
  344. pass
  345. # optimistic: create the node first then look if it was correct to do so
  346. cur = self.__class__(x, cur)
  347. if not cur.exists():
  348. cur.evict()
  349. return None
  350. if not cur.exists():
  351. cur.evict()
  352. return None
  353. return cur
  354. def make_node(self, lst):
  355. """
  356. Returns or creates a Node object corresponding to the input path without considering the filesystem.
  357. :param lst: relative path
  358. :type lst: string or list of string
  359. :rtype: :py:class:´waflib.Node.Node´
  360. """
  361. if isinstance(lst, str):
  362. lst = [x for x in Utils.split_path(lst) if x and x != '.']
  363. cur = self
  364. for x in lst:
  365. if x == '..':
  366. cur = cur.parent or cur
  367. continue
  368. try:
  369. cur = cur.children[x]
  370. except AttributeError:
  371. cur.children = self.dict_class()
  372. except KeyError:
  373. pass
  374. else:
  375. continue
  376. cur = self.__class__(x, cur)
  377. return cur
  378. def search_node(self, lst):
  379. """
  380. Returns a Node previously defined in the data structure. The filesystem is not considered.
  381. :param lst: relative path
  382. :type lst: string or list of string
  383. :rtype: :py:class:´waflib.Node.Node´ or None if there is no entry in the Node datastructure
  384. """
  385. if isinstance(lst, str):
  386. lst = [x for x in Utils.split_path(lst) if x and x != '.']
  387. cur = self
  388. for x in lst:
  389. if x == '..':
  390. cur = cur.parent or cur
  391. else:
  392. try:
  393. cur = cur.children[x]
  394. except (AttributeError, KeyError):
  395. return None
  396. return cur
  397. def path_from(self, node):
  398. """
  399. Path of this node seen from the other::
  400. def build(bld):
  401. n1 = bld.path.find_node('foo/bar/xyz.txt')
  402. n2 = bld.path.find_node('foo/stuff/')
  403. n1.path_from(n2) # '../bar/xyz.txt'
  404. :param node: path to use as a reference
  405. :type node: :py:class:`waflib.Node.Node`
  406. :returns: a relative path or an absolute one if that is better
  407. :rtype: string
  408. """
  409. c1 = self
  410. c2 = node
  411. c1h = c1.height()
  412. c2h = c2.height()
  413. lst = []
  414. up = 0
  415. while c1h > c2h:
  416. lst.append(c1.name)
  417. c1 = c1.parent
  418. c1h -= 1
  419. while c2h > c1h:
  420. up += 1
  421. c2 = c2.parent
  422. c2h -= 1
  423. while not c1 is c2:
  424. lst.append(c1.name)
  425. up += 1
  426. c1 = c1.parent
  427. c2 = c2.parent
  428. if c1.parent:
  429. lst.extend(['..'] * up)
  430. lst.reverse()
  431. return os.sep.join(lst) or '.'
  432. else:
  433. return self.abspath()
  434. def abspath(self):
  435. """
  436. Returns the absolute path. A cache is kept in the context as ``cache_node_abspath``
  437. :rtype: string
  438. """
  439. try:
  440. return self.cache_abspath
  441. except AttributeError:
  442. pass
  443. # think twice before touching this (performance + complexity + correctness)
  444. if not self.parent:
  445. val = os.sep
  446. elif not self.parent.name:
  447. val = os.sep + self.name
  448. else:
  449. val = self.parent.abspath() + os.sep + self.name
  450. self.cache_abspath = val
  451. return val
  452. if Utils.is_win32:
  453. def abspath(self):
  454. try:
  455. return self.cache_abspath
  456. except AttributeError:
  457. pass
  458. if not self.parent:
  459. val = ''
  460. elif not self.parent.name:
  461. val = self.name + os.sep
  462. else:
  463. val = self.parent.abspath().rstrip(os.sep) + os.sep + self.name
  464. self.cache_abspath = val
  465. return val
  466. def is_child_of(self, node):
  467. """
  468. Returns whether the object belongs to a subtree of the input node::
  469. def build(bld):
  470. node = bld.path.find_node('wscript')
  471. node.is_child_of(bld.path) # True
  472. :param node: path to use as a reference
  473. :type node: :py:class:`waflib.Node.Node`
  474. :rtype: bool
  475. """
  476. p = self
  477. diff = self.height() - node.height()
  478. while diff > 0:
  479. diff -= 1
  480. p = p.parent
  481. return p is node
  482. def ant_iter(self, accept=None, maxdepth=25, pats=[], dir=False, src=True, remove=True, quiet=False):
  483. """
  484. Recursive method used by :py:meth:`waflib.Node.ant_glob`.
  485. :param accept: function used for accepting/rejecting a node, returns the patterns that can be still accepted in recursion
  486. :type accept: function
  487. :param maxdepth: maximum depth in the filesystem (25)
  488. :type maxdepth: int
  489. :param pats: list of patterns to accept and list of patterns to exclude
  490. :type pats: tuple
  491. :param dir: return folders too (False by default)
  492. :type dir: bool
  493. :param src: return files (True by default)
  494. :type src: bool
  495. :param remove: remove files/folders that do not exist (True by default)
  496. :type remove: bool
  497. :param quiet: disable build directory traversal warnings (verbose mode)
  498. :type quiet: bool
  499. :returns: A generator object to iterate from
  500. :rtype: iterator
  501. """
  502. dircont = self.listdir()
  503. try:
  504. lst = set(self.children.keys())
  505. except AttributeError:
  506. self.children = self.dict_class()
  507. else:
  508. if remove:
  509. for x in lst - set(dircont):
  510. self.children[x].evict()
  511. for name in dircont:
  512. npats = accept(name, pats)
  513. if npats and npats[0]:
  514. accepted = [] in npats[0]
  515. node = self.make_node([name])
  516. isdir = node.isdir()
  517. if accepted:
  518. if isdir:
  519. if dir:
  520. yield node
  521. elif src:
  522. yield node
  523. if isdir:
  524. node.cache_isdir = True
  525. if maxdepth:
  526. for k in node.ant_iter(accept=accept, maxdepth=maxdepth - 1, pats=npats, dir=dir, src=src, remove=remove, quiet=quiet):
  527. yield k
  528. def ant_glob(self, *k, **kw):
  529. """
  530. Finds files across folders and returns Node objects:
  531. * ``**/*`` find all files recursively
  532. * ``**/*.class`` find all files ending by .class
  533. * ``..`` find files having two dot characters
  534. For example::
  535. def configure(cfg):
  536. # find all .cpp files
  537. cfg.path.ant_glob('**/*.cpp')
  538. # find particular files from the root filesystem (can be slow)
  539. cfg.root.ant_glob('etc/*.txt')
  540. # simple exclusion rule example
  541. cfg.path.ant_glob('*.c*', excl=['*.c'], src=True, dir=False)
  542. For more information about the patterns, consult http://ant.apache.org/manual/dirtasks.html
  543. Please remember that the '..' sequence does not represent the parent directory::
  544. def configure(cfg):
  545. cfg.path.ant_glob('../*.h') # incorrect
  546. cfg.path.parent.ant_glob('*.h') # correct
  547. The Node structure is itself a filesystem cache, so certain precautions must
  548. be taken while matching files in the build or installation phases.
  549. Nodes objects that do have a corresponding file or folder are garbage-collected by default.
  550. This garbage collection is usually required to prevent returning files that do not
  551. exist anymore. Yet, this may also remove Node objects of files that are yet-to-be built.
  552. This typically happens when trying to match files in the build directory,
  553. but there are also cases when files are created in the source directory.
  554. Run ``waf -v`` to display any warnings, and try consider passing ``remove=False``
  555. when matching files in the build directory.
  556. Since ant_glob can traverse both source and build folders, it is a best practice
  557. to call this method only from the most specific build node::
  558. def build(bld):
  559. # traverses the build directory, may need ``remove=False``:
  560. bld.path.ant_glob('project/dir/**/*.h')
  561. # better, no accidental build directory traversal:
  562. bld.path.find_node('project/dir').ant_glob('**/*.h') # best
  563. In addition, files and folders are listed immediately. When matching files in the
  564. build folders, consider passing ``generator=True`` so that the generator object
  565. returned can defer computation to a later stage. For example::
  566. def build(bld):
  567. bld(rule='tar xvf ${SRC}', source='arch.tar')
  568. bld.add_group()
  569. gen = bld.bldnode.ant_glob("*.h", generator=True, remove=True)
  570. # files will be listed only after the arch.tar is unpacked
  571. bld(rule='ls ${SRC}', source=gen, name='XYZ')
  572. :param incl: ant patterns or list of patterns to include
  573. :type incl: string or list of strings
  574. :param excl: ant patterns or list of patterns to exclude
  575. :type excl: string or list of strings
  576. :param dir: return folders too (False by default)
  577. :type dir: bool
  578. :param src: return files (True by default)
  579. :type src: bool
  580. :param maxdepth: maximum depth of recursion
  581. :type maxdepth: int
  582. :param ignorecase: ignore case while matching (False by default)
  583. :type ignorecase: bool
  584. :param generator: Whether to evaluate the Nodes lazily
  585. :type generator: bool
  586. :param remove: remove files/folders that do not exist (True by default)
  587. :type remove: bool
  588. :param quiet: disable build directory traversal warnings (verbose mode)
  589. :type quiet: bool
  590. :returns: The corresponding Node objects as a list or as a generator object (generator=True)
  591. :rtype: by default, list of :py:class:`waflib.Node.Node` instances
  592. """
  593. src = kw.get('src', True)
  594. dir = kw.get('dir')
  595. excl = kw.get('excl', exclude_regs)
  596. incl = k and k[0] or kw.get('incl', '**')
  597. remove = kw.get('remove', True)
  598. maxdepth = kw.get('maxdepth', 25)
  599. ignorecase = kw.get('ignorecase', False)
  600. quiet = kw.get('quiet', False)
  601. pats = (ant_matcher(incl, ignorecase), ant_matcher(excl, ignorecase))
  602. if kw.get('generator'):
  603. return Utils.lazy_generator(self.ant_iter, (ant_sub_matcher, maxdepth, pats, dir, src, remove, quiet))
  604. it = self.ant_iter(ant_sub_matcher, maxdepth, pats, dir, src, remove, quiet)
  605. if kw.get('flat'):
  606. # returns relative paths as a space-delimited string
  607. # prefer Node objects whenever possible
  608. return ' '.join(x.path_from(self) for x in it)
  609. return list(it)
  610. # ----------------------------------------------------------------------------
  611. # the methods below require the source/build folders (bld.srcnode/bld.bldnode)
  612. def is_src(self):
  613. """
  614. Returns True if the node is below the source directory. Note that ``!is_src() ≠ is_bld()``
  615. :rtype: bool
  616. """
  617. cur = self
  618. x = self.ctx.srcnode
  619. y = self.ctx.bldnode
  620. while cur.parent:
  621. if cur is y:
  622. return False
  623. if cur is x:
  624. return True
  625. cur = cur.parent
  626. return False
  627. def is_bld(self):
  628. """
  629. Returns True if the node is below the build directory. Note that ``!is_bld() ≠ is_src()``
  630. :rtype: bool
  631. """
  632. cur = self
  633. y = self.ctx.bldnode
  634. while cur.parent:
  635. if cur is y:
  636. return True
  637. cur = cur.parent
  638. return False
  639. def get_src(self):
  640. """
  641. Returns the corresponding Node object in the source directory (or self if already
  642. under the source directory). Use this method only if the purpose is to create
  643. a Node object (this is common with folders but not with files, see ticket 1937)
  644. :rtype: :py:class:`waflib.Node.Node`
  645. """
  646. cur = self
  647. x = self.ctx.srcnode
  648. y = self.ctx.bldnode
  649. lst = []
  650. while cur.parent:
  651. if cur is y:
  652. lst.reverse()
  653. return x.make_node(lst)
  654. if cur is x:
  655. return self
  656. lst.append(cur.name)
  657. cur = cur.parent
  658. return self
  659. def get_bld(self):
  660. """
  661. Return the corresponding Node object in the build directory (or self if already
  662. under the build directory). Use this method only if the purpose is to create
  663. a Node object (this is common with folders but not with files, see ticket 1937)
  664. :rtype: :py:class:`waflib.Node.Node`
  665. """
  666. cur = self
  667. x = self.ctx.srcnode
  668. y = self.ctx.bldnode
  669. lst = []
  670. while cur.parent:
  671. if cur is y:
  672. return self
  673. if cur is x:
  674. lst.reverse()
  675. return self.ctx.bldnode.make_node(lst)
  676. lst.append(cur.name)
  677. cur = cur.parent
  678. # the file is external to the current project, make a fake root in the current build directory
  679. lst.reverse()
  680. if lst and Utils.is_win32 and len(lst[0]) == 2 and lst[0].endswith(':'):
  681. lst[0] = lst[0][0]
  682. return self.ctx.bldnode.make_node(['__root__'] + lst)
  683. def find_resource(self, lst):
  684. """
  685. Use this method in the build phase to find source files corresponding to the relative path given.
  686. First it looks up the Node data structure to find any declared Node object in the build directory.
  687. If None is found, it then considers the filesystem in the source directory.
  688. :param lst: relative path
  689. :type lst: string or list of string
  690. :returns: the corresponding Node object or None
  691. :rtype: :py:class:`waflib.Node.Node`
  692. """
  693. if isinstance(lst, str):
  694. lst = [x for x in Utils.split_path(lst) if x and x != '.']
  695. node = self.get_bld().search_node(lst)
  696. if not node:
  697. node = self.get_src().find_node(lst)
  698. if node and node.isdir():
  699. return None
  700. return node
  701. def find_or_declare(self, lst):
  702. """
  703. Use this method in the build phase to declare output files which
  704. are meant to be written in the build directory.
  705. This method creates the Node object and its parent folder
  706. as needed.
  707. :param lst: relative path
  708. :type lst: string or list of string
  709. """
  710. if isinstance(lst, str) and os.path.isabs(lst):
  711. node = self.ctx.root.make_node(lst)
  712. else:
  713. node = self.get_bld().make_node(lst)
  714. node.parent.mkdir()
  715. return node
  716. def find_dir(self, lst):
  717. """
  718. Searches for a folder on the filesystem (see :py:meth:`waflib.Node.Node.find_node`)
  719. :param lst: relative path
  720. :type lst: string or list of string
  721. :returns: The corresponding Node object or None if there is no such folder
  722. :rtype: :py:class:`waflib.Node.Node`
  723. """
  724. if isinstance(lst, str):
  725. lst = [x for x in Utils.split_path(lst) if x and x != '.']
  726. node = self.find_node(lst)
  727. if node and not node.isdir():
  728. return None
  729. return node
  730. # helpers for building things
  731. def change_ext(self, ext, ext_in=None):
  732. """
  733. Declares a build node with a distinct extension; this is uses :py:meth:`waflib.Node.Node.find_or_declare`
  734. :return: A build node of the same path, but with a different extension
  735. :rtype: :py:class:`waflib.Node.Node`
  736. """
  737. name = self.name
  738. if ext_in is None:
  739. k = name.rfind('.')
  740. if k >= 0:
  741. name = name[:k] + ext
  742. else:
  743. name = name + ext
  744. else:
  745. name = name[:- len(ext_in)] + ext
  746. return self.parent.find_or_declare([name])
  747. def bldpath(self):
  748. """
  749. Returns the relative path seen from the build directory ``src/foo.cpp``
  750. :rtype: string
  751. """
  752. return self.path_from(self.ctx.bldnode)
  753. def srcpath(self):
  754. """
  755. Returns the relative path seen from the source directory ``../src/foo.cpp``
  756. :rtype: string
  757. """
  758. return self.path_from(self.ctx.srcnode)
  759. def relpath(self):
  760. """
  761. If a file in the build directory, returns :py:meth:`waflib.Node.Node.bldpath`,
  762. else returns :py:meth:`waflib.Node.Node.srcpath`
  763. :rtype: string
  764. """
  765. cur = self
  766. x = self.ctx.bldnode
  767. while cur.parent:
  768. if cur is x:
  769. return self.bldpath()
  770. cur = cur.parent
  771. return self.srcpath()
  772. def bld_dir(self):
  773. """
  774. Equivalent to self.parent.bldpath()
  775. :rtype: string
  776. """
  777. return self.parent.bldpath()
  778. def h_file(self):
  779. """
  780. See :py:func:`waflib.Utils.h_file`
  781. :return: a hash representing the file contents
  782. :rtype: string or bytes
  783. """
  784. return Utils.h_file(self.abspath())
  785. def get_bld_sig(self):
  786. """
  787. Returns a signature (see :py:meth:`waflib.Node.Node.h_file`) for the purpose
  788. of build dependency calculation. This method uses a per-context cache.
  789. :return: a hash representing the object contents
  790. :rtype: string or bytes
  791. """
  792. # previous behaviour can be set by returning self.ctx.node_sigs[self] when a build node
  793. try:
  794. cache = self.ctx.cache_sig
  795. except AttributeError:
  796. cache = self.ctx.cache_sig = {}
  797. try:
  798. ret = cache[self]
  799. except KeyError:
  800. p = self.abspath()
  801. try:
  802. ret = cache[self] = self.h_file()
  803. except EnvironmentError:
  804. if self.isdir():
  805. # allow folders as build nodes, do not use the creation time
  806. st = os.stat(p)
  807. ret = cache[self] = Utils.h_list([p, st.st_ino, st.st_mode])
  808. return ret
  809. raise
  810. return ret
  811. pickle_lock = Utils.threading.Lock()
  812. """Lock mandatory for thread-safe node serialization"""
  813. class Nod3(Node):
  814. """Mandatory subclass for thread-safe node serialization"""
  815. pass # do not remove