libwbclient: Fix wbcListGroups against too small num_entries
[Samba/ekacnet.git] / buildtools / wafsamba / samba_utils.py
blobb989f912523bcd9bcb4577406abcf59f4dc6cd5f
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 @conf
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,
20 ctx.curdir,
21 value, cache[target]))
22 sys.exit(1)
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))
25 return True
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:
32 return None
33 return cache[target]
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
40 runonce_ret = {}
41 def runonce(function):
42 def runonce_wrapper(*args):
43 if args in runonce_ret:
44 return runonce_ret[args]
45 else:
46 ret = function(*args)
47 runonce_ret[args] = ret
48 return 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']
56 else:
57 oldpath = ''
58 newpath = oldpath.split(':')
59 if not path in newpath:
60 newpath.append(path)
61 os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
64 def install_rpath(bld):
65 '''the rpath value for installation'''
66 bld.env['RPATH'] = []
67 bld.env['RPATH_ST'] = []
68 if bld.env.RPATH_ON_INSTALL:
69 return ['-Wl,-rpath=%s/lib' % bld.env.PREFIX]
70 return []
73 def build_rpath(bld):
74 '''the rpath value for build'''
75 rpath = os.path.normpath('%s/%s' % (bld.env.BUILD_DIRECTORY, LIB_PATH))
76 bld.env['RPATH'] = []
77 bld.env['RPATH_ST'] = []
78 if bld.env.RPATH_ON_BUILD:
79 return ['-Wl,-rpath=%s' % 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):
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()
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 def force_previous_groups(self):
244 if getattr(self.bld, 'enforced_group_ordering', False) == True:
245 return
246 self.bld.enforced_group_ordering = True
248 def group_name(g):
249 tm = self.bld.task_manager
250 return [x for x in tm.groups_names if id(tm.groups_names[x]) == id(g)][0]
252 my_id = id(self)
253 bld = self.bld
254 stop = None
255 for g in bld.task_manager.groups:
256 for t in g.tasks_gen:
257 if id(t) == my_id:
258 stop = id(g)
259 debug('group: Forcing up to group %s for target %s',
260 group_name(g), self.name or self.target)
261 break
262 if stop != None:
263 break
264 if stop is None:
265 return
267 for g in bld.task_manager.groups:
268 if id(g) == stop:
269 break
270 debug('group: Forcing group %s', group_name(g))
271 for t in g.tasks_gen:
272 if getattr(t, 'forced_groups', False) != True:
273 debug('group: Posting %s', t.name or t.target)
274 t.forced_groups = True
275 t.post()
276 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
279 def recursive_dirlist(dir, relbase, pattern=None):
280 '''recursive directory list'''
281 ret = []
282 for f in os.listdir(dir):
283 f2 = dir + '/' + f
284 if os.path.isdir(f2):
285 ret.extend(recursive_dirlist(f2, relbase))
286 else:
287 if pattern and not fnmatch.fnmatch(f, pattern):
288 continue
289 ret.append(os_path_relpath(f2, relbase))
290 return ret
293 def mkdir_p(dir):
294 '''like mkdir -p'''
295 if os.path.isdir(dir):
296 return
297 mkdir_p(os.path.dirname(dir))
298 os.mkdir(dir)
301 def SUBST_VARS_RECURSIVE(string, env):
302 '''recursively expand variables'''
303 if string is None:
304 return string
305 limit=100
306 while (string.find('${') != -1 and limit > 0):
307 string = subst_vars_error(string, env)
308 limit -= 1
309 return string
312 @conf
313 def EXPAND_VARIABLES(ctx, varstr, vars=None):
314 '''expand variables from a user supplied dictionary
316 This is most useful when you pass vars=locals() to expand
317 all your local variables in strings
320 if isinstance(varstr, list):
321 ret = []
322 for s in varstr:
323 ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
324 return ret
326 import Environment
327 env = Environment.Environment()
328 ret = varstr
329 # substitute on user supplied dict if avaiilable
330 if vars is not None:
331 for v in vars.keys():
332 env[v] = vars[v]
333 ret = SUBST_VARS_RECURSIVE(ret, env)
335 # if anything left, subst on the environment as well
336 if ret.find('${') != -1:
337 ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
338 # make sure there is nothing left. Also check for the common
339 # typo of $( instead of ${
340 if ret.find('${') != -1 or ret.find('$(') != -1:
341 Logs.error('Failed to substitute all variables in varstr=%s' % ret)
342 sys.exit(1)
343 return ret
344 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
347 def RUN_COMMAND(cmd,
348 env=None,
349 shell=False):
350 '''run a external command, return exit code or signal'''
351 if env:
352 cmd = SUBST_VARS_RECURSIVE(cmd, env)
354 status = os.system(cmd)
355 if os.WIFEXITED(status):
356 return os.WEXITSTATUS(status)
357 if os.WIFSIGNALED(status):
358 return - os.WTERMSIG(status)
359 Logs.error("Unknown exit reason %d for command: %s" (status, cmd))
360 return -1
363 # make sure we have md5. some systems don't have it
364 try:
365 from hashlib import md5
366 except:
367 try:
368 import md5
369 except:
370 import Constants
371 Constants.SIG_NIL = hash('abcd')
372 class replace_md5(object):
373 def __init__(self):
374 self.val = None
375 def update(self, val):
376 self.val = hash((self.val, val))
377 def digest(self):
378 return str(self.val)
379 def hexdigest(self):
380 return self.digest().encode('hex')
381 def replace_h_file(filename):
382 f = open(filename, 'rb')
383 m = replace_md5()
384 while (filename):
385 filename = f.read(100000)
386 m.update(filename)
387 f.close()
388 return m.digest()
389 Utils.md5 = replace_md5
390 Task.md5 = replace_md5
391 Utils.h_file = replace_h_file
394 def LOAD_ENVIRONMENT():
395 '''load the configuration environment, allowing access to env vars
396 from new commands'''
397 import Environment
398 env = Environment.Environment()
399 env.load('.lock-wscript')
400 env.load(env.blddir + '/c4che/default.cache.py')
401 return env
404 def IS_NEWER(bld, file1, file2):
405 '''return True if file1 is newer than file2'''
406 t1 = os.stat(os.path.join(bld.curdir, file1)).st_mtime
407 t2 = os.stat(os.path.join(bld.curdir, file2)).st_mtime
408 return t1 > t2
409 Build.BuildContext.IS_NEWER = IS_NEWER
412 @conf
413 def RECURSE(ctx, directory):
414 '''recurse into a directory, relative to the curdir or top level'''
415 try:
416 visited_dirs = ctx.visited_dirs
417 except:
418 visited_dirs = ctx.visited_dirs = set()
419 d = os.path.join(ctx.curdir, directory)
420 if os.path.exists(d):
421 abspath = os.path.abspath(d)
422 else:
423 abspath = os.path.abspath(os.path.join(Utils.g_module.srcdir, directory))
424 ctxclass = ctx.__class__.__name__
425 key = ctxclass + ':' + abspath
426 if key in visited_dirs:
427 # already done it
428 return
429 visited_dirs.add(key)
430 relpath = os_path_relpath(abspath, ctx.curdir)
431 if ctxclass == 'Handler':
432 return ctx.sub_options(relpath)
433 if ctxclass == 'ConfigurationContext':
434 return ctx.sub_config(relpath)
435 if ctxclass == 'BuildContext':
436 return ctx.add_subdirs(relpath)
437 Logs.error('Unknown RECURSE context class', ctxclass)
438 raise
439 Options.Handler.RECURSE = RECURSE
440 Build.BuildContext.RECURSE = RECURSE
443 def CHECK_MAKEFLAGS(bld):
444 '''check for MAKEFLAGS environment variable in case we are being
445 called from a Makefile try to honor a few make command line flags'''
446 if not 'WAF_MAKE' in os.environ:
447 return
448 makeflags = os.environ.get('MAKEFLAGS')
449 jobs_set = False
450 for opt in makeflags.split():
451 # options can come either as -x or as x
452 if opt[0:2] == 'V=':
453 Options.options.verbose = Logs.verbose = int(opt[2:])
454 if Logs.verbose > 0:
455 Logs.zones = ['runner']
456 if Logs.verbose > 2:
457 Logs.zones = ['*']
458 elif opt[0].isupper() and opt.find('=') != -1:
459 loc = opt.find('=')
460 setattr(Options.options, opt[0:loc], opt[loc+1:])
461 elif opt[0] != '-':
462 for v in opt:
463 if v == 'j':
464 jobs_set = True
465 elif v == 'k':
466 Options.options.keep = True
467 elif opt == '-j':
468 jobs_set = True
469 elif opt == '-k':
470 Options.options.keep = True
471 if not jobs_set:
472 # default to one job
473 Options.options.jobs = 1
475 Build.BuildContext.CHECK_MAKEFLAGS = CHECK_MAKEFLAGS
477 option_groups = {}
479 def option_group(opt, name):
480 '''find or create an option group'''
481 global option_groups
482 if name in option_groups:
483 return option_groups[name]
484 gr = opt.add_option_group(name)
485 option_groups[name] = gr
486 return gr
487 Options.Handler.option_group = option_group
490 def save_file(filename, contents, create_dir=False):
491 '''save data to a file'''
492 if create_dir:
493 mkdir_p(os.path.dirname(filename))
494 try:
495 f = open(filename, 'w')
496 f.write(contents)
497 f.close()
498 except:
499 return False
500 return True
503 def load_file(filename):
504 '''return contents of a file'''
505 try:
506 f = open(filename, 'r')
507 r = f.read()
508 f.close()
509 except:
510 return None
511 return r