buildtools/wafsamba: adopt to waf 2.0.8
[samba.git] / buildtools / wafsamba / samba_waf18.py
1 # compatibility layer for building with more recent waf versions
2
3 import os, shlex, sys
4 from waflib import Build, Configure, Node, Utils, Options, Logs
5 from waflib import ConfigSet
6 from waflib.TaskGen import feature, after
7 from waflib.Configure import conf, ConfigurationContext
8
9 from waflib.Tools import bison, flex
10 sys.modules['bison'] = bison
11 sys.modules['flex'] = flex
12
13 for y in (Build.BuildContext, Build.CleanContext, Build.InstallContext, Build.UninstallContext, Build.ListContext):
14     class tmp(y):
15         variant = 'default'
16
17 def pre_build(self):
18     self.cwdx = self.bldnode.parent
19     self.cwd = self.cwdx.abspath()
20     self.bdir = self.bldnode.abspath()
21     return Build.BuildContext.old_pre_build(self)
22 Build.BuildContext.old_pre_build = Build.BuildContext.pre_build
23 Build.BuildContext.pre_build = pre_build
24
25 def abspath(self, env=None):
26     if env and hasattr(self, 'children'):
27         return self.get_bld().abspath()
28     return self.old_abspath()
29 Node.Node.old_abspath = Node.Node.abspath
30 Node.Node.abspath = abspath
31
32 def bldpath(self, env=None):
33     return self.abspath()
34     #return self.path_from(self.ctx.bldnode.parent)
35 Node.Node.bldpath = bldpath
36
37 def srcpath(self, env=None):
38     return self.abspath()
39     #return self.path_from(self.ctx.bldnode.parent)
40 Node.Node.srcpath = srcpath
41
42 def store_fast(self, filename):
43     file = open(filename, 'wb')
44     data = self.get_merged_dict()
45     try:
46         Build.cPickle.dump(data, file, -1)
47     finally:
48         file.close()
49 ConfigSet.ConfigSet.store_fast = store_fast
50
51 def load_fast(self, filename):
52     file = open(filename, 'rb')
53     try:
54         data = Build.cPickle.load(file)
55     finally:
56         file.close()
57     self.table.update(data)
58 ConfigSet.ConfigSet.load_fast = load_fast
59
60 @feature('c', 'cxx', 'd', 'asm', 'fc', 'includes')
61 @after('propagate_uselib_vars', 'process_source')
62 def apply_incpaths(self):
63     lst = self.to_incnodes(self.to_list(getattr(self, 'includes', [])) + self.env['INCLUDES'])
64     self.includes_nodes = lst
65     cwdx = getattr(self.bld, 'cwdx', self.bld.bldnode)
66     self.env['INCPATHS'] = [x.path_from(cwdx) for x in lst]
67
68 @conf
69 def define(self, key, val, quote=True, comment=None):
70    assert key and isinstance(key, str)
71
72    if val is True:
73            val = 1
74    elif val in (False, None):
75            val = 0
76
77    # waf 1.5
78    self.env[key] = val
79
80    if isinstance(val, int) or isinstance(val, float):
81            s = '%s=%s'
82    else:
83            s = quote and '%s="%s"' or '%s=%s'
84    app = s % (key, str(val))
85
86    ban = key + '='
87    lst = self.env.DEFINES
88    for x in lst:
89            if x.startswith(ban):
90                    lst[lst.index(x)] = app
91                    break
92    else:
93            self.env.append_value('DEFINES', app)
94
95    self.env.append_unique('define_key', key)
96
97 # compat15 removes this but we want to keep it
98 @conf
99 def undefine(self, key, from_env=True, comment=None):
100     assert key and isinstance(key, str)
101
102     ban = key + '='
103     self.env.DEFINES = [x for x in self.env.DEFINES if not x.startswith(ban)]
104     self.env.append_unique('define_key', key)
105     # waf 1.5
106     if from_env:
107         self.env[key] = ()
108
109 class ConfigurationContext(Configure.ConfigurationContext):
110     def init_dirs(self):
111         self.setenv('default')
112         self.env.merge_config_header = True
113         return super(ConfigurationContext, self).init_dirs()
114
115 def find_program_samba(self, *k, **kw):
116     kw['mandatory'] = False
117     ret = self.find_program_old(*k, **kw)
118     return ret
119 Configure.ConfigurationContext.find_program_old = Configure.ConfigurationContext.find_program
120 Configure.ConfigurationContext.find_program = find_program_samba
121
122 Build.BuildContext.ENFORCE_GROUP_ORDERING = Utils.nada
123 Build.BuildContext.AUTOCLEANUP_STALE_FILES = Utils.nada
124
125 @conf
126 def check(self, *k, **kw):
127     '''Override the waf defaults to inject --with-directory options'''
128
129     # match the configuration test with speficic options, for example:
130     # --with-libiconv -> Options.options.iconv_open -> "Checking for library iconv"
131     self.validate_c(kw)
132
133     additional_dirs = []
134     if 'msg' in kw:
135         msg = kw['msg']
136         for x in Options.OptionsContext.parser.parser.option_list:
137              if getattr(x, 'match', None) and msg in x.match:
138                  d = getattr(Options.options, x.dest, '')
139                  if d:
140                      additional_dirs.append(d)
141
142     # we add the additional dirs twice: once for the test data, and again if the compilation test suceeds below
143     def add_options_dir(dirs, env):
144         for x in dirs:
145              if not x in env.CPPPATH:
146                  env.CPPPATH = [os.path.join(x, 'include')] + env.CPPPATH
147              if not x in env.LIBPATH:
148                  env.LIBPATH = [os.path.join(x, 'lib')] + env.LIBPATH
149
150     add_options_dir(additional_dirs, kw['env'])
151
152     self.start_msg(kw['msg'], **kw)
153     ret = None
154     try:
155         ret = self.run_build(*k, **kw)
156     except self.errors.ConfigurationError:
157         self.end_msg(kw['errmsg'], 'YELLOW', **kw)
158         if Logs.verbose > 1:
159             raise
160         else:
161             self.fatal('The configuration failed')
162     else:
163         kw['success'] = ret
164         # success! time for brandy
165         add_options_dir(additional_dirs, self.env)
166
167     ret = self.post_check(*k, **kw)
168     if not ret:
169         self.end_msg(kw['errmsg'], 'YELLOW', **kw)
170         self.fatal('The configuration failed %r' % ret)
171     else:
172         self.end_msg(self.ret_msg(kw['okmsg'], kw), **kw)
173     return ret
174
175 @conf
176 def CHECK_LIBRARY_SUPPORT(conf, rpath=False, version_script=False, msg=None):
177     '''see if the platform supports building libraries'''
178
179     if msg is None:
180         if rpath:
181             msg = "rpath library support"
182         else:
183             msg = "building library support"
184
185     def build(bld):
186         lib_node = bld.srcnode.make_node('libdir/liblc1.c')
187         lib_node.parent.mkdir()
188         lib_node.write('int lib_func(void) { return 42; }\n', 'w')
189         main_node = bld.srcnode.make_node('main.c')
190         main_node.write('int main(void) {return !(lib_func() == 42);}', 'w')
191         linkflags = []
192         if version_script:
193             script = bld.srcnode.make_node('ldscript')
194             script.write('TEST_1.0A2 { global: *; };\n', 'w')
195             linkflags.append('-Wl,--version-script=%s' % script.abspath())
196         bld(features='c cshlib', source=lib_node, target='lib1', linkflags=linkflags, name='lib1')
197         o = bld(features='c cprogram', source=main_node, target='prog1', uselib_local='lib1')
198         if rpath:
199             o.rpath = [lib_node.parent.abspath()]
200         def run_app(self):
201              args = conf.SAMBA_CROSS_ARGS(msg=msg)
202              env = dict(os.environ)
203              env['LD_LIBRARY_PATH'] = self.inputs[0].parent.abspath() + os.pathsep + env.get('LD_LIBRARY_PATH', '')
204              self.generator.bld.cmd_and_log([self.inputs[0].abspath()] + args, env=env)
205         o.post()
206         bld(rule=run_app, source=o.link_task.outputs[0])
207
208     # ok, so it builds
209     try:
210         conf.check(build_fun=build, msg='Checking for %s' % msg)
211     except conf.errors.ConfigurationError:
212         return False
213     return True
214
215 @conf
216 def CHECK_NEED_LC(conf, msg):
217     '''check if we need -lc'''
218     def build(bld):
219         lib_node = bld.srcnode.make_node('libdir/liblc1.c')
220         lib_node.parent.mkdir()
221         lib_node.write('#include <stdio.h>\nint lib_func(void) { FILE *f = fopen("foo", "r");}\n', 'w')
222         bld(features='c cshlib', source=[lib_node], linkflags=conf.env.EXTRA_LDFLAGS, target='liblc')
223     try:
224         conf.check(build_fun=build, msg=msg, okmsg='-lc is unnecessary', errmsg='-lc is necessary')
225     except conf.errors.ConfigurationError:
226         return False
227     return True
228
229 # already implemented on "waf -v"
230 def order(bld, tgt_list):
231     return True
232 Build.BuildContext.check_group_ordering = order
233
234 @conf
235 def CHECK_CFG(self, *k, **kw):
236     if 'args' in kw:
237         kw['args'] = shlex.split(kw['args'])
238     if not 'mandatory' in kw:
239         kw['mandatory'] = False
240     kw['global_define'] = True
241     return self.check_cfg(*k, **kw)
242
243 def cmd_output(cmd, **kw):
244
245         silent = False
246         if 'silent' in kw:
247                 silent = kw['silent']
248                 del(kw['silent'])
249
250         if 'e' in kw:
251                 tmp = kw['e']
252                 del(kw['e'])
253                 kw['env'] = tmp
254
255         kw['shell'] = isinstance(cmd, str)
256         kw['stdout'] = Utils.subprocess.PIPE
257         if silent:
258                 kw['stderr'] = Utils.subprocess.PIPE
259
260         try:
261                 p = Utils.subprocess.Popen(cmd, **kw)
262                 output = p.communicate()[0]
263         except OSError as e:
264                 raise ValueError(str(e))
265
266         if p.returncode:
267                 if not silent:
268                         msg = "command execution failed: %s -> %r" % (cmd, str(output))
269                         raise ValueError(msg)
270                 output = ''
271         return output
272 Utils.cmd_output = cmd_output