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