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
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')
19 ASSERT(ctx
, cache
[target
] == value
,
20 "Target '%s' re-defined as %s - was %s" % (target
, value
, cache
[target
]))
21 debug("task_gen: Skipping duplicate target %s (curdir=%s)" % (target
, ctx
.curdir
))
23 LOCAL_CACHE_SET(ctx
, 'TARGET_TYPE', target
, value
)
24 debug("task_gen: Target '%s' created of type '%s' in %s" % (target
, value
, ctx
.curdir
))
28 def GET_TARGET_TYPE(ctx
, target
):
29 '''get target type from cache'''
30 cache
= LOCAL_CACHE(ctx
, 'TARGET_TYPE')
31 if not target
in cache
:
36 ######################################################
37 # this is used as a decorator to make functions only
38 # run once. Based on the idea from
39 # http://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values
41 def runonce(function
):
42 def runonce_wrapper(*args
):
43 if args
in runonce_ret
:
44 return runonce_ret
[args
]
47 runonce_ret
[args
] = ret
49 return runonce_wrapper
52 def ADD_LD_LIBRARY_PATH(path
):
53 '''add something to LD_LIBRARY_PATH'''
54 if 'LD_LIBRARY_PATH' in os
.environ
:
55 oldpath
= os
.environ
['LD_LIBRARY_PATH']
58 newpath
= oldpath
.split(':')
59 if not path
in newpath
:
61 os
.environ
['LD_LIBRARY_PATH'] = ':'.join(newpath
)
64 def install_rpath(bld
):
65 '''the rpath value for installation'''
67 bld
.env
['RPATH_ST'] = []
68 if bld
.env
.RPATH_ON_INSTALL
:
69 return ['-Wl,-rpath=%s/lib' % bld
.env
.PREFIX
]
74 '''the rpath value for build'''
75 rpath
= os
.path
.normpath('%s/%s' % (bld
.env
['BUILD_DIRECTORY'], LIB_PATH
))
77 bld
.env
['RPATH_ST'] = []
78 if bld
.env
.RPATH_ON_BUILD
:
79 return ['-Wl,-rpath=%s' % rpath
]
80 ADD_LD_LIBRARY_PATH(rpath
)
85 def LOCAL_CACHE(ctx
, name
):
86 '''return a named build cache dictionary, used to store
87 state inside other functions'''
95 def LOCAL_CACHE_SET(ctx
, cachename
, key
, value
):
96 '''set a value in a local cache'''
97 cache
= LOCAL_CACHE(ctx
, cachename
)
102 def ASSERT(ctx
, expression
, msg
):
103 '''a build assert call'''
105 sys
.stderr
.write("ERROR: %s\n" % msg
)
107 Build
.BuildContext
.ASSERT
= ASSERT
110 def SUBDIR(bld
, subdir
, list):
111 '''create a list of files by pre-pending each with a subdir name'''
113 for l
in TO_LIST(list):
114 ret
= ret
+ os
.path
.normpath(os
.path
.join(subdir
, l
)) + ' '
116 Build
.BuildContext
.SUBDIR
= SUBDIR
119 def dict_concat(d1
, d2
):
120 '''concatenate two dictionaries d1 += d2'''
126 def exec_command(self
, cmd
, **kw
):
127 '''this overrides the 'waf -v' debug output to be in a nice
128 unix like format instead of a python list.
129 Thanks to ita on #waf for this'''
132 if isinstance(cmd
, list):
134 debug('runner: %s' % _cmd
)
136 self
.log
.write('%s\n' % cmd
)
139 if not kw
.get('cwd', None):
141 except AttributeError:
142 self
.cwd
= kw
['cwd'] = self
.bldnode
.abspath()
143 return Utils
.exec_command(cmd
, **kw
)
144 Build
.BuildContext
.exec_command
= exec_command
147 def ADD_COMMAND(opt
, name
, function
):
148 '''add a new top level command to waf'''
149 Utils
.g_module
.__dict
__[name
] = function
151 Options
.Handler
.ADD_COMMAND
= ADD_COMMAND
154 @feature('cc', 'cshlib', 'cprogram')
155 @before('apply_core','exec_rule')
156 def process_depends_on(self
):
157 '''The new depends_on attribute for build rules
158 allow us to specify a dependency on output from
159 a source generation rule'''
160 if getattr(self
, 'depends_on', None):
161 lst
= self
.to_list(self
.depends_on
)
163 y
= self
.bld
.name_to_obj(x
, self
.env
)
164 self
.bld
.ASSERT(y
is not None, "Failed to find dependency %s of %s" % (x
, self
.name
))
166 if getattr(y
, 'more_includes', None):
167 self
.includes
+= " " + y
.more_includes
170 os_path_relpath
= getattr(os
.path
, 'relpath', None)
171 if os_path_relpath
is None:
172 # Python < 2.6 does not have os.path.relpath, provide a replacement
173 # (imported from Python2.6.5~rc2)
174 def os_path_relpath(path
, start
):
175 """Return a relative version of a path"""
176 start_list
= os
.path
.abspath(start
).split("/")
177 path_list
= os
.path
.abspath(path
).split("/")
179 # Work out how much of the filepath is shared by start and path.
180 i
= len(os
.path
.commonprefix([start_list
, path_list
]))
182 rel_list
= ['..'] * (len(start_list
)-i
) + path_list
[i
:]
185 return os
.path
.join(*rel_list
)
188 def unique_list(seq
):
189 '''return a uniquified list in the same order as the existing list'''
193 if item
in seen
: continue
200 '''Split a list, preserving quoted strings and existing lists'''
203 if isinstance(str, list):
206 # the string may have had quotes in it, now we
207 # check if we did have quotes, and use the slower shlex
211 return shlex
.split(str)
215 def subst_vars_error(string
, env
):
216 '''substitute vars, throw an error if a variable is not defined'''
217 lst
= re
.split('(\$\{\w+\})', string
)
220 if re
.match('\$\{\w+\}', v
):
223 print "Failed to find variable %s in %s" % (vname
, string
)
231 def SUBST_ENV_VAR(ctx
, varname
):
232 '''Substitute an environment variable for any embedded variables'''
233 return subst_vars_error(ctx
.env
[varname
], ctx
.env
)
234 Build
.BuildContext
.SUBST_ENV_VAR
= SUBST_ENV_VAR
237 def ENFORCE_GROUP_ORDERING(bld
):
238 '''enforce group ordering for the project. This
239 makes the group ordering apply only when you specify
240 a target with --target'''
241 if Options
.options
.compile_targets
:
243 def force_previous_groups(self
):
244 if getattr(self
.bld
, 'enforced_group_ordering', False) == True:
246 self
.bld
.enforced_group_ordering
= True
249 tm
= self
.bld
.task_manager
250 return [x
for x
in tm
.groups_names
if id(tm
.groups_names
[x
]) == id(g
)][0]
255 for g
in bld
.task_manager
.groups
:
256 for t
in g
.tasks_gen
:
259 debug('group: Forcing up to group %s', group_name(g
))
266 for g
in bld
.task_manager
.groups
:
269 debug('group: Forcing group %s', group_name(g
))
270 for t
in g
.tasks_gen
:
271 if getattr(t
, 'forced_groups', False) != True:
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 print('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 print "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()
398 env
.load('bin/c4che/default.cache.py')
402 def IS_NEWER(bld
, file1
, file2
):
403 '''return True if file1 is newer than file2'''
404 t1
= os
.stat(os
.path
.join(bld
.curdir
, file1
)).st_mtime
405 t2
= os
.stat(os
.path
.join(bld
.curdir
, file2
)).st_mtime
407 Build
.BuildContext
.IS_NEWER
= IS_NEWER