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.

1515 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. if Logs.verbose > 1:
  619. Logs.warn('Building from the build directory, forcing --targets=*')
  620. ln = self.srcnode
  621. elif not ln.is_child_of(self.srcnode):
  622. if Logs.verbose > 1:
  623. Logs.warn('CWD %s is not under %s, forcing --targets=* (run distclean?)', ln.abspath(), self.srcnode.abspath())
  624. ln = self.srcnode
  625. def is_post(tg, ln):
  626. try:
  627. p = tg.path
  628. except AttributeError:
  629. pass
  630. else:
  631. if p.is_child_of(ln):
  632. return True
  633. def is_post_group():
  634. for i, g in enumerate(self.groups):
  635. if i > self.current_group:
  636. for tg in g:
  637. if is_post(tg, ln):
  638. return True
  639. if self.post_mode == POST_LAZY and ln != self.srcnode:
  640. # partial folder builds require all targets from a previous build group
  641. if is_post_group():
  642. ln = self.srcnode
  643. for tg in self.groups[self.current_group]:
  644. if is_post(tg, ln):
  645. tgpost(tg)
  646. def get_tasks_group(self, idx):
  647. """
  648. Returns all task instances for the build group at position idx,
  649. used internally by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
  650. :rtype: list of :py:class:`waflib.Task.Task`
  651. """
  652. tasks = []
  653. for tg in self.groups[idx]:
  654. try:
  655. tasks.extend(tg.tasks)
  656. except AttributeError: # not a task generator
  657. tasks.append(tg)
  658. return tasks
  659. def get_build_iterator(self):
  660. """
  661. Creates a Python generator object that returns lists of tasks that may be processed in parallel.
  662. :return: tasks which can be executed immediately
  663. :rtype: generator returning lists of :py:class:`waflib.Task.Task`
  664. """
  665. if self.targets and self.targets != '*':
  666. (self._min_grp, self._exact_tg) = self.get_targets()
  667. if self.post_mode != POST_LAZY:
  668. for self.current_group, _ in enumerate(self.groups):
  669. self.post_group()
  670. for self.current_group, _ in enumerate(self.groups):
  671. # first post the task generators for the group
  672. if self.post_mode != POST_AT_ONCE:
  673. self.post_group()
  674. # then extract the tasks
  675. tasks = self.get_tasks_group(self.current_group)
  676. # if the constraints are set properly (ext_in/ext_out, before/after)
  677. # the call to set_file_constraints may be removed (can be a 15% penalty on no-op rebuilds)
  678. # (but leave set_file_constraints for the installation step)
  679. #
  680. # if the tasks have only files, set_file_constraints is required but set_precedence_constraints is not necessary
  681. #
  682. Task.set_file_constraints(tasks)
  683. Task.set_precedence_constraints(tasks)
  684. self.cur_tasks = tasks
  685. if tasks:
  686. yield tasks
  687. while 1:
  688. # the build stops once there are no tasks to process
  689. yield []
  690. def install_files(self, dest, files, **kw):
  691. """
  692. Creates a task generator to install files on the system::
  693. def build(bld):
  694. bld.install_files('${DATADIR}', self.path.find_resource('wscript'))
  695. :param dest: path representing the destination directory
  696. :type dest: :py:class:`waflib.Node.Node` or string (absolute path)
  697. :param files: input files
  698. :type files: list of strings or list of :py:class:`waflib.Node.Node`
  699. :param env: configuration set to expand *dest*
  700. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  701. :param relative_trick: preserve the folder hierarchy when installing whole folders
  702. :type relative_trick: bool
  703. :param cwd: parent node for searching srcfile, when srcfile is not an instance of :py:class:`waflib.Node.Node`
  704. :type cwd: :py:class:`waflib.Node.Node`
  705. :param postpone: execute the task immediately to perform the installation (False by default)
  706. :type postpone: bool
  707. """
  708. assert(dest)
  709. tg = self(features='install_task', install_to=dest, install_from=files, **kw)
  710. tg.dest = tg.install_to
  711. tg.type = 'install_files'
  712. if not kw.get('postpone', True):
  713. tg.post()
  714. return tg
  715. def install_as(self, dest, srcfile, **kw):
  716. """
  717. Creates a task generator to install a file on the system with a different name::
  718. def build(bld):
  719. bld.install_as('${PREFIX}/bin', 'myapp', chmod=Utils.O755)
  720. :param dest: destination file
  721. :type dest: :py:class:`waflib.Node.Node` or string (absolute path)
  722. :param srcfile: input file
  723. :type srcfile: string or :py:class:`waflib.Node.Node`
  724. :param cwd: parent node for searching srcfile, when srcfile is not an instance of :py:class:`waflib.Node.Node`
  725. :type cwd: :py:class:`waflib.Node.Node`
  726. :param env: configuration set for performing substitutions in dest
  727. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  728. :param postpone: execute the task immediately to perform the installation (False by default)
  729. :type postpone: bool
  730. """
  731. assert(dest)
  732. tg = self(features='install_task', install_to=dest, install_from=srcfile, **kw)
  733. tg.dest = tg.install_to
  734. tg.type = 'install_as'
  735. if not kw.get('postpone', True):
  736. tg.post()
  737. return tg
  738. def symlink_as(self, dest, src, **kw):
  739. """
  740. Creates a task generator to install a symlink::
  741. def build(bld):
  742. bld.symlink_as('${PREFIX}/lib/libfoo.so', 'libfoo.so.1.2.3')
  743. :param dest: absolute path of the symlink
  744. :type dest: :py:class:`waflib.Node.Node` or string (absolute path)
  745. :param src: link contents, which is a relative or absolute path which may exist or not
  746. :type src: string
  747. :param env: configuration set for performing substitutions in dest
  748. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  749. :param add: add the task created to a build group - set ``False`` only if the installation task is created after the build has started
  750. :type add: bool
  751. :param postpone: execute the task immediately to perform the installation
  752. :type postpone: bool
  753. :param relative_trick: make the symlink relative (default: ``False``)
  754. :type relative_trick: bool
  755. """
  756. assert(dest)
  757. tg = self(features='install_task', install_to=dest, install_from=src, **kw)
  758. tg.dest = tg.install_to
  759. tg.type = 'symlink_as'
  760. tg.link = src
  761. # TODO if add: self.add_to_group(tsk)
  762. if not kw.get('postpone', True):
  763. tg.post()
  764. return tg
  765. @TaskGen.feature('install_task')
  766. @TaskGen.before_method('process_rule', 'process_source')
  767. def process_install_task(self):
  768. """Creates the installation task for the current task generator; uses :py:func:`waflib.Build.add_install_task` internally."""
  769. self.add_install_task(**self.__dict__)
  770. @TaskGen.taskgen_method
  771. def add_install_task(self, **kw):
  772. """
  773. Creates the installation task for the current task generator, and executes it immediately if necessary
  774. :returns: An installation task
  775. :rtype: :py:class:`waflib.Build.inst`
  776. """
  777. if not self.bld.is_install:
  778. return
  779. if not kw['install_to']:
  780. return
  781. if kw['type'] == 'symlink_as' and Utils.is_win32:
  782. if kw.get('win32_install'):
  783. kw['type'] = 'install_as'
  784. else:
  785. # just exit
  786. return
  787. tsk = self.install_task = self.create_task('inst')
  788. tsk.chmod = kw.get('chmod', Utils.O644)
  789. tsk.link = kw.get('link', '') or kw.get('install_from', '')
  790. tsk.relative_trick = kw.get('relative_trick', False)
  791. tsk.type = kw['type']
  792. tsk.install_to = tsk.dest = kw['install_to']
  793. tsk.install_from = kw['install_from']
  794. tsk.relative_base = kw.get('cwd') or kw.get('relative_base', self.path)
  795. tsk.install_user = kw.get('install_user')
  796. tsk.install_group = kw.get('install_group')
  797. tsk.init_files()
  798. if not kw.get('postpone', True):
  799. tsk.run_now()
  800. return tsk
  801. @TaskGen.taskgen_method
  802. def add_install_files(self, **kw):
  803. """
  804. Creates an installation task for files
  805. :returns: An installation task
  806. :rtype: :py:class:`waflib.Build.inst`
  807. """
  808. kw['type'] = 'install_files'
  809. return self.add_install_task(**kw)
  810. @TaskGen.taskgen_method
  811. def add_install_as(self, **kw):
  812. """
  813. Creates an installation task for a single file
  814. :returns: An installation task
  815. :rtype: :py:class:`waflib.Build.inst`
  816. """
  817. kw['type'] = 'install_as'
  818. return self.add_install_task(**kw)
  819. @TaskGen.taskgen_method
  820. def add_symlink_as(self, **kw):
  821. """
  822. Creates an installation task for a symbolic link
  823. :returns: An installation task
  824. :rtype: :py:class:`waflib.Build.inst`
  825. """
  826. kw['type'] = 'symlink_as'
  827. return self.add_install_task(**kw)
  828. class inst(Task.Task):
  829. """Task that installs files or symlinks; it is typically executed by :py:class:`waflib.Build.InstallContext` and :py:class:`waflib.Build.UnInstallContext`"""
  830. def __str__(self):
  831. """Returns an empty string to disable the standard task display"""
  832. return ''
  833. def uid(self):
  834. """Returns a unique identifier for the task"""
  835. lst = self.inputs + self.outputs + [self.link, self.generator.path.abspath()]
  836. return Utils.h_list(lst)
  837. def init_files(self):
  838. """
  839. Initializes the task input and output nodes
  840. """
  841. if self.type == 'symlink_as':
  842. inputs = []
  843. else:
  844. inputs = self.generator.to_nodes(self.install_from)
  845. if self.type == 'install_as':
  846. assert len(inputs) == 1
  847. self.set_inputs(inputs)
  848. dest = self.get_install_path()
  849. outputs = []
  850. if self.type == 'symlink_as':
  851. if self.relative_trick:
  852. self.link = os.path.relpath(self.link, os.path.dirname(dest))
  853. outputs.append(self.generator.bld.root.make_node(dest))
  854. elif self.type == 'install_as':
  855. outputs.append(self.generator.bld.root.make_node(dest))
  856. else:
  857. for y in inputs:
  858. if self.relative_trick:
  859. destfile = os.path.join(dest, y.path_from(self.relative_base))
  860. else:
  861. destfile = os.path.join(dest, y.name)
  862. outputs.append(self.generator.bld.root.make_node(destfile))
  863. self.set_outputs(outputs)
  864. def runnable_status(self):
  865. """
  866. Installation tasks are always executed, so this method returns either :py:const:`waflib.Task.ASK_LATER` or :py:const:`waflib.Task.RUN_ME`.
  867. """
  868. ret = super(inst, self).runnable_status()
  869. if ret == Task.SKIP_ME and self.generator.bld.is_install:
  870. return Task.RUN_ME
  871. return ret
  872. def post_run(self):
  873. """
  874. Disables any post-run operations
  875. """
  876. pass
  877. def get_install_path(self, destdir=True):
  878. """
  879. Returns the destination path where files will be installed, pre-pending `destdir`.
  880. Relative paths will be interpreted relative to `PREFIX` if no `destdir` is given.
  881. :rtype: string
  882. """
  883. if isinstance(self.install_to, Node.Node):
  884. dest = self.install_to.abspath()
  885. else:
  886. dest = os.path.normpath(Utils.subst_vars(self.install_to, self.env))
  887. if not os.path.isabs(dest):
  888. dest = os.path.join(self.env.PREFIX, dest)
  889. if destdir and Options.options.destdir:
  890. dest = Options.options.destdir.rstrip(os.sep) + os.sep + os.path.splitdrive(dest)[1].lstrip(os.sep)
  891. return dest
  892. def copy_fun(self, src, tgt):
  893. """
  894. Copies a file from src to tgt, preserving permissions and trying to work
  895. around path limitations on Windows platforms. On Unix-like platforms,
  896. the owner/group of the target file may be set through install_user/install_group
  897. :param src: absolute path
  898. :type src: string
  899. :param tgt: absolute path
  900. :type tgt: string
  901. """
  902. # override this if you want to strip executables
  903. # kw['tsk'].source is the task that created the files in the build
  904. if Utils.is_win32 and len(tgt) > 259 and not tgt.startswith('\\\\?\\'):
  905. tgt = '\\\\?\\' + tgt
  906. shutil.copy2(src, tgt)
  907. self.fix_perms(tgt)
  908. def rm_empty_dirs(self, tgt):
  909. """
  910. Removes empty folders recursively when uninstalling.
  911. :param tgt: absolute path
  912. :type tgt: string
  913. """
  914. while tgt:
  915. tgt = os.path.dirname(tgt)
  916. try:
  917. os.rmdir(tgt)
  918. except OSError:
  919. break
  920. def run(self):
  921. """
  922. Performs file or symlink installation
  923. """
  924. is_install = self.generator.bld.is_install
  925. if not is_install: # unnecessary?
  926. return
  927. for x in self.outputs:
  928. if is_install == INSTALL:
  929. x.parent.mkdir()
  930. if self.type == 'symlink_as':
  931. fun = is_install == INSTALL and self.do_link or self.do_unlink
  932. fun(self.link, self.outputs[0].abspath())
  933. else:
  934. fun = is_install == INSTALL and self.do_install or self.do_uninstall
  935. launch_node = self.generator.bld.launch_node()
  936. for x, y in zip(self.inputs, self.outputs):
  937. fun(x.abspath(), y.abspath(), x.path_from(launch_node))
  938. def run_now(self):
  939. """
  940. Try executing the installation task right now
  941. :raises: :py:class:`waflib.Errors.TaskNotReady`
  942. """
  943. status = self.runnable_status()
  944. if status not in (Task.RUN_ME, Task.SKIP_ME):
  945. raise Errors.TaskNotReady('Could not process %r: status %r' % (self, status))
  946. self.run()
  947. self.hasrun = Task.SUCCESS
  948. def do_install(self, src, tgt, lbl, **kw):
  949. """
  950. Copies a file from src to tgt with given file permissions. The actual copy is only performed
  951. if the source and target file sizes or timestamps differ. When the copy occurs,
  952. the file is always first removed and then copied so as to prevent stale inodes.
  953. :param src: file name as absolute path
  954. :type src: string
  955. :param tgt: file destination, as absolute path
  956. :type tgt: string
  957. :param lbl: file source description
  958. :type lbl: string
  959. :param chmod: installation mode
  960. :type chmod: int
  961. :raises: :py:class:`waflib.Errors.WafError` if the file cannot be written
  962. """
  963. if not Options.options.force:
  964. # check if the file is already there to avoid a copy
  965. try:
  966. st1 = os.stat(tgt)
  967. st2 = os.stat(src)
  968. except OSError:
  969. pass
  970. else:
  971. # same size and identical timestamps -> make no copy
  972. if st1.st_mtime + 2 >= st2.st_mtime and st1.st_size == st2.st_size:
  973. if not self.generator.bld.progress_bar:
  974. c1 = Logs.colors.NORMAL
  975. c2 = Logs.colors.BLUE
  976. Logs.info('%s- install %s%s%s (from %s)', c1, c2, tgt, c1, lbl)
  977. return False
  978. if not self.generator.bld.progress_bar:
  979. c1 = Logs.colors.NORMAL
  980. c2 = Logs.colors.BLUE
  981. Logs.info('%s+ install %s%s%s (from %s)', c1, c2, tgt, c1, lbl)
  982. # Give best attempt at making destination overwritable,
  983. # like the 'install' utility used by 'make install' does.
  984. try:
  985. os.chmod(tgt, Utils.O644 | stat.S_IMODE(os.stat(tgt).st_mode))
  986. except EnvironmentError:
  987. pass
  988. # following is for shared libs and stale inodes (-_-)
  989. try:
  990. os.remove(tgt)
  991. except OSError:
  992. pass
  993. try:
  994. self.copy_fun(src, tgt)
  995. except EnvironmentError as e:
  996. if not os.path.exists(src):
  997. Logs.error('File %r does not exist', src)
  998. elif not os.path.isfile(src):
  999. Logs.error('Input %r is not a file', src)
  1000. raise Errors.WafError('Could not install the file %r' % tgt, e)
  1001. def fix_perms(self, tgt):
  1002. """
  1003. Change the ownership of the file/folder/link pointed by the given path
  1004. This looks up for `install_user` or `install_group` attributes
  1005. on the task or on the task generator::
  1006. def build(bld):
  1007. bld.install_as('${PREFIX}/wscript',
  1008. 'wscript',
  1009. install_user='nobody', install_group='nogroup')
  1010. bld.symlink_as('${PREFIX}/wscript_link',
  1011. Utils.subst_vars('${PREFIX}/wscript', bld.env),
  1012. install_user='nobody', install_group='nogroup')
  1013. """
  1014. if not Utils.is_win32:
  1015. user = getattr(self, 'install_user', None) or getattr(self.generator, 'install_user', None)
  1016. group = getattr(self, 'install_group', None) or getattr(self.generator, 'install_group', None)
  1017. if user or group:
  1018. Utils.lchown(tgt, user or -1, group or -1)
  1019. if not os.path.islink(tgt):
  1020. os.chmod(tgt, self.chmod)
  1021. def do_link(self, src, tgt, **kw):
  1022. """
  1023. Creates a symlink from tgt to src.
  1024. :param src: file name as absolute path
  1025. :type src: string
  1026. :param tgt: file destination, as absolute path
  1027. :type tgt: string
  1028. """
  1029. if os.path.islink(tgt) and os.readlink(tgt) == src:
  1030. if not self.generator.bld.progress_bar:
  1031. c1 = Logs.colors.NORMAL
  1032. c2 = Logs.colors.BLUE
  1033. Logs.info('%s- symlink %s%s%s (to %s)', c1, c2, tgt, c1, src)
  1034. else:
  1035. try:
  1036. os.remove(tgt)
  1037. except OSError:
  1038. pass
  1039. if not self.generator.bld.progress_bar:
  1040. c1 = Logs.colors.NORMAL
  1041. c2 = Logs.colors.BLUE
  1042. Logs.info('%s+ symlink %s%s%s (to %s)', c1, c2, tgt, c1, src)
  1043. os.symlink(src, tgt)
  1044. self.fix_perms(tgt)
  1045. def do_uninstall(self, src, tgt, lbl, **kw):
  1046. """
  1047. See :py:meth:`waflib.Build.inst.do_install`
  1048. """
  1049. if not self.generator.bld.progress_bar:
  1050. c1 = Logs.colors.NORMAL
  1051. c2 = Logs.colors.BLUE
  1052. Logs.info('%s- remove %s%s%s', c1, c2, tgt, c1)
  1053. #self.uninstall.append(tgt)
  1054. try:
  1055. os.remove(tgt)
  1056. except OSError as e:
  1057. if e.errno != errno.ENOENT:
  1058. if not getattr(self, 'uninstall_error', None):
  1059. self.uninstall_error = True
  1060. Logs.warn('build: some files could not be uninstalled (retry with -vv to list them)')
  1061. if Logs.verbose > 1:
  1062. Logs.warn('Could not remove %s (error code %r)', e.filename, e.errno)
  1063. self.rm_empty_dirs(tgt)
  1064. def do_unlink(self, src, tgt, **kw):
  1065. """
  1066. See :py:meth:`waflib.Build.inst.do_link`
  1067. """
  1068. try:
  1069. if not self.generator.bld.progress_bar:
  1070. c1 = Logs.colors.NORMAL
  1071. c2 = Logs.colors.BLUE
  1072. Logs.info('%s- remove %s%s%s', c1, c2, tgt, c1)
  1073. os.remove(tgt)
  1074. except OSError:
  1075. pass
  1076. self.rm_empty_dirs(tgt)
  1077. class InstallContext(BuildContext):
  1078. '''installs the targets on the system'''
  1079. cmd = 'install'
  1080. def __init__(self, **kw):
  1081. super(InstallContext, self).__init__(**kw)
  1082. self.is_install = INSTALL
  1083. class UninstallContext(InstallContext):
  1084. '''removes the targets installed'''
  1085. cmd = 'uninstall'
  1086. def __init__(self, **kw):
  1087. super(UninstallContext, self).__init__(**kw)
  1088. self.is_install = UNINSTALL
  1089. class CleanContext(BuildContext):
  1090. '''cleans the project'''
  1091. cmd = 'clean'
  1092. def execute(self):
  1093. """
  1094. See :py:func:`waflib.Build.BuildContext.execute`.
  1095. """
  1096. self.restore()
  1097. if not self.all_envs:
  1098. self.load_envs()
  1099. self.recurse([self.run_dir])
  1100. try:
  1101. self.clean()
  1102. finally:
  1103. self.store()
  1104. def clean(self):
  1105. """
  1106. Remove most files from the build directory, and reset all caches.
  1107. Custom lists of files to clean can be declared as `bld.clean_files`.
  1108. For example, exclude `build/program/myprogram` from getting removed::
  1109. def build(bld):
  1110. bld.clean_files = bld.bldnode.ant_glob('**',
  1111. excl='.lock* config.log c4che/* config.h program/myprogram',
  1112. quiet=True, generator=True)
  1113. """
  1114. Logs.debug('build: clean called')
  1115. if hasattr(self, 'clean_files'):
  1116. for n in self.clean_files:
  1117. n.delete()
  1118. elif self.bldnode != self.srcnode:
  1119. # would lead to a disaster if top == out
  1120. lst = []
  1121. for env in self.all_envs.values():
  1122. lst.extend(self.root.find_or_declare(f) for f in env[CFG_FILES])
  1123. excluded_dirs = '.lock* *conf_check_*/** config.log %s/*' % CACHE_DIR
  1124. for n in self.bldnode.ant_glob('**/*', excl=excluded_dirs, quiet=True):
  1125. if n in lst:
  1126. continue
  1127. n.delete()
  1128. self.root.children = {}
  1129. for v in SAVED_ATTRS:
  1130. if v == 'root':
  1131. continue
  1132. setattr(self, v, {})
  1133. class ListContext(BuildContext):
  1134. '''lists the targets to execute'''
  1135. cmd = 'list'
  1136. def execute(self):
  1137. """
  1138. In addition to printing the name of each build target,
  1139. a description column will include text for each task
  1140. generator which has a "description" field set.
  1141. See :py:func:`waflib.Build.BuildContext.execute`.
  1142. """
  1143. self.restore()
  1144. if not self.all_envs:
  1145. self.load_envs()
  1146. self.recurse([self.run_dir])
  1147. self.pre_build()
  1148. # display the time elapsed in the progress bar
  1149. self.timer = Utils.Timer()
  1150. for g in self.groups:
  1151. for tg in g:
  1152. try:
  1153. f = tg.post
  1154. except AttributeError:
  1155. pass
  1156. else:
  1157. f()
  1158. try:
  1159. # force the cache initialization
  1160. self.get_tgen_by_name('')
  1161. except Errors.WafError:
  1162. pass
  1163. targets = sorted(self.task_gen_cache_names)
  1164. # figure out how much to left-justify, for largest target name
  1165. line_just = max(len(t) for t in targets) if targets else 0
  1166. for target in targets:
  1167. tgen = self.task_gen_cache_names[target]
  1168. # Support displaying the description for the target
  1169. # if it was set on the tgen
  1170. descript = getattr(tgen, 'description', '')
  1171. if descript:
  1172. target = target.ljust(line_just)
  1173. descript = ': %s' % descript
  1174. Logs.pprint('GREEN', target, label=descript)
  1175. class StepContext(BuildContext):
  1176. '''executes tasks in a step-by-step fashion, for debugging'''
  1177. cmd = 'step'
  1178. def __init__(self, **kw):
  1179. super(StepContext, self).__init__(**kw)
  1180. self.files = Options.options.files
  1181. def compile(self):
  1182. """
  1183. Overrides :py:meth:`waflib.Build.BuildContext.compile` to perform a partial build
  1184. on tasks matching the input/output pattern given (regular expression matching)::
  1185. $ waf step --files=foo.c,bar.c,in:truc.c,out:bar.o
  1186. $ waf step --files=in:foo.cpp.1.o # link task only
  1187. """
  1188. if not self.files:
  1189. Logs.warn('Add a pattern for the debug build, for example "waf step --files=main.c,app"')
  1190. BuildContext.compile(self)
  1191. return
  1192. targets = []
  1193. if self.targets and self.targets != '*':
  1194. targets = self.targets.split(',')
  1195. for g in self.groups:
  1196. for tg in g:
  1197. if targets and tg.name not in targets:
  1198. continue
  1199. try:
  1200. f = tg.post
  1201. except AttributeError:
  1202. pass
  1203. else:
  1204. f()
  1205. for pat in self.files.split(','):
  1206. matcher = self.get_matcher(pat)
  1207. for tg in g:
  1208. if isinstance(tg, Task.Task):
  1209. lst = [tg]
  1210. else:
  1211. lst = tg.tasks
  1212. for tsk in lst:
  1213. do_exec = False
  1214. for node in tsk.inputs:
  1215. if matcher(node, output=False):
  1216. do_exec = True
  1217. break
  1218. for node in tsk.outputs:
  1219. if matcher(node, output=True):
  1220. do_exec = True
  1221. break
  1222. if do_exec:
  1223. ret = tsk.run()
  1224. Logs.info('%s -> exit %r', tsk, ret)
  1225. def get_matcher(self, pat):
  1226. """
  1227. Converts a step pattern into a function
  1228. :param: pat: pattern of the form in:truc.c,out:bar.o
  1229. :returns: Python function that uses Node objects as inputs and returns matches
  1230. :rtype: function
  1231. """
  1232. # this returns a function
  1233. inn = True
  1234. out = True
  1235. if pat.startswith('in:'):
  1236. out = False
  1237. pat = pat.replace('in:', '')
  1238. elif pat.startswith('out:'):
  1239. inn = False
  1240. pat = pat.replace('out:', '')
  1241. anode = self.root.find_node(pat)
  1242. pattern = None
  1243. if not anode:
  1244. if not pat.startswith('^'):
  1245. pat = '^.+?%s' % pat
  1246. if not pat.endswith('$'):
  1247. pat = '%s$' % pat
  1248. pattern = re.compile(pat)
  1249. def match(node, output):
  1250. if output and not out:
  1251. return False
  1252. if not output and not inn:
  1253. return False
  1254. if anode:
  1255. return anode == node
  1256. else:
  1257. return pattern.match(node.abspath())
  1258. return match
  1259. class EnvContext(BuildContext):
  1260. """Subclass EnvContext to create commands that require configuration data in 'env'"""
  1261. fun = cmd = None
  1262. def execute(self):
  1263. """
  1264. See :py:func:`waflib.Build.BuildContext.execute`.
  1265. """
  1266. self.restore()
  1267. if not self.all_envs:
  1268. self.load_envs()
  1269. self.recurse([self.run_dir])