ldb: Run the Python testsuite
[Samba.git] / buildtools / wafsamba / samba_utils.py
blobfb1355c768eeea90bd1ff6428d1c1dd993603066
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 os, sys, re, fnmatch, shlex
5 import Build, Options, Utils, Task, Logs, Configure
6 from TaskGen import feature, before
7 from Configure import conf, ConfigurationContext
8 from Logs import debug
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 def runonce(function):
43 runonce_ret = {}
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 needs_private_lib(bld, target):
67 '''return True if a target links to a private library'''
68 for lib in getattr(target, "final_libs", []):
69 t = bld.get_tgen_by_name(lib)
70 if t and getattr(t, 'private_library', False):
71 return True
72 return False
75 def install_rpath(target):
76 '''the rpath value for installation'''
77 bld = target.bld
78 bld.env['RPATH'] = []
79 ret = set()
80 if bld.env.RPATH_ON_INSTALL:
81 ret.add(bld.EXPAND_VARIABLES(bld.env.LIBDIR))
82 if bld.env.RPATH_ON_INSTALL_PRIVATE and needs_private_lib(bld, target):
83 ret.add(bld.EXPAND_VARIABLES(bld.env.PRIVATELIBDIR))
84 return list(ret)
87 def build_rpath(bld):
88 '''the rpath value for build'''
89 rpaths = [os.path.normpath('%s/%s' % (bld.env.BUILD_DIRECTORY, d)) for d in ("shared", "shared/private")]
90 bld.env['RPATH'] = []
91 if bld.env.RPATH_ON_BUILD:
92 return rpaths
93 for rpath in rpaths:
94 ADD_LD_LIBRARY_PATH(rpath)
95 return []
98 @conf
99 def LOCAL_CACHE(ctx, name):
100 '''return a named build cache dictionary, used to store
101 state inside other functions'''
102 if name in ctx.env:
103 return ctx.env[name]
104 ctx.env[name] = {}
105 return ctx.env[name]
108 @conf
109 def LOCAL_CACHE_SET(ctx, cachename, key, value):
110 '''set a value in a local cache'''
111 cache = LOCAL_CACHE(ctx, cachename)
112 cache[key] = value
115 @conf
116 def ASSERT(ctx, expression, msg):
117 '''a build assert call'''
118 if not expression:
119 raise Utils.WafError("ERROR: %s\n" % msg)
120 Build.BuildContext.ASSERT = ASSERT
123 def SUBDIR(bld, subdir, list):
124 '''create a list of files by pre-pending each with a subdir name'''
125 ret = ''
126 for l in TO_LIST(list):
127 ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
128 return ret
129 Build.BuildContext.SUBDIR = SUBDIR
132 def dict_concat(d1, d2):
133 '''concatenate two dictionaries d1 += d2'''
134 for t in d2:
135 if t not in d1:
136 d1[t] = d2[t]
139 def exec_command(self, cmd, **kw):
140 '''this overrides the 'waf -v' debug output to be in a nice
141 unix like format instead of a python list.
142 Thanks to ita on #waf for this'''
143 _cmd = cmd
144 if isinstance(cmd, list):
145 _cmd = ' '.join(cmd)
146 debug('runner: %s' % _cmd)
147 if self.log:
148 self.log.write('%s\n' % cmd)
149 kw['log'] = self.log
150 try:
151 if not kw.get('cwd', None):
152 kw['cwd'] = self.cwd
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 def ADD_COMMAND(opt, name, function):
160 '''add a new top level command to waf'''
161 Utils.g_module.__dict__[name] = function
162 opt.name = function
163 Options.Handler.ADD_COMMAND = ADD_COMMAND
166 @feature('c', 'cc', 'cshlib', 'cprogram')
167 @before('apply_core','exec_rule')
168 def process_depends_on(self):
169 '''The new depends_on attribute for build rules
170 allow us to specify a dependency on output from
171 a source generation rule'''
172 if getattr(self , 'depends_on', None):
173 lst = self.to_list(self.depends_on)
174 for x in lst:
175 y = self.bld.get_tgen_by_name(x)
176 self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
177 y.post()
178 if getattr(y, 'more_includes', None):
179 self.includes += " " + y.more_includes
182 os_path_relpath = getattr(os.path, 'relpath', None)
183 if os_path_relpath is None:
184 # Python < 2.6 does not have os.path.relpath, provide a replacement
185 # (imported from Python2.6.5~rc2)
186 def os_path_relpath(path, start):
187 """Return a relative version of a path"""
188 start_list = os.path.abspath(start).split("/")
189 path_list = os.path.abspath(path).split("/")
191 # Work out how much of the filepath is shared by start and path.
192 i = len(os.path.commonprefix([start_list, path_list]))
194 rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
195 if not rel_list:
196 return start
197 return os.path.join(*rel_list)
200 def unique_list(seq):
201 '''return a uniquified list in the same order as the existing list'''
202 seen = {}
203 result = []
204 for item in seq:
205 if item in seen: continue
206 seen[item] = True
207 result.append(item)
208 return result
211 def TO_LIST(str, delimiter=None):
212 '''Split a list, preserving quoted strings and existing lists'''
213 if str is None:
214 return []
215 if isinstance(str, list):
216 # we need to return a new independent list...
217 return list(str)
218 if len(str) == 0:
219 return []
220 lst = str.split(delimiter)
221 # the string may have had quotes in it, now we
222 # check if we did have quotes, and use the slower shlex
223 # if we need to
224 for e in lst:
225 if e[0] == '"':
226 return shlex.split(str)
227 return lst
230 def subst_vars_error(string, env):
231 '''substitute vars, throw an error if a variable is not defined'''
232 lst = re.split('(\$\{\w+\})', string)
233 out = []
234 for v in lst:
235 if re.match('\$\{\w+\}', v):
236 vname = v[2:-1]
237 if not vname in env:
238 raise KeyError("Failed to find variable %s in %s" % (vname, string))
239 v = env[vname]
240 out.append(v)
241 return ''.join(out)
244 @conf
245 def SUBST_ENV_VAR(ctx, varname):
246 '''Substitute an environment variable for any embedded variables'''
247 return subst_vars_error(ctx.env[varname], ctx.env)
248 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
251 def ENFORCE_GROUP_ORDERING(bld):
252 '''enforce group ordering for the project. This
253 makes the group ordering apply only when you specify
254 a target with --target'''
255 if Options.options.compile_targets:
256 @feature('*')
257 @before('exec_rule', 'apply_core', 'collect')
258 def force_previous_groups(self):
259 if getattr(self.bld, 'enforced_group_ordering', False):
260 return
261 self.bld.enforced_group_ordering = True
263 def group_name(g):
264 tm = self.bld.task_manager
265 return [x for x in tm.groups_names if id(tm.groups_names[x]) == id(g)][0]
267 my_id = id(self)
268 bld = self.bld
269 stop = None
270 for g in bld.task_manager.groups:
271 for t in g.tasks_gen:
272 if id(t) == my_id:
273 stop = id(g)
274 debug('group: Forcing up to group %s for target %s',
275 group_name(g), self.name or self.target)
276 break
277 if stop is not None:
278 break
279 if stop is None:
280 return
282 for i in xrange(len(bld.task_manager.groups)):
283 g = bld.task_manager.groups[i]
284 bld.task_manager.current_group = i
285 if id(g) == stop:
286 break
287 debug('group: Forcing group %s', group_name(g))
288 for t in g.tasks_gen:
289 if not getattr(t, 'forced_groups', False):
290 debug('group: Posting %s', t.name or t.target)
291 t.forced_groups = True
292 t.post()
293 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
296 def recursive_dirlist(dir, relbase, pattern=None):
297 '''recursive directory list'''
298 ret = []
299 for f in os.listdir(dir):
300 f2 = dir + '/' + f
301 if os.path.isdir(f2):
302 ret.extend(recursive_dirlist(f2, relbase))
303 else:
304 if pattern and not fnmatch.fnmatch(f, pattern):
305 continue
306 ret.append(os_path_relpath(f2, relbase))
307 return ret
310 def mkdir_p(dir):
311 '''like mkdir -p'''
312 if not dir:
313 return
314 if dir.endswith("/"):
315 mkdir_p(dir[:-1])
316 return
317 if os.path.isdir(dir):
318 return
319 mkdir_p(os.path.dirname(dir))
320 os.mkdir(dir)
323 def SUBST_VARS_RECURSIVE(string, env):
324 '''recursively expand variables'''
325 if string is None:
326 return string
327 limit=100
328 while (string.find('${') != -1 and limit > 0):
329 string = subst_vars_error(string, env)
330 limit -= 1
331 return string
334 @conf
335 def EXPAND_VARIABLES(ctx, varstr, vars=None):
336 '''expand variables from a user supplied dictionary
338 This is most useful when you pass vars=locals() to expand
339 all your local variables in strings
342 if isinstance(varstr, list):
343 ret = []
344 for s in varstr:
345 ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
346 return ret
348 if not isinstance(varstr, str):
349 return varstr
351 import Environment
352 env = Environment.Environment()
353 ret = varstr
354 # substitute on user supplied dict if avaiilable
355 if vars is not None:
356 for v in vars.keys():
357 env[v] = vars[v]
358 ret = SUBST_VARS_RECURSIVE(ret, env)
360 # if anything left, subst on the environment as well
361 if ret.find('${') != -1:
362 ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
363 # make sure there is nothing left. Also check for the common
364 # typo of $( instead of ${
365 if ret.find('${') != -1 or ret.find('$(') != -1:
366 Logs.error('Failed to substitute all variables in varstr=%s' % ret)
367 sys.exit(1)
368 return ret
369 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
372 def RUN_COMMAND(cmd,
373 env=None,
374 shell=False):
375 '''run a external command, return exit code or signal'''
376 if env:
377 cmd = SUBST_VARS_RECURSIVE(cmd, env)
379 status = os.system(cmd)
380 if os.WIFEXITED(status):
381 return os.WEXITSTATUS(status)
382 if os.WIFSIGNALED(status):
383 return - os.WTERMSIG(status)
384 Logs.error("Unknown exit reason %d for command: %s" (status, cmd))
385 return -1
388 def RUN_PYTHON_TESTS(testfiles, pythonpath=None, extra_env=None):
389 env = LOAD_ENVIRONMENT()
390 if pythonpath is None:
391 pythonpath = os.path.join(Utils.g_module.blddir, 'python')
392 result = 0
393 for interp in env.python_interpreters:
394 for testfile in testfiles:
395 cmd = "PYTHONPATH=%s %s %s" % (pythonpath, interp, testfile)
396 if extra_env:
397 for key, value in extra_env.items():
398 cmd = "%s=%s %s" % (key, value, cmd)
399 print('Running Python test with %s: %s' % (interp, testfile))
400 ret = RUN_COMMAND(cmd)
401 if ret:
402 print('Python test failed: %s' % cmd)
403 result = ret
404 return result
407 # make sure we have md5. some systems don't have it
408 try:
409 from hashlib import md5
410 # Even if hashlib.md5 exists, it may be unusable.
411 # Try to use MD5 function. In FIPS mode this will cause an exception
412 # and we'll get to the replacement code
413 foo = md5('abcd')
414 except:
415 try:
416 import md5
417 # repeat the same check here, mere success of import is not enough.
418 # Try to use MD5 function. In FIPS mode this will cause an exception
419 foo = md5.md5('abcd')
420 except:
421 import Constants
422 Constants.SIG_NIL = hash('abcd')
423 class replace_md5(object):
424 def __init__(self):
425 self.val = None
426 def update(self, val):
427 self.val = hash((self.val, val))
428 def digest(self):
429 return str(self.val)
430 def hexdigest(self):
431 return self.digest().encode('hex')
432 def replace_h_file(filename):
433 f = open(filename, 'rb')
434 m = replace_md5()
435 while (filename):
436 filename = f.read(100000)
437 m.update(filename)
438 f.close()
439 return m.digest()
440 Utils.md5 = replace_md5
441 Task.md5 = replace_md5
442 Utils.h_file = replace_h_file
445 def LOAD_ENVIRONMENT():
446 '''load the configuration environment, allowing access to env vars
447 from new commands'''
448 import Environment
449 env = Environment.Environment()
450 try:
451 env.load('.lock-wscript')
452 env.load(env.blddir + '/c4che/default.cache.py')
453 except:
454 pass
455 return env
458 def IS_NEWER(bld, file1, file2):
459 '''return True if file1 is newer than file2'''
460 t1 = os.stat(os.path.join(bld.curdir, file1)).st_mtime
461 t2 = os.stat(os.path.join(bld.curdir, file2)).st_mtime
462 return t1 > t2
463 Build.BuildContext.IS_NEWER = IS_NEWER
466 @conf
467 def RECURSE(ctx, directory):
468 '''recurse into a directory, relative to the curdir or top level'''
469 try:
470 visited_dirs = ctx.visited_dirs
471 except:
472 visited_dirs = ctx.visited_dirs = set()
473 d = os.path.join(ctx.curdir, directory)
474 if os.path.exists(d):
475 abspath = os.path.abspath(d)
476 else:
477 abspath = os.path.abspath(os.path.join(Utils.g_module.srcdir, directory))
478 ctxclass = ctx.__class__.__name__
479 key = ctxclass + ':' + abspath
480 if key in visited_dirs:
481 # already done it
482 return
483 visited_dirs.add(key)
484 relpath = os_path_relpath(abspath, ctx.curdir)
485 if ctxclass == 'Handler':
486 return ctx.sub_options(relpath)
487 if ctxclass == 'ConfigurationContext':
488 return ctx.sub_config(relpath)
489 if ctxclass == 'BuildContext':
490 return ctx.add_subdirs(relpath)
491 Logs.error('Unknown RECURSE context class', ctxclass)
492 raise
493 Options.Handler.RECURSE = RECURSE
494 Build.BuildContext.RECURSE = RECURSE
497 def CHECK_MAKEFLAGS(bld):
498 '''check for MAKEFLAGS environment variable in case we are being
499 called from a Makefile try to honor a few make command line flags'''
500 if not 'WAF_MAKE' in os.environ:
501 return
502 makeflags = os.environ.get('MAKEFLAGS')
503 if makeflags is None:
504 return
505 jobs_set = False
506 # we need to use shlex.split to cope with the escaping of spaces
507 # in makeflags
508 for opt in shlex.split(makeflags):
509 # options can come either as -x or as x
510 if opt[0:2] == 'V=':
511 Options.options.verbose = Logs.verbose = int(opt[2:])
512 if Logs.verbose > 0:
513 Logs.zones = ['runner']
514 if Logs.verbose > 2:
515 Logs.zones = ['*']
516 elif opt[0].isupper() and opt.find('=') != -1:
517 # this allows us to set waf options on the make command line
518 # for example, if you do "make FOO=blah", then we set the
519 # option 'FOO' in Options.options, to blah. If you look in wafsamba/wscript
520 # you will see that the command line accessible options have their dest=
521 # set to uppercase, to allow for passing of options from make in this way
522 # this is also how "make test TESTS=testpattern" works, and
523 # "make VERBOSE=1" as well as things like "make SYMBOLCHECK=1"
524 loc = opt.find('=')
525 setattr(Options.options, opt[0:loc], opt[loc+1:])
526 elif opt[0] != '-':
527 for v in opt:
528 if v == 'j':
529 jobs_set = True
530 elif v == 'k':
531 Options.options.keep = True
532 elif opt == '-j':
533 jobs_set = True
534 elif opt == '-k':
535 Options.options.keep = True
536 if not jobs_set:
537 # default to one job
538 Options.options.jobs = 1
540 Build.BuildContext.CHECK_MAKEFLAGS = CHECK_MAKEFLAGS
542 option_groups = {}
544 def option_group(opt, name):
545 '''find or create an option group'''
546 global option_groups
547 if name in option_groups:
548 return option_groups[name]
549 gr = opt.add_option_group(name)
550 option_groups[name] = gr
551 return gr
552 Options.Handler.option_group = option_group
555 def save_file(filename, contents, create_dir=False):
556 '''save data to a file'''
557 if create_dir:
558 mkdir_p(os.path.dirname(filename))
559 try:
560 f = open(filename, 'w')
561 f.write(contents)
562 f.close()
563 except:
564 return False
565 return True
568 def load_file(filename):
569 '''return contents of a file'''
570 try:
571 f = open(filename, 'r')
572 r = f.read()
573 f.close()
574 except:
575 return None
576 return r
579 def reconfigure(ctx):
580 '''rerun configure if necessary'''
581 import Configure, samba_wildcard, Scripting
582 if not os.path.exists(".lock-wscript"):
583 raise Utils.WafError('configure has not been run')
584 bld = samba_wildcard.fake_build_environment()
585 Configure.autoconfig = True
586 Scripting.check_configured(bld)
589 def map_shlib_extension(ctx, name, python=False):
590 '''map a filename with a shared library extension of .so to the real shlib name'''
591 if name is None:
592 return None
593 if name[-1:].isdigit():
594 # some libraries have specified versions in the wscript rule
595 return name
596 (root1, ext1) = os.path.splitext(name)
597 if python:
598 return ctx.env.pyext_PATTERN % root1
599 else:
600 (root2, ext2) = os.path.splitext(ctx.env.shlib_PATTERN)
601 return root1+ext2
602 Build.BuildContext.map_shlib_extension = map_shlib_extension
604 def apply_pattern(filename, pattern):
605 '''apply a filename pattern to a filename that may have a directory component'''
606 dirname = os.path.dirname(filename)
607 if not dirname:
608 return pattern % filename
609 basename = os.path.basename(filename)
610 return os.path.join(dirname, pattern % basename)
612 def make_libname(ctx, name, nolibprefix=False, version=None, python=False):
613 """make a library filename
614 Options:
615 nolibprefix: don't include the lib prefix
616 version : add a version number
617 python : if we should use python module name conventions"""
619 if python:
620 libname = apply_pattern(name, ctx.env.pyext_PATTERN)
621 else:
622 libname = apply_pattern(name, ctx.env.shlib_PATTERN)
623 if nolibprefix and libname[0:3] == 'lib':
624 libname = libname[3:]
625 if version:
626 if version[0] == '.':
627 version = version[1:]
628 (root, ext) = os.path.splitext(libname)
629 if ext == ".dylib":
630 # special case - version goes before the prefix
631 libname = "%s.%s%s" % (root, version, ext)
632 else:
633 libname = "%s%s.%s" % (root, ext, version)
634 return libname
635 Build.BuildContext.make_libname = make_libname
638 def get_tgt_list(bld):
639 '''return a list of build objects for samba'''
641 targets = LOCAL_CACHE(bld, 'TARGET_TYPE')
643 # build a list of task generators we are interested in
644 tgt_list = []
645 for tgt in targets:
646 type = targets[tgt]
647 if not type in ['SUBSYSTEM', 'MODULE', 'BINARY', 'LIBRARY', 'ASN1', 'PYTHON']:
648 continue
649 t = bld.get_tgen_by_name(tgt)
650 if t is None:
651 Logs.error("Target %s of type %s has no task generator" % (tgt, type))
652 sys.exit(1)
653 tgt_list.append(t)
654 return tgt_list
656 from Constants import WSCRIPT_FILE
657 def PROCESS_SEPARATE_RULE(self, rule):
658 ''' cause waf to process additional script based on `rule'.
659 You should have file named wscript_<stage>_rule in the current directory
660 where stage is either 'configure' or 'build'
662 stage = ''
663 if isinstance(self, Configure.ConfigurationContext):
664 stage = 'configure'
665 elif isinstance(self, Build.BuildContext):
666 stage = 'build'
667 file_path = os.path.join(self.curdir, WSCRIPT_FILE+'_'+stage+'_'+rule)
668 txt = load_file(file_path)
669 if txt:
670 dc = {'ctx': self}
671 if getattr(self.__class__, 'pre_recurse', None):
672 dc = self.pre_recurse(txt, file_path, self.curdir)
673 exec(compile(txt, file_path, 'exec'), dc)
674 if getattr(self.__class__, 'post_recurse', None):
675 dc = self.post_recurse(txt, file_path, self.curdir)
677 Build.BuildContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
678 ConfigurationContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
680 def AD_DC_BUILD_IS_ENABLED(self):
681 if self.CONFIG_SET('AD_DC_BUILD_IS_ENABLED'):
682 return True
683 return False
685 Build.BuildContext.AD_DC_BUILD_IS_ENABLED = AD_DC_BUILD_IS_ENABLED