1 # compatibility layer for building with more recent waf versions
4 from waflib import Build, Configure, Node, Utils, Options, Logs, TaskGen
5 from waflib import ConfigSet
6 from waflib.TaskGen import feature, after
7 from waflib.Configure import conf, ConfigurationContext
9 from waflib.Tools.flex import decide_ext
11 # This version of flexfun runs in tsk.get_cwd() as opposed to the
12 # bld.variant_dir: since input paths adjusted against tsk.get_cwd(), we have to
13 # use tsk.get_cwd() for the work directory as well.
16 bld = tsk.generator.bld
18 if isinstance(xx, str):
21 tsk.last_cmd = lst = []
22 lst.extend(to_list(env.FLEX))
23 lst.extend(to_list(env.FLEXFLAGS))
24 inputs = [a.path_from(tsk.get_cwd()) for a in tsk.inputs]
26 inputs = [x.replace(os.sep, '/') for x in inputs]
28 lst = [x for x in lst if x]
29 txt = bld.cmd_and_log(lst, cwd=tsk.get_cwd(), env=env.env or None, quiet=0)
30 tsk.outputs[0].write(txt.replace('\r\n', '\n').replace('\r', '\n')) # issue #1207
32 TaskGen.declare_chain(
34 rule = flexfun, # issue #854
40 for y in (Build.BuildContext, Build.CleanContext, Build.InstallContext, Build.UninstallContext, Build.ListContext):
45 self.cwdx = self.bldnode.parent
46 self.cwd = self.cwdx.abspath()
47 self.bdir = self.bldnode.abspath()
48 return Build.BuildContext.old_pre_build(self)
49 Build.BuildContext.old_pre_build = Build.BuildContext.pre_build
50 Build.BuildContext.pre_build = pre_build
52 def abspath(self, env=None):
53 if env and hasattr(self, 'children'):
54 return self.get_bld().abspath()
55 return self.old_abspath()
56 Node.Node.old_abspath = Node.Node.abspath
57 Node.Node.abspath = abspath
59 def bldpath(self, env=None):
61 #return self.path_from(self.ctx.bldnode.parent)
62 Node.Node.bldpath = bldpath
64 def srcpath(self, env=None):
66 #return self.path_from(self.ctx.bldnode.parent)
67 Node.Node.srcpath = srcpath
69 def store_fast(self, filename):
70 file = open(filename, 'wb')
71 data = self.get_merged_dict()
73 Build.cPickle.dump(data, file, -1)
76 ConfigSet.ConfigSet.store_fast = store_fast
78 def load_fast(self, filename):
79 file = open(filename, 'rb')
81 data = Build.cPickle.load(file)
84 self.table.update(data)
85 ConfigSet.ConfigSet.load_fast = load_fast
87 @feature('c', 'cxx', 'd', 'asm', 'fc', 'includes')
88 @after('propagate_uselib_vars', 'process_source')
89 def apply_incpaths(self):
90 lst = self.to_incnodes(self.to_list(getattr(self, 'includes', [])) + self.env['INCLUDES'])
91 self.includes_nodes = lst
92 cwdx = getattr(self.bld, 'cwdx', self.bld.bldnode)
93 self.env['INCPATHS'] = [x.path_from(cwdx) for x in lst]
96 def define(self, key, val, quote=True, comment=None):
97 assert key and isinstance(key, str)
101 elif isinstance(val, bool):
107 if isinstance(val, int) or isinstance(val, float):
110 s = quote and '%s="%s"' or '%s=%s'
111 app = s % (key, str(val))
114 lst = self.env.DEFINES
116 if x.startswith(ban):
117 lst[lst.index(x)] = app
120 self.env.append_value('DEFINES', app)
122 self.env.append_unique('define_key', key)
124 # compat15 removes this but we want to keep it
126 def undefine(self, key, from_env=True, comment=None):
127 assert key and isinstance(key, str)
130 self.env.DEFINES = [x for x in self.env.DEFINES if not x.startswith(ban)]
131 self.env.append_unique('define_key', key)
136 class ConfigurationContext(Configure.ConfigurationContext):
138 self.setenv('default')
139 self.env.merge_config_header = True
140 return super(ConfigurationContext, self).init_dirs()
142 def find_program_samba(self, *k, **kw):
143 kw['mandatory'] = False
144 ret = self.find_program_old(*k, **kw)
146 Configure.ConfigurationContext.find_program_old = Configure.ConfigurationContext.find_program
147 Configure.ConfigurationContext.find_program = find_program_samba
149 Build.BuildContext.ENFORCE_GROUP_ORDERING = Utils.nada
150 Build.BuildContext.AUTOCLEANUP_STALE_FILES = Utils.nada
153 def check(self, *k, **kw):
154 '''Override the waf defaults to inject --with-directory options'''
156 # match the configuration test with speficic options, for example:
157 # --with-libiconv -> Options.options.iconv_open -> "Checking for library iconv"
163 for x in Options.OptionsContext.parser.parser.option_list:
164 if getattr(x, 'match', None) and msg in x.match:
165 d = getattr(Options.options, x.dest, '')
167 additional_dirs.append(d)
169 # we add the additional dirs twice: once for the test data, and again if the compilation test suceeds below
170 def add_options_dir(dirs, env):
172 if not x in env.CPPPATH:
173 env.CPPPATH = [os.path.join(x, 'include')] + env.CPPPATH
174 if not x in env.LIBPATH:
175 env.LIBPATH = [os.path.join(x, 'lib')] + env.LIBPATH
177 add_options_dir(additional_dirs, kw['env'])
179 self.start_msg(kw['msg'], **kw)
182 ret = self.run_build(*k, **kw)
183 except self.errors.ConfigurationError:
184 self.end_msg(kw['errmsg'], 'YELLOW', **kw)
188 self.fatal('The configuration failed')
191 # success! time for brandy
192 add_options_dir(additional_dirs, self.env)
194 ret = self.post_check(*k, **kw)
196 self.end_msg(kw['errmsg'], 'YELLOW', **kw)
197 self.fatal('The configuration failed %r' % ret)
199 self.end_msg(self.ret_msg(kw['okmsg'], kw), **kw)
203 def CHECK_LIBRARY_SUPPORT(conf, rpath=False, version_script=False, msg=None):
204 '''see if the platform supports building libraries'''
208 msg = "rpath library support"
210 msg = "building library support"
213 lib_node = bld.srcnode.make_node('libdir/liblc1.c')
214 lib_node.parent.mkdir()
215 lib_node.write('int lib_func(void) { return 42; }\n', 'w')
216 main_node = bld.srcnode.make_node('main.c')
217 main_node.write('int main(void) {return !(lib_func() == 42);}', 'w')
220 script = bld.srcnode.make_node('ldscript')
221 script.write('TEST_1.0A2 { global: *; };\n', 'w')
222 linkflags.append('-Wl,--version-script=%s' % script.abspath())
223 bld(features='c cshlib', source=lib_node, target='lib1', linkflags=linkflags, name='lib1')
224 o = bld(features='c cprogram', source=main_node, target='prog1', uselib_local='lib1')
226 o.rpath = [lib_node.parent.abspath()]
228 args = conf.SAMBA_CROSS_ARGS(msg=msg)
229 env = dict(os.environ)
230 env['LD_LIBRARY_PATH'] = self.inputs[0].parent.abspath() + os.pathsep + env.get('LD_LIBRARY_PATH', '')
231 self.generator.bld.cmd_and_log([self.inputs[0].abspath()] + args, env=env)
233 bld(rule=run_app, source=o.link_task.outputs[0])
237 conf.check(build_fun=build, msg='Checking for %s' % msg)
238 except conf.errors.ConfigurationError:
243 def CHECK_NEED_LC(conf, msg):
244 '''check if we need -lc'''
246 lib_node = bld.srcnode.make_node('libdir/liblc1.c')
247 lib_node.parent.mkdir()
248 lib_node.write('#include <stdio.h>\nint lib_func(void) { FILE *f = fopen("foo", "r");}\n', 'w')
249 bld(features='c cshlib', source=[lib_node], linkflags=conf.env.EXTRA_LDFLAGS, target='liblc')
251 conf.check(build_fun=build, msg=msg, okmsg='-lc is unnecessary', errmsg='-lc is necessary')
252 except conf.errors.ConfigurationError:
256 # already implemented on "waf -v"
257 def order(bld, tgt_list):
259 Build.BuildContext.check_group_ordering = order
262 def CHECK_CFG(self, *k, **kw):
264 kw['args'] = shlex.split(kw['args'])
265 if not 'mandatory' in kw:
266 kw['mandatory'] = False
267 kw['global_define'] = True
268 return self.check_cfg(*k, **kw)
270 def cmd_output(cmd, **kw):
274 silent = kw['silent']
282 kw['shell'] = isinstance(cmd, str)
283 kw['stdout'] = Utils.subprocess.PIPE
285 kw['stderr'] = Utils.subprocess.PIPE
288 p = Utils.subprocess.Popen(cmd, **kw)
289 output = p.communicate()[0]
291 raise ValueError(str(e))
295 msg = "command execution failed: %s -> %r" % (cmd, str(output))
296 raise ValueError(msg)
299 Utils.cmd_output = cmd_output
302 @TaskGen.feature('c', 'cxx', 'd')
303 @TaskGen.before('apply_incpaths', 'propagate_uselib_vars')
304 @TaskGen.after('apply_link', 'process_source')
305 def apply_uselib_local(self):
307 process the uselib_local attribute
308 execute after apply_link because of the execution order set on 'link_task'
311 from waflib.Tools.ccroot import stlink_task
313 # 1. the case of the libs defined in the project (visit ancestors first)
314 # the ancestors external libraries (uselib) will be prepended
315 self.uselib = self.to_list(getattr(self, 'uselib', []))
316 self.includes = self.to_list(getattr(self, 'includes', []))
317 names = self.to_list(getattr(self, 'uselib_local', []))
318 get = self.bld.get_tgen_by_name
321 tmp = Utils.deque(names) # consume a copy of the list of names
324 Logs.warn('compat: "uselib_local" is deprecated, replace by "use"')
326 lib_name = tmp.popleft()
327 # visit dependencies only once
335 # object has ancestors to process (shared libraries): add them to the end of the list
336 if getattr(y, 'uselib_local', None):
337 for x in self.to_list(getattr(y, 'uselib_local', [])):
340 if getattr(obj, 'link_task', None):
341 if not isinstance(obj.link_task, stlink_task):
344 # link task and flags
345 if getattr(y, 'link_task', None):
347 link_name = y.target[y.target.rfind(os.sep) + 1:]
348 if isinstance(y.link_task, stlink_task):
349 env.append_value('STLIB', [link_name])
351 # some linkers can link against programs
352 env.append_value('LIB', [link_name])
355 self.link_task.set_run_after(y.link_task)
357 # for the recompilation
358 self.link_task.dep_nodes += y.link_task.outputs
360 # add the link path too
361 tmp_path = y.link_task.outputs[0].parent.bldpath()
362 if not tmp_path in env['LIBPATH']:
363 env.prepend_value('LIBPATH', [tmp_path])
365 # add ancestors uselib too - but only propagate those that have no staticlib defined
366 for v in self.to_list(getattr(y, 'uselib', [])):
367 if v not in seen_uselib:
369 if not env['STLIB_' + v]:
370 if not v in self.uselib:
371 self.uselib.insert(0, v)
373 # if the library task generator provides 'export_includes', add to the include path
374 # the export_includes must be a list of paths relative to the other library
375 if getattr(y, 'export_includes', None):
376 self.includes.extend(y.to_incnodes(y.export_includes))
378 @TaskGen.feature('cprogram', 'cxxprogram', 'cstlib', 'cxxstlib', 'cshlib', 'cxxshlib', 'dprogram', 'dstlib', 'dshlib')
379 @TaskGen.after('apply_link')
380 def apply_objdeps(self):
381 "add the .o files produced by some other object files in the same manner as uselib_local"
382 names = getattr(self, 'add_objects', [])
385 names = self.to_list(names)
387 get = self.bld.get_tgen_by_name
392 # visit dependencies only once
397 # object does not exist ?
400 # object has ancestors to process first ? update the list of names
401 if getattr(y, 'add_objects', None):
403 lst = y.to_list(y.add_objects)
411 continue # list of names modified, loop
413 # safe to process the current object
417 for t in getattr(y, 'compiled_tasks', []):
418 self.link_task.inputs.extend(t.outputs)
420 @TaskGen.after('apply_link')
421 def process_obj_files(self):
422 if not hasattr(self, 'obj_files'):
424 for x in self.obj_files:
425 node = self.path.find_resource(x)
426 self.link_task.inputs.append(node)
428 @TaskGen.taskgen_method
429 def add_obj_file(self, file):
430 """Small example on how to link object files as if they were source
431 obj = bld.create_obj('cc')
432 obj.add_obj_file('foo.o')"""
433 if not hasattr(self, 'obj_files'):
435 if not 'process_obj_files' in self.meths:
436 self.meths.append('process_obj_files')
437 self.obj_files.append(file)