aa4fa20a43962806e1850b9dd732dc549cfc2995
[kai/samba.git] / buildtools / wafsamba / samba_utils.py
1 # a waf tool to add autoconf-like macros to the configure section
2 # and for SAMBA_ macros for building libraries, binaries etc
3
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
9
10 # TODO: make this a --option
11 LIB_PATH="shared"
12
13
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
26
27
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]
34
35
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
50
51
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)
62
63
64 def install_rpath(bld):
65     '''the rpath value for installation'''
66     bld.env['RPATH'] = []
67     if bld.env.RPATH_ON_INSTALL:
68         return ['%s/lib' % bld.env.PREFIX]
69     return []
70
71
72 def build_rpath(bld):
73     '''the rpath value for build'''
74     rpath = os.path.normpath('%s/%s' % (bld.env.BUILD_DIRECTORY, LIB_PATH))
75     bld.env['RPATH'] = []
76     if bld.env.RPATH_ON_BUILD:
77         return [rpath]
78     ADD_LD_LIBRARY_PATH(rpath)
79     return []
80
81
82 @conf
83 def LOCAL_CACHE(ctx, name):
84     '''return a named build cache dictionary, used to store
85        state inside other functions'''
86     if name in ctx.env:
87         return ctx.env[name]
88     ctx.env[name] = {}
89     return ctx.env[name]
90
91
92 @conf
93 def LOCAL_CACHE_SET(ctx, cachename, key, value):
94     '''set a value in a local cache'''
95     cache = LOCAL_CACHE(ctx, cachename)
96     cache[key] = value
97
98
99 @conf
100 def ASSERT(ctx, expression, msg):
101     '''a build assert call'''
102     if not expression:
103         Logs.error("ERROR: %s\n" % msg)
104         raise AssertionError
105 Build.BuildContext.ASSERT = ASSERT
106
107
108 def SUBDIR(bld, subdir, list):
109     '''create a list of files by pre-pending each with a subdir name'''
110     ret = ''
111     for l in TO_LIST(list):
112         ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
113     return ret
114 Build.BuildContext.SUBDIR = SUBDIR
115
116
117 def dict_concat(d1, d2):
118     '''concatenate two dictionaries d1 += d2'''
119     for t in d2:
120         if t not in d1:
121             d1[t] = d2[t]
122
123
124 def exec_command(self, cmd, **kw):
125     '''this overrides the 'waf -v' debug output to be in a nice
126     unix like format instead of a python list.
127     Thanks to ita on #waf for this'''
128     import Utils, Logs
129     _cmd = cmd
130     if isinstance(cmd, list):
131         _cmd = ' '.join(cmd)
132     debug('runner: %s' % _cmd)
133     if self.log:
134         self.log.write('%s\n' % cmd)
135         kw['log'] = self.log
136     try:
137         if not kw.get('cwd', None):
138             kw['cwd'] = self.cwd
139     except AttributeError:
140         self.cwd = kw['cwd'] = self.bldnode.abspath()
141     return Utils.exec_command(cmd, **kw)
142 Build.BuildContext.exec_command = exec_command
143
144
145 def ADD_COMMAND(opt, name, function):
146     '''add a new top level command to waf'''
147     Utils.g_module.__dict__[name] = function
148     opt.name = function
149 Options.Handler.ADD_COMMAND = ADD_COMMAND
150
151
152 @feature('cc', 'cshlib', 'cprogram')
153 @before('apply_core','exec_rule')
154 def process_depends_on(self):
155     '''The new depends_on attribute for build rules
156        allow us to specify a dependency on output from
157        a source generation rule'''
158     if getattr(self , 'depends_on', None):
159         lst = self.to_list(self.depends_on)
160         for x in lst:
161             y = self.bld.name_to_obj(x, self.env)
162             self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
163             y.post()
164             if getattr(y, 'more_includes', None):
165                   self.includes += " " + y.more_includes
166
167
168 os_path_relpath = getattr(os.path, 'relpath', None)
169 if os_path_relpath is None:
170     # Python < 2.6 does not have os.path.relpath, provide a replacement
171     # (imported from Python2.6.5~rc2)
172     def os_path_relpath(path, start):
173         """Return a relative version of a path"""
174         start_list = os.path.abspath(start).split("/")
175         path_list = os.path.abspath(path).split("/")
176
177         # Work out how much of the filepath is shared by start and path.
178         i = len(os.path.commonprefix([start_list, path_list]))
179
180         rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
181         if not rel_list:
182             return start
183         return os.path.join(*rel_list)
184
185
186 def unique_list(seq):
187     '''return a uniquified list in the same order as the existing list'''
188     seen = {}
189     result = []
190     for item in seq:
191         if item in seen: continue
192         seen[item] = True
193         result.append(item)
194     return result
195
196
197 def TO_LIST(str, delimiter=None):
198     '''Split a list, preserving quoted strings and existing lists'''
199     if str is None:
200         return []
201     if isinstance(str, list):
202         return str
203     lst = str.split(delimiter)
204     # the string may have had quotes in it, now we
205     # check if we did have quotes, and use the slower shlex
206     # if we need to
207     for e in lst:
208         if e[0] == '"':
209             return shlex.split(str)
210     return lst
211
212
213 def subst_vars_error(string, env):
214     '''substitute vars, throw an error if a variable is not defined'''
215     lst = re.split('(\$\{\w+\})', string)
216     out = []
217     for v in lst:
218         if re.match('\$\{\w+\}', v):
219             vname = v[2:-1]
220             if not vname in env:
221                 Logs.error("Failed to find variable %s in %s" % (vname, string))
222                 sys.exit(1)
223             v = env[vname]
224         out.append(v)
225     return ''.join(out)
226
227
228 @conf
229 def SUBST_ENV_VAR(ctx, varname):
230     '''Substitute an environment variable for any embedded variables'''
231     return subst_vars_error(ctx.env[varname], ctx.env)
232 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
233
234
235 def ENFORCE_GROUP_ORDERING(bld):
236     '''enforce group ordering for the project. This
237        makes the group ordering apply only when you specify
238        a target with --target'''
239     if Options.options.compile_targets:
240         @feature('*')
241         @before('exec_rule', 'apply_core', 'collect')
242         def force_previous_groups(self):
243             if getattr(self.bld, 'enforced_group_ordering', False) == True:
244                 return
245             self.bld.enforced_group_ordering = True
246
247             def group_name(g):
248                 tm = self.bld.task_manager
249                 return [x for x in tm.groups_names if id(tm.groups_names[x]) == id(g)][0]
250
251             my_id = id(self)
252             bld = self.bld
253             stop = None
254             for g in bld.task_manager.groups:
255                 for t in g.tasks_gen:
256                     if id(t) == my_id:
257                         stop = id(g)
258                         debug('group: Forcing up to group %s for target %s',
259                               group_name(g), self.name or self.target)
260                         break
261                 if stop != None:
262                     break
263             if stop is None:
264                 return
265
266             for i in xrange(len(bld.task_manager.groups)):
267                 g = bld.task_manager.groups[i]
268                 bld.task_manager.current_group = i
269                 if id(g) == stop:
270                     break
271                 debug('group: Forcing group %s', group_name(g))
272                 for t in g.tasks_gen:
273                     if not getattr(t, 'forced_groups', False):
274                         debug('group: Posting %s', t.name or t.target)
275                         t.forced_groups = True
276                         t.post()
277 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
278
279
280 def recursive_dirlist(dir, relbase, pattern=None):
281     '''recursive directory list'''
282     ret = []
283     for f in os.listdir(dir):
284         f2 = dir + '/' + f
285         if os.path.isdir(f2):
286             ret.extend(recursive_dirlist(f2, relbase))
287         else:
288             if pattern and not fnmatch.fnmatch(f, pattern):
289                 continue
290             ret.append(os_path_relpath(f2, relbase))
291     return ret
292
293
294 def mkdir_p(dir):
295     '''like mkdir -p'''
296     if os.path.isdir(dir):
297         return
298     mkdir_p(os.path.dirname(dir))
299     os.mkdir(dir)
300
301
302 def SUBST_VARS_RECURSIVE(string, env):
303     '''recursively expand variables'''
304     if string is None:
305         return string
306     limit=100
307     while (string.find('${') != -1 and limit > 0):
308         string = subst_vars_error(string, env)
309         limit -= 1
310     return string
311
312
313 @conf
314 def EXPAND_VARIABLES(ctx, varstr, vars=None):
315     '''expand variables from a user supplied dictionary
316
317     This is most useful when you pass vars=locals() to expand
318     all your local variables in strings
319     '''
320
321     if isinstance(varstr, list):
322         ret = []
323         for s in varstr:
324             ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
325         return ret
326
327     import Environment
328     env = Environment.Environment()
329     ret = varstr
330     # substitute on user supplied dict if avaiilable
331     if vars is not None:
332         for v in vars.keys():
333             env[v] = vars[v]
334         ret = SUBST_VARS_RECURSIVE(ret, env)
335
336     # if anything left, subst on the environment as well
337     if ret.find('${') != -1:
338         ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
339     # make sure there is nothing left. Also check for the common
340     # typo of $( instead of ${
341     if ret.find('${') != -1 or ret.find('$(') != -1:
342         Logs.error('Failed to substitute all variables in varstr=%s' % ret)
343         sys.exit(1)
344     return ret
345 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
346
347
348 def RUN_COMMAND(cmd,
349                 env=None,
350                 shell=False):
351     '''run a external command, return exit code or signal'''
352     if env:
353         cmd = SUBST_VARS_RECURSIVE(cmd, env)
354
355     status = os.system(cmd)
356     if os.WIFEXITED(status):
357         return os.WEXITSTATUS(status)
358     if os.WIFSIGNALED(status):
359         return - os.WTERMSIG(status)
360     Logs.error("Unknown exit reason %d for command: %s" (status, cmd))
361     return -1
362
363
364 # make sure we have md5. some systems don't have it
365 try:
366     from hashlib import md5
367 except:
368     try:
369         import md5
370     except:
371         import Constants
372         Constants.SIG_NIL = hash('abcd')
373         class replace_md5(object):
374             def __init__(self):
375                 self.val = None
376             def update(self, val):
377                 self.val = hash((self.val, val))
378             def digest(self):
379                 return str(self.val)
380             def hexdigest(self):
381                 return self.digest().encode('hex')
382         def replace_h_file(filename):
383             f = open(filename, 'rb')
384             m = replace_md5()
385             while (filename):
386                 filename = f.read(100000)
387                 m.update(filename)
388             f.close()
389             return m.digest()
390         Utils.md5 = replace_md5
391         Task.md5 = replace_md5
392         Utils.h_file = replace_h_file
393
394
395 def LOAD_ENVIRONMENT():
396     '''load the configuration environment, allowing access to env vars
397        from new commands'''
398     import Environment
399     env = Environment.Environment()
400     try:
401         env.load('.lock-wscript')
402         env.load(env.blddir + '/c4che/default.cache.py')
403     except:
404         pass
405     return env
406
407
408 def IS_NEWER(bld, file1, file2):
409     '''return True if file1 is newer than file2'''
410     t1 = os.stat(os.path.join(bld.curdir, file1)).st_mtime
411     t2 = os.stat(os.path.join(bld.curdir, file2)).st_mtime
412     return t1 > t2
413 Build.BuildContext.IS_NEWER = IS_NEWER
414
415
416 @conf
417 def RECURSE(ctx, directory):
418     '''recurse into a directory, relative to the curdir or top level'''
419     try:
420         visited_dirs = ctx.visited_dirs
421     except:
422         visited_dirs = ctx.visited_dirs = set()
423     d = os.path.join(ctx.curdir, directory)
424     if os.path.exists(d):
425         abspath = os.path.abspath(d)
426     else:
427         abspath = os.path.abspath(os.path.join(Utils.g_module.srcdir, directory))
428     ctxclass = ctx.__class__.__name__
429     key = ctxclass + ':' + abspath
430     if key in visited_dirs:
431         # already done it
432         return
433     visited_dirs.add(key)
434     relpath = os_path_relpath(abspath, ctx.curdir)
435     if ctxclass == 'Handler':
436         return ctx.sub_options(relpath)
437     if ctxclass == 'ConfigurationContext':
438         return ctx.sub_config(relpath)
439     if ctxclass == 'BuildContext':
440         return ctx.add_subdirs(relpath)
441     Logs.error('Unknown RECURSE context class', ctxclass)
442     raise
443 Options.Handler.RECURSE = RECURSE
444 Build.BuildContext.RECURSE = RECURSE
445
446
447 def CHECK_MAKEFLAGS(bld):
448     '''check for MAKEFLAGS environment variable in case we are being
449     called from a Makefile try to honor a few make command line flags'''
450     if not 'WAF_MAKE' in os.environ:
451         return
452     makeflags = os.environ.get('MAKEFLAGS')
453     jobs_set = False
454     # we need to use shlex.split to cope with the escaping of spaces
455     # in makeflags
456     for opt in shlex.split(makeflags):
457         # options can come either as -x or as x
458         if opt[0:2] == 'V=':
459             Options.options.verbose = Logs.verbose = int(opt[2:])
460             if Logs.verbose > 0:
461                 Logs.zones = ['runner']
462             if Logs.verbose > 2:
463                 Logs.zones = ['*']
464         elif opt[0].isupper() and opt.find('=') != -1:
465             loc = opt.find('=')
466             setattr(Options.options, opt[0:loc], opt[loc+1:])
467         elif opt[0] != '-':
468             for v in opt:
469                 if v == 'j':
470                     jobs_set = True
471                 elif v == 'k':
472                     Options.options.keep = True                
473         elif opt == '-j':
474             jobs_set = True
475         elif opt == '-k':
476             Options.options.keep = True                
477     if not jobs_set:
478         # default to one job
479         Options.options.jobs = 1
480             
481 Build.BuildContext.CHECK_MAKEFLAGS = CHECK_MAKEFLAGS
482
483 option_groups = {}
484
485 def option_group(opt, name):
486     '''find or create an option group'''
487     global option_groups
488     if name in option_groups:
489         return option_groups[name]
490     gr = opt.add_option_group(name)
491     option_groups[name] = gr
492     return gr
493 Options.Handler.option_group = option_group
494
495
496 def save_file(filename, contents, create_dir=False):
497     '''save data to a file'''
498     if create_dir:
499         mkdir_p(os.path.dirname(filename))
500     try:
501         f = open(filename, 'w')
502         f.write(contents)
503         f.close()
504     except:
505         return False
506     return True
507
508
509 def load_file(filename):
510     '''return contents of a file'''
511     try:
512         f = open(filename, 'r')
513         r = f.read()
514         f.close()
515     except:
516         return None
517     return r
518
519
520 def reconfigure(ctx):
521     '''rerun configure if necessary'''
522     import Configure, samba_wildcard, Scripting
523     if not os.path.exists(".lock-wscript"):
524         raise Utils.WafError('configure has not been run')
525     bld = samba_wildcard.fake_build_environment()
526     Configure.autoconfig = True
527     Scripting.check_configured(bld)