build: a useful example of a debug technique in waf
[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
10 LIB_PATH="shared"
11
12
13 ##########################################################
14 # create a node with a new name, based on an existing node
15 def NEW_NODE(node, name):
16     ret = node.parent.find_or_declare([name])
17     ASSERT(node, ret is not None, "Unable to find new target with name '%s' from '%s'" % (
18             name, node.name))
19     return ret
20
21
22 #############################################################
23 # set a value in a local cache
24 # return False if it's already set
25 def SET_TARGET_TYPE(ctx, target, value):
26     cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
27     if target in cache:
28         ASSERT(ctx, cache[target] == value,
29                "Target '%s' re-defined as %s - was %s" % (target, value, cache[target]))
30         debug("task_gen: Skipping duplicate target %s (curdir=%s)" % (target, ctx.curdir))
31         return False
32     assumed = LOCAL_CACHE(ctx, 'ASSUMED_TARGET')
33     if target in assumed:
34         #if assumed[target] != value:
35         #    print "Target '%s' was assumed of type '%s' but is '%s'" % (target, assumed[target], value)
36         ASSERT(ctx, assumed[target] == value,
37                "Target '%s' was assumed of type '%s' but is '%s'" % (target, assumed[target], value))
38     predeclared = LOCAL_CACHE(ctx, 'PREDECLARED_TARGET')
39     if target in predeclared:
40         ASSERT(ctx, predeclared[target] == value,
41                "Target '%s' was predeclared of type '%s' but is '%s'" % (target, predeclared[target], value))
42     LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
43     debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.curdir))
44     return True
45
46 ######################################################
47 # this is used as a decorator to make functions only
48 # run once. Based on the idea from
49 # http://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values
50 runonce_ret = {}
51 def runonce(function):
52     def wrapper(*args):
53         if args in runonce_ret:
54             return runonce_ret[args]
55         else:
56             ret = function(*args)
57             runonce_ret[args] = ret
58             return ret
59     return wrapper
60
61
62
63 ################################################################
64 # magic rpath handling
65 #
66 # we want a different rpath when installing and when building
67 # Note that this should really check if rpath is available on this platform
68 # and it should also honor an --enable-rpath option
69 def set_rpath(bld):
70     if Options.is_install:
71         if bld.env['RPATH_ON_INSTALL']:
72             bld.env['RPATH'] = ['-Wl,-rpath=%s/lib' % bld.env.PREFIX]
73         else:
74             bld.env['RPATH'] = []
75     else:
76         rpath = os.path.normpath('%s/%s' % (bld.env['BUILD_DIRECTORY'], LIB_PATH))
77         bld.env.append_value('RPATH', '-Wl,-rpath=%s' % rpath)
78 Build.BuildContext.set_rpath = set_rpath
79
80
81 #############################################################
82 # return a named build cache dictionary, used to store
83 # state inside the following functions
84 @conf
85 def LOCAL_CACHE(ctx, name):
86     if name in ctx.env:
87         return ctx.env[name]
88     ctx.env[name] = {}
89     return ctx.env[name]
90
91
92 #############################################################
93 # set a value in a local cache
94 @conf
95 def LOCAL_CACHE_SET(ctx, cachename, key, value):
96     cache = LOCAL_CACHE(ctx, cachename)
97     cache[key] = value
98
99 #############################################################
100 # a build assert call
101 @conf
102 def ASSERT(ctx, expression, msg):
103     if not expression:
104         sys.stderr.write("ERROR: %s\n" % msg)
105         raise AssertionError
106 Build.BuildContext.ASSERT = ASSERT
107
108 ################################################################
109 # create a list of files by pre-pending each with a subdir name
110 def SUBDIR(bld, subdir, list):
111     ret = ''
112     for l in list.split():
113         ret = ret + subdir + '/' + l + ' '
114     return ret
115 Build.BuildContext.SUBDIR = SUBDIR
116
117 ##############################################
118 # remove .. elements from a path list
119 def NORMPATH(bld, ilist):
120     return " ".join([os.path.normpath(p) for p in ilist.split(" ")])
121 Build.BuildContext.NORMPATH = NORMPATH
122
123 #######################################################
124 # d1 += d2
125 def dict_concat(d1, d2):
126     for t in d2:
127         if t not in d1:
128             d1[t] = d2[t]
129
130 ############################################################
131 # this overrides the 'waf -v' debug output to be in a nice
132 # unix like format instead of a python list.
133 # Thanks to ita on #waf for this
134 def exec_command(self, cmd, **kw):
135     import Utils, Logs
136     _cmd = cmd
137     if isinstance(cmd, list):
138         _cmd = ' '.join(cmd)
139     debug('runner: %s' % _cmd)
140     if self.log:
141         self.log.write('%s\n' % cmd)
142         kw['log'] = self.log
143     try:
144         if not kw.get('cwd', None):
145             kw['cwd'] = self.cwd
146     except AttributeError:
147         self.cwd = kw['cwd'] = self.bldnode.abspath()
148     return Utils.exec_command(cmd, **kw)
149 Build.BuildContext.exec_command = exec_command
150
151
152 ##########################################################
153 # add a new top level command to waf
154 def ADD_COMMAND(opt, name, function):
155     Utils.g_module.__dict__[name] = function
156     opt.name = function
157 Options.Handler.ADD_COMMAND = ADD_COMMAND
158
159
160 @feature('*')
161 @before('apply_core','exec_rule')
162 def process_depends_on(self):
163     '''The new depends_on attribute for build rules
164        allow us to specify a dependency on output from
165        a source generation rule'''
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             if getattr(y, 'more_includes', None):
173                   self.includes += " " + y.more_includes
174
175
176 #@feature('cprogram cc cshlib')
177 #@before('apply_core')
178 #def process_generated_dependencies(self):
179 #    '''Ensure that any dependent source generation happens
180 #       before any task that requires the output'''
181 #    if getattr(self , 'depends_on', None):
182 #        lst = self.to_list(self.depends_on)
183 #        for x in lst:
184 #            y = self.bld.name_to_obj(x, self.env)
185 #            y.post()
186
187
188 def FIND_TASKGEN(bld, name):
189     '''find a waf task generator given a target name'''
190     return bld.name_to_obj(name)
191 Build.BuildContext.FIND_TASKGEN = FIND_TASKGEN
192
193
194 #import TaskGen, Task
195 #
196 #old_post_run = Task.Task.post_run
197 #def new_post_run(self):
198 #    self.cached = True
199 #    return old_post_run(self)
200 #
201 #for y in ['cc', 'cxx']:
202 #    TaskGen.classes[y].post_run = new_post_run
203
204 def ENABLE_MAGIC_ORDERING(bld):
205     '''enable automatic build order constraint calculation
206        see page 35 of the waf book'''
207     print "NOT Enabling magic ordering"
208     #bld.use_the_magic()
209 Build.BuildContext.ENABLE_MAGIC_ORDERING = ENABLE_MAGIC_ORDERING
210
211
212 def BUILD_PATH(bld, relpath):
213     '''return a relative build path, given a relative path
214        for example, if called in the source4/librpc directory, with the path
215        gen_ndr/tables.c, then it will return default/source4/gen_ndr/tables.c
216     '''
217
218     ret = os.path.normpath(os.path.join(os.path.relpath(bld.curdir, bld.env.TOPDIR), relpath))
219     ret = 'default/%s' % ret
220     return ret
221 Build.BuildContext.BUILD_PATH = BUILD_PATH
222
223
224 # this is a useful way of debugging some of the rules in waf
225 from TaskGen import feature, after
226 @feature('dbg')
227 @after('apply_core', 'apply_obj_vars_cc')
228 def dbg(self):
229         if self.target == 'HEIMDAL_HEIM_ASN1':
230                 print "@@@@@@@@@@@@@@2", self.includes, self.env._CCINCFLAGS
231