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.

1492 lines
42KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2018 (ita)
  4. """
  5. Classes related to the build phase (build, clean, install, step, etc)
  6. The inheritance tree is the following:
  7. """
  8. import os, sys, errno, re, shutil, stat
  9. try:
  10. import cPickle
  11. except ImportError:
  12. import pickle as cPickle
  13. from waflib import Node, Runner, TaskGen, Utils, ConfigSet, Task, Logs, Options, Context, Errors
  14. CACHE_DIR = 'c4che'
  15. """Name of the cache directory"""
  16. CACHE_SUFFIX = '_cache.py'
  17. """ConfigSet cache files for variants are written under :py:attr:´waflib.Build.CACHE_DIR´ in the form ´variant_name´_cache.py"""
  18. INSTALL = 1337
  19. """Positive value '->' install, see :py:attr:`waflib.Build.BuildContext.is_install`"""
  20. UNINSTALL = -1337
  21. """Negative value '<-' uninstall, see :py:attr:`waflib.Build.BuildContext.is_install`"""
  22. SAVED_ATTRS = 'root node_sigs task_sigs imp_sigs raw_deps node_deps'.split()
  23. """Build class members to save between the runs; these should be all dicts
  24. except for `root` which represents a :py:class:`waflib.Node.Node` instance
  25. """
  26. CFG_FILES = 'cfg_files'
  27. """Files from the build directory to hash before starting the build (``config.h`` written during the configuration)"""
  28. POST_AT_ONCE = 0
  29. """Post mode: all task generators are posted before any task executed"""
  30. POST_LAZY = 1
  31. """Post mode: post the task generators group after group, the tasks in the next group are created when the tasks in the previous groups are done"""
  32. PROTOCOL = -1
  33. if sys.platform == 'cli':
  34. PROTOCOL = 0
  35. class BuildContext(Context.Context):
  36. '''executes the build'''
  37. cmd = 'build'
  38. variant = ''
  39. def __init__(self, **kw):
  40. super(BuildContext, self).__init__(**kw)
  41. self.is_install = 0
  42. """Non-zero value when installing or uninstalling file"""
  43. self.top_dir = kw.get('top_dir', Context.top_dir)
  44. """See :py:attr:`waflib.Context.top_dir`; prefer :py:attr:`waflib.Build.BuildContext.srcnode`"""
  45. self.out_dir = kw.get('out_dir', Context.out_dir)
  46. """See :py:attr:`waflib.Context.out_dir`; prefer :py:attr:`waflib.Build.BuildContext.bldnode`"""
  47. self.run_dir = kw.get('run_dir', Context.run_dir)
  48. """See :py:attr:`waflib.Context.run_dir`"""
  49. self.launch_dir = Context.launch_dir
  50. """See :py:attr:`waflib.Context.out_dir`; prefer :py:meth:`waflib.Build.BuildContext.launch_node`"""
  51. self.post_mode = POST_LAZY
  52. """Whether to post the task generators at once or group-by-group (default is group-by-group)"""
  53. self.cache_dir = kw.get('cache_dir')
  54. if not self.cache_dir:
  55. self.cache_dir = os.path.join(self.out_dir, CACHE_DIR)
  56. self.all_envs = {}
  57. """Map names to :py:class:`waflib.ConfigSet.ConfigSet`, the empty string must map to the default environment"""
  58. # ======================================= #
  59. # cache variables
  60. self.node_sigs = {}
  61. """Dict mapping build nodes to task identifier (uid), it indicates whether a task created a particular file (persists across builds)"""
  62. self.task_sigs = {}
  63. """Dict mapping task identifiers (uid) to task signatures (persists across builds)"""
  64. self.imp_sigs = {}
  65. """Dict mapping task identifiers (uid) to implicit task dependencies used for scanning targets (persists across builds)"""
  66. self.node_deps = {}
  67. """Dict mapping task identifiers (uid) to node dependencies found by :py:meth:`waflib.Task.Task.scan` (persists across builds)"""
  68. self.raw_deps = {}
  69. """Dict mapping task identifiers (uid) to custom data returned by :py:meth:`waflib.Task.Task.scan` (persists across builds)"""
  70. self.task_gen_cache_names = {}
  71. self.jobs = Options.options.jobs
  72. """Amount of jobs to run in parallel"""
  73. self.targets = Options.options.targets
  74. """List of targets to build (default: \*)"""
  75. self.keep = Options.options.keep
  76. """Whether the build should continue past errors"""
  77. self.progress_bar = Options.options.progress_bar
  78. """
  79. Level of progress status:
  80. 0. normal output
  81. 1. progress bar
  82. 2. IDE output
  83. 3. No output at all
  84. """
  85. # Manual dependencies.
  86. self.deps_man = Utils.defaultdict(list)
  87. """Manual dependencies set by :py:meth:`waflib.Build.BuildContext.add_manual_dependency`"""
  88. # just the structure here
  89. self.current_group = 0
  90. """
  91. Current build group
  92. """
  93. self.groups = []
  94. """
  95. List containing lists of task generators
  96. """
  97. self.group_names = {}
  98. """
  99. Map group names to the group lists. See :py:meth:`waflib.Build.BuildContext.add_group`
  100. """
  101. for v in SAVED_ATTRS:
  102. if not hasattr(self, v):
  103. setattr(self, v, {})
  104. def get_variant_dir(self):
  105. """Getter for the variant_dir attribute"""
  106. if not self.variant:
  107. return self.out_dir
  108. return os.path.join(self.out_dir, os.path.normpath(self.variant))
  109. variant_dir = property(get_variant_dir, None)
  110. def __call__(self, *k, **kw):
  111. """
  112. Create a task generator and add it to the current build group. The following forms are equivalent::
  113. def build(bld):
  114. tg = bld(a=1, b=2)
  115. def build(bld):
  116. tg = bld()
  117. tg.a = 1
  118. tg.b = 2
  119. def build(bld):
  120. tg = TaskGen.task_gen(a=1, b=2)
  121. bld.add_to_group(tg, None)
  122. :param group: group name to add the task generator to
  123. :type group: string
  124. """
  125. kw['bld'] = self
  126. ret = TaskGen.task_gen(*k, **kw)
  127. self.task_gen_cache_names = {} # reset the cache, each time
  128. self.add_to_group(ret, group=kw.get('group'))
  129. return ret
  130. def __copy__(self):
  131. """
  132. Build contexts cannot be copied
  133. :raises: :py:class:`waflib.Errors.WafError`
  134. """
  135. raise Errors.WafError('build contexts cannot be copied')
  136. def load_envs(self):
  137. """
  138. The configuration command creates files of the form ``build/c4che/NAMEcache.py``. This method
  139. creates a :py:class:`waflib.ConfigSet.ConfigSet` instance for each ``NAME`` by reading those
  140. files and stores them in :py:attr:`waflib.Build.BuildContext.allenvs`.
  141. """
  142. node = self.root.find_node(self.cache_dir)
  143. if not node:
  144. raise Errors.WafError('The project was not configured: run "waf configure" first!')
  145. lst = node.ant_glob('**/*%s' % CACHE_SUFFIX, quiet=True)
  146. if not lst:
  147. raise Errors.WafError('The cache directory is empty: reconfigure the project')
  148. for x in lst:
  149. name = x.path_from(node).replace(CACHE_SUFFIX, '').replace('\\', '/')
  150. env = ConfigSet.ConfigSet(x.abspath())
  151. self.all_envs[name] = env
  152. for f in env[CFG_FILES]:
  153. newnode = self.root.find_resource(f)
  154. if not newnode or not newnode.exists():
  155. raise Errors.WafError('Missing configuration file %r, reconfigure the project!' % f)
  156. def init_dirs(self):
  157. """
  158. Initialize the project directory and the build directory by creating the nodes
  159. :py:attr:`waflib.Build.BuildContext.srcnode` and :py:attr:`waflib.Build.BuildContext.bldnode`
  160. corresponding to ``top_dir`` and ``variant_dir`` respectively. The ``bldnode`` directory is
  161. created if necessary.
  162. """
  163. if not (os.path.isabs(self.top_dir) and os.path.isabs(self.out_dir)):
  164. raise Errors.WafError('The project was not configured: run "waf configure" first!')
  165. self.path = self.srcnode = self.root.find_dir(self.top_dir)
  166. self.bldnode = self.root.make_node(self.variant_dir)
  167. self.bldnode.mkdir()
  168. def execute(self):
  169. """
  170. Restore data from previous builds and call :py:meth:`waflib.Build.BuildContext.execute_build`.
  171. Overrides from :py:func:`waflib.Context.Context.execute`
  172. """
  173. self.restore()
  174. if not self.all_envs:
  175. self.load_envs()
  176. self.execute_build()
  177. def execute_build(self):
  178. """
  179. Execute the build by:
  180. * reading the scripts (see :py:meth:`waflib.Context.Context.recurse`)
  181. * calling :py:meth:`waflib.Build.BuildContext.pre_build` to call user build functions
  182. * calling :py:meth:`waflib.Build.BuildContext.compile` to process the tasks
  183. * calling :py:meth:`waflib.Build.BuildContext.post_build` to call user build functions
  184. """
  185. Logs.info("Waf: Entering directory `%s'", self.variant_dir)
  186. self.recurse([self.run_dir])
  187. self.pre_build()
  188. # display the time elapsed in the progress bar
  189. self.timer = Utils.Timer()
  190. try:
  191. self.compile()
  192. finally:
  193. if self.progress_bar == 1 and sys.stderr.isatty():
  194. c = self.producer.processed or 1
  195. m = self.progress_line(c, c, Logs.colors.BLUE, Logs.colors.NORMAL)
  196. Logs.info(m, extra={'stream': sys.stderr, 'c1': Logs.colors.cursor_off, 'c2' : Logs.colors.cursor_on})
  197. Logs.info("Waf: Leaving directory `%s'", self.variant_dir)
  198. try:
  199. self.producer.bld = None
  200. del self.producer
  201. except AttributeError:
  202. pass
  203. self.post_build()
  204. def restore(self):
  205. """
  206. Load data from a previous run, sets the attributes listed in :py:const:`waflib.Build.SAVED_ATTRS`
  207. """
  208. try:
  209. env = ConfigSet.ConfigSet(os.path.join(self.cache_dir, 'build.config.py'))
  210. except EnvironmentError:
  211. pass
  212. else:
  213. if env.version < Context.HEXVERSION:
  214. raise Errors.WafError('Project was configured with a different version of Waf, please reconfigure it')
  215. for t in env.tools:
  216. self.setup(**t)
  217. dbfn = os.path.join(self.variant_dir, Context.DBFILE)
  218. try:
  219. data = Utils.readf(dbfn, 'rb')
  220. except (EnvironmentError, EOFError):
  221. # handle missing file/empty file
  222. Logs.debug('build: Could not load the build cache %s (missing)', dbfn)
  223. else:
  224. try:
  225. Node.pickle_lock.acquire()
  226. Node.Nod3 = self.node_class
  227. try:
  228. data = cPickle.loads(data)
  229. except Exception as e:
  230. Logs.debug('build: Could not pickle the build cache %s: %r', dbfn, e)
  231. else:
  232. for x in SAVED_ATTRS:
  233. setattr(self, x, data.get(x, {}))
  234. finally:
  235. Node.pickle_lock.release()
  236. self.init_dirs()
  237. def store(self):
  238. """
  239. Store data for next runs, set the attributes listed in :py:const:`waflib.Build.SAVED_ATTRS`. Uses a temporary
  240. file to avoid problems on ctrl+c.
  241. """
  242. data = {}
  243. for x in SAVED_ATTRS:
  244. data[x] = getattr(self, x)
  245. db = os.path.join(self.variant_dir, Context.DBFILE)
  246. try:
  247. Node.pickle_lock.acquire()
  248. Node.Nod3 = self.node_class
  249. x = cPickle.dumps(data, PROTOCOL)
  250. finally:
  251. Node.pickle_lock.release()
  252. Utils.writef(db + '.tmp', x, m='wb')
  253. try:
  254. st = os.stat(db)
  255. os.remove(db)
  256. if not Utils.is_win32: # win32 has no chown but we're paranoid
  257. os.chown(db + '.tmp', st.st_uid, st.st_gid)
  258. except (AttributeError, OSError):
  259. pass
  260. # do not use shutil.move (copy is not thread-safe)
  261. os.rename(db + '.tmp', db)
  262. def compile(self):
  263. """
  264. Run the build by creating an instance of :py:class:`waflib.Runner.Parallel`
  265. The cache file is written when at least a task was executed.
  266. :raises: :py:class:`waflib.Errors.BuildError` in case the build fails
  267. """
  268. Logs.debug('build: compile()')
  269. # delegate the producer-consumer logic to another object to reduce the complexity
  270. self.producer = Runner.Parallel(self, self.jobs)
  271. self.producer.biter = self.get_build_iterator()
  272. try:
  273. self.producer.start()
  274. except KeyboardInterrupt:
  275. if self.is_dirty():
  276. self.store()
  277. raise
  278. else:
  279. if self.is_dirty():
  280. self.store()
  281. if self.producer.error:
  282. raise Errors.BuildError(self.producer.error)
  283. def is_dirty(self):
  284. return self.producer.dirty
  285. def setup(self, tool, tooldir=None, funs=None):
  286. """
  287. Import waf tools defined during the configuration::
  288. def configure(conf):
  289. conf.load('glib2')
  290. def build(bld):
  291. pass # glib2 is imported implicitly
  292. :param tool: tool list
  293. :type tool: list
  294. :param tooldir: optional tool directory (sys.path)
  295. :type tooldir: list of string
  296. :param funs: unused variable
  297. """
  298. if isinstance(tool, list):
  299. for i in tool:
  300. self.setup(i, tooldir)
  301. return
  302. module = Context.load_tool(tool, tooldir)
  303. if hasattr(module, "setup"):
  304. module.setup(self)
  305. def get_env(self):
  306. """Getter for the env property"""
  307. try:
  308. return self.all_envs[self.variant]
  309. except KeyError:
  310. return self.all_envs['']
  311. def set_env(self, val):
  312. """Setter for the env property"""
  313. self.all_envs[self.variant] = val
  314. env = property(get_env, set_env)
  315. def add_manual_dependency(self, path, value):
  316. """
  317. Adds a dependency from a node object to a value::
  318. def build(bld):
  319. bld.add_manual_dependency(
  320. bld.path.find_resource('wscript'),
  321. bld.root.find_resource('/etc/fstab'))
  322. :param path: file path
  323. :type path: string or :py:class:`waflib.Node.Node`
  324. :param value: value to depend
  325. :type value: :py:class:`waflib.Node.Node`, byte object, or function returning a byte object
  326. """
  327. if not path:
  328. raise ValueError('Invalid input path %r' % path)
  329. if isinstance(path, Node.Node):
  330. node = path
  331. elif os.path.isabs(path):
  332. node = self.root.find_resource(path)
  333. else:
  334. node = self.path.find_resource(path)
  335. if not node:
  336. raise ValueError('Could not find the path %r' % path)
  337. if isinstance(value, list):
  338. self.deps_man[node].extend(value)
  339. else:
  340. self.deps_man[node].append(value)
  341. def launch_node(self):
  342. """Returns the launch directory as a :py:class:`waflib.Node.Node` object (cached)"""
  343. try:
  344. # private cache
  345. return self.p_ln
  346. except AttributeError:
  347. self.p_ln = self.root.find_dir(self.launch_dir)
  348. return self.p_ln
  349. def hash_env_vars(self, env, vars_lst):
  350. """
  351. Hashes configuration set variables::
  352. def build(bld):
  353. bld.hash_env_vars(bld.env, ['CXX', 'CC'])
  354. This method uses an internal cache.
  355. :param env: Configuration Set
  356. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  357. :param vars_lst: list of variables
  358. :type vars_list: list of string
  359. """
  360. if not env.table:
  361. env = env.parent
  362. if not env:
  363. return Utils.SIG_NIL
  364. idx = str(id(env)) + str(vars_lst)
  365. try:
  366. cache = self.cache_env
  367. except AttributeError:
  368. cache = self.cache_env = {}
  369. else:
  370. try:
  371. return self.cache_env[idx]
  372. except KeyError:
  373. pass
  374. lst = [env[a] for a in vars_lst]
  375. cache[idx] = ret = Utils.h_list(lst)
  376. Logs.debug('envhash: %s %r', Utils.to_hex(ret), lst)
  377. return ret
  378. def get_tgen_by_name(self, name):
  379. """
  380. Fetches a task generator by its name or its target attribute;
  381. the name must be unique in a build::
  382. def build(bld):
  383. tg = bld(name='foo')
  384. tg == bld.get_tgen_by_name('foo')
  385. This method use a private internal cache.
  386. :param name: Task generator name
  387. :raises: :py:class:`waflib.Errors.WafError` in case there is no task genenerator by that name
  388. """
  389. cache = self.task_gen_cache_names
  390. if not cache:
  391. # create the index lazily
  392. for g in self.groups:
  393. for tg in g:
  394. try:
  395. cache[tg.name] = tg
  396. except AttributeError:
  397. # raised if not a task generator, which should be uncommon
  398. pass
  399. try:
  400. return cache[name]
  401. except KeyError:
  402. raise Errors.WafError('Could not find a task generator for the name %r' % name)
  403. def progress_line(self, idx, total, col1, col2):
  404. """
  405. Computes a progress bar line displayed when running ``waf -p``
  406. :returns: progress bar line
  407. :rtype: string
  408. """
  409. if not sys.stderr.isatty():
  410. return ''
  411. n = len(str(total))
  412. Utils.rot_idx += 1
  413. ind = Utils.rot_chr[Utils.rot_idx % 4]
  414. pc = (100. * idx)/total
  415. fs = "[%%%dd/%%d][%%s%%2d%%%%%%s][%s][" % (n, ind)
  416. left = fs % (idx, total, col1, pc, col2)
  417. right = '][%s%s%s]' % (col1, self.timer, col2)
  418. cols = Logs.get_term_cols() - len(left) - len(right) + 2*len(col1) + 2*len(col2)
  419. if cols < 7:
  420. cols = 7
  421. ratio = ((cols * idx)//total) - 1
  422. bar = ('='*ratio+'>').ljust(cols)
  423. msg = Logs.indicator % (left, bar, right)
  424. return msg
  425. def declare_chain(self, *k, **kw):
  426. """
  427. Wraps :py:func:`waflib.TaskGen.declare_chain` for convenience
  428. """
  429. return TaskGen.declare_chain(*k, **kw)
  430. def pre_build(self):
  431. """Executes user-defined methods before the build starts, see :py:meth:`waflib.Build.BuildContext.add_pre_fun`"""
  432. for m in getattr(self, 'pre_funs', []):
  433. m(self)
  434. def post_build(self):
  435. """Executes user-defined methods after the build is successful, see :py:meth:`waflib.Build.BuildContext.add_post_fun`"""
  436. for m in getattr(self, 'post_funs', []):
  437. m(self)
  438. def add_pre_fun(self, meth):
  439. """
  440. Binds a callback method to execute after the scripts are read and before the build starts::
  441. def mycallback(bld):
  442. print("Hello, world!")
  443. def build(bld):
  444. bld.add_pre_fun(mycallback)
  445. """
  446. try:
  447. self.pre_funs.append(meth)
  448. except AttributeError:
  449. self.pre_funs = [meth]
  450. def add_post_fun(self, meth):
  451. """
  452. Binds a callback method to execute immediately after the build is successful::
  453. def call_ldconfig(bld):
  454. bld.exec_command('/sbin/ldconfig')
  455. def build(bld):
  456. if bld.cmd == 'install':
  457. bld.add_pre_fun(call_ldconfig)
  458. """
  459. try:
  460. self.post_funs.append(meth)
  461. except AttributeError:
  462. self.post_funs = [meth]
  463. def get_group(self, x):
  464. """
  465. Returns the build group named `x`, or the current group if `x` is None
  466. :param x: name or number or None
  467. :type x: string, int or None
  468. """
  469. if not self.groups:
  470. self.add_group()
  471. if x is None:
  472. return self.groups[self.current_group]
  473. if x in self.group_names:
  474. return self.group_names[x]
  475. return self.groups[x]
  476. def add_to_group(self, tgen, group=None):
  477. """Adds a task or a task generator to the build; there is no attempt to remove it if it was already added."""
  478. assert(isinstance(tgen, TaskGen.task_gen) or isinstance(tgen, Task.Task))
  479. tgen.bld = self
  480. self.get_group(group).append(tgen)
  481. def get_group_name(self, g):
  482. """
  483. Returns the name of the input build group
  484. :param g: build group object or build group index
  485. :type g: integer or list
  486. :return: name
  487. :rtype: string
  488. """
  489. if not isinstance(g, list):
  490. g = self.groups[g]
  491. for x in self.group_names:
  492. if id(self.group_names[x]) == id(g):
  493. return x
  494. return ''
  495. def get_group_idx(self, tg):
  496. """
  497. Returns the index of the group containing the task generator given as argument::
  498. def build(bld):
  499. tg = bld(name='nada')
  500. 0 == bld.get_group_idx(tg)
  501. :param tg: Task generator object
  502. :type tg: :py:class:`waflib.TaskGen.task_gen`
  503. :rtype: int
  504. """
  505. se = id(tg)
  506. for i, tmp in enumerate(self.groups):
  507. for t in tmp:
  508. if id(t) == se:
  509. return i
  510. return None
  511. def add_group(self, name=None, move=True):
  512. """
  513. Adds a new group of tasks/task generators. By default the new group becomes
  514. the default group for new task generators (make sure to create build groups in order).
  515. :param name: name for this group
  516. :type name: string
  517. :param move: set this new group as default group (True by default)
  518. :type move: bool
  519. :raises: :py:class:`waflib.Errors.WafError` if a group by the name given already exists
  520. """
  521. if name and name in self.group_names:
  522. raise Errors.WafError('add_group: name %s already present', name)
  523. g = []
  524. self.group_names[name] = g
  525. self.groups.append(g)
  526. if move:
  527. self.current_group = len(self.groups) - 1
  528. def set_group(self, idx):
  529. """
  530. Sets the build group at position idx as current so that newly added
  531. task generators are added to this one by default::
  532. def build(bld):
  533. bld(rule='touch ${TGT}', target='foo.txt')
  534. bld.add_group() # now the current group is 1
  535. bld(rule='touch ${TGT}', target='bar.txt')
  536. bld.set_group(0) # now the current group is 0
  537. bld(rule='touch ${TGT}', target='truc.txt') # build truc.txt before bar.txt
  538. :param idx: group name or group index
  539. :type idx: string or int
  540. """
  541. if isinstance(idx, str):
  542. g = self.group_names[idx]
  543. for i, tmp in enumerate(self.groups):
  544. if id(g) == id(tmp):
  545. self.current_group = i
  546. break
  547. else:
  548. self.current_group = idx
  549. def total(self):
  550. """
  551. Approximate task count: this value may be inaccurate if task generators
  552. are posted lazily (see :py:attr:`waflib.Build.BuildContext.post_mode`).
  553. The value :py:attr:`waflib.Runner.Parallel.total` is updated during the task execution.
  554. :rtype: int
  555. """
  556. total = 0
  557. for group in self.groups:
  558. for tg in group:
  559. try:
  560. total += len(tg.tasks)
  561. except AttributeError:
  562. total += 1
  563. return total
  564. def get_targets(self):
  565. """
  566. This method returns a pair containing the index of the last build group to post,
  567. and the list of task generator objects corresponding to the target names.
  568. This is used internally by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
  569. to perform partial builds::
  570. $ waf --targets=myprogram,myshlib
  571. :return: the minimum build group index, and list of task generators
  572. :rtype: tuple
  573. """
  574. to_post = []
  575. min_grp = 0
  576. for name in self.targets.split(','):
  577. tg = self.get_tgen_by_name(name)
  578. m = self.get_group_idx(tg)
  579. if m > min_grp:
  580. min_grp = m
  581. to_post = [tg]
  582. elif m == min_grp:
  583. to_post.append(tg)
  584. return (min_grp, to_post)
  585. def get_all_task_gen(self):
  586. """
  587. Returns a list of all task generators for troubleshooting purposes.
  588. """
  589. lst = []
  590. for g in self.groups:
  591. lst.extend(g)
  592. return lst
  593. def post_group(self):
  594. """
  595. Post task generators from the group indexed by self.current_group; used internally
  596. by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
  597. """
  598. def tgpost(tg):
  599. try:
  600. f = tg.post
  601. except AttributeError:
  602. pass
  603. else:
  604. f()
  605. if self.targets == '*':
  606. for tg in self.groups[self.current_group]:
  607. tgpost(tg)
  608. elif self.targets:
  609. if self.current_group < self._min_grp:
  610. for tg in self.groups[self.current_group]:
  611. tgpost(tg)
  612. else:
  613. for tg in self._exact_tg:
  614. tg.post()
  615. else:
  616. ln = self.launch_node()
  617. if ln.is_child_of(self.bldnode):
  618. Logs.warn('Building from the build directory, forcing --targets=*')
  619. ln = self.srcnode
  620. elif not ln.is_child_of(self.srcnode):
  621. Logs.warn('CWD %s is not under %s, forcing --targets=* (run distclean?)', ln.abspath(), self.srcnode.abspath())
  622. ln = self.srcnode
  623. def is_post(tg, ln):
  624. try:
  625. p = tg.path
  626. except AttributeError:
  627. pass
  628. else:
  629. if p.is_child_of(ln):
  630. return True
  631. def is_post_group():
  632. for i, g in enumerate(self.groups):
  633. if i > self.current_group:
  634. for tg in g:
  635. if is_post(tg, ln):
  636. return True
  637. if self.post_mode == POST_LAZY and ln != self.srcnode:
  638. # partial folder builds require all targets from a previous build group
  639. if is_post_group():
  640. ln = self.srcnode
  641. for tg in self.groups[self.current_group]:
  642. if is_post(tg, ln):
  643. tgpost(tg)
  644. def get_tasks_group(self, idx):
  645. """
  646. Returns all task instances for the build group at position idx,
  647. used internally by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
  648. :rtype: list of :py:class:`waflib.Task.Task`
  649. """
  650. tasks = []
  651. for tg in self.groups[idx]:
  652. try:
  653. tasks.extend(tg.tasks)
  654. except AttributeError: # not a task generator
  655. tasks.append(tg)
  656. return tasks
  657. def get_build_iterator(self):
  658. """
  659. Creates a Python generator object that returns lists of tasks that may be processed in parallel.
  660. :return: tasks which can be executed immediately
  661. :rtype: generator returning lists of :py:class:`waflib.Task.Task`
  662. """
  663. if self.targets and self.targets != '*':
  664. (self._min_grp, self._exact_tg) = self.get_targets()
  665. if self.post_mode != POST_LAZY:
  666. for self.current_group, _ in enumerate(self.groups):
  667. self.post_group()
  668. for self.current_group, _ in enumerate(self.groups):
  669. # first post the task generators for the group
  670. if self.post_mode != POST_AT_ONCE:
  671. self.post_group()
  672. # then extract the tasks
  673. tasks = self.get_tasks_group(self.current_group)
  674. # if the constraints are set properly (ext_in/ext_out, before/after)
  675. # the call to set_file_constraints may be removed (can be a 15% penalty on no-op rebuilds)
  676. # (but leave set_file_constraints for the installation step)
  677. #
  678. # if the tasks have only files, set_file_constraints is required but set_precedence_constraints is not necessary
  679. #
  680. Task.set_file_constraints(tasks)
  681. Task.set_precedence_constraints(tasks)
  682. self.cur_tasks = tasks
  683. if tasks:
  684. yield tasks
  685. while 1:
  686. # the build stops once there are no tasks to process
  687. yield []
  688. def install_files(self, dest, files, **kw):
  689. """
  690. Creates a task generator to install files on the system::
  691. def build(bld):
  692. bld.install_files('${DATADIR}', self.path.find_resource('wscript'))
  693. :param dest: path representing the destination directory
  694. :type dest: :py:class:`waflib.Node.Node` or string (absolute path)
  695. :param files: input files
  696. :type files: list of strings or list of :py:class:`waflib.Node.Node`
  697. :param env: configuration set to expand *dest*
  698. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  699. :param relative_trick: preserve the folder hierarchy when installing whole folders
  700. :type relative_trick: bool
  701. :param cwd: parent node for searching srcfile, when srcfile is not an instance of :py:class:`waflib.Node.Node`
  702. :type cwd: :py:class:`waflib.Node.Node`
  703. :param postpone: execute the task immediately to perform the installation (False by default)
  704. :type postpone: bool
  705. """
  706. assert(dest)
  707. tg = self(features='install_task', install_to=dest, install_from=files, **kw)
  708. tg.dest = tg.install_to
  709. tg.type = 'install_files'
  710. if not kw.get('postpone', True):
  711. tg.post()
  712. return tg
  713. def install_as(self, dest, srcfile, **kw):
  714. """
  715. Creates a task generator to install a file on the system with a different name::
  716. def build(bld):
  717. bld.install_as('${PREFIX}/bin', 'myapp', chmod=Utils.O755)
  718. :param dest: destination file
  719. :type dest: :py:class:`waflib.Node.Node` or string (absolute path)
  720. :param srcfile: input file
  721. :type srcfile: string or :py:class:`waflib.Node.Node`
  722. :param cwd: parent node for searching srcfile, when srcfile is not an instance of :py:class:`waflib.Node.Node`
  723. :type cwd: :py:class:`waflib.Node.Node`
  724. :param env: configuration set for performing substitutions in dest
  725. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  726. :param postpone: execute the task immediately to perform the installation (False by default)
  727. :type postpone: bool
  728. """
  729. assert(dest)
  730. tg = self(features='install_task', install_to=dest, install_from=srcfile, **kw)
  731. tg.dest = tg.install_to
  732. tg.type = 'install_as'
  733. if not kw.get('postpone', True):
  734. tg.post()
  735. return tg
  736. def symlink_as(self, dest, src, **kw):
  737. """
  738. Creates a task generator to install a symlink::
  739. def build(bld):
  740. bld.symlink_as('${PREFIX}/lib/libfoo.so', 'libfoo.so.1.2.3')
  741. :param dest: absolute path of the symlink
  742. :type dest: :py:class:`waflib.Node.Node` or string (absolute path)
  743. :param src: link contents, which is a relative or absolute path which may exist or not
  744. :type src: string
  745. :param env: configuration set for performing substitutions in dest
  746. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  747. :param add: add the task created to a build group - set ``False`` only if the installation task is created after the build has started
  748. :type add: bool
  749. :param postpone: execute the task immediately to perform the installation
  750. :type postpone: bool
  751. :param relative_trick: make the symlink relative (default: ``False``)
  752. :type relative_trick: bool
  753. """
  754. assert(dest)
  755. tg = self(features='install_task', install_to=dest, install_from=src, **kw)
  756. tg.dest = tg.install_to
  757. tg.type = 'symlink_as'
  758. tg.link = src
  759. # TODO if add: self.add_to_group(tsk)
  760. if not kw.get('postpone', True):
  761. tg.post()
  762. return tg
  763. @TaskGen.feature('install_task')
  764. @TaskGen.before_method('process_rule', 'process_source')
  765. def process_install_task(self):
  766. """Creates the installation task for the current task generator; uses :py:func:`waflib.Build.add_install_task` internally."""
  767. self.add_install_task(**self.__dict__)
  768. @TaskGen.taskgen_method
  769. def add_install_task(self, **kw):
  770. """
  771. Creates the installation task for the current task generator, and executes it immediately if necessary
  772. :returns: An installation task
  773. :rtype: :py:class:`waflib.Build.inst`
  774. """
  775. if not self.bld.is_install:
  776. return
  777. if not kw['install_to']:
  778. return
  779. if kw['type'] == 'symlink_as' and Utils.is_win32:
  780. if kw.get('win32_install'):
  781. kw['type'] = 'install_as'
  782. else:
  783. # just exit
  784. return
  785. tsk = self.install_task = self.create_task('inst')
  786. tsk.chmod = kw.get('chmod', Utils.O644)
  787. tsk.link = kw.get('link', '') or kw.get('install_from', '')
  788. tsk.relative_trick = kw.get('relative_trick', False)
  789. tsk.type = kw['type']
  790. tsk.install_to = tsk.dest = kw['install_to']
  791. tsk.install_from = kw['install_from']
  792. tsk.relative_base = kw.get('cwd') or kw.get('relative_base', self.path)
  793. tsk.install_user = kw.get('install_user')
  794. tsk.install_group = kw.get('install_group')
  795. tsk.init_files()
  796. if not kw.get('postpone', True):
  797. tsk.run_now()
  798. return tsk
  799. @TaskGen.taskgen_method
  800. def add_install_files(self, **kw):
  801. """
  802. Creates an installation task for files
  803. :returns: An installation task
  804. :rtype: :py:class:`waflib.Build.inst`
  805. """
  806. kw['type'] = 'install_files'
  807. return self.add_install_task(**kw)
  808. @TaskGen.taskgen_method
  809. def add_install_as(self, **kw):
  810. """
  811. Creates an installation task for a single file
  812. :returns: An installation task
  813. :rtype: :py:class:`waflib.Build.inst`
  814. """
  815. kw['type'] = 'install_as'
  816. return self.add_install_task(**kw)
  817. @TaskGen.taskgen_method
  818. def add_symlink_as(self, **kw):
  819. """
  820. Creates an installation task for a symbolic link
  821. :returns: An installation task
  822. :rtype: :py:class:`waflib.Build.inst`
  823. """
  824. kw['type'] = 'symlink_as'
  825. return self.add_install_task(**kw)
  826. class inst(Task.Task):
  827. """Task that installs files or symlinks; it is typically executed by :py:class:`waflib.Build.InstallContext` and :py:class:`waflib.Build.UnInstallContext`"""
  828. def __str__(self):
  829. """Returns an empty string to disable the standard task display"""
  830. return ''
  831. def uid(self):
  832. """Returns a unique identifier for the task"""
  833. lst = self.inputs + self.outputs + [self.link, self.generator.path.abspath()]
  834. return Utils.h_list(lst)
  835. def init_files(self):
  836. """
  837. Initializes the task input and output nodes
  838. """
  839. if self.type == 'symlink_as':
  840. inputs = []
  841. else:
  842. inputs = self.generator.to_nodes(self.install_from)
  843. if self.type == 'install_as':
  844. assert len(inputs) == 1
  845. self.set_inputs(inputs)
  846. dest = self.get_install_path()
  847. outputs = []
  848. if self.type == 'symlink_as':
  849. if self.relative_trick:
  850. self.link = os.path.relpath(self.link, os.path.dirname(dest))
  851. outputs.append(self.generator.bld.root.make_node(dest))
  852. elif self.type == 'install_as':
  853. outputs.append(self.generator.bld.root.make_node(dest))
  854. else:
  855. for y in inputs:
  856. if self.relative_trick:
  857. destfile = os.path.join(dest, y.path_from(self.relative_base))
  858. else:
  859. destfile = os.path.join(dest, y.name)
  860. outputs.append(self.generator.bld.root.make_node(destfile))
  861. self.set_outputs(outputs)
  862. def runnable_status(self):
  863. """
  864. Installation tasks are always executed, so this method returns either :py:const:`waflib.Task.ASK_LATER` or :py:const:`waflib.Task.RUN_ME`.
  865. """
  866. ret = super(inst, self).runnable_status()
  867. if ret == Task.SKIP_ME and self.generator.bld.is_install:
  868. return Task.RUN_ME
  869. return ret
  870. def post_run(self):
  871. """
  872. Disables any post-run operations
  873. """
  874. pass
  875. def get_install_path(self, destdir=True):
  876. """
  877. Returns the destination path where files will be installed, pre-pending `destdir`.
  878. :rtype: string
  879. """
  880. if isinstance(self.install_to, Node.Node):
  881. dest = self.install_to.abspath()
  882. else:
  883. dest = Utils.subst_vars(self.install_to, self.env)
  884. if destdir and Options.options.destdir:
  885. dest = os.path.join(Options.options.destdir, os.path.splitdrive(dest)[1].lstrip(os.sep))
  886. return dest
  887. def copy_fun(self, src, tgt):
  888. """
  889. Copies a file from src to tgt, preserving permissions and trying to work
  890. around path limitations on Windows platforms. On Unix-like platforms,
  891. the owner/group of the target file may be set through install_user/install_group
  892. :param src: absolute path
  893. :type src: string
  894. :param tgt: absolute path
  895. :type tgt: string
  896. """
  897. # override this if you want to strip executables
  898. # kw['tsk'].source is the task that created the files in the build
  899. if Utils.is_win32 and len(tgt) > 259 and not tgt.startswith('\\\\?\\'):
  900. tgt = '\\\\?\\' + tgt
  901. shutil.copy2(src, tgt)
  902. self.fix_perms(tgt)
  903. def rm_empty_dirs(self, tgt):
  904. """
  905. Removes empty folders recursively when uninstalling.
  906. :param tgt: absolute path
  907. :type tgt: string
  908. """
  909. while tgt:
  910. tgt = os.path.dirname(tgt)
  911. try:
  912. os.rmdir(tgt)
  913. except OSError:
  914. break
  915. def run(self):
  916. """
  917. Performs file or symlink installation
  918. """
  919. is_install = self.generator.bld.is_install
  920. if not is_install: # unnecessary?
  921. return
  922. for x in self.outputs:
  923. if is_install == INSTALL:
  924. x.parent.mkdir()
  925. if self.type == 'symlink_as':
  926. fun = is_install == INSTALL and self.do_link or self.do_unlink
  927. fun(self.link, self.outputs[0].abspath())
  928. else:
  929. fun = is_install == INSTALL and self.do_install or self.do_uninstall
  930. launch_node = self.generator.bld.launch_node()
  931. for x, y in zip(self.inputs, self.outputs):
  932. fun(x.abspath(), y.abspath(), x.path_from(launch_node))
  933. def run_now(self):
  934. """
  935. Try executing the installation task right now
  936. :raises: :py:class:`waflib.Errors.TaskNotReady`
  937. """
  938. status = self.runnable_status()
  939. if status not in (Task.RUN_ME, Task.SKIP_ME):
  940. raise Errors.TaskNotReady('Could not process %r: status %r' % (self, status))
  941. self.run()
  942. self.hasrun = Task.SUCCESS
  943. def do_install(self, src, tgt, lbl, **kw):
  944. """
  945. Copies a file from src to tgt with given file permissions. The actual copy is only performed
  946. if the source and target file sizes or timestamps differ. When the copy occurs,
  947. the file is always first removed and then copied so as to prevent stale inodes.
  948. :param src: file name as absolute path
  949. :type src: string
  950. :param tgt: file destination, as absolute path
  951. :type tgt: string
  952. :param lbl: file source description
  953. :type lbl: string
  954. :param chmod: installation mode
  955. :type chmod: int
  956. :raises: :py:class:`waflib.Errors.WafError` if the file cannot be written
  957. """
  958. if not Options.options.force:
  959. # check if the file is already there to avoid a copy
  960. try:
  961. st1 = os.stat(tgt)
  962. st2 = os.stat(src)
  963. except OSError:
  964. pass
  965. else:
  966. # same size and identical timestamps -> make no copy
  967. if st1.st_mtime + 2 >= st2.st_mtime and st1.st_size == st2.st_size:
  968. if not self.generator.bld.progress_bar:
  969. Logs.info('- install %s (from %s)', tgt, lbl)
  970. return False
  971. if not self.generator.bld.progress_bar:
  972. Logs.info('+ install %s (from %s)', tgt, lbl)
  973. # Give best attempt at making destination overwritable,
  974. # like the 'install' utility used by 'make install' does.
  975. try:
  976. os.chmod(tgt, Utils.O644 | stat.S_IMODE(os.stat(tgt).st_mode))
  977. except EnvironmentError:
  978. pass
  979. # following is for shared libs and stale inodes (-_-)
  980. try:
  981. os.remove(tgt)
  982. except OSError:
  983. pass
  984. try:
  985. self.copy_fun(src, tgt)
  986. except EnvironmentError as e:
  987. if not os.path.exists(src):
  988. Logs.error('File %r does not exist', src)
  989. elif not os.path.isfile(src):
  990. Logs.error('Input %r is not a file', src)
  991. raise Errors.WafError('Could not install the file %r' % tgt, e)
  992. def fix_perms(self, tgt):
  993. """
  994. Change the ownership of the file/folder/link pointed by the given path
  995. This looks up for `install_user` or `install_group` attributes
  996. on the task or on the task generator::
  997. def build(bld):
  998. bld.install_as('${PREFIX}/wscript',
  999. 'wscript',
  1000. install_user='nobody', install_group='nogroup')
  1001. bld.symlink_as('${PREFIX}/wscript_link',
  1002. Utils.subst_vars('${PREFIX}/wscript', bld.env),
  1003. install_user='nobody', install_group='nogroup')
  1004. """
  1005. if not Utils.is_win32:
  1006. user = getattr(self, 'install_user', None) or getattr(self.generator, 'install_user', None)
  1007. group = getattr(self, 'install_group', None) or getattr(self.generator, 'install_group', None)
  1008. if user or group:
  1009. Utils.lchown(tgt, user or -1, group or -1)
  1010. if not os.path.islink(tgt):
  1011. os.chmod(tgt, self.chmod)
  1012. def do_link(self, src, tgt, **kw):
  1013. """
  1014. Creates a symlink from tgt to src.
  1015. :param src: file name as absolute path
  1016. :type src: string
  1017. :param tgt: file destination, as absolute path
  1018. :type tgt: string
  1019. """
  1020. if os.path.islink(tgt) and os.readlink(tgt) == src:
  1021. if not self.generator.bld.progress_bar:
  1022. Logs.info('- symlink %s (to %s)', tgt, src)
  1023. else:
  1024. try:
  1025. os.remove(tgt)
  1026. except OSError:
  1027. pass
  1028. if not self.generator.bld.progress_bar:
  1029. Logs.info('+ symlink %s (to %s)', tgt, src)
  1030. os.symlink(src, tgt)
  1031. self.fix_perms(tgt)
  1032. def do_uninstall(self, src, tgt, lbl, **kw):
  1033. """
  1034. See :py:meth:`waflib.Build.inst.do_install`
  1035. """
  1036. if not self.generator.bld.progress_bar:
  1037. Logs.info('- remove %s', tgt)
  1038. #self.uninstall.append(tgt)
  1039. try:
  1040. os.remove(tgt)
  1041. except OSError as e:
  1042. if e.errno != errno.ENOENT:
  1043. if not getattr(self, 'uninstall_error', None):
  1044. self.uninstall_error = True
  1045. Logs.warn('build: some files could not be uninstalled (retry with -vv to list them)')
  1046. if Logs.verbose > 1:
  1047. Logs.warn('Could not remove %s (error code %r)', e.filename, e.errno)
  1048. self.rm_empty_dirs(tgt)
  1049. def do_unlink(self, src, tgt, **kw):
  1050. """
  1051. See :py:meth:`waflib.Build.inst.do_link`
  1052. """
  1053. try:
  1054. if not self.generator.bld.progress_bar:
  1055. Logs.info('- remove %s', tgt)
  1056. os.remove(tgt)
  1057. except OSError:
  1058. pass
  1059. self.rm_empty_dirs(tgt)
  1060. class InstallContext(BuildContext):
  1061. '''installs the targets on the system'''
  1062. cmd = 'install'
  1063. def __init__(self, **kw):
  1064. super(InstallContext, self).__init__(**kw)
  1065. self.is_install = INSTALL
  1066. class UninstallContext(InstallContext):
  1067. '''removes the targets installed'''
  1068. cmd = 'uninstall'
  1069. def __init__(self, **kw):
  1070. super(UninstallContext, self).__init__(**kw)
  1071. self.is_install = UNINSTALL
  1072. class CleanContext(BuildContext):
  1073. '''cleans the project'''
  1074. cmd = 'clean'
  1075. def execute(self):
  1076. """
  1077. See :py:func:`waflib.Build.BuildContext.execute`.
  1078. """
  1079. self.restore()
  1080. if not self.all_envs:
  1081. self.load_envs()
  1082. self.recurse([self.run_dir])
  1083. try:
  1084. self.clean()
  1085. finally:
  1086. self.store()
  1087. def clean(self):
  1088. """
  1089. Remove most files from the build directory, and reset all caches.
  1090. Custom lists of files to clean can be declared as `bld.clean_files`.
  1091. For example, exclude `build/program/myprogram` from getting removed::
  1092. def build(bld):
  1093. bld.clean_files = bld.bldnode.ant_glob('**',
  1094. excl='.lock* config.log c4che/* config.h program/myprogram',
  1095. quiet=True, generator=True)
  1096. """
  1097. Logs.debug('build: clean called')
  1098. if hasattr(self, 'clean_files'):
  1099. for n in self.clean_files:
  1100. n.delete()
  1101. elif self.bldnode != self.srcnode:
  1102. # would lead to a disaster if top == out
  1103. lst = []
  1104. for env in self.all_envs.values():
  1105. lst.extend(self.root.find_or_declare(f) for f in env[CFG_FILES])
  1106. for n in self.bldnode.ant_glob('**/*', excl='.lock* *conf_check_*/** config.log c4che/*', quiet=True):
  1107. if n in lst:
  1108. continue
  1109. n.delete()
  1110. self.root.children = {}
  1111. for v in SAVED_ATTRS:
  1112. if v == 'root':
  1113. continue
  1114. setattr(self, v, {})
  1115. class ListContext(BuildContext):
  1116. '''lists the targets to execute'''
  1117. cmd = 'list'
  1118. def execute(self):
  1119. """
  1120. In addition to printing the name of each build target,
  1121. a description column will include text for each task
  1122. generator which has a "description" field set.
  1123. See :py:func:`waflib.Build.BuildContext.execute`.
  1124. """
  1125. self.restore()
  1126. if not self.all_envs:
  1127. self.load_envs()
  1128. self.recurse([self.run_dir])
  1129. self.pre_build()
  1130. # display the time elapsed in the progress bar
  1131. self.timer = Utils.Timer()
  1132. for g in self.groups:
  1133. for tg in g:
  1134. try:
  1135. f = tg.post
  1136. except AttributeError:
  1137. pass
  1138. else:
  1139. f()
  1140. try:
  1141. # force the cache initialization
  1142. self.get_tgen_by_name('')
  1143. except Errors.WafError:
  1144. pass
  1145. targets = sorted(self.task_gen_cache_names)
  1146. # figure out how much to left-justify, for largest target name
  1147. line_just = max(len(t) for t in targets) if targets else 0
  1148. for target in targets:
  1149. tgen = self.task_gen_cache_names[target]
  1150. # Support displaying the description for the target
  1151. # if it was set on the tgen
  1152. descript = getattr(tgen, 'description', '')
  1153. if descript:
  1154. target = target.ljust(line_just)
  1155. descript = ': %s' % descript
  1156. Logs.pprint('GREEN', target, label=descript)
  1157. class StepContext(BuildContext):
  1158. '''executes tasks in a step-by-step fashion, for debugging'''
  1159. cmd = 'step'
  1160. def __init__(self, **kw):
  1161. super(StepContext, self).__init__(**kw)
  1162. self.files = Options.options.files
  1163. def compile(self):
  1164. """
  1165. Overrides :py:meth:`waflib.Build.BuildContext.compile` to perform a partial build
  1166. on tasks matching the input/output pattern given (regular expression matching)::
  1167. $ waf step --files=foo.c,bar.c,in:truc.c,out:bar.o
  1168. $ waf step --files=in:foo.cpp.1.o # link task only
  1169. """
  1170. if not self.files:
  1171. Logs.warn('Add a pattern for the debug build, for example "waf step --files=main.c,app"')
  1172. BuildContext.compile(self)
  1173. return
  1174. targets = []
  1175. if self.targets and self.targets != '*':
  1176. targets = self.targets.split(',')
  1177. for g in self.groups:
  1178. for tg in g:
  1179. if targets and tg.name not in targets:
  1180. continue
  1181. try:
  1182. f = tg.post
  1183. except AttributeError:
  1184. pass
  1185. else:
  1186. f()
  1187. for pat in self.files.split(','):
  1188. matcher = self.get_matcher(pat)
  1189. for tg in g:
  1190. if isinstance(tg, Task.Task):
  1191. lst = [tg]
  1192. else:
  1193. lst = tg.tasks
  1194. for tsk in lst:
  1195. do_exec = False
  1196. for node in tsk.inputs:
  1197. if matcher(node, output=False):
  1198. do_exec = True
  1199. break
  1200. for node in tsk.outputs:
  1201. if matcher(node, output=True):
  1202. do_exec = True
  1203. break
  1204. if do_exec:
  1205. ret = tsk.run()
  1206. Logs.info('%s -> exit %r', tsk, ret)
  1207. def get_matcher(self, pat):
  1208. """
  1209. Converts a step pattern into a function
  1210. :param: pat: pattern of the form in:truc.c,out:bar.o
  1211. :returns: Python function that uses Node objects as inputs and returns matches
  1212. :rtype: function
  1213. """
  1214. # this returns a function
  1215. inn = True
  1216. out = True
  1217. if pat.startswith('in:'):
  1218. out = False
  1219. pat = pat.replace('in:', '')
  1220. elif pat.startswith('out:'):
  1221. inn = False
  1222. pat = pat.replace('out:', '')
  1223. anode = self.root.find_node(pat)
  1224. pattern = None
  1225. if not anode:
  1226. if not pat.startswith('^'):
  1227. pat = '^.+?%s' % pat
  1228. if not pat.endswith('$'):
  1229. pat = '%s$' % pat
  1230. pattern = re.compile(pat)
  1231. def match(node, output):
  1232. if output and not out:
  1233. return False
  1234. if not output and not inn:
  1235. return False
  1236. if anode:
  1237. return anode == node
  1238. else:
  1239. return pattern.match(node.abspath())
  1240. return match
  1241. class EnvContext(BuildContext):
  1242. """Subclass EnvContext to create commands that require configuration data in 'env'"""
  1243. fun = cmd = None
  1244. def execute(self):
  1245. """
  1246. See :py:func:`waflib.Build.BuildContext.execute`.
  1247. """
  1248. self.restore()
  1249. if not self.all_envs:
  1250. self.load_envs()
  1251. self.recurse([self.run_dir])