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
5 from TaskGen import feature, before
6 from Configure import conf
10 # TODO: make this a --option
14 ##########################################################
15 # create a node with a new name, based on an existing node
16 def NEW_NODE(node, name):
17 ret = node.parent.find_or_declare([name])
18 ASSERT(node, ret is not None, "Unable to find new target with name '%s' from '%s'" % (
23 #############################################################
24 # set a value in a local cache
25 # return False if it's already set
27 def SET_TARGET_TYPE(ctx, target, value):
28 cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
30 ASSERT(ctx, cache[target] == value,
31 "Target '%s' re-defined as %s - was %s" % (target, value, cache[target]))
32 debug("task_gen: Skipping duplicate target %s (curdir=%s)" % (target, ctx.curdir))
34 LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
35 debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.curdir))
39 def GET_TARGET_TYPE(ctx, target):
40 '''get target type from cache'''
41 cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
42 if not target in cache:
47 ######################################################
48 # this is used as a decorator to make functions only
49 # run once. Based on the idea from
50 # http://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values
52 def runonce(function):
54 if args in runonce_ret:
55 return runonce_ret[args]
58 runonce_ret[args] = ret
63 def ADD_LD_LIBRARY_PATH(path):
64 '''add something to LD_LIBRARY_PATH'''
65 if 'LD_LIBRARY_PATH' in os.environ:
66 oldpath = os.environ['LD_LIBRARY_PATH']
69 newpath = oldpath.split(':')
70 if not path in newpath:
72 os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
74 def install_rpath(bld):
75 '''the rpath value for installation'''
77 bld.env['RPATH_ST'] = []
78 if bld.env.RPATH_ON_INSTALL:
79 return ['-Wl,-rpath=%s/lib' % bld.env.PREFIX]
84 '''the rpath value for build'''
85 rpath = os.path.normpath('%s/%s' % (bld.env['BUILD_DIRECTORY'], LIB_PATH))
87 bld.env['RPATH_ST'] = []
88 if bld.env.RPATH_ON_BUILD:
89 return ['-Wl,-rpath=%s' % rpath]
90 ADD_LD_LIBRARY_PATH(rpath)
94 #############################################################
95 # return a named build cache dictionary, used to store
96 # state inside the following functions
98 def LOCAL_CACHE(ctx, name):
105 #############################################################
106 # set a value in a local cache
108 def LOCAL_CACHE_SET(ctx, cachename, key, value):
109 cache = LOCAL_CACHE(ctx, cachename)
112 #############################################################
113 # a build assert call
115 def ASSERT(ctx, expression, msg):
117 sys.stderr.write("ERROR: %s\n" % msg)
119 Build.BuildContext.ASSERT = ASSERT
121 ################################################################
122 # create a list of files by pre-pending each with a subdir name
123 def SUBDIR(bld, subdir, list):
125 for l in TO_LIST(list):
126 ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
128 Build.BuildContext.SUBDIR = SUBDIR
130 #######################################################
132 def dict_concat(d1, d2):
137 ############################################################
138 # this overrides the 'waf -v' debug output to be in a nice
139 # unix like format instead of a python list.
140 # Thanks to ita on #waf for this
141 def exec_command(self, cmd, **kw):
144 if isinstance(cmd, list):
146 debug('runner: %s' % _cmd)
148 self.log.write('%s\n' % cmd)
151 if not kw.get('cwd', None):
153 except AttributeError:
154 self.cwd = kw['cwd'] = self.bldnode.abspath()
155 return Utils.exec_command(cmd, **kw)
156 Build.BuildContext.exec_command = exec_command
159 ##########################################################
160 # add a new top level command to waf
161 def ADD_COMMAND(opt, name, function):
162 Utils.g_module.__dict__[name] = function
164 Options.Handler.ADD_COMMAND = ADD_COMMAND
167 @feature('cc', 'cshlib', 'cprogram')
168 @before('apply_core','exec_rule')
169 def process_depends_on(self):
170 '''The new depends_on attribute for build rules
171 allow us to specify a dependency on output from
172 a source generation rule'''
173 if getattr(self , 'depends_on', None):
174 lst = self.to_list(self.depends_on)
176 y = self.bld.name_to_obj(x, self.env)
177 self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
179 if getattr(y, 'more_includes', None):
180 self.includes += " " + y.more_includes
183 #@feature('cprogram', 'cc', 'cshlib')
184 #@before('apply_core')
185 #def process_generated_dependencies(self):
186 # '''Ensure that any dependent source generation happens
187 # before any task that requires the output'''
188 # if getattr(self , 'depends_on', None):
189 # lst = self.to_list(self.depends_on)
191 # y = self.bld.name_to_obj(x, self.env)
195 #import TaskGen, Task
197 #old_post_run = Task.Task.post_run
198 #def new_post_run(self):
200 # return old_post_run(self)
202 #for y in ['cc', 'cxx']:
203 # TaskGen.classes[y].post_run = new_post_run
205 def ENABLE_MAGIC_ORDERING(bld):
206 '''enable automatic build order constraint calculation
207 see page 35 of the waf book'''
208 print "NOT Enabling magic ordering"
210 Build.BuildContext.ENABLE_MAGIC_ORDERING = ENABLE_MAGIC_ORDERING
213 os_path_relpath = getattr(os.path, 'relpath', None)
214 if os_path_relpath is None:
215 # Python < 2.6 does not have os.path.relpath, provide a replacement
216 # (imported from Python2.6.5~rc2)
217 def os_path_relpath(path, start):
218 """Return a relative version of a path"""
219 start_list = os.path.abspath(start).split("/")
220 path_list = os.path.abspath(path).split("/")
222 # Work out how much of the filepath is shared by start and path.
223 i = len(os.path.commonprefix([start_list, path_list]))
225 rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
228 return os.path.join(*rel_list)
231 def unique_list(seq):
232 '''return a uniquified list in the same order as the existing list'''
236 if item in seen: continue
242 '''Split a list, preserving quoted strings and existing lists'''
245 if isinstance(str, list):
248 # the string may have had quotes in it, now we
249 # check if we did have quotes, and use the slower shlex
253 return shlex.split(str)
257 def subst_vars_error(string, env):
258 '''substitute vars, throw an error if a variable is not defined'''
259 lst = re.split('(\$\{\w+\})', string)
262 if re.match('\$\{\w+\}', v):
265 print "Failed to find variable %s in %s" % (vname, string)
272 def SUBST_ENV_VAR(ctx, varname):
273 '''Substitute an environment variable for any embedded variables'''
274 return subst_vars_error(ctx.env[varname], ctx.env)
275 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
278 def ENFORCE_GROUP_ORDERING(bld):
279 '''enforce group ordering for the project. This
280 makes the group ordering apply only when you specify
281 a target with --target'''
282 if Options.options.compile_targets:
284 def force_previous_groups(self):
289 for g in bld.task_manager.groups:
290 for t in g.tasks_gen:
297 for g in bld.task_manager.groups:
300 for t in g.tasks_gen:
302 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
305 # @before('apply_lib_vars')
306 # def process_objects(self):
307 # if getattr(self, 'add_objects', None):
308 # lst = self.to_list(self.add_objects)
310 # y = self.name_to_obj(x)
312 # raise Utils.WafError('object %r was not found in uselib_local (required by add_objects %r)' % (x, self.name))
314 # self.env.append_unique('INC_PATHS', y.env.INC_PATHS)
317 def recursive_dirlist(dir, relbase):
318 '''recursive directory list'''
320 for f in os.listdir(dir):
322 if os.path.isdir(f2):
323 ret.extend(recursive_dirlist(f2, relbase))
325 ret.append(os_path_relpath(f2, relbase))
331 if os.path.isdir(dir):
333 mkdir_p(os.path.dirname(dir))
336 def SUBST_VARS_RECURSIVE(string, env):
337 '''recursively expand variables'''
341 while (string.find('${') != -1 and limit > 0):
342 string = subst_vars_error(string, env)
347 def EXPAND_VARIABLES(ctx, varstr, vars=None):
348 '''expand variables from a user supplied dictionary
350 This is most useful when you pass vars=locals() to expand
351 all your local variables in strings
354 if isinstance(varstr, list):
357 ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
361 env = Environment.Environment()
363 # substitute on user supplied dict if avaiilable
365 for v in vars.keys():
367 ret = SUBST_VARS_RECURSIVE(ret, env)
369 # if anything left, subst on the environment as well
370 if ret.find('${') != -1:
371 ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
372 # make sure there is nothing left. Also check for the common
373 # typo of $( instead of ${
374 if ret.find('${') != -1 or ret.find('$(') != -1:
375 print('Failed to substitute all variables in varstr=%s' % ret)
378 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
384 '''run a external command, return exit code or signal'''
386 cmd = SUBST_VARS_RECURSIVE(cmd, env)
388 status = os.system(cmd)
389 if os.WIFEXITED(status):
390 return os.WEXITSTATUS(status)
391 if os.WIFSIGNALED(status):
392 return - os.WTERMSIG(status)
393 print "Unknown exit reason %d for command: %s" (status, cmd)
397 # make sure we have md5. some systems don't have it
399 from hashlib import md5
405 Constants.SIG_NIL = hash('abcd')
406 class replace_md5(object):
409 def update(self, val):
410 self.val = hash((self.val, val))
414 return self.digest().encode('hex')
415 def replace_h_file(filename):
416 f = open(filename, 'rb')
419 filename = f.read(100000)
423 Utils.md5 = replace_md5
424 Task.md5 = replace_md5
425 Utils.h_file = replace_h_file