Build.py 41 KB

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