waf: automap shared library names from .so to the right extension
[Samba/gebeck_regimport.git] / buildtools / wafsamba / samba_utils.py
blobe86056e7e803a5c6d993d1b8c6d944efaa6b88bb
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
7 from Logs import debug
8 import shlex
10 # TODO: make this a --option
11 LIB_PATH="shared"
14 # sigh, python octal constants are a mess
15 MODE_644 = int('644', 8)
16 MODE_755 = int('755', 8)
18 @conf
19 def SET_TARGET_TYPE(ctx, target, value):
20 '''set the target type of a target'''
21 cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
22 if target in cache and cache[target] != 'EMPTY':
23 Logs.error("ERROR: Target '%s' in directory %s re-defined as %s - was %s" % (target, ctx.curdir, value, cache[target]))
24 sys.exit(1)
25 LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
26 debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.curdir))
27 return True
30 def GET_TARGET_TYPE(ctx, target):
31 '''get target type from cache'''
32 cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
33 if not target in cache:
34 return None
35 return cache[target]
38 ######################################################
39 # this is used as a decorator to make functions only
40 # run once. Based on the idea from
41 # http://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values
42 runonce_ret = {}
43 def runonce(function):
44 def runonce_wrapper(*args):
45 if args in runonce_ret:
46 return runonce_ret[args]
47 else:
48 ret = function(*args)
49 runonce_ret[args] = ret
50 return ret
51 return runonce_wrapper
54 def ADD_LD_LIBRARY_PATH(path):
55 '''add something to LD_LIBRARY_PATH'''
56 if 'LD_LIBRARY_PATH' in os.environ:
57 oldpath = os.environ['LD_LIBRARY_PATH']
58 else:
59 oldpath = ''
60 newpath = oldpath.split(':')
61 if not path in newpath:
62 newpath.append(path)
63 os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
66 def install_rpath(bld):
67 '''the rpath value for installation'''
68 bld.env['RPATH'] = []
69 if bld.env.RPATH_ON_INSTALL:
70 return ['%s/lib' % bld.env.PREFIX]
71 return []
74 def build_rpath(bld):
75 '''the rpath value for build'''
76 rpath = os.path.normpath('%s/%s' % (bld.env.BUILD_DIRECTORY, LIB_PATH))
77 bld.env['RPATH'] = []
78 if bld.env.RPATH_ON_BUILD:
79 return [rpath]
80 ADD_LD_LIBRARY_PATH(rpath)
81 return []
84 @conf
85 def LOCAL_CACHE(ctx, name):
86 '''return a named build cache dictionary, used to store
87 state inside other functions'''
88 if name in ctx.env:
89 return ctx.env[name]
90 ctx.env[name] = {}
91 return ctx.env[name]
94 @conf
95 def LOCAL_CACHE_SET(ctx, cachename, key, value):
96 '''set a value in a local cache'''
97 cache = LOCAL_CACHE(ctx, cachename)
98 cache[key] = value
101 @conf
102 def ASSERT(ctx, expression, msg):
103 '''a build assert call'''
104 if not expression:
105 Logs.error("ERROR: %s\n" % msg)
106 raise AssertionError
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'''
112 ret = ''
113 for l in TO_LIST(list):
114 ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
115 return ret
116 Build.BuildContext.SUBDIR = SUBDIR
119 def dict_concat(d1, d2):
120 '''concatenate two dictionaries d1 += d2'''
121 for t in d2:
122 if t not in d1:
123 d1[t] = d2[t]
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'''
130 import Utils, Logs
131 _cmd = cmd
132 if isinstance(cmd, list):
133 _cmd = ' '.join(cmd)
134 debug('runner: %s' % _cmd)
135 if self.log:
136 self.log.write('%s\n' % cmd)
137 kw['log'] = self.log
138 try:
139 if not kw.get('cwd', None):
140 kw['cwd'] = self.cwd
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
150 opt.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)
162 for x in lst:
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))
165 y.post()
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:]
183 if not rel_list:
184 return start
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'''
190 seen = {}
191 result = []
192 for item in seq:
193 if item in seen: continue
194 seen[item] = True
195 result.append(item)
196 return result
199 def TO_LIST(str, delimiter=None):
200 '''Split a list, preserving quoted strings and existing lists'''
201 if str is None:
202 return []
203 if isinstance(str, list):
204 return str
205 lst = str.split(delimiter)
206 # the string may have had quotes in it, now we
207 # check if we did have quotes, and use the slower shlex
208 # if we need to
209 for e in lst:
210 if e[0] == '"':
211 return shlex.split(str)
212 return lst
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)
218 out = []
219 for v in lst:
220 if re.match('\$\{\w+\}', v):
221 vname = v[2:-1]
222 if not vname in env:
223 Logs.error("Failed to find variable %s in %s" % (vname, string))
224 sys.exit(1)
225 v = env[vname]
226 out.append(v)
227 return ''.join(out)
230 @conf
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:
242 @feature('*')
243 @before('exec_rule', 'apply_core', 'collect')
244 def force_previous_groups(self):
245 if getattr(self.bld, 'enforced_group_ordering', False) == True:
246 return
247 self.bld.enforced_group_ordering = True
249 def group_name(g):
250 tm = self.bld.task_manager
251 return [x for x in tm.groups_names if id(tm.groups_names[x]) == id(g)][0]
253 my_id = id(self)
254 bld = self.bld
255 stop = None
256 for g in bld.task_manager.groups:
257 for t in g.tasks_gen:
258 if id(t) == my_id:
259 stop = id(g)
260 debug('group: Forcing up to group %s for target %s',
261 group_name(g), self.name or self.target)
262 break
263 if stop != None:
264 break
265 if stop is None:
266 return
268 for i in xrange(len(bld.task_manager.groups)):
269 g = bld.task_manager.groups[i]
270 bld.task_manager.current_group = i
271 if id(g) == stop:
272 break
273 debug('group: Forcing group %s', group_name(g))
274 for t in g.tasks_gen:
275 if not getattr(t, 'forced_groups', False):
276 debug('group: Posting %s', t.name or t.target)
277 t.forced_groups = True
278 t.post()
279 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
282 def recursive_dirlist(dir, relbase, pattern=None):
283 '''recursive directory list'''
284 ret = []
285 for f in os.listdir(dir):
286 f2 = dir + '/' + f
287 if os.path.isdir(f2):
288 ret.extend(recursive_dirlist(f2, relbase))
289 else:
290 if pattern and not fnmatch.fnmatch(f, pattern):
291 continue
292 ret.append(os_path_relpath(f2, relbase))
293 return ret
296 def mkdir_p(dir):
297 '''like mkdir -p'''
298 if os.path.isdir(dir):
299 return
300 mkdir_p(os.path.dirname(dir))
301 os.mkdir(dir)
304 def SUBST_VARS_RECURSIVE(string, env):
305 '''recursively expand variables'''
306 if string is None:
307 return string
308 limit=100
309 while (string.find('${') != -1 and limit > 0):
310 string = subst_vars_error(string, env)
311 limit -= 1
312 return string
315 @conf
316 def EXPAND_VARIABLES(ctx, varstr, vars=None):
317 '''expand variables from a user supplied dictionary
319 This is most useful when you pass vars=locals() to expand
320 all your local variables in strings
323 if isinstance(varstr, list):
324 ret = []
325 for s in varstr:
326 ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
327 return ret
329 import Environment
330 env = Environment.Environment()
331 ret = varstr
332 # substitute on user supplied dict if avaiilable
333 if vars is not None:
334 for v in vars.keys():
335 env[v] = vars[v]
336 ret = SUBST_VARS_RECURSIVE(ret, env)
338 # if anything left, subst on the environment as well
339 if ret.find('${') != -1:
340 ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
341 # make sure there is nothing left. Also check for the common
342 # typo of $( instead of ${
343 if ret.find('${') != -1 or ret.find('$(') != -1:
344 Logs.error('Failed to substitute all variables in varstr=%s' % ret)
345 sys.exit(1)
346 return ret
347 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
350 def RUN_COMMAND(cmd,
351 env=None,
352 shell=False):
353 '''run a external command, return exit code or signal'''
354 if env:
355 cmd = SUBST_VARS_RECURSIVE(cmd, env)
357 status = os.system(cmd)
358 if os.WIFEXITED(status):
359 return os.WEXITSTATUS(status)
360 if os.WIFSIGNALED(status):
361 return - os.WTERMSIG(status)
362 Logs.error("Unknown exit reason %d for command: %s" (status, cmd))
363 return -1
366 # make sure we have md5. some systems don't have it
367 try:
368 from hashlib import md5
369 except:
370 try:
371 import md5
372 except:
373 import Constants
374 Constants.SIG_NIL = hash('abcd')
375 class replace_md5(object):
376 def __init__(self):
377 self.val = None
378 def update(self, val):
379 self.val = hash((self.val, val))
380 def digest(self):
381 return str(self.val)
382 def hexdigest(self):
383 return self.digest().encode('hex')
384 def replace_h_file(filename):
385 f = open(filename, 'rb')
386 m = replace_md5()
387 while (filename):
388 filename = f.read(100000)
389 m.update(filename)
390 f.close()
391 return m.digest()
392 Utils.md5 = replace_md5
393 Task.md5 = replace_md5
394 Utils.h_file = replace_h_file
397 def LOAD_ENVIRONMENT():
398 '''load the configuration environment, allowing access to env vars
399 from new commands'''
400 import Environment
401 env = Environment.Environment()
402 try:
403 env.load('.lock-wscript')
404 env.load(env.blddir + '/c4che/default.cache.py')
405 except:
406 pass
407 return env
410 def IS_NEWER(bld, file1, file2):
411 '''return True if file1 is newer than file2'''
412 t1 = os.stat(os.path.join(bld.curdir, file1)).st_mtime
413 t2 = os.stat(os.path.join(bld.curdir, file2)).st_mtime
414 return t1 > t2
415 Build.BuildContext.IS_NEWER = IS_NEWER
418 @conf
419 def RECURSE(ctx, directory):
420 '''recurse into a directory, relative to the curdir or top level'''
421 try:
422 visited_dirs = ctx.visited_dirs
423 except:
424 visited_dirs = ctx.visited_dirs = set()
425 d = os.path.join(ctx.curdir, directory)
426 if os.path.exists(d):
427 abspath = os.path.abspath(d)
428 else:
429 abspath = os.path.abspath(os.path.join(Utils.g_module.srcdir, directory))
430 ctxclass = ctx.__class__.__name__
431 key = ctxclass + ':' + abspath
432 if key in visited_dirs:
433 # already done it
434 return
435 visited_dirs.add(key)
436 relpath = os_path_relpath(abspath, ctx.curdir)
437 if ctxclass == 'Handler':
438 return ctx.sub_options(relpath)
439 if ctxclass == 'ConfigurationContext':
440 return ctx.sub_config(relpath)
441 if ctxclass == 'BuildContext':
442 return ctx.add_subdirs(relpath)
443 Logs.error('Unknown RECURSE context class', ctxclass)
444 raise
445 Options.Handler.RECURSE = RECURSE
446 Build.BuildContext.RECURSE = RECURSE
449 def CHECK_MAKEFLAGS(bld):
450 '''check for MAKEFLAGS environment variable in case we are being
451 called from a Makefile try to honor a few make command line flags'''
452 if not 'WAF_MAKE' in os.environ:
453 return
454 makeflags = os.environ.get('MAKEFLAGS')
455 jobs_set = False
456 # we need to use shlex.split to cope with the escaping of spaces
457 # in makeflags
458 for opt in shlex.split(makeflags):
459 # options can come either as -x or as x
460 if opt[0:2] == 'V=':
461 Options.options.verbose = Logs.verbose = int(opt[2:])
462 if Logs.verbose > 0:
463 Logs.zones = ['runner']
464 if Logs.verbose > 2:
465 Logs.zones = ['*']
466 elif opt[0].isupper() and opt.find('=') != -1:
467 loc = opt.find('=')
468 setattr(Options.options, opt[0:loc], opt[loc+1:])
469 elif opt[0] != '-':
470 for v in opt:
471 if v == 'j':
472 jobs_set = True
473 elif v == 'k':
474 Options.options.keep = True
475 elif opt == '-j':
476 jobs_set = True
477 elif opt == '-k':
478 Options.options.keep = True
479 if not jobs_set:
480 # default to one job
481 Options.options.jobs = 1
483 Build.BuildContext.CHECK_MAKEFLAGS = CHECK_MAKEFLAGS
485 option_groups = {}
487 def option_group(opt, name):
488 '''find or create an option group'''
489 global option_groups
490 if name in option_groups:
491 return option_groups[name]
492 gr = opt.add_option_group(name)
493 option_groups[name] = gr
494 return gr
495 Options.Handler.option_group = option_group
498 def save_file(filename, contents, create_dir=False):
499 '''save data to a file'''
500 if create_dir:
501 mkdir_p(os.path.dirname(filename))
502 try:
503 f = open(filename, 'w')
504 f.write(contents)
505 f.close()
506 except:
507 return False
508 return True
511 def load_file(filename):
512 '''return contents of a file'''
513 try:
514 f = open(filename, 'r')
515 r = f.read()
516 f.close()
517 except:
518 return None
519 return r
522 def reconfigure(ctx):
523 '''rerun configure if necessary'''
524 import Configure, samba_wildcard, Scripting
525 if not os.path.exists(".lock-wscript"):
526 raise Utils.WafError('configure has not been run')
527 bld = samba_wildcard.fake_build_environment()
528 Configure.autoconfig = True
529 Scripting.check_configured(bld)
532 def map_shlib_extension(ctx, name, python=False):
533 '''map a filename with a shared library extension of .so to the real shlib name'''
534 if name is None:
535 return None
536 (root1, ext1) = os.path.splitext(name)
537 if python:
538 (root2, ext2) = os.path.splitext(ctx.env.pyext_PATTERN)
539 else:
540 (root2, ext2) = os.path.splitext(ctx.env.shlib_PATTERN)
541 return root1+ext2
542 Build.BuildContext.map_shlib_extension = map_shlib_extension
545 def make_libname(ctx, name, nolibprefix=False, version=None, python=False):
546 """make a library filename
547 Options:
548 nolibprefix: don't include the lib prefix
549 version : add a version number
550 python : if we should use python module name conventions"""
552 if python:
553 libname = ctx.env.pyext_PATTERN % name
554 else:
555 libname = ctx.env.shlib_PATTERN % name
556 if nolibprefix and libname[0:3] == 'lib':
557 libname = libname[3:]
558 if version:
559 if version[0] == '.':
560 version = version[1:]
561 (root, ext) = os.path.splitext(libname)
562 if ext == ".dylib":
563 # special case - version goes before the prefix
564 libname = "%s.%s%s" % (root, version, ext)
565 else:
566 libname = "%s%s.%s" % (root, ext, version)
567 return libname
568 Build.BuildContext.make_libname = make_libname