build: replace h_file when replacing md5
[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
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 install_rpath(bld):
64     '''the rpath value for installation'''
65     bld.env['RPATH'] = []
66     bld.env['RPATH_ST'] = []
67     if bld.env.RPATH_ON_INSTALL:
68         return ['-Wl,-rpath=%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     bld.env['RPATH_ST'] = []
77     if bld.env.RPATH_ON_BUILD:
78         return ['-Wl,-rpath=%s' % rpath]
79     os.environ['LD_LIBRARY_PATH'] = rpath
80     return []
81
82
83 #############################################################
84 # return a named build cache dictionary, used to store
85 # state inside the following functions
86 @conf
87 def LOCAL_CACHE(ctx, name):
88     if name in ctx.env:
89         return ctx.env[name]
90     ctx.env[name] = {}
91     return ctx.env[name]
92
93
94 #############################################################
95 # set a value in a local cache
96 @conf
97 def LOCAL_CACHE_SET(ctx, cachename, key, value):
98     cache = LOCAL_CACHE(ctx, cachename)
99     cache[key] = value
100
101 #############################################################
102 # a build assert call
103 @conf
104 def ASSERT(ctx, expression, msg):
105     if not expression:
106         sys.stderr.write("ERROR: %s\n" % msg)
107         raise AssertionError
108 Build.BuildContext.ASSERT = ASSERT
109
110 ################################################################
111 # create a list of files by pre-pending each with a subdir name
112 def SUBDIR(bld, subdir, list):
113     ret = ''
114     for l in TO_LIST(list):
115         ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
116     return ret
117 Build.BuildContext.SUBDIR = SUBDIR
118
119 #######################################################
120 # d1 += d2
121 def dict_concat(d1, d2):
122     for t in d2:
123         if t not in d1:
124             d1[t] = d2[t]
125
126 ############################################################
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 def exec_command(self, cmd, **kw):
131     import Utils, Logs
132     _cmd = cmd
133     if isinstance(cmd, list):
134         _cmd = ' '.join(cmd)
135     debug('runner: %s' % _cmd)
136     if self.log:
137         self.log.write('%s\n' % cmd)
138         kw['log'] = self.log
139     try:
140         if not kw.get('cwd', None):
141             kw['cwd'] = self.cwd
142     except AttributeError:
143         self.cwd = kw['cwd'] = self.bldnode.abspath()
144     return Utils.exec_command(cmd, **kw)
145 Build.BuildContext.exec_command = exec_command
146
147
148 ##########################################################
149 # add a new top level command to waf
150 def ADD_COMMAND(opt, name, function):
151     Utils.g_module.__dict__[name] = function
152     opt.name = function
153 Options.Handler.ADD_COMMAND = ADD_COMMAND
154
155
156 @feature('cc', 'cshlib', 'cprogram')
157 @before('apply_core','exec_rule')
158 def process_depends_on(self):
159     '''The new depends_on attribute for build rules
160        allow us to specify a dependency on output from
161        a source generation rule'''
162     if getattr(self , 'depends_on', None):
163         lst = self.to_list(self.depends_on)
164         for x in lst:
165             y = self.bld.name_to_obj(x, self.env)
166             self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
167             y.post()
168             if getattr(y, 'more_includes', None):
169                   self.includes += " " + y.more_includes
170
171
172 #@feature('cprogram', 'cc', 'cshlib')
173 #@before('apply_core')
174 #def process_generated_dependencies(self):
175 #    '''Ensure that any dependent source generation happens
176 #       before any task that requires the output'''
177 #    if getattr(self , 'depends_on', None):
178 #        lst = self.to_list(self.depends_on)
179 #        for x in lst:
180 #            y = self.bld.name_to_obj(x, self.env)
181 #            y.post()
182
183
184 #import TaskGen, Task
185 #
186 #old_post_run = Task.Task.post_run
187 #def new_post_run(self):
188 #    self.cached = True
189 #    return old_post_run(self)
190 #
191 #for y in ['cc', 'cxx']:
192 #    TaskGen.classes[y].post_run = new_post_run
193
194 def ENABLE_MAGIC_ORDERING(bld):
195     '''enable automatic build order constraint calculation
196        see page 35 of the waf book'''
197     print "NOT Enabling magic ordering"
198     #bld.use_the_magic()
199 Build.BuildContext.ENABLE_MAGIC_ORDERING = ENABLE_MAGIC_ORDERING
200
201
202 os_path_relpath = getattr(os.path, 'relpath', None)
203 if os_path_relpath is None:
204     # Python < 2.6 does not have os.path.relpath, provide a replacement
205     # (imported from Python2.6.5~rc2)
206     def os_path_relpath(path, start):
207         """Return a relative version of a path"""
208         start_list = os.path.abspath(start).split("/")
209         path_list = os.path.abspath(path).split("/")
210
211         # Work out how much of the filepath is shared by start and path.
212         i = len(os.path.commonprefix([start_list, path_list]))
213
214         rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
215         if not rel_list:
216             return start
217         return os.path.join(*rel_list)
218
219
220 # this is a useful way of debugging some of the rules in waf
221 from TaskGen import feature, after
222 @feature('dbg')
223 @after('apply_core', 'apply_obj_vars_cc')
224 def dbg(self):
225         if self.target == 'HEIMDAL_HEIM_ASN1':
226                 print "@@@@@@@@@@@@@@2", self.includes, self.env._CCINCFLAGS
227
228 def unique_list(seq):
229     '''return a uniquified list in the same order as the existing list'''
230     seen = {}
231     result = []
232     for item in seq:
233         if item in seen: continue
234         seen[item] = True
235         result.append(item)
236     return result
237
238 def TO_LIST(str):
239     '''Split a list, preserving quoted strings and existing lists'''
240     if str is None:
241         return []
242     if isinstance(str, list):
243         return str
244     lst = str.split()
245     # the string may have had quotes in it, now we
246     # check if we did have quotes, and use the slower shlex
247     # if we need to
248     for e in lst:
249         if e[0] == '"':
250             return shlex.split(str)
251     return lst
252
253 @conf
254 def SUBST_ENV_VAR(ctx, varname):
255     '''Substitute an environment variable for any embedded variables'''
256     return Utils.subst_vars(ctx.env[varname], ctx.env)
257 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
258
259
260 def ENFORCE_GROUP_ORDERING(bld):
261     '''enforce group ordering for the project. This
262        makes the group ordering apply only when you specify
263        a target with --target'''
264     if Options.options.compile_targets:
265         @feature('*')
266         def force_previous_groups(self):
267             my_id = id(self)
268
269             bld = self.bld
270             stop = None
271             for g in bld.task_manager.groups:
272                 for t in g.tasks_gen:
273                     if id(t) == my_id:
274                         stop = id(g)
275                         break
276                 if stop is None:
277                     return
278
279                 for g in bld.task_manager.groups:
280                     if id(g) == stop:
281                         break
282                     for t in g.tasks_gen:
283                         t.post()
284 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
285
286 # @feature('cc')
287 # @before('apply_lib_vars')
288 # def process_objects(self):
289 #     if getattr(self, 'add_objects', None):
290 #         lst = self.to_list(self.add_objects)
291 #         for x in lst:
292 #             y = self.name_to_obj(x)
293 #             if not y:
294 #                 raise Utils.WafError('object %r was not found in uselib_local (required by add_objects %r)' % (x, self.name))
295 #             y.post()
296 #             self.env.append_unique('INC_PATHS', y.env.INC_PATHS)
297
298
299 def recursive_dirlist(dir, relbase):
300     '''recursive directory list'''
301     ret = []
302     for f in os.listdir(dir):
303         f2 = dir + '/' + f
304         if os.path.isdir(f2):
305             ret.extend(recursive_dirlist(f2, relbase))
306         else:
307             ret.append(os_path_relpath(f2, relbase))
308     return ret
309
310
311 def mkdir_p(dir):
312     '''like mkdir -p'''
313     if os.path.isdir(dir):
314         return
315     mkdir_p(os.path.dirname(dir))
316     os.mkdir(dir)
317
318
319 def SUBST_VARS_RECURSIVE(string, env):
320     '''recursively expand variables'''
321     if string is None:
322         return string
323     limit=100
324     while (string.find('${') != -1 and limit > 0):
325         string = Utils.subst_vars(string, env)
326         limit -= 1
327     return string
328
329
330 def RUN_COMMAND(cmd,
331                 env=None,
332                 shell=False):
333     '''run a external command, return exit code or signal'''
334     if env:
335         cmd = SUBST_VARS_RECURSIVE(cmd, env)
336
337     status = os.system(cmd)
338     if os.WIFEXITED(status):
339         return os.WEXITSTATUS(status)
340     if os.WIFSIGNALED(status):
341         return - os.WTERMSIG(status)
342     print "Unknown exit reason %d for command: %s" (status, cmd)
343     return -1
344
345
346 # make sure we have md5. some systems don't have it
347 try:
348     from hashlib import md5
349 except:
350     try:
351         import md5
352     except:
353         import Constants
354         Constants.SIG_NIL = hash('abcd')
355         class replace_md5(object):
356             def __init__(self):
357                 self.val = None
358             def update(self, val):
359                 self.val = hash((self.val, val))
360             def digest(self):
361                 return str(self.val)
362             def hexdigest(self):
363                 return self.digest().encode('hex')
364         Utils.md5 = replace_md5
365         def h_file(filename):
366             f = open(filename, 'rb')
367             m = replace_md5()
368             while (filename):
369                 filename = f.read(100000)
370                 m.update(filename)
371             f.close()
372             return m.digest()