build: try faster includes processing
[nivanova/samba-autobuild/.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 def SET_TARGET_TYPE(ctx, target, value):
27     cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
28     if target in cache:
29         ASSERT(ctx, cache[target] == value,
30                "Target '%s' re-defined as %s - was %s" % (target, value, cache[target]))
31         debug("task_gen: Skipping duplicate target %s (curdir=%s)" % (target, ctx.curdir))
32         return False
33     LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
34     debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.curdir))
35     return True
36
37 ######################################################
38 # this is used as a decorator to make functions only
39 # run once. Based on the idea from
40 # http://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values
41 runonce_ret = {}
42 def runonce(function):
43     def wrapper(*args):
44         if args in runonce_ret:
45             return runonce_ret[args]
46         else:
47             ret = function(*args)
48             runonce_ret[args] = ret
49             return ret
50     return wrapper
51
52
53
54 ################################################################
55 # magic rpath handling
56 #
57 # we want a different rpath when installing and when building
58 # Note that this should really check if rpath is available on this platform
59 # and it should also honor an --enable-rpath option
60 def set_rpath(bld):
61     if Options.is_install:
62         if bld.env['RPATH_ON_INSTALL']:
63             bld.env['RPATH'] = ['-Wl,-rpath=%s/lib' % bld.env.PREFIX]
64         else:
65             bld.env['RPATH'] = []
66     else:
67         rpath = os.path.normpath('%s/%s' % (bld.env['BUILD_DIRECTORY'], LIB_PATH))
68         bld.env.append_value('RPATH', '-Wl,-rpath=%s' % rpath)
69 Build.BuildContext.set_rpath = set_rpath
70
71
72 #############################################################
73 # return a named build cache dictionary, used to store
74 # state inside the following functions
75 @conf
76 def LOCAL_CACHE(ctx, name):
77     if name in ctx.env:
78         return ctx.env[name]
79     ctx.env[name] = {}
80     return ctx.env[name]
81
82
83 #############################################################
84 # set a value in a local cache
85 @conf
86 def LOCAL_CACHE_SET(ctx, cachename, key, value):
87     cache = LOCAL_CACHE(ctx, cachename)
88     cache[key] = value
89
90 #############################################################
91 # a build assert call
92 @conf
93 def ASSERT(ctx, expression, msg):
94     if not expression:
95         sys.stderr.write("ERROR: %s\n" % msg)
96         raise AssertionError
97 Build.BuildContext.ASSERT = ASSERT
98
99 ################################################################
100 # create a list of files by pre-pending each with a subdir name
101 def SUBDIR(bld, subdir, list):
102     ret = ''
103     for l in TO_LIST(list):
104         ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
105     return ret
106 Build.BuildContext.SUBDIR = SUBDIR
107
108 #######################################################
109 # d1 += d2
110 def dict_concat(d1, d2):
111     for t in d2:
112         if t not in d1:
113             d1[t] = d2[t]
114
115 ############################################################
116 # this overrides the 'waf -v' debug output to be in a nice
117 # unix like format instead of a python list.
118 # Thanks to ita on #waf for this
119 def exec_command(self, cmd, **kw):
120     import Utils, Logs
121     _cmd = cmd
122     if isinstance(cmd, list):
123         _cmd = ' '.join(cmd)
124     debug('runner: %s' % _cmd)
125     if self.log:
126         self.log.write('%s\n' % cmd)
127         kw['log'] = self.log
128     try:
129         if not kw.get('cwd', None):
130             kw['cwd'] = self.cwd
131     except AttributeError:
132         self.cwd = kw['cwd'] = self.bldnode.abspath()
133     return Utils.exec_command(cmd, **kw)
134 Build.BuildContext.exec_command = exec_command
135
136
137 ##########################################################
138 # add a new top level command to waf
139 def ADD_COMMAND(opt, name, function):
140     Utils.g_module.__dict__[name] = function
141     opt.name = function
142 Options.Handler.ADD_COMMAND = ADD_COMMAND
143
144
145 @feature('cc', 'cshlib', 'cprogram')
146 @before('apply_core','exec_rule')
147 def process_depends_on(self):
148     '''The new depends_on attribute for build rules
149        allow us to specify a dependency on output from
150        a source generation rule'''
151     if getattr(self , 'depends_on', None):
152         lst = self.to_list(self.depends_on)
153         for x in lst:
154             y = self.bld.name_to_obj(x, self.env)
155             self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
156             y.post()
157             if getattr(y, 'more_includes', None):
158                   self.includes += " " + y.more_includes
159
160
161 #@feature('cprogram', 'cc', 'cshlib')
162 #@before('apply_core')
163 #def process_generated_dependencies(self):
164 #    '''Ensure that any dependent source generation happens
165 #       before any task that requires the output'''
166 #    if getattr(self , 'depends_on', None):
167 #        lst = self.to_list(self.depends_on)
168 #        for x in lst:
169 #            y = self.bld.name_to_obj(x, self.env)
170 #            y.post()
171
172
173 #import TaskGen, Task
174 #
175 #old_post_run = Task.Task.post_run
176 #def new_post_run(self):
177 #    self.cached = True
178 #    return old_post_run(self)
179 #
180 #for y in ['cc', 'cxx']:
181 #    TaskGen.classes[y].post_run = new_post_run
182
183 def ENABLE_MAGIC_ORDERING(bld):
184     '''enable automatic build order constraint calculation
185        see page 35 of the waf book'''
186     print "NOT Enabling magic ordering"
187     #bld.use_the_magic()
188 Build.BuildContext.ENABLE_MAGIC_ORDERING = ENABLE_MAGIC_ORDERING
189
190
191 os_path_relpath = getattr(os.path, 'relpath', None)
192 if os_path_relpath is None:
193     # Python < 2.6 does not have os.path.relpath, provide a replacement
194     # (imported from Python2.6.5~rc2)
195     def os_path_relpath(path, start):
196         """Return a relative version of a path"""
197         start_list = os.path.abspath(start).split("/")
198         path_list = os.path.abspath(path).split("/")
199
200         # Work out how much of the filepath is shared by start and path.
201         i = len(os.path.commonprefix([start_list, path_list]))
202
203         rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
204         if not rel_list:
205             return start
206         return os.path.join(*rel_list)
207
208
209 # this is a useful way of debugging some of the rules in waf
210 from TaskGen import feature, after
211 @feature('dbg')
212 @after('apply_core', 'apply_obj_vars_cc')
213 def dbg(self):
214         if self.target == 'HEIMDAL_HEIM_ASN1':
215                 print "@@@@@@@@@@@@@@2", self.includes, self.env._CCINCFLAGS
216
217 def unique_list(seq):
218     '''return a uniquified list in the same order as the existing list'''
219     seen = {}
220     result = []
221     for item in seq:
222         if item in seen: continue
223         seen[item] = True
224         result.append(item)
225     return result
226
227 def TO_LIST(str):
228     '''Split a list, preserving quoted strings and existing lists'''
229     if isinstance(str, list):
230         return str
231     lst = str.split()
232     # the string may have had quotes in it, now we
233     # check if we did have quotes, and use the slower shlex
234     # if we need to
235     for e in lst:
236         if e[0] == '"':
237             return shlex.split(str)
238     return lst
239
240 @conf
241 def SUBST_ENV_VAR(ctx, varname):
242     '''Substitute an environment variable for any embedded variables'''
243     return Utils.subst_vars(ctx.env[varname], ctx.env)
244 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
245
246
247 def ENFORCE_GROUP_ORDERING(bld):
248     '''enforce group ordering for the project. This
249        makes the group ordering apply only when you specify
250        a target with --target'''
251     if Options.options.compile_targets:
252         @feature('*')
253         def force_previous_groups(self):
254             my_id = id(self)
255
256             bld = self.bld
257             stop = None
258             for g in bld.task_manager.groups:
259                 for t in g.tasks_gen:
260                     if id(t) == my_id:
261                         stop = id(g)
262                         break
263                 if stop is None:
264                     return
265
266                 for g in bld.task_manager.groups:
267                     if id(g) == stop:
268                         break
269                     for t in g.tasks_gen:
270                         t.post()
271 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
272
273 # @feature('cc')
274 # @before('apply_lib_vars')
275 # def process_objects(self):
276 #     if getattr(self, 'add_objects', None):
277 #         lst = self.to_list(self.add_objects)
278 #         for x in lst:
279 #             y = self.name_to_obj(x)
280 #             if not y:
281 #                 raise Utils.WafError('object %r was not found in uselib_local (required by add_objects %r)' % (x, self.name))
282 #             y.post()
283 #             self.env.append_unique('INC_PATHS', y.env.INC_PATHS)
284
285
286 def recursive_dirlist(dir, relbase):
287     '''recursive directory list'''
288     ret = []
289     for f in os.listdir(dir):
290         f2 = dir + '/' + f
291         if os.path.isdir(f2):
292             ret.extend(recursive_dirlist(f2, relbase))
293         else:
294             ret.append(os_path_relpath(f2, relbase))
295     return ret
296
297
298 def mkdir_p(dir):
299     '''like mkdir -p'''
300     if os.path.isdir(dir):
301         return
302     mkdir_p(os.path.dirname(dir))
303     os.mkdir(dir)