3 # Thomas Nagy, 2005-2018 (ita)
6 Classes related to the build phase (build, clean, install, step, etc)
8 The inheritance tree is the following:
12 import os
, sys
, errno
, re
, shutil
, stat
16 import pickle
as cPickle
17 from waflib
import Node
, Runner
, TaskGen
, Utils
, ConfigSet
, Task
, Logs
, Options
, Context
, Errors
20 """Name of the cache directory"""
22 CACHE_SUFFIX
= '_cache.py'
23 """ConfigSet cache files for variants are written under :py:attr:´waflib.Build.CACHE_DIR´ in the form ´variant_name´_cache.py"""
26 """Positive value '->' install, see :py:attr:`waflib.Build.BuildContext.is_install`"""
29 """Negative value '<-' uninstall, see :py:attr:`waflib.Build.BuildContext.is_install`"""
31 SAVED_ATTRS
= 'root node_sigs task_sigs imp_sigs raw_deps node_deps'.split()
32 """Build class members to save between the runs; these should be all dicts
33 except for `root` which represents a :py:class:`waflib.Node.Node` instance
36 CFG_FILES
= 'cfg_files'
37 """Files from the build directory to hash before starting the build (``config.h`` written during the configuration)"""
40 """Post mode: all task generators are posted before any task executed"""
43 """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"""
46 if sys
.platform
== 'cli':
49 class BuildContext(Context
.Context
):
50 '''executes the build'''
55 def __init__(self
, **kw
):
56 super(BuildContext
, self
).__init
__(**kw
)
59 """Non-zero value when installing or uninstalling file"""
61 self
.top_dir
= kw
.get('top_dir', Context
.top_dir
)
62 """See :py:attr:`waflib.Context.top_dir`; prefer :py:attr:`waflib.Build.BuildContext.srcnode`"""
64 self
.out_dir
= kw
.get('out_dir', Context
.out_dir
)
65 """See :py:attr:`waflib.Context.out_dir`; prefer :py:attr:`waflib.Build.BuildContext.bldnode`"""
67 self
.run_dir
= kw
.get('run_dir', Context
.run_dir
)
68 """See :py:attr:`waflib.Context.run_dir`"""
70 self
.launch_dir
= Context
.launch_dir
71 """See :py:attr:`waflib.Context.out_dir`; prefer :py:meth:`waflib.Build.BuildContext.launch_node`"""
73 self
.post_mode
= POST_LAZY
74 """Whether to post the task generators at once or group-by-group (default is group-by-group)"""
76 self
.cache_dir
= kw
.get('cache_dir')
77 if not self
.cache_dir
:
78 self
.cache_dir
= os
.path
.join(self
.out_dir
, CACHE_DIR
)
81 """Map names to :py:class:`waflib.ConfigSet.ConfigSet`, the empty string must map to the default environment"""
83 # ======================================= #
87 """Dict mapping build nodes to task identifier (uid), it indicates whether a task created a particular file (persists across builds)"""
90 """Dict mapping task identifiers (uid) to task signatures (persists across builds)"""
93 """Dict mapping task identifiers (uid) to implicit task dependencies used for scanning targets (persists across builds)"""
96 """Dict mapping task identifiers (uid) to node dependencies found by :py:meth:`waflib.Task.Task.scan` (persists across builds)"""
99 """Dict mapping task identifiers (uid) to custom data returned by :py:meth:`waflib.Task.Task.scan` (persists across builds)"""
101 self
.task_gen_cache_names
= {}
103 self
.jobs
= Options
.options
.jobs
104 """Amount of jobs to run in parallel"""
106 self
.targets
= Options
.options
.targets
107 """List of targets to build (default: \*)"""
109 self
.keep
= Options
.options
.keep
110 """Whether the build should continue past errors"""
112 self
.progress_bar
= Options
.options
.progress_bar
114 Level of progress status:
122 # Manual dependencies.
123 self
.deps_man
= Utils
.defaultdict(list)
124 """Manual dependencies set by :py:meth:`waflib.Build.BuildContext.add_manual_dependency`"""
126 # just the structure here
127 self
.current_group
= 0
134 List containing lists of task generators
137 self
.group_names
= {}
139 Map group names to the group lists. See :py:meth:`waflib.Build.BuildContext.add_group`
142 for v
in SAVED_ATTRS
:
143 if not hasattr(self
, v
):
146 def get_variant_dir(self
):
147 """Getter for the variant_dir attribute"""
150 return os
.path
.join(self
.out_dir
, os
.path
.normpath(self
.variant
))
151 variant_dir
= property(get_variant_dir
, None)
153 def __call__(self
, *k
, **kw
):
155 Create a task generator and add it to the current build group. The following forms are equivalent::
166 tg = TaskGen.task_gen(a=1, b=2)
167 bld.add_to_group(tg, None)
169 :param group: group name to add the task generator to
173 ret
= TaskGen
.task_gen(*k
, **kw
)
174 self
.task_gen_cache_names
= {} # reset the cache, each time
175 self
.add_to_group(ret
, group
=kw
.get('group'))
180 Build contexts cannot be copied
182 :raises: :py:class:`waflib.Errors.WafError`
184 raise Errors
.WafError('build contexts cannot be copied')
188 The configuration command creates files of the form ``build/c4che/NAMEcache.py``. This method
189 creates a :py:class:`waflib.ConfigSet.ConfigSet` instance for each ``NAME`` by reading those
190 files and stores them in :py:attr:`waflib.Build.BuildContext.allenvs`.
192 node
= self
.root
.find_node(self
.cache_dir
)
194 raise Errors
.WafError('The project was not configured: run "waf configure" first!')
195 lst
= node
.ant_glob('**/*%s' % CACHE_SUFFIX
, quiet
=True)
198 raise Errors
.WafError('The cache directory is empty: reconfigure the project')
201 name
= x
.path_from(node
).replace(CACHE_SUFFIX
, '').replace('\\', '/')
202 env
= ConfigSet
.ConfigSet(x
.abspath())
203 self
.all_envs
[name
] = env
204 for f
in env
[CFG_FILES
]:
205 newnode
= self
.root
.find_resource(f
)
206 if not newnode
or not newnode
.exists():
207 raise Errors
.WafError('Missing configuration file %r, reconfigure the project!' % f
)
211 Initialize the project directory and the build directory by creating the nodes
212 :py:attr:`waflib.Build.BuildContext.srcnode` and :py:attr:`waflib.Build.BuildContext.bldnode`
213 corresponding to ``top_dir`` and ``variant_dir`` respectively. The ``bldnode`` directory is
214 created if necessary.
216 if not (os
.path
.isabs(self
.top_dir
) and os
.path
.isabs(self
.out_dir
)):
217 raise Errors
.WafError('The project was not configured: run "waf configure" first!')
219 self
.path
= self
.srcnode
= self
.root
.find_dir(self
.top_dir
)
220 self
.bldnode
= self
.root
.make_node(self
.variant_dir
)
225 Restore data from previous builds and call :py:meth:`waflib.Build.BuildContext.execute_build`.
226 Overrides from :py:func:`waflib.Context.Context.execute`
229 if not self
.all_envs
:
233 def execute_build(self
):
235 Execute the build by:
237 * reading the scripts (see :py:meth:`waflib.Context.Context.recurse`)
238 * calling :py:meth:`waflib.Build.BuildContext.pre_build` to call user build functions
239 * calling :py:meth:`waflib.Build.BuildContext.compile` to process the tasks
240 * calling :py:meth:`waflib.Build.BuildContext.post_build` to call user build functions
243 Logs
.info("Waf: Entering directory `%s'", self
.variant_dir
)
244 self
.recurse([self
.run_dir
])
247 # display the time elapsed in the progress bar
248 self
.timer
= Utils
.Timer()
253 if self
.progress_bar
== 1 and sys
.stderr
.isatty():
254 c
= self
.producer
.processed
or 1
255 m
= self
.progress_line(c
, c
, Logs
.colors
.BLUE
, Logs
.colors
.NORMAL
)
256 Logs
.info(m
, extra
={'stream': sys
.stderr
, 'c1': Logs
.colors
.cursor_off
, 'c2' : Logs
.colors
.cursor_on
})
257 Logs
.info("Waf: Leaving directory `%s'", self
.variant_dir
)
259 self
.producer
.bld
= None
261 except AttributeError:
267 Load data from a previous run, sets the attributes listed in :py:const:`waflib.Build.SAVED_ATTRS`
270 env
= ConfigSet
.ConfigSet(os
.path
.join(self
.cache_dir
, 'build.config.py'))
271 except EnvironmentError:
274 if env
.version
< Context
.HEXVERSION
:
275 raise Errors
.WafError('Project was configured with a different version of Waf, please reconfigure it')
280 dbfn
= os
.path
.join(self
.variant_dir
, Context
.DBFILE
)
282 data
= Utils
.readf(dbfn
, 'rb')
283 except (EnvironmentError, EOFError):
284 # handle missing file/empty file
285 Logs
.debug('build: Could not load the build cache %s (missing)', dbfn
)
288 Node
.pickle_lock
.acquire()
289 Node
.Nod3
= self
.node_class
291 data
= cPickle
.loads(data
)
292 except Exception as e
:
293 Logs
.debug('build: Could not pickle the build cache %s: %r', dbfn
, e
)
295 for x
in SAVED_ATTRS
:
296 setattr(self
, x
, data
.get(x
, {}))
298 Node
.pickle_lock
.release()
304 Store data for next runs, set the attributes listed in :py:const:`waflib.Build.SAVED_ATTRS`. Uses a temporary
305 file to avoid problems on ctrl+c.
308 for x
in SAVED_ATTRS
:
309 data
[x
] = getattr(self
, x
)
310 db
= os
.path
.join(self
.variant_dir
, Context
.DBFILE
)
313 Node
.pickle_lock
.acquire()
314 Node
.Nod3
= self
.node_class
315 x
= cPickle
.dumps(data
, PROTOCOL
)
317 Node
.pickle_lock
.release()
319 Utils
.writef(db
+ '.tmp', x
, m
='wb')
324 if not Utils
.is_win32
: # win32 has no chown but we're paranoid
325 os
.chown(db
+ '.tmp', st
.st_uid
, st
.st_gid
)
326 except (AttributeError, OSError):
329 # do not use shutil.move (copy is not thread-safe)
330 os
.rename(db
+ '.tmp', db
)
334 Run the build by creating an instance of :py:class:`waflib.Runner.Parallel`
335 The cache file is written when at least a task was executed.
337 :raises: :py:class:`waflib.Errors.BuildError` in case the build fails
339 Logs
.debug('build: compile()')
341 # delegate the producer-consumer logic to another object to reduce the complexity
342 self
.producer
= Runner
.Parallel(self
, self
.jobs
)
343 self
.producer
.biter
= self
.get_build_iterator()
345 self
.producer
.start()
346 except KeyboardInterrupt:
354 if self
.producer
.error
:
355 raise Errors
.BuildError(self
.producer
.error
)
358 return self
.producer
.dirty
360 def setup(self
, tool
, tooldir
=None, funs
=None):
362 Import waf tools defined during the configuration::
368 pass # glib2 is imported implicitly
370 :param tool: tool list
372 :param tooldir: optional tool directory (sys.path)
373 :type tooldir: list of string
374 :param funs: unused variable
376 if isinstance(tool
, list):
378 self
.setup(i
, tooldir
)
381 module
= Context
.load_tool(tool
, tooldir
)
382 if hasattr(module
, "setup"):
386 """Getter for the env property"""
388 return self
.all_envs
[self
.variant
]
390 return self
.all_envs
['']
391 def set_env(self
, val
):
392 """Setter for the env property"""
393 self
.all_envs
[self
.variant
] = val
395 env
= property(get_env
, set_env
)
397 def add_manual_dependency(self
, path
, value
):
399 Adds a dependency from a node object to a value::
402 bld.add_manual_dependency(
403 bld.path.find_resource('wscript'),
404 bld.root.find_resource('/etc/fstab'))
406 :param path: file path
407 :type path: string or :py:class:`waflib.Node.Node`
408 :param value: value to depend
409 :type value: :py:class:`waflib.Node.Node`, byte object, or function returning a byte object
412 raise ValueError('Invalid input path %r' % path
)
414 if isinstance(path
, Node
.Node
):
416 elif os
.path
.isabs(path
):
417 node
= self
.root
.find_resource(path
)
419 node
= self
.path
.find_resource(path
)
421 raise ValueError('Could not find the path %r' % path
)
423 if isinstance(value
, list):
424 self
.deps_man
[node
].extend(value
)
426 self
.deps_man
[node
].append(value
)
428 def launch_node(self
):
429 """Returns the launch directory as a :py:class:`waflib.Node.Node` object (cached)"""
433 except AttributeError:
434 self
.p_ln
= self
.root
.find_dir(self
.launch_dir
)
437 def hash_env_vars(self
, env
, vars_lst
):
439 Hashes configuration set variables::
442 bld.hash_env_vars(bld.env, ['CXX', 'CC'])
444 This method uses an internal cache.
446 :param env: Configuration Set
447 :type env: :py:class:`waflib.ConfigSet.ConfigSet`
448 :param vars_lst: list of variables
449 :type vars_list: list of string
457 idx
= str(id(env
)) + str(vars_lst
)
459 cache
= self
.cache_env
460 except AttributeError:
461 cache
= self
.cache_env
= {}
464 return self
.cache_env
[idx
]
468 lst
= [env
[a
] for a
in vars_lst
]
469 cache
[idx
] = ret
= Utils
.h_list(lst
)
470 Logs
.debug('envhash: %s %r', Utils
.to_hex(ret
), lst
)
473 def get_tgen_by_name(self
, name
):
475 Fetches a task generator by its name or its target attribute;
476 the name must be unique in a build::
480 tg == bld.get_tgen_by_name('foo')
482 This method use a private internal cache.
484 :param name: Task generator name
485 :raises: :py:class:`waflib.Errors.WafError` in case there is no task genenerator by that name
487 cache
= self
.task_gen_cache_names
489 # create the index lazily
490 for g
in self
.groups
:
494 except AttributeError:
495 # raised if not a task generator, which should be uncommon
500 raise Errors
.WafError('Could not find a task generator for the name %r' % name
)
502 def progress_line(self
, idx
, total
, col1
, col2
):
504 Computes a progress bar line displayed when running ``waf -p``
506 :returns: progress bar line
509 if not sys
.stderr
.isatty():
515 ind
= Utils
.rot_chr
[Utils
.rot_idx
% 4]
517 pc
= (100. * idx
)/total
518 fs
= "[%%%dd/%%d][%%s%%2d%%%%%%s][%s][" % (n
, ind
)
519 left
= fs
% (idx
, total
, col1
, pc
, col2
)
520 right
= '][%s%s%s]' % (col1
, self
.timer
, col2
)
522 cols
= Logs
.get_term_cols() - len(left
) - len(right
) + 2*len(col1
) + 2*len(col2
)
526 ratio
= ((cols
* idx
)//total
) - 1
528 bar
= ('='*ratio
+'>').ljust(cols
)
529 msg
= Logs
.indicator
% (left
, bar
, right
)
533 def declare_chain(self
, *k
, **kw
):
535 Wraps :py:func:`waflib.TaskGen.declare_chain` for convenience
537 return TaskGen
.declare_chain(*k
, **kw
)
540 """Executes user-defined methods before the build starts, see :py:meth:`waflib.Build.BuildContext.add_pre_fun`"""
541 for m
in getattr(self
, 'pre_funs', []):
544 def post_build(self
):
545 """Executes user-defined methods after the build is successful, see :py:meth:`waflib.Build.BuildContext.add_post_fun`"""
546 for m
in getattr(self
, 'post_funs', []):
549 def add_pre_fun(self
, meth
):
551 Binds a callback method to execute after the scripts are read and before the build starts::
554 print("Hello, world!")
557 bld.add_pre_fun(mycallback)
560 self
.pre_funs
.append(meth
)
561 except AttributeError:
562 self
.pre_funs
= [meth
]
564 def add_post_fun(self
, meth
):
566 Binds a callback method to execute immediately after the build is successful::
568 def call_ldconfig(bld):
569 bld.exec_command('/sbin/ldconfig')
572 if bld.cmd == 'install':
573 bld.add_pre_fun(call_ldconfig)
576 self
.post_funs
.append(meth
)
577 except AttributeError:
578 self
.post_funs
= [meth
]
580 def get_group(self
, x
):
582 Returns the build group named `x`, or the current group if `x` is None
584 :param x: name or number or None
585 :type x: string, int or None
590 return self
.groups
[self
.current_group
]
591 if x
in self
.group_names
:
592 return self
.group_names
[x
]
593 return self
.groups
[x
]
595 def add_to_group(self
, tgen
, group
=None):
596 """Adds a task or a task generator to the build; there is no attempt to remove it if it was already added."""
597 assert(isinstance(tgen
, TaskGen
.task_gen
) or isinstance(tgen
, Task
.Task
))
599 self
.get_group(group
).append(tgen
)
601 def get_group_name(self
, g
):
603 Returns the name of the input build group
605 :param g: build group object or build group index
606 :type g: integer or list
610 if not isinstance(g
, list):
612 for x
in self
.group_names
:
613 if id(self
.group_names
[x
]) == id(g
):
617 def get_group_idx(self
, tg
):
619 Returns the index of the group containing the task generator given as argument::
622 tg = bld(name='nada')
623 0 == bld.get_group_idx(tg)
625 :param tg: Task generator object
626 :type tg: :py:class:`waflib.TaskGen.task_gen`
630 for i
, tmp
in enumerate(self
.groups
):
636 def add_group(self
, name
=None, move
=True):
638 Adds a new group of tasks/task generators. By default the new group becomes
639 the default group for new task generators (make sure to create build groups in order).
641 :param name: name for this group
643 :param move: set this new group as default group (True by default)
645 :raises: :py:class:`waflib.Errors.WafError` if a group by the name given already exists
647 if name
and name
in self
.group_names
:
648 raise Errors
.WafError('add_group: name %s already present', name
)
650 self
.group_names
[name
] = g
651 self
.groups
.append(g
)
653 self
.current_group
= len(self
.groups
) - 1
655 def set_group(self
, idx
):
657 Sets the build group at position idx as current so that newly added
658 task generators are added to this one by default::
661 bld(rule='touch ${TGT}', target='foo.txt')
662 bld.add_group() # now the current group is 1
663 bld(rule='touch ${TGT}', target='bar.txt')
664 bld.set_group(0) # now the current group is 0
665 bld(rule='touch ${TGT}', target='truc.txt') # build truc.txt before bar.txt
667 :param idx: group name or group index
668 :type idx: string or int
670 if isinstance(idx
, str):
671 g
= self
.group_names
[idx
]
672 for i
, tmp
in enumerate(self
.groups
):
674 self
.current_group
= i
677 self
.current_group
= idx
681 Approximate task count: this value may be inaccurate if task generators
682 are posted lazily (see :py:attr:`waflib.Build.BuildContext.post_mode`).
683 The value :py:attr:`waflib.Runner.Parallel.total` is updated during the task execution.
688 for group
in self
.groups
:
691 total
+= len(tg
.tasks
)
692 except AttributeError:
696 def get_targets(self
):
698 This method returns a pair containing the index of the last build group to post,
699 and the list of task generator objects corresponding to the target names.
701 This is used internally by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
702 to perform partial builds::
704 $ waf --targets=myprogram,myshlib
706 :return: the minimum build group index, and list of task generators
711 for name
in self
.targets
.split(','):
712 tg
= self
.get_tgen_by_name(name
)
713 m
= self
.get_group_idx(tg
)
719 return (min_grp
, to_post
)
721 def get_all_task_gen(self
):
723 Returns a list of all task generators for troubleshooting purposes.
726 for g
in self
.groups
:
730 def post_group(self
):
732 Post task generators from the group indexed by self.current_group; used internally
733 by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
738 except AttributeError:
743 if self
.targets
== '*':
744 for tg
in self
.groups
[self
.current_group
]:
747 if self
.current_group
< self
._min
_grp
:
748 for tg
in self
.groups
[self
.current_group
]:
751 for tg
in self
._exact
_tg
:
754 ln
= self
.launch_node()
755 if ln
.is_child_of(self
.bldnode
):
756 Logs
.warn('Building from the build directory, forcing --targets=*')
758 elif not ln
.is_child_of(self
.srcnode
):
759 Logs
.warn('CWD %s is not under %s, forcing --targets=* (run distclean?)', ln
.abspath(), self
.srcnode
.abspath())
765 except AttributeError:
768 if p
.is_child_of(ln
):
772 for i
, g
in enumerate(self
.groups
):
773 if i
> self
.current_group
:
778 if self
.post_mode
== POST_LAZY
and ln
!= self
.srcnode
:
779 # partial folder builds require all targets from a previous build group
783 for tg
in self
.groups
[self
.current_group
]:
787 def get_tasks_group(self
, idx
):
789 Returns all task instances for the build group at position idx,
790 used internally by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
792 :rtype: list of :py:class:`waflib.Task.Task`
795 for tg
in self
.groups
[idx
]:
797 tasks
.extend(tg
.tasks
)
798 except AttributeError: # not a task generator
802 def get_build_iterator(self
):
804 Creates a Python generator object that returns lists of tasks that may be processed in parallel.
806 :return: tasks which can be executed immediately
807 :rtype: generator returning lists of :py:class:`waflib.Task.Task`
809 if self
.targets
and self
.targets
!= '*':
810 (self
._min
_grp
, self
._exact
_tg
) = self
.get_targets()
812 if self
.post_mode
!= POST_LAZY
:
813 for self
.current_group
, _
in enumerate(self
.groups
):
816 for self
.current_group
, _
in enumerate(self
.groups
):
817 # first post the task generators for the group
818 if self
.post_mode
!= POST_AT_ONCE
:
821 # then extract the tasks
822 tasks
= self
.get_tasks_group(self
.current_group
)
824 # if the constraints are set properly (ext_in/ext_out, before/after)
825 # the call to set_file_constraints may be removed (can be a 15% penalty on no-op rebuilds)
826 # (but leave set_file_constraints for the installation step)
828 # if the tasks have only files, set_file_constraints is required but set_precedence_constraints is not necessary
830 Task
.set_file_constraints(tasks
)
831 Task
.set_precedence_constraints(tasks
)
833 self
.cur_tasks
= tasks
838 # the build stops once there are no tasks to process
841 def install_files(self
, dest
, files
, **kw
):
843 Creates a task generator to install files on the system::
846 bld.install_files('${DATADIR}', self.path.find_resource('wscript'))
848 :param dest: path representing the destination directory
849 :type dest: :py:class:`waflib.Node.Node` or string (absolute path)
850 :param files: input files
851 :type files: list of strings or list of :py:class:`waflib.Node.Node`
852 :param env: configuration set to expand *dest*
853 :type env: :py:class:`waflib.ConfigSet.ConfigSet`
854 :param relative_trick: preserve the folder hierarchy when installing whole folders
855 :type relative_trick: bool
856 :param cwd: parent node for searching srcfile, when srcfile is not an instance of :py:class:`waflib.Node.Node`
857 :type cwd: :py:class:`waflib.Node.Node`
858 :param postpone: execute the task immediately to perform the installation (False by default)
862 tg
= self(features
='install_task', install_to
=dest
, install_from
=files
, **kw
)
863 tg
.dest
= tg
.install_to
864 tg
.type = 'install_files'
865 if not kw
.get('postpone', True):
869 def install_as(self
, dest
, srcfile
, **kw
):
871 Creates a task generator to install a file on the system with a different name::
874 bld.install_as('${PREFIX}/bin', 'myapp', chmod=Utils.O755)
876 :param dest: destination file
877 :type dest: :py:class:`waflib.Node.Node` or string (absolute path)
878 :param srcfile: input file
879 :type srcfile: string or :py:class:`waflib.Node.Node`
880 :param cwd: parent node for searching srcfile, when srcfile is not an instance of :py:class:`waflib.Node.Node`
881 :type cwd: :py:class:`waflib.Node.Node`
882 :param env: configuration set for performing substitutions in dest
883 :type env: :py:class:`waflib.ConfigSet.ConfigSet`
884 :param postpone: execute the task immediately to perform the installation (False by default)
888 tg
= self(features
='install_task', install_to
=dest
, install_from
=srcfile
, **kw
)
889 tg
.dest
= tg
.install_to
890 tg
.type = 'install_as'
891 if not kw
.get('postpone', True):
895 def symlink_as(self
, dest
, src
, **kw
):
897 Creates a task generator to install a symlink::
900 bld.symlink_as('${PREFIX}/lib/libfoo.so', 'libfoo.so.1.2.3')
902 :param dest: absolute path of the symlink
903 :type dest: :py:class:`waflib.Node.Node` or string (absolute path)
904 :param src: link contents, which is a relative or absolute path which may exist or not
906 :param env: configuration set for performing substitutions in dest
907 :type env: :py:class:`waflib.ConfigSet.ConfigSet`
908 :param add: add the task created to a build group - set ``False`` only if the installation task is created after the build has started
910 :param postpone: execute the task immediately to perform the installation
912 :param relative_trick: make the symlink relative (default: ``False``)
913 :type relative_trick: bool
916 tg
= self(features
='install_task', install_to
=dest
, install_from
=src
, **kw
)
917 tg
.dest
= tg
.install_to
918 tg
.type = 'symlink_as'
920 # TODO if add: self.add_to_group(tsk)
921 if not kw
.get('postpone', True):
925 @TaskGen.feature('install_task')
926 @TaskGen.before_method('process_rule', 'process_source')
927 def process_install_task(self
):
928 """Creates the installation task for the current task generator; uses :py:func:`waflib.Build.add_install_task` internally."""
929 self
.add_install_task(**self
.__dict
__)
931 @TaskGen.taskgen_method
932 def add_install_task(self
, **kw
):
934 Creates the installation task for the current task generator, and executes it immediately if necessary
936 :returns: An installation task
937 :rtype: :py:class:`waflib.Build.inst`
939 if not self
.bld
.is_install
:
941 if not kw
['install_to']:
944 if kw
['type'] == 'symlink_as' and Utils
.is_win32
:
945 if kw
.get('win32_install'):
946 kw
['type'] = 'install_as'
951 tsk
= self
.install_task
= self
.create_task('inst')
952 tsk
.chmod
= kw
.get('chmod', Utils
.O644
)
953 tsk
.link
= kw
.get('link', '') or kw
.get('install_from', '')
954 tsk
.relative_trick
= kw
.get('relative_trick', False)
955 tsk
.type = kw
['type']
956 tsk
.install_to
= tsk
.dest
= kw
['install_to']
957 tsk
.install_from
= kw
['install_from']
958 tsk
.relative_base
= kw
.get('cwd') or kw
.get('relative_base', self
.path
)
959 tsk
.install_user
= kw
.get('install_user')
960 tsk
.install_group
= kw
.get('install_group')
962 if not kw
.get('postpone', True):
966 @TaskGen.taskgen_method
967 def add_install_files(self
, **kw
):
969 Creates an installation task for files
971 :returns: An installation task
972 :rtype: :py:class:`waflib.Build.inst`
974 kw
['type'] = 'install_files'
975 return self
.add_install_task(**kw
)
977 @TaskGen.taskgen_method
978 def add_install_as(self
, **kw
):
980 Creates an installation task for a single file
982 :returns: An installation task
983 :rtype: :py:class:`waflib.Build.inst`
985 kw
['type'] = 'install_as'
986 return self
.add_install_task(**kw
)
988 @TaskGen.taskgen_method
989 def add_symlink_as(self
, **kw
):
991 Creates an installation task for a symbolic link
993 :returns: An installation task
994 :rtype: :py:class:`waflib.Build.inst`
996 kw
['type'] = 'symlink_as'
997 return self
.add_install_task(**kw
)
999 class inst(Task
.Task
):
1000 """Task that installs files or symlinks; it is typically executed by :py:class:`waflib.Build.InstallContext` and :py:class:`waflib.Build.UnInstallContext`"""
1002 """Returns an empty string to disable the standard task display"""
1006 """Returns a unique identifier for the task"""
1007 lst
= self
.inputs
+ self
.outputs
+ [self
.link
, self
.generator
.path
.abspath()]
1008 return Utils
.h_list(lst
)
1010 def init_files(self
):
1012 Initializes the task input and output nodes
1014 if self
.type == 'symlink_as':
1017 inputs
= self
.generator
.to_nodes(self
.install_from
)
1018 if self
.type == 'install_as':
1019 assert len(inputs
) == 1
1020 self
.set_inputs(inputs
)
1022 dest
= self
.get_install_path()
1024 if self
.type == 'symlink_as':
1025 if self
.relative_trick
:
1026 self
.link
= os
.path
.relpath(self
.link
, os
.path
.dirname(dest
))
1027 outputs
.append(self
.generator
.bld
.root
.make_node(dest
))
1028 elif self
.type == 'install_as':
1029 outputs
.append(self
.generator
.bld
.root
.make_node(dest
))
1032 if self
.relative_trick
:
1033 destfile
= os
.path
.join(dest
, y
.path_from(self
.relative_base
))
1035 destfile
= os
.path
.join(dest
, y
.name
)
1036 outputs
.append(self
.generator
.bld
.root
.make_node(destfile
))
1037 self
.set_outputs(outputs
)
1039 def runnable_status(self
):
1041 Installation tasks are always executed, so this method returns either :py:const:`waflib.Task.ASK_LATER` or :py:const:`waflib.Task.RUN_ME`.
1043 ret
= super(inst
, self
).runnable_status()
1044 if ret
== Task
.SKIP_ME
and self
.generator
.bld
.is_install
:
1050 Disables any post-run operations
1054 def get_install_path(self
, destdir
=True):
1056 Returns the destination path where files will be installed, pre-pending `destdir`.
1058 Relative paths will be interpreted relative to `PREFIX` if no `destdir` is given.
1062 if isinstance(self
.install_to
, Node
.Node
):
1063 dest
= self
.install_to
.abspath()
1065 dest
= Utils
.subst_vars(self
.install_to
, self
.env
)
1066 if not os
.path
.isabs(dest
):
1067 dest
= os
.path
.join(self
.env
.PREFIX
, dest
)
1068 if destdir
and Options
.options
.destdir
:
1069 dest
= os
.path
.join(Options
.options
.destdir
, os
.path
.splitdrive(dest
)[1].lstrip(os
.sep
))
1072 def copy_fun(self
, src
, tgt
):
1074 Copies a file from src to tgt, preserving permissions and trying to work
1075 around path limitations on Windows platforms. On Unix-like platforms,
1076 the owner/group of the target file may be set through install_user/install_group
1078 :param src: absolute path
1080 :param tgt: absolute path
1083 # override this if you want to strip executables
1084 # kw['tsk'].source is the task that created the files in the build
1085 if Utils
.is_win32
and len(tgt
) > 259 and not tgt
.startswith('\\\\?\\'):
1086 tgt
= '\\\\?\\' + tgt
1087 shutil
.copy2(src
, tgt
)
1090 def rm_empty_dirs(self
, tgt
):
1092 Removes empty folders recursively when uninstalling.
1094 :param tgt: absolute path
1098 tgt
= os
.path
.dirname(tgt
)
1106 Performs file or symlink installation
1108 is_install
= self
.generator
.bld
.is_install
1109 if not is_install
: # unnecessary?
1112 for x
in self
.outputs
:
1113 if is_install
== INSTALL
:
1115 if self
.type == 'symlink_as':
1116 fun
= is_install
== INSTALL
and self
.do_link
or self
.do_unlink
1117 fun(self
.link
, self
.outputs
[0].abspath())
1119 fun
= is_install
== INSTALL
and self
.do_install
or self
.do_uninstall
1120 launch_node
= self
.generator
.bld
.launch_node()
1121 for x
, y
in zip(self
.inputs
, self
.outputs
):
1122 fun(x
.abspath(), y
.abspath(), x
.path_from(launch_node
))
1126 Try executing the installation task right now
1128 :raises: :py:class:`waflib.Errors.TaskNotReady`
1130 status
= self
.runnable_status()
1131 if status
not in (Task
.RUN_ME
, Task
.SKIP_ME
):
1132 raise Errors
.TaskNotReady('Could not process %r: status %r' % (self
, status
))
1134 self
.hasrun
= Task
.SUCCESS
1136 def do_install(self
, src
, tgt
, lbl
, **kw
):
1138 Copies a file from src to tgt with given file permissions. The actual copy is only performed
1139 if the source and target file sizes or timestamps differ. When the copy occurs,
1140 the file is always first removed and then copied so as to prevent stale inodes.
1142 :param src: file name as absolute path
1144 :param tgt: file destination, as absolute path
1146 :param lbl: file source description
1148 :param chmod: installation mode
1150 :raises: :py:class:`waflib.Errors.WafError` if the file cannot be written
1152 if not Options
.options
.force
:
1153 # check if the file is already there to avoid a copy
1160 # same size and identical timestamps -> make no copy
1161 if st1
.st_mtime
+ 2 >= st2
.st_mtime
and st1
.st_size
== st2
.st_size
:
1162 if not self
.generator
.bld
.progress_bar
:
1163 Logs
.info('- install %s (from %s)', tgt
, lbl
)
1166 if not self
.generator
.bld
.progress_bar
:
1167 Logs
.info('+ install %s (from %s)', tgt
, lbl
)
1169 # Give best attempt at making destination overwritable,
1170 # like the 'install' utility used by 'make install' does.
1172 os
.chmod(tgt
, Utils
.O644 | stat
.S_IMODE(os
.stat(tgt
).st_mode
))
1173 except EnvironmentError:
1176 # following is for shared libs and stale inodes (-_-)
1183 self
.copy_fun(src
, tgt
)
1184 except EnvironmentError as e
:
1185 if not os
.path
.exists(src
):
1186 Logs
.error('File %r does not exist', src
)
1187 elif not os
.path
.isfile(src
):
1188 Logs
.error('Input %r is not a file', src
)
1189 raise Errors
.WafError('Could not install the file %r' % tgt
, e
)
1191 def fix_perms(self
, tgt
):
1193 Change the ownership of the file/folder/link pointed by the given path
1194 This looks up for `install_user` or `install_group` attributes
1195 on the task or on the task generator::
1198 bld.install_as('${PREFIX}/wscript',
1200 install_user='nobody', install_group='nogroup')
1201 bld.symlink_as('${PREFIX}/wscript_link',
1202 Utils.subst_vars('${PREFIX}/wscript', bld.env),
1203 install_user='nobody', install_group='nogroup')
1205 if not Utils
.is_win32
:
1206 user
= getattr(self
, 'install_user', None) or getattr(self
.generator
, 'install_user', None)
1207 group
= getattr(self
, 'install_group', None) or getattr(self
.generator
, 'install_group', None)
1209 Utils
.lchown(tgt
, user
or -1, group
or -1)
1210 if not os
.path
.islink(tgt
):
1211 os
.chmod(tgt
, self
.chmod
)
1213 def do_link(self
, src
, tgt
, **kw
):
1215 Creates a symlink from tgt to src.
1217 :param src: file name as absolute path
1219 :param tgt: file destination, as absolute path
1222 if os
.path
.islink(tgt
) and os
.readlink(tgt
) == src
:
1223 if not self
.generator
.bld
.progress_bar
:
1224 Logs
.info('- symlink %s (to %s)', tgt
, src
)
1230 if not self
.generator
.bld
.progress_bar
:
1231 Logs
.info('+ symlink %s (to %s)', tgt
, src
)
1232 os
.symlink(src
, tgt
)
1235 def do_uninstall(self
, src
, tgt
, lbl
, **kw
):
1237 See :py:meth:`waflib.Build.inst.do_install`
1239 if not self
.generator
.bld
.progress_bar
:
1240 Logs
.info('- remove %s', tgt
)
1242 #self.uninstall.append(tgt)
1245 except OSError as e
:
1246 if e
.errno
!= errno
.ENOENT
:
1247 if not getattr(self
, 'uninstall_error', None):
1248 self
.uninstall_error
= True
1249 Logs
.warn('build: some files could not be uninstalled (retry with -vv to list them)')
1250 if Logs
.verbose
> 1:
1251 Logs
.warn('Could not remove %s (error code %r)', e
.filename
, e
.errno
)
1252 self
.rm_empty_dirs(tgt
)
1254 def do_unlink(self
, src
, tgt
, **kw
):
1256 See :py:meth:`waflib.Build.inst.do_link`
1259 if not self
.generator
.bld
.progress_bar
:
1260 Logs
.info('- remove %s', tgt
)
1264 self
.rm_empty_dirs(tgt
)
1266 class InstallContext(BuildContext
):
1267 '''installs the targets on the system'''
1270 def __init__(self
, **kw
):
1271 super(InstallContext
, self
).__init
__(**kw
)
1272 self
.is_install
= INSTALL
1274 class UninstallContext(InstallContext
):
1275 '''removes the targets installed'''
1278 def __init__(self
, **kw
):
1279 super(UninstallContext
, self
).__init
__(**kw
)
1280 self
.is_install
= UNINSTALL
1282 class CleanContext(BuildContext
):
1283 '''cleans the project'''
1287 See :py:func:`waflib.Build.BuildContext.execute`.
1290 if not self
.all_envs
:
1293 self
.recurse([self
.run_dir
])
1301 Remove most files from the build directory, and reset all caches.
1303 Custom lists of files to clean can be declared as `bld.clean_files`.
1304 For example, exclude `build/program/myprogram` from getting removed::
1307 bld.clean_files = bld.bldnode.ant_glob('**',
1308 excl='.lock* config.log c4che/* config.h program/myprogram',
1309 quiet=True, generator=True)
1311 Logs
.debug('build: clean called')
1313 if hasattr(self
, 'clean_files'):
1314 for n
in self
.clean_files
:
1316 elif self
.bldnode
!= self
.srcnode
:
1317 # would lead to a disaster if top == out
1319 for env
in self
.all_envs
.values():
1320 lst
.extend(self
.root
.find_or_declare(f
) for f
in env
[CFG_FILES
])
1321 for n
in self
.bldnode
.ant_glob('**/*', excl
='.lock* *conf_check_*/** config.log c4che/*', quiet
=True):
1325 self
.root
.children
= {}
1327 for v
in SAVED_ATTRS
:
1330 setattr(self
, v
, {})
1332 class ListContext(BuildContext
):
1333 '''lists the targets to execute'''
1338 In addition to printing the name of each build target,
1339 a description column will include text for each task
1340 generator which has a "description" field set.
1342 See :py:func:`waflib.Build.BuildContext.execute`.
1345 if not self
.all_envs
:
1348 self
.recurse([self
.run_dir
])
1351 # display the time elapsed in the progress bar
1352 self
.timer
= Utils
.Timer()
1354 for g
in self
.groups
:
1358 except AttributeError:
1364 # force the cache initialization
1365 self
.get_tgen_by_name('')
1366 except Errors
.WafError
:
1369 targets
= sorted(self
.task_gen_cache_names
)
1371 # figure out how much to left-justify, for largest target name
1372 line_just
= max(len(t
) for t
in targets
) if targets
else 0
1374 for target
in targets
:
1375 tgen
= self
.task_gen_cache_names
[target
]
1377 # Support displaying the description for the target
1378 # if it was set on the tgen
1379 descript
= getattr(tgen
, 'description', '')
1381 target
= target
.ljust(line_just
)
1382 descript
= ': %s' % descript
1384 Logs
.pprint('GREEN', target
, label
=descript
)
1386 class StepContext(BuildContext
):
1387 '''executes tasks in a step-by-step fashion, for debugging'''
1390 def __init__(self
, **kw
):
1391 super(StepContext
, self
).__init
__(**kw
)
1392 self
.files
= Options
.options
.files
1396 Overrides :py:meth:`waflib.Build.BuildContext.compile` to perform a partial build
1397 on tasks matching the input/output pattern given (regular expression matching)::
1399 $ waf step --files=foo.c,bar.c,in:truc.c,out:bar.o
1400 $ waf step --files=in:foo.cpp.1.o # link task only
1404 Logs
.warn('Add a pattern for the debug build, for example "waf step --files=main.c,app"')
1405 BuildContext
.compile(self
)
1409 if self
.targets
and self
.targets
!= '*':
1410 targets
= self
.targets
.split(',')
1412 for g
in self
.groups
:
1414 if targets
and tg
.name
not in targets
:
1419 except AttributeError:
1424 for pat
in self
.files
.split(','):
1425 matcher
= self
.get_matcher(pat
)
1427 if isinstance(tg
, Task
.Task
):
1433 for node
in tsk
.inputs
:
1434 if matcher(node
, output
=False):
1437 for node
in tsk
.outputs
:
1438 if matcher(node
, output
=True):
1443 Logs
.info('%s -> exit %r', tsk
, ret
)
1445 def get_matcher(self
, pat
):
1447 Converts a step pattern into a function
1449 :param: pat: pattern of the form in:truc.c,out:bar.o
1450 :returns: Python function that uses Node objects as inputs and returns matches
1453 # this returns a function
1456 if pat
.startswith('in:'):
1458 pat
= pat
.replace('in:', '')
1459 elif pat
.startswith('out:'):
1461 pat
= pat
.replace('out:', '')
1463 anode
= self
.root
.find_node(pat
)
1466 if not pat
.startswith('^'):
1467 pat
= '^.+?%s' % pat
1468 if not pat
.endswith('$'):
1470 pattern
= re
.compile(pat
)
1472 def match(node
, output
):
1473 if output
and not out
:
1475 if not output
and not inn
:
1479 return anode
== node
1481 return pattern
.match(node
.abspath())
1484 class EnvContext(BuildContext
):
1485 """Subclass EnvContext to create commands that require configuration data in 'env'"""
1489 See :py:func:`waflib.Build.BuildContext.execute`.
1492 if not self
.all_envs
:
1494 self
.recurse([self
.run_dir
])