build: throw an error on all bad variable substitutions
[abartlet/samba.git/.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
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 ##########################################################
15 # create a node with a new name, based on an existing node
16 def NEW_NODE(node, name):
17     ret = node.parent.find_or_declare([name])
18     ASSERT(node, ret is not None, "Unable to find new target with name '%s' from '%s'" % (
19             name, node.name))
20     return ret
21
22
23 #############################################################
24 # set a value in a local cache
25 # return False if it's already set
26 @conf
27 def SET_TARGET_TYPE(ctx, target, value):
28     cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
29     if target in cache:
30         ASSERT(ctx, cache[target] == value,
31                "Target '%s' re-defined as %s - was %s" % (target, value, cache[target]))
32         debug("task_gen: Skipping duplicate target %s (curdir=%s)" % (target, ctx.curdir))
33         return False
34     LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
35     debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.curdir))
36     return True
37
38
39 def GET_TARGET_TYPE(ctx, target):
40     '''get target type from cache'''
41     cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
42     if not target in cache:
43         return None
44     return cache[target]
45
46
47 ######################################################
48 # this is used as a decorator to make functions only
49 # run once. Based on the idea from
50 # http://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values
51 runonce_ret = {}
52 def runonce(function):
53     def wrapper(*args):
54         if args in runonce_ret:
55             return runonce_ret[args]
56         else:
57             ret = function(*args)
58             runonce_ret[args] = ret
59             return ret
60     return wrapper
61
62
63 def ADD_LD_LIBRARY_PATH(path):
64     '''add something to LD_LIBRARY_PATH'''
65     if 'LD_LIBRARY_PATH' in os.environ:
66         oldpath = os.environ['LD_LIBRARY_PATH']
67     else:
68         oldpath = ''
69     newpath = oldpath.split(':')
70     if not path in newpath:
71         newpath.append(path)
72         os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
73
74 def install_rpath(bld):
75     '''the rpath value for installation'''
76     bld.env['RPATH'] = []
77     bld.env['RPATH_ST'] = []
78     if bld.env.RPATH_ON_INSTALL:
79         return ['-Wl,-rpath=%s/lib' % bld.env.PREFIX]
80     return []
81
82
83 def build_rpath(bld):
84     '''the rpath value for build'''
85     rpath = os.path.normpath('%s/%s' % (bld.env['BUILD_DIRECTORY'], LIB_PATH))
86     bld.env['RPATH'] = []
87     bld.env['RPATH_ST'] = []
88     if bld.env.RPATH_ON_BUILD:
89         return ['-Wl,-rpath=%s' % rpath]
90     ADD_LD_LIBRARY_PATH(rpath)
91     return []
92
93
94 #############################################################
95 # return a named build cache dictionary, used to store
96 # state inside the following functions
97 @conf
98 def LOCAL_CACHE(ctx, name):
99     if name in ctx.env:
100         return ctx.env[name]
101     ctx.env[name] = {}
102     return ctx.env[name]
103
104
105 #############################################################
106 # set a value in a local cache
107 @conf
108 def LOCAL_CACHE_SET(ctx, cachename, key, value):
109     cache = LOCAL_CACHE(ctx, cachename)
110     cache[key] = value
111
112 #############################################################
113 # a build assert call
114 @conf
115 def ASSERT(ctx, expression, msg):
116     if not expression:
117         sys.stderr.write("ERROR: %s\n" % msg)
118         raise AssertionError
119 Build.BuildContext.ASSERT = ASSERT
120
121 ################################################################
122 # create a list of files by pre-pending each with a subdir name
123 def SUBDIR(bld, subdir, list):
124     ret = ''
125     for l in TO_LIST(list):
126         ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
127     return ret
128 Build.BuildContext.SUBDIR = SUBDIR
129
130 #######################################################
131 # d1 += d2
132 def dict_concat(d1, d2):
133     for t in d2:
134         if t not in d1:
135             d1[t] = d2[t]
136
137 ############################################################
138 # this overrides the 'waf -v' debug output to be in a nice
139 # unix like format instead of a python list.
140 # Thanks to ita on #waf for this
141 def exec_command(self, cmd, **kw):
142     import Utils, Logs
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
157
158
159 ##########################################################
160 # add a new top level command to waf
161 def ADD_COMMAND(opt, name, function):
162     Utils.g_module.__dict__[name] = function
163     opt.name = function
164 Options.Handler.ADD_COMMAND = ADD_COMMAND
165
166
167 @feature('cc', 'cshlib', 'cprogram')
168 @before('apply_core','exec_rule')
169 def process_depends_on(self):
170     '''The new depends_on attribute for build rules
171        allow us to specify a dependency on output from
172        a source generation rule'''
173     if getattr(self , 'depends_on', None):
174         lst = self.to_list(self.depends_on)
175         for x in lst:
176             y = self.bld.name_to_obj(x, self.env)
177             self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
178             y.post()
179             if getattr(y, 'more_includes', None):
180                   self.includes += " " + y.more_includes
181
182
183 #@feature('cprogram', 'cc', 'cshlib')
184 #@before('apply_core')
185 #def process_generated_dependencies(self):
186 #    '''Ensure that any dependent source generation happens
187 #       before any task that requires the output'''
188 #    if getattr(self , 'depends_on', None):
189 #        lst = self.to_list(self.depends_on)
190 #        for x in lst:
191 #            y = self.bld.name_to_obj(x, self.env)
192 #            y.post()
193
194
195 #import TaskGen, Task
196 #
197 #old_post_run = Task.Task.post_run
198 #def new_post_run(self):
199 #    self.cached = True
200 #    return old_post_run(self)
201 #
202 #for y in ['cc', 'cxx']:
203 #    TaskGen.classes[y].post_run = new_post_run
204
205 def ENABLE_MAGIC_ORDERING(bld):
206     '''enable automatic build order constraint calculation
207        see page 35 of the waf book'''
208     print "NOT Enabling magic ordering"
209     #bld.use_the_magic()
210 Build.BuildContext.ENABLE_MAGIC_ORDERING = ENABLE_MAGIC_ORDERING
211
212
213 os_path_relpath = getattr(os.path, 'relpath', None)
214 if os_path_relpath is None:
215     # Python < 2.6 does not have os.path.relpath, provide a replacement
216     # (imported from Python2.6.5~rc2)
217     def os_path_relpath(path, start):
218         """Return a relative version of a path"""
219         start_list = os.path.abspath(start).split("/")
220         path_list = os.path.abspath(path).split("/")
221
222         # Work out how much of the filepath is shared by start and path.
223         i = len(os.path.commonprefix([start_list, path_list]))
224
225         rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
226         if not rel_list:
227             return start
228         return os.path.join(*rel_list)
229
230
231 def unique_list(seq):
232     '''return a uniquified list in the same order as the existing list'''
233     seen = {}
234     result = []
235     for item in seq:
236         if item in seen: continue
237         seen[item] = True
238         result.append(item)
239     return result
240
241 def TO_LIST(str):
242     '''Split a list, preserving quoted strings and existing lists'''
243     if str is None:
244         return []
245     if isinstance(str, list):
246         return str
247     lst = str.split()
248     # the string may have had quotes in it, now we
249     # check if we did have quotes, and use the slower shlex
250     # if we need to
251     for e in lst:
252         if e[0] == '"':
253             return shlex.split(str)
254     return lst
255
256
257 def subst_vars_error(string, env):
258     '''substitute vars, throw an error if a variable is not defined'''
259     lst = re.split('(\$\{\w+\})', string)
260     out = []
261     for v in lst:
262         if re.match('\$\{\w+\}', v):
263             vname = v[2:-1]
264             if not vname in env:
265                 print "Failed to find variable %s in %s" % (vname, string)
266                 raise
267             v = env[vname]
268         out.append(v)
269     return ''.join(out)
270
271 @conf
272 def SUBST_ENV_VAR(ctx, varname):
273     '''Substitute an environment variable for any embedded variables'''
274     return subst_vars_error(ctx.env[varname], ctx.env)
275 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
276
277
278 def ENFORCE_GROUP_ORDERING(bld):
279     '''enforce group ordering for the project. This
280        makes the group ordering apply only when you specify
281        a target with --target'''
282     if Options.options.compile_targets:
283         @feature('*')
284         def force_previous_groups(self):
285             my_id = id(self)
286
287             bld = self.bld
288             stop = None
289             for g in bld.task_manager.groups:
290                 for t in g.tasks_gen:
291                     if id(t) == my_id:
292                         stop = id(g)
293                         break
294                 if stop is None:
295                     return
296
297                 for g in bld.task_manager.groups:
298                     if id(g) == stop:
299                         break
300                     for t in g.tasks_gen:
301                         t.post()
302 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
303
304 # @feature('cc')
305 # @before('apply_lib_vars')
306 # def process_objects(self):
307 #     if getattr(self, 'add_objects', None):
308 #         lst = self.to_list(self.add_objects)
309 #         for x in lst:
310 #             y = self.name_to_obj(x)
311 #             if not y:
312 #                 raise Utils.WafError('object %r was not found in uselib_local (required by add_objects %r)' % (x, self.name))
313 #             y.post()
314 #             self.env.append_unique('INC_PATHS', y.env.INC_PATHS)
315
316
317 def recursive_dirlist(dir, relbase):
318     '''recursive directory list'''
319     ret = []
320     for f in os.listdir(dir):
321         f2 = dir + '/' + f
322         if os.path.isdir(f2):
323             ret.extend(recursive_dirlist(f2, relbase))
324         else:
325             ret.append(os_path_relpath(f2, relbase))
326     return ret
327
328
329 def mkdir_p(dir):
330     '''like mkdir -p'''
331     if os.path.isdir(dir):
332         return
333     mkdir_p(os.path.dirname(dir))
334     os.mkdir(dir)
335
336 def SUBST_VARS_RECURSIVE(string, env):
337     '''recursively expand variables'''
338     if string is None:
339         return string
340     limit=100
341     while (string.find('${') != -1 and limit > 0):
342         string = subst_vars_error(string, env)
343         limit -= 1
344     return string
345
346 @conf
347 def EXPAND_VARIABLES(ctx, varstr, vars=None):
348     '''expand variables from a user supplied dictionary
349
350     This is most useful when you pass vars=locals() to expand
351     all your local variables in strings
352     '''
353
354     if isinstance(varstr, list):
355         ret = []
356         for s in varstr:
357             ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
358         return ret
359
360     import Environment
361     env = Environment.Environment()
362     ret = varstr
363     # substitute on user supplied dict if avaiilable
364     if vars is not None:
365         for v in vars.keys():
366             env[v] = vars[v]
367         ret = SUBST_VARS_RECURSIVE(ret, env)
368
369     # if anything left, subst on the environment as well
370     if ret.find('${') != -1:
371         ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
372     # make sure there is nothing left. Also check for the common
373     # typo of $( instead of ${
374     if ret.find('${') != -1 or ret.find('$(') != -1:
375         print('Failed to substitute all variables in varstr=%s' % ret)
376         raise
377     return ret
378 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
379
380
381 def RUN_COMMAND(cmd,
382                 env=None,
383                 shell=False):
384     '''run a external command, return exit code or signal'''
385     if env:
386         cmd = SUBST_VARS_RECURSIVE(cmd, env)
387
388     status = os.system(cmd)
389     if os.WIFEXITED(status):
390         return os.WEXITSTATUS(status)
391     if os.WIFSIGNALED(status):
392         return - os.WTERMSIG(status)
393     print "Unknown exit reason %d for command: %s" (status, cmd)
394     return -1
395
396
397 # make sure we have md5. some systems don't have it
398 try:
399     from hashlib import md5
400 except:
401     try:
402         import md5
403     except:
404         import Constants
405         Constants.SIG_NIL = hash('abcd')
406         class replace_md5(object):
407             def __init__(self):
408                 self.val = None
409             def update(self, val):
410                 self.val = hash((self.val, val))
411             def digest(self):
412                 return str(self.val)
413             def hexdigest(self):
414                 return self.digest().encode('hex')
415         def replace_h_file(filename):
416             f = open(filename, 'rb')
417             m = replace_md5()
418             while (filename):
419                 filename = f.read(100000)
420                 m.update(filename)
421             f.close()
422             return m.digest()
423         Utils.md5 = replace_md5
424         Task.md5 = replace_md5
425         Utils.h_file = replace_h_file
426