1 # a waf tool to add autoconf-like macros to the configure section
2 # and for SAMBA_ macros for building libraries, binaries etc
4 import Build, os, sys, Options, Utils, Task, re, fnmatch, Logs
5 from TaskGen import feature, before
6 from Configure import conf
10 # TODO: make this a --option
15 def SET_TARGET_TYPE(ctx, target, value):
16 '''set the target type of a target'''
17 cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
18 if target in cache and cache[target] != 'EMPTY':
19 Logs.error("ERROR: Target '%s' in directory %s re-defined as %s - was %s" % (target, ctx.curdir, value, cache[target]))
21 LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
22 debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.curdir))
26 def GET_TARGET_TYPE(ctx, target):
27 '''get target type from cache'''
28 cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
29 if not target in cache:
34 ######################################################
35 # this is used as a decorator to make functions only
36 # run once. Based on the idea from
37 # http://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values
39 def runonce(function):
40 def runonce_wrapper(*args):
41 if args in runonce_ret:
42 return runonce_ret[args]
45 runonce_ret[args] = ret
47 return runonce_wrapper
50 def ADD_LD_LIBRARY_PATH(path):
51 '''add something to LD_LIBRARY_PATH'''
52 if 'LD_LIBRARY_PATH' in os.environ:
53 oldpath = os.environ['LD_LIBRARY_PATH']
56 newpath = oldpath.split(':')
57 if not path in newpath:
59 os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
62 def install_rpath(bld):
63 '''the rpath value for installation'''
65 if bld.env.RPATH_ON_INSTALL:
66 return ['%s/lib' % bld.env.PREFIX]
71 '''the rpath value for build'''
72 rpath = os.path.normpath('%s/%s' % (bld.env.BUILD_DIRECTORY, LIB_PATH))
74 if bld.env.RPATH_ON_BUILD:
76 ADD_LD_LIBRARY_PATH(rpath)
81 def LOCAL_CACHE(ctx, name):
82 '''return a named build cache dictionary, used to store
83 state inside other functions'''
91 def LOCAL_CACHE_SET(ctx, cachename, key, value):
92 '''set a value in a local cache'''
93 cache = LOCAL_CACHE(ctx, cachename)
98 def ASSERT(ctx, expression, msg):
99 '''a build assert call'''
101 Logs.error("ERROR: %s\n" % msg)
103 Build.BuildContext.ASSERT = ASSERT
106 def SUBDIR(bld, subdir, list):
107 '''create a list of files by pre-pending each with a subdir name'''
109 for l in TO_LIST(list):
110 ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
112 Build.BuildContext.SUBDIR = SUBDIR
115 def dict_concat(d1, d2):
116 '''concatenate two dictionaries d1 += d2'''
122 def exec_command(self, cmd, **kw):
123 '''this overrides the 'waf -v' debug output to be in a nice
124 unix like format instead of a python list.
125 Thanks to ita on #waf for this'''
128 if isinstance(cmd, list):
130 debug('runner: %s' % _cmd)
132 self.log.write('%s\n' % cmd)
135 if not kw.get('cwd', None):
137 except AttributeError:
138 self.cwd = kw['cwd'] = self.bldnode.abspath()
139 return Utils.exec_command(cmd, **kw)
140 Build.BuildContext.exec_command = exec_command
143 def ADD_COMMAND(opt, name, function):
144 '''add a new top level command to waf'''
145 Utils.g_module.__dict__[name] = function
147 Options.Handler.ADD_COMMAND = ADD_COMMAND
150 @feature('cc', 'cshlib', 'cprogram')
151 @before('apply_core','exec_rule')
152 def process_depends_on(self):
153 '''The new depends_on attribute for build rules
154 allow us to specify a dependency on output from
155 a source generation rule'''
156 if getattr(self , 'depends_on', None):
157 lst = self.to_list(self.depends_on)
159 y = self.bld.name_to_obj(x, self.env)
160 self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
162 if getattr(y, 'more_includes', None):
163 self.includes += " " + y.more_includes
166 os_path_relpath = getattr(os.path, 'relpath', None)
167 if os_path_relpath is None:
168 # Python < 2.6 does not have os.path.relpath, provide a replacement
169 # (imported from Python2.6.5~rc2)
170 def os_path_relpath(path, start):
171 """Return a relative version of a path"""
172 start_list = os.path.abspath(start).split("/")
173 path_list = os.path.abspath(path).split("/")
175 # Work out how much of the filepath is shared by start and path.
176 i = len(os.path.commonprefix([start_list, path_list]))
178 rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
181 return os.path.join(*rel_list)
184 def unique_list(seq):
185 '''return a uniquified list in the same order as the existing list'''
189 if item in seen: continue
195 def TO_LIST(str, delimiter=None):
196 '''Split a list, preserving quoted strings and existing lists'''
199 if isinstance(str, list):
201 lst = str.split(delimiter)
202 # the string may have had quotes in it, now we
203 # check if we did have quotes, and use the slower shlex
207 return shlex.split(str)
211 def subst_vars_error(string, env):
212 '''substitute vars, throw an error if a variable is not defined'''
213 lst = re.split('(\$\{\w+\})', string)
216 if re.match('\$\{\w+\}', v):
219 Logs.error("Failed to find variable %s in %s" % (vname, string))
227 def SUBST_ENV_VAR(ctx, varname):
228 '''Substitute an environment variable for any embedded variables'''
229 return subst_vars_error(ctx.env[varname], ctx.env)
230 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
233 def ENFORCE_GROUP_ORDERING(bld):
234 '''enforce group ordering for the project. This
235 makes the group ordering apply only when you specify
236 a target with --target'''
237 if Options.options.compile_targets:
239 @before('exec_rule', 'apply_core', 'collect')
240 def force_previous_groups(self):
241 if getattr(self.bld, 'enforced_group_ordering', False) == True:
243 self.bld.enforced_group_ordering = True
246 tm = self.bld.task_manager
247 return [x for x in tm.groups_names if id(tm.groups_names[x]) == id(g)][0]
252 for g in bld.task_manager.groups:
253 for t in g.tasks_gen:
256 debug('group: Forcing up to group %s for target %s',
257 group_name(g), self.name or self.target)
264 for i in xrange(len(bld.task_manager.groups)):
265 g = bld.task_manager.groups[i]
266 bld.task_manager.current_group = i
269 debug('group: Forcing group %s', group_name(g))
270 for t in g.tasks_gen:
271 if not getattr(t, 'forced_groups', False):
272 debug('group: Posting %s', t.name or t.target)
273 t.forced_groups = True
275 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
278 def recursive_dirlist(dir, relbase, pattern=None):
279 '''recursive directory list'''
281 for f in os.listdir(dir):
283 if os.path.isdir(f2):
284 ret.extend(recursive_dirlist(f2, relbase))
286 if pattern and not fnmatch.fnmatch(f, pattern):
288 ret.append(os_path_relpath(f2, relbase))
294 if os.path.isdir(dir):
296 mkdir_p(os.path.dirname(dir))
300 def SUBST_VARS_RECURSIVE(string, env):
301 '''recursively expand variables'''
305 while (string.find('${') != -1 and limit > 0):
306 string = subst_vars_error(string, env)
312 def EXPAND_VARIABLES(ctx, varstr, vars=None):
313 '''expand variables from a user supplied dictionary
315 This is most useful when you pass vars=locals() to expand
316 all your local variables in strings
319 if isinstance(varstr, list):
322 ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
326 env = Environment.Environment()
328 # substitute on user supplied dict if avaiilable
330 for v in vars.keys():
332 ret = SUBST_VARS_RECURSIVE(ret, env)
334 # if anything left, subst on the environment as well
335 if ret.find('${') != -1:
336 ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
337 # make sure there is nothing left. Also check for the common
338 # typo of $( instead of ${
339 if ret.find('${') != -1 or ret.find('$(') != -1:
340 Logs.error('Failed to substitute all variables in varstr=%s' % ret)
343 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
349 '''run a external command, return exit code or signal'''
351 cmd = SUBST_VARS_RECURSIVE(cmd, env)
353 status = os.system(cmd)
354 if os.WIFEXITED(status):
355 return os.WEXITSTATUS(status)
356 if os.WIFSIGNALED(status):
357 return - os.WTERMSIG(status)
358 Logs.error("Unknown exit reason %d for command: %s" (status, cmd))
362 # make sure we have md5. some systems don't have it
364 from hashlib import md5
370 Constants.SIG_NIL = hash('abcd')
371 class replace_md5(object):
374 def update(self, val):
375 self.val = hash((self.val, val))
379 return self.digest().encode('hex')
380 def replace_h_file(filename):
381 f = open(filename, 'rb')
384 filename = f.read(100000)
388 Utils.md5 = replace_md5
389 Task.md5 = replace_md5
390 Utils.h_file = replace_h_file
393 def LOAD_ENVIRONMENT():
394 '''load the configuration environment, allowing access to env vars
397 env = Environment.Environment()
399 env.load('.lock-wscript')
400 env.load(env.blddir + '/c4che/default.cache.py')
406 def IS_NEWER(bld, file1, file2):
407 '''return True if file1 is newer than file2'''
408 t1 = os.stat(os.path.join(bld.curdir, file1)).st_mtime
409 t2 = os.stat(os.path.join(bld.curdir, file2)).st_mtime
411 Build.BuildContext.IS_NEWER = IS_NEWER
415 def RECURSE(ctx, directory):
416 '''recurse into a directory, relative to the curdir or top level'''
418 visited_dirs = ctx.visited_dirs
420 visited_dirs = ctx.visited_dirs = set()
421 d = os.path.join(ctx.curdir, directory)
422 if os.path.exists(d):
423 abspath = os.path.abspath(d)
425 abspath = os.path.abspath(os.path.join(Utils.g_module.srcdir, directory))
426 ctxclass = ctx.__class__.__name__
427 key = ctxclass + ':' + abspath
428 if key in visited_dirs:
431 visited_dirs.add(key)
432 relpath = os_path_relpath(abspath, ctx.curdir)
433 if ctxclass == 'Handler':
434 return ctx.sub_options(relpath)
435 if ctxclass == 'ConfigurationContext':
436 return ctx.sub_config(relpath)
437 if ctxclass == 'BuildContext':
438 return ctx.add_subdirs(relpath)
439 Logs.error('Unknown RECURSE context class', ctxclass)
441 Options.Handler.RECURSE = RECURSE
442 Build.BuildContext.RECURSE = RECURSE
445 def CHECK_MAKEFLAGS(bld):
446 '''check for MAKEFLAGS environment variable in case we are being
447 called from a Makefile try to honor a few make command line flags'''
448 if not 'WAF_MAKE' in os.environ:
450 makeflags = os.environ.get('MAKEFLAGS')
452 # we need to use shlex.split to cope with the escaping of spaces
454 for opt in shlex.split(makeflags):
455 # options can come either as -x or as x
457 Options.options.verbose = Logs.verbose = int(opt[2:])
459 Logs.zones = ['runner']
462 elif opt[0].isupper() and opt.find('=') != -1:
464 setattr(Options.options, opt[0:loc], opt[loc+1:])
470 Options.options.keep = True
474 Options.options.keep = True
477 Options.options.jobs = 1
479 Build.BuildContext.CHECK_MAKEFLAGS = CHECK_MAKEFLAGS
483 def option_group(opt, name):
484 '''find or create an option group'''
486 if name in option_groups:
487 return option_groups[name]
488 gr = opt.add_option_group(name)
489 option_groups[name] = gr
491 Options.Handler.option_group = option_group
494 def save_file(filename, contents, create_dir=False):
495 '''save data to a file'''
497 mkdir_p(os.path.dirname(filename))
499 f = open(filename, 'w')
507 def load_file(filename):
508 '''return contents of a file'''
510 f = open(filename, 'r')
518 def reconfigure(ctx):
519 '''rerun configure if necessary'''
520 import Configure, samba_wildcard, Scripting
521 if not os.path.exists(".lock-wscript"):
522 raise Utils.WafError('configure has not been run')
523 bld = samba_wildcard.fake_build_environment()
524 Configure.autoconfig = True
525 Scripting.check_configured(bld)