build: assert on missing dependency
[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, Logs, sys, Configure, Options, string, Task, Utils, optparse
5 from TaskGen import feature, before
6 from Configure import conf
7 from Logs import debug
8 from TaskGen import extension
9 import shlex
10
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     assumed = LOCAL_CACHE(ctx, 'ASSUMED_TARGET')
34     if target in assumed:
35         #if assumed[target] != value:
36         #    print "Target '%s' was assumed of type '%s' but is '%s'" % (target, assumed[target], value)
37         ASSERT(ctx, assumed[target] == value,
38                "Target '%s' was assumed of type '%s' but is '%s'" % (target, assumed[target], value))
39     predeclared = LOCAL_CACHE(ctx, 'PREDECLARED_TARGET')
40     if target in predeclared:
41         ASSERT(ctx, predeclared[target] == value,
42                "Target '%s' was predeclared of type '%s' but is '%s'" % (target, predeclared[target], value))
43     LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
44     debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.curdir))
45     return True
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
64 ################################################################
65 # magic rpath handling
66 #
67 # we want a different rpath when installing and when building
68 # Note that this should really check if rpath is available on this platform
69 # and it should also honor an --enable-rpath option
70 def set_rpath(bld):
71     if Options.is_install:
72         if bld.env['RPATH_ON_INSTALL']:
73             bld.env['RPATH'] = ['-Wl,-rpath=%s/lib' % bld.env.PREFIX]
74         else:
75             bld.env['RPATH'] = []
76     else:
77         rpath = os.path.normpath('%s/%s' % (bld.env['BUILD_DIRECTORY'], LIB_PATH))
78         bld.env.append_value('RPATH', '-Wl,-rpath=%s' % rpath)
79 Build.BuildContext.set_rpath = set_rpath
80
81
82 #############################################################
83 # return a named build cache dictionary, used to store
84 # state inside the following functions
85 @conf
86 def LOCAL_CACHE(ctx, name):
87     if name in ctx.env:
88         return ctx.env[name]
89     ctx.env[name] = {}
90     return ctx.env[name]
91
92
93 #############################################################
94 # set a value in a local cache
95 @conf
96 def LOCAL_CACHE_SET(ctx, cachename, key, value):
97     cache = LOCAL_CACHE(ctx, cachename)
98     cache[key] = value
99
100 #############################################################
101 # a build assert call
102 @conf
103 def ASSERT(ctx, expression, msg):
104     if not expression:
105         sys.stderr.write("ERROR: %s\n" % msg)
106         raise AssertionError
107 Build.BuildContext.ASSERT = ASSERT
108
109 ################################################################
110 # create a list of files by pre-pending each with a subdir name
111 def SUBDIR(bld, subdir, list):
112     ret = ''
113     for l in to_list(list):
114         ret = ret + subdir + '/' + l + ' '
115     return ret
116 Build.BuildContext.SUBDIR = SUBDIR
117
118 ##############################################
119 # remove .. elements from a path list
120 def NORMPATH(bld, ilist):
121     return " ".join([os.path.normpath(p) for p in to_list(ilist)])
122 Build.BuildContext.NORMPATH = NORMPATH
123
124 #######################################################
125 # d1 += d2
126 def dict_concat(d1, d2):
127     for t in d2:
128         if t not in d1:
129             d1[t] = d2[t]
130
131 ############################################################
132 # this overrides the 'waf -v' debug output to be in a nice
133 # unix like format instead of a python list.
134 # Thanks to ita on #waf for this
135 def exec_command(self, cmd, **kw):
136     import Utils, Logs
137     _cmd = cmd
138     if isinstance(cmd, list):
139         _cmd = ' '.join(cmd)
140     debug('runner: %s' % _cmd)
141     if self.log:
142         self.log.write('%s\n' % cmd)
143         kw['log'] = self.log
144     try:
145         if not kw.get('cwd', None):
146             kw['cwd'] = self.cwd
147     except AttributeError:
148         self.cwd = kw['cwd'] = self.bldnode.abspath()
149     return Utils.exec_command(cmd, **kw)
150 Build.BuildContext.exec_command = exec_command
151
152
153 ##########################################################
154 # add a new top level command to waf
155 def ADD_COMMAND(opt, name, function):
156     Utils.g_module.__dict__[name] = function
157     opt.name = function
158 Options.Handler.ADD_COMMAND = ADD_COMMAND
159
160
161 @feature('*')
162 @before('apply_core','exec_rule')
163 def process_depends_on(self):
164     '''The new depends_on attribute for build rules
165        allow us to specify a dependency on output from
166        a source generation rule'''
167     if getattr(self , 'depends_on', None):
168         lst = self.to_list(self.depends_on)
169         for x in lst:
170             y = self.bld.name_to_obj(x, self.env)
171             self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
172             y.post()
173             if getattr(y, 'more_includes', None):
174                   self.includes += " " + y.more_includes
175
176
177 #@feature('cprogram cc cshlib')
178 #@before('apply_core')
179 #def process_generated_dependencies(self):
180 #    '''Ensure that any dependent source generation happens
181 #       before any task that requires the output'''
182 #    if getattr(self , 'depends_on', None):
183 #        lst = self.to_list(self.depends_on)
184 #        for x in lst:
185 #            y = self.bld.name_to_obj(x, self.env)
186 #            y.post()
187
188
189 def FIND_TASKGEN(bld, name):
190     '''find a waf task generator given a target name'''
191     return bld.name_to_obj(name)
192 Build.BuildContext.FIND_TASKGEN = FIND_TASKGEN
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 def BUILD_PATH(bld, relpath):
214     '''return a relative build path, given a relative path
215        for example, if called in the source4/librpc directory, with the path
216        gen_ndr/tables.c, then it will return default/source4/gen_ndr/tables.c
217     '''
218
219     ret = os.path.normpath(os.path.join(os.path.relpath(bld.curdir, bld.env.TOPDIR), relpath))
220     ret = 'default/%s' % ret
221     return ret
222 Build.BuildContext.BUILD_PATH = BUILD_PATH
223
224
225 # this is a useful way of debugging some of the rules in waf
226 from TaskGen import feature, after
227 @feature('dbg')
228 @after('apply_core', 'apply_obj_vars_cc')
229 def dbg(self):
230         if self.target == 'HEIMDAL_HEIM_ASN1':
231                 print "@@@@@@@@@@@@@@2", self.includes, self.env._CCINCFLAGS
232
233
234 def to_list(str):
235     '''Split a list, preserving quoted strings and existing lists'''
236     if isinstance(str, list):
237         return str
238     return shlex.split(str)
239
240 @conf
241 def SUBST_ENV_VAR(conf, varname):
242     '''Substitute an environment variable for any embedded variables'''
243     return Utils.subst_vars(conf.env[varname], conf.env)
244
245
246 def ENFORCE_GROUP_ORDERING(bld):
247     '''enforce group ordering for the project. This
248        makes the group ordering apply even when you specify
249        a target with --target'''
250     if Options.options.compile_targets:
251         @feature('*')
252         def force_previous_groups(self):
253             my_id = id(self)
254
255             bld = self.bld
256             stop = None
257             for g in bld.task_manager.groups:
258                 for t in g.tasks_gen:
259                     if id(t) == my_id:
260                         stop = id(g)
261                         break
262                 if stop is None:
263                     return
264
265                 for g in bld.task_manager.groups:
266                     if id(g) == stop:
267                         break
268                     for t in g.tasks_gen:
269                         t.post()
270 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
271
272 # @feature('cc')
273 # @before('apply_lib_vars')
274 # def process_objects(self):
275 #     if getattr(self, 'add_objects', None):
276 #         lst = self.to_list(self.add_objects)
277 #         for x in lst:
278 #             y = self.name_to_obj(x)
279 #             if not y:
280 #                 raise Utils.WafError('object %r was not found in uselib_local (required by add_objects %r)' % (x, self.name))
281 #             y.post()
282 #             self.env.append_unique('INC_PATHS', y.env.INC_PATHS)
283