diff --git a/.bzrignore b/.bzrignore index 1208379..879d722 100644 --- a/.bzrignore +++ b/.bzrignore @@ -9,3 +9,4 @@ ./doc/figures/work-flow-gccxml-apidefs.png ./doc/figures/work-flow-gccxml.png +.lock-waf_linux2_build diff --git a/examples/wscript b/examples/wscript index 5512602..0116749 100644 --- a/examples/wscript +++ b/examples/wscript @@ -1,6 +1,6 @@ ## -*- python -*- -def set_options(opt): +def options(opt): pass#opt.tool_options('boost') def build(bld): diff --git a/pybindgen/wscript b/pybindgen/wscript index e3f57bc..76e0a0c 100644 --- a/pybindgen/wscript +++ b/pybindgen/wscript @@ -3,17 +3,17 @@ def build(bld): obj = bld.new_task_gen('py') - obj.find_sources_in_dirs('.') + obj.source = obj.path.ant_glob('*.py') obj.source.append('version.py') obj.install_path = '${PYTHONDIR}/pybindgen' obj.prio = 50 obj = bld.new_task_gen('py') - obj.find_sources_in_dirs('typehandlers') + obj.source = obj.path.ant_glob('typehandlers/*.py') obj.install_path = '${PYTHONDIR}/pybindgen/typehandlers' obj.prio = 50 obj = bld.new_task_gen('py') - obj.find_sources_in_dirs('typehandlers/ctypeparser') + obj.source = obj.path.ant_glob('typehandlers/ctypeparser/*.py') obj.install_path = '${PYTHONDIR}/pybindgen/typehandlers/ctypeparser' obj.prio = 50 diff --git a/tests/c-hello/wscript b/tests/c-hello/wscript index 09e5793..907652c 100644 --- a/tests/c-hello/wscript +++ b/tests/c-hello/wscript @@ -3,6 +3,7 @@ #import Object #import Params #import Task +import os if 0: DEPRECATION_ERRORS = '-Werror::DeprecationWarning' # deprecations become errors @@ -20,13 +21,15 @@ def build(bld): target='hellomodule.c', command='${PYTHON} %s ${SRC[0]} ${SRC[1]} > ${TGT[0]}' % (DEPRECATION_ERRORS,)) + os.environ["PYTHONPATH"] = os.pathsep.join([os.environ.get("PYTHONPATH", ''), bindgen.path.get_bld().abspath()]) + if bld.env['CXX']: - obj = bld.new_task_gen(features='cc cshlib pyext') + obj = bld.new_task_gen(features='c cshlib pyext') obj.source = [ 'hello.c', 'hellomodule.c' ] obj.target = 'hello' obj.install_path = None # do not install - obj.includes = '.' + obj.env.append_value("INCLUDES", '.') diff --git a/tests/wscript b/tests/wscript index 609a990..ab02c1f 100644 --- a/tests/wscript +++ b/tests/wscript @@ -7,7 +7,7 @@ import Task import sys import os.path import os -import pproc as subprocess +import subprocess # uncomment to enable profiling information # epydoc uses the profile data to generate call graphs @@ -45,14 +45,14 @@ def build(bld): command='${PYTHON} %s ${SRC[0]} ${TOP_SRCDIR} > ${TGT[0]}' % (DEPRECATION_ERRORS,)) if env['CXX']: - obj = bld.new_task_gen(features='cxx cshlib pyext') + obj = bld(features='cxx cxxshlib pyext') obj.source = [ 'foo.cc', 'foomodule.cc' ] obj.target = 'foo' obj.install_path = None - obj.includes = '.' + obj.env.append_value("INCLUDES", '.') ## automatic code scanning using gccxml if env['ENABLE_PYGCCXML']: @@ -63,16 +63,16 @@ def build(bld): source='foomodulegen-auto.py foo.h', target='foomodule2.cc foomodulegen_generated.py', command='${PYTHON} %s ${SRC[0]} ${SRC[1]} ${cpp_path_repr} ${TGT[1]} > ${TGT[0]}' % (DEPRECATION_ERRORS,), - variables=dict(cpp_path_repr=repr(bindgen.env['CPPPATH']+bindgen.env['CPPPATH_PYEXT']))) + variables=dict(cpp_path_repr=repr(bindgen.env['INCLUDES']+bindgen.env['INCLUDES_PYEXT']))) - obj = bld.new_task_gen(features='cxx cshlib pyext') + obj = bld.new_task_gen(features='cxx cxxshlib pyext') obj.source = [ 'foo.cc', 'foomodule2.cc' ] obj.target = 'foo2' obj.install_path = None - obj.includes = '.' + obj.env.append_value("INCLUDES", '.') ### Now using the generated python script @@ -84,16 +84,16 @@ def build(bld): ## yes, this global manipulation of PYTHONPATH is kind of evil :-/ ## TODO: add WAF command-output support for customising command OS environment - os.environ["PYTHONPATH"] = os.pathsep.join([os.environ.get("PYTHONPATH", ''), bindgen.path.abspath(bindgen.env)]) + os.environ["PYTHONPATH"] = os.pathsep.join([os.environ.get("PYTHONPATH", ''), bindgen.path.get_bld().abspath()]) - obj = bld.new_task_gen(features='cxx cshlib pyext') + obj = bld.new_task_gen(features='cxx cxxshlib pyext') obj.source = [ 'foo.cc', 'foomodule3.cc' ] obj.target = 'foo3' obj.install_path = None # do not install - obj.includes = '.' + obj.env.append_value("INCLUDES", '.') ## --- @@ -102,7 +102,7 @@ def build(bld): source='foomodulegen-auto-split.py foo.h', target='foomodulegen_split.py foomodulegen_module1.py foomodulegen_module2.py', command='${PYTHON} %s ${SRC[0]} ${SRC[1]} ${cpp_path_repr} ${TGT[0]} ${TGT[1]} ${TGT[2]}' % (DEPRECATION_ERRORS,), - variables=dict(cpp_path_repr=repr(bindgen.env['CPPPATH']+bindgen.env['CPPPATH_PYEXT']))) + variables=dict(cpp_path_repr=repr(bindgen.env['INCLUDES']+bindgen.env['INCLUDES_PYEXT']))) bld.new_task_gen( features='command', @@ -121,7 +121,7 @@ def build(bld): command='${PYTHON} %s ${SRC[0]} ${TGT[0]}' % (DEPRECATION_ERRORS,)) - obj = bld.new_task_gen(features='cxx cshlib pyext') + obj = bld.new_task_gen(features='cxx cxxshlib pyext') obj.source = [ 'foo.cc', 'foomodule4.cc', @@ -130,7 +130,7 @@ def build(bld): ] obj.target = 'foo4' obj.install_path = None # do not install - obj.includes = '.' + obj.env.append_value("INCLUDES", '.') ## pure C tests bld.add_subdirs('c-hello') diff --git a/waf b/waf index 65b8d9f..e1e34d4 100755 Binary files a/waf and b/waf differ diff --git a/waf-tools/boost.py b/waf-tools/boost.py new file mode 100644 index 0000000..2ca82e2 --- /dev/null +++ b/waf-tools/boost.py @@ -0,0 +1,278 @@ +#!/usr/bin/env python +# encoding: utf-8 +# +# partially based on boost.py written by Gernot Vormayr +# written by Ruediger Sonderfeld , 2008 +# modified by Bjoern Michaelsen, 2008 +# modified by Luca Fossati, 2008 +# rewritten for waf 1.5.1, Thomas Nagy, 2008 +# rewritten for waf 1.6.2, Sylvain Rouquette, 2011 + +''' +To add the boost tool to the waf file: +$ ./waf-light --tools=compat15,boost + or, if you have waf >= 1.6.2 +$ ./waf update --files=boost + +The wscript will look like: + +def options(opt): + opt.load('compiler_cxx boost') + +def configure(conf): + conf.load('compiler_cxx boost') + conf.check_boost(lib='system filesystem', mt=True, static=True) + +def build(bld): + bld(source='main.cpp', target='app', use='BOOST') +''' + +import sys +import re +from waflib import Utils, Logs +from waflib.Configure import conf +from waflib.Errors import WafError + +BOOST_LIBS = ('/usr/lib', '/usr/local/lib', + '/opt/local/lib', '/sw/lib', '/lib') +BOOST_INCLUDES = ('/usr/include', '/usr/local/include', + '/opt/local/include', '/sw/include') +BOOST_VERSION_FILE = 'boost/version.hpp' +BOOST_VERSION_CODE = ''' +#include +#include +int main() { std::cout << BOOST_LIB_VERSION << std::endl; } +''' + +# toolsets from {boost_dir}/tools/build/v2/tools/common.jam +PLATFORM = Utils.unversioned_sys_platform() +detect_intel = lambda env: (PLATFORM == 'win32') and 'iw' or 'il' +detect_clang = lambda env: (PLATFORM == 'darwin') and 'clang-darwin' or 'clang' +detect_mingw = lambda env: (re.search('MinGW', env.CXX[0])) and 'mgw' or 'gcc' +BOOST_TOOLSETS = { + 'borland': 'bcb', + 'clang': detect_clang, + 'como': 'como', + 'cw': 'cw', + 'darwin': 'xgcc', + 'edg': 'edg', + 'g++': detect_mingw, + 'gcc': detect_mingw, + 'icpc': detect_intel, + 'intel': detect_intel, + 'kcc': 'kcc', + 'kylix': 'bck', + 'mipspro': 'mp', + 'mingw': 'mgw', + 'msvc': 'vc', + 'qcc': 'qcc', + 'sun': 'sw', + 'sunc++': 'sw', + 'tru64cxx': 'tru', + 'vacpp': 'xlc' +} + + +def options(opt): + opt.add_option('--boost-includes', type='string', + default='', dest='boost_includes', + help='''path to the boost directory where the includes are + e.g. /boost_1_45_0/include''') + opt.add_option('--boost-libs', type='string', + default='', dest='boost_libs', + help='''path to the directory where the boost libs are + e.g. /boost_1_45_0/stage/lib''') + opt.add_option('--boost-static', action='store_true', + default=False, dest='boost_static', + help='link static libraries') + opt.add_option('--boost-mt', action='store_true', + default=False, dest='boost_mt', + help='select multi-threaded libraries') + opt.add_option('--boost-abi', type='string', default='', dest='boost_abi', + help='''select libraries with tags (dgsyp, d for debug), + see doc Boost, Getting Started, chapter 6.1''') + opt.add_option('--boost-toolset', type='string', + default='', dest='boost_toolset', + help='force a toolset e.g. msvc, vc90, \ + gcc, mingw, mgw45 (default: auto)') + py_version = '%d%d' % (sys.version_info[0], sys.version_info[1]) + opt.add_option('--boost-python', type='string', + default=py_version, dest='boost_python', + help='select the lib python with this version \ + (default: %s)' % py_version) + + +@conf +def __boost_get_version_file(self, dir): + try: + return self.root.find_dir(dir).find_node(BOOST_VERSION_FILE) + except: + return None + + +@conf +def boost_get_version(self, dir): + """silently retrieve the boost version number""" + re_but = re.compile('^#define\\s+BOOST_LIB_VERSION\\s+"(.*)"$', re.M) + try: + val = re_but.search(self.__boost_get_version_file(dir).read()).group(1) + except: + val = self.check_cxx(fragment=BOOST_VERSION_CODE, includes=[dir], + execute=True, define_ret=True) + return val + + +@conf +def boost_get_includes(self, *k, **kw): + includes = k and k[0] or kw.get('includes', None) + if includes and self.__boost_get_version_file(includes): + return includes + for dir in BOOST_INCLUDES: + if self.__boost_get_version_file(dir): + return dir + if includes: + self.fatal('headers not found in %s' % includes) + else: + self.fatal('headers not found, use --boost-includes=/path/to/boost') + + +@conf +def boost_get_toolset(self, cc): + toolset = cc + if not cc: + build_platform = Utils.unversioned_sys_platform() + if build_platform in BOOST_TOOLSETS: + cc = build_platform + else: + cc = self.env.CXX_NAME + if cc in BOOST_TOOLSETS: + toolset = BOOST_TOOLSETS[cc] + return isinstance(toolset, str) and toolset or toolset(self.env) + + +@conf +def __boost_get_libs_path(self, *k, **kw): + ''' return the lib path and all the files in it ''' + if 'files' in kw: + return self.root.find_dir('.'), Utils.to_list(kw['files']) + libs = k and k[0] or kw.get('libs', None) + if libs: + path = self.root.find_dir(libs) + files = path.ant_glob('*boost_*') + if not libs or not files: + for dir in BOOST_LIBS: + try: + path = self.root.find_dir(dir) + files = path.ant_glob('*boost_*') + if files: + break + path = self.root.find_dir(dir + '64') + files = path.ant_glob('*boost_*') + if files: + break + except: + path = None + if not path: + if libs: + self.fatal('libs not found in %s' % libs) + else: + self.fatal('libs not found, \ + use --boost-includes=/path/to/boost/lib') + return path, files + + +@conf +def boost_get_libs(self, *k, **kw): + ''' + return the lib path and the required libs + according to the parameters + ''' + path, files = self.__boost_get_libs_path(**kw) + t = [] + if kw.get('mt', False): + t.append('mt') + if kw.get('abi', None): + t.append(kw['abi']) + tags = t and '(-%s)+' % '-'.join(t) or '' + toolset = '(-%s[0-9]{0,3})+' % self.boost_get_toolset(kw.get('toolset', '')) + version = '(-%s)+' % self.env.BOOST_VERSION + + def find_lib(re_lib, files): + for file in files: + if re_lib.search(file.name): + return file + return None + + def format_lib_name(name): + if name.startswith('lib'): + name = name[3:] + return name.split('.')[0] + + libs = [] + for lib in Utils.to_list(k and k[0] or kw.get('lib', None)): + py = (lib == 'python') and '(-py%s)+' % kw['python'] or '' + # Trying libraries, from most strict match to least one + for pattern in ['boost_%s%s%s%s%s' % (lib, toolset, tags, py, version), + 'boost_%s%s%s%s' % (lib, tags, py, version), + 'boost_%s%s%s' % (lib, tags, version), + # Give up trying to find the right version + 'boost_%s%s%s%s' % (lib, toolset, tags, py), + 'boost_%s%s%s' % (lib, tags, py), + 'boost_%s%s' % (lib, tags)]: + file = find_lib(re.compile(pattern), files) + if file: + libs.append(format_lib_name(file.name)) + break + else: + self.fatal('lib %s not found in %s' % (lib, path)) + + return path.abspath(), libs + + +@conf +def check_boost(self, *k, **kw): + """ + initialize boost + + You can pass the same parameters as the command line (without "--boost-"), + but the command line has the priority. + """ + if not self.env['CXX']: + self.fatal('load a c++ compiler first, conf.load("compiler_cxx")') + + params = {'lib': k and k[0] or kw.get('lib', None)} + for key, value in self.options.__dict__.items(): + if not key.startswith('boost_'): + continue + key = key[len('boost_'):] + params[key] = value and value or kw.get(key, '') + + var = kw.get('uselib_store', 'BOOST') + + self.start_msg('Checking boost includes') + try: + self.env['INCLUDES_%s' % var] = self.boost_get_includes(**params) + self.env.BOOST_VERSION = self.boost_get_version(self.env['INCLUDES_%s' % var]) + except WafError: + self.end_msg("not found", 'YELLOW') + raise + self.end_msg(self.env.BOOST_VERSION) + if Logs.verbose: + Logs.pprint('CYAN', ' path : %s' % self.env['INCLUDES_%s' % var]) + + if not params['lib']: + return + self.start_msg('Checking boost libs') + try: + suffix = params.get('static', 'ST') or '' + path, libs = self.boost_get_libs(**params) + except WafError: + self.end_msg("not found", 'YELLOW') + raise + self.env['%sLIBPATH_%s' % (suffix, var)] = [path] + self.env['%sLIB_%s' % (suffix, var)] = libs + self.end_msg('ok') + if Logs.verbose: + Logs.pprint('CYAN', ' path : %s' % path) + Logs.pprint('CYAN', ' libs : %s' % libs) + diff --git a/waf-tools/cflags.py b/waf-tools/cflags.py new file mode 100644 index 0000000..cf9c93c --- /dev/null +++ b/waf-tools/cflags.py @@ -0,0 +1,192 @@ +import Logs +import Options +import Utils + + +class CompilerTraits(object): + def get_warnings_flags(self, level): + """get_warnings_flags(level) -> list of cflags""" + raise NotImplementedError + + def get_optimization_flags(self, level): + """get_optimization_flags(level) -> list of cflags""" + raise NotImplementedError + + def get_debug_flags(self, level): + """get_debug_flags(level) -> (list of cflags, list of cppdefines)""" + raise NotImplementedError + + +class GccTraits(CompilerTraits): + def __init__(self): + super(GccTraits, self).__init__() + # cumulative list of warnings per level + self.warnings_flags = [['-Wall'], ['-Werror'], ['-Wextra']] + + def get_warnings_flags(self, level): + warnings = [] + for l in range(level): + if l < len(self.warnings_flags): + warnings.extend(self.warnings_flags[l]) + else: + break + return warnings + + def get_optimization_flags(self, level): + if level == 0: + return ['-O0'] + elif level == 1: + return ['-O'] + elif level == 2: + return ['-O2'] + elif level == 3: + return ['-O3'] + + def get_debug_flags(self, level): + if level == 0: + return (['-g0'], ['NDEBUG']) + elif level == 1: + return (['-g'], []) + elif level >= 2: + return (['-ggdb', '-g3'], ['_DEBUG']) + + +class IccTraits(CompilerTraits): + def __init__(self): + super(IccTraits, self).__init__() + # cumulative list of warnings per level + # icc is _very_ verbose with -Wall, -Werror is barely achievable + self.warnings_flags = [[], [], ['-Wall']] + + def get_warnings_flags(self, level): + warnings = [] + for l in range(level): + if l < len(self.warnings_flags): + warnings.extend(self.warnings_flags[l]) + else: + break + return warnings + + def get_optimization_flags(self, level): + if level == 0: + return ['-O0'] + elif level == 1: + return ['-O'] + elif level == 2: + return ['-O2'] + elif level == 3: + return ['-O3'] + + def get_debug_flags(self, level): + if level == 0: + return (['-g0'], ['NDEBUG']) + elif level == 1: + return (['-g'], []) + elif level >= 2: + return (['-ggdb', '-g3'], ['_DEBUG']) + + + +class MsvcTraits(CompilerTraits): + def __init__(self): + super(MsvcTraits, self).__init__() + # cumulative list of warnings per level + self.warnings_flags = [['/W2'], ['/WX'], ['/Wall']] + + def get_warnings_flags(self, level): + warnings = [] + for l in range(level): + if l < len(self.warnings_flags): + warnings.extend(self.warnings_flags[l]) + else: + break + return warnings + + def get_optimization_flags(self, level): + if level == 0: + return ['/Od'] + elif level == 1: + return [] + elif level == 2: + return ['/O2'] + elif level == 3: + return ['/Ox'] + + def get_debug_flags(self, level): + if level == 0: + return ([], ['NDEBUG']) + elif level == 1: + return (['/ZI', '/RTC1'], []) + elif level >= 2: + return (['/ZI', '/RTC1'], ['_DEBUG']) + + + +gcc = GccTraits() +icc = IccTraits() +msvc = MsvcTraits() + +# how to map env['COMPILER_CC'] or env['COMPILER_CXX'] into a traits object +compiler_mapping = { + 'gcc': gcc, + 'g++': gcc, + 'msvc': msvc, + 'icc': icc, + 'icpc': icc, +} + +profiles = { + # profile name: [optimization_level, warnings_level, debug_level] + 'default': [2, 1, 1], + 'debug': [0, 2, 3], + 'release': [3, 1, 0], + } + +default_profile = 'default' + +def options(opt): + assert default_profile in profiles + opt.add_option('-d', '--build-profile', + action='store', + default=default_profile, + help=("Specify the build profile. " + "Build profiles control the default compilation flags" + " used for C/C++ programs, if CCFLAGS/CXXFLAGS are not" + " set set in the environment. [Allowed Values: %s]" + % ", ".join([repr(p) for p in profiles.keys()])), + choices=profiles.keys(), + dest='build_profile') + +def configure(conf): + cc = conf.env['COMPILER_CC'] or None + cxx = conf.env['COMPILER_CXX'] or None + if not (cc or cxx): + raise Utils.WafError("neither COMPILER_CC nor COMPILER_CXX are defined; " + "maybe the compiler_cc or compiler_cxx tool has not been configured yet?") + + try: + compiler = compiler_mapping[cc] + except KeyError: + try: + compiler = compiler_mapping[cxx] + except KeyError: + Logs.warn("No compiler flags support for compiler %r or %r" + % (cc, cxx)) + return + + opt_level, warn_level, dbg_level = profiles[Options.options.build_profile] + + optimizations = compiler.get_optimization_flags(opt_level) + debug, debug_defs = compiler.get_debug_flags(dbg_level) + warnings = compiler.get_warnings_flags(warn_level) + + if cc and not conf.env['CCFLAGS']: + conf.env.append_value('CCFLAGS', optimizations) + conf.env.append_value('CCFLAGS', debug) + conf.env.append_value('CCFLAGS', warnings) + conf.env.append_value('CCDEFINES', debug_defs) + if cxx and not conf.env['CXXFLAGS']: + conf.env.append_value('CXXFLAGS', optimizations) + conf.env.append_value('CXXFLAGS', debug) + conf.env.append_value('CXXFLAGS', warnings) + conf.env.append_value('CXXDEFINES', debug_defs) diff --git a/waf-tools/command.py b/waf-tools/command.py new file mode 100644 index 0000000..770c342 --- /dev/null +++ b/waf-tools/command.py @@ -0,0 +1,155 @@ +import TaskGen# import feature, taskgen_method, before_method, task_gen +import Node, Task, Utils, Build +import subprocess +import Options + +import shellcmd +#shellcmd.subprocess = pproc # the WAF version of the subprocess module is supposedly less buggy + +from Logs import debug, error +shellcmd.debug = debug + +import Task + +import re + + +arg_rx = re.compile(r"(?P\$\$)|(?P\$\{(?P\w+)(?P.*?)\})", re.M) + +class command_task(Task.Task): + color = "BLUE" + def __init__(self, env, generator): + Task.Task.__init__(self, env=env, normal=1, generator=generator) + + def __str__(self): + "string to display to the user" + env = self.env + src_str = ' '.join([a.nice_path(env) for a in self.inputs]) + tgt_str = ' '.join([a.nice_path(env) for a in self.outputs]) + if self.outputs: + sep = ' -> ' + else: + sep = '' + + pipeline = shellcmd.Pipeline() + pipeline.parse(self.generator.command) + cmd = pipeline.get_abbreviated_command() + return 'command (%s): %s%s%s\n' % (cmd, src_str, sep, tgt_str) + + def _subst_arg(self, arg, direction, namespace): + """ + @param arg: the command argument (or stdin/stdout/stderr) to substitute + @param direction: direction of the argument: 'in', 'out', or None + """ + def repl(match): + if match.group('dollar'): + return "$" + elif match.group('subst'): + var = match.group('var') + code = match.group('code') + result = eval(var+code, namespace) + if isinstance(result, Node.Node): + if var == 'TGT': + return result.get_bld().abspath() + elif var == 'SRC': + return result.srcpath() + else: + raise ValueError("Bad subst variable %r" % var) + elif result is self.inputs: + if len(self.inputs) == 1: + return result[0].srcpath() + else: + raise ValueError("${SRC} requested but have multiple sources; which one?") + elif result is self.outputs: + if len(self.outputs) == 1: + return result[0].get_bld().abspath() + else: + raise ValueError("${TGT} requested but have multiple targets; which one?") + elif isinstance(result, list): + assert len(result) == 1 + return result[0] + else: + return result + return None + + return arg_rx.sub(repl, arg) + + def run(self): + pipeline = shellcmd.Pipeline() + pipeline.parse(self.generator.command) + namespace = self.env.get_merged_dict() + if self.generator.variables is not None: + namespace.update(self.generator.variables) + namespace.update(env=self.env, SRC=self.inputs, TGT=self.outputs) + for cmd in pipeline.pipeline: + if isinstance(cmd, shellcmd.Command): + if isinstance(cmd.stdin, basestring): + cmd.stdin = self._subst_arg(cmd.stdin, 'in', namespace) + if isinstance(cmd.stdout, basestring): + cmd.stdout = self._subst_arg(cmd.stdout, 'out', namespace) + if isinstance(cmd.stderr, basestring): + cmd.stderr = self._subst_arg(cmd.stderr, 'out', namespace) + for argI in xrange(len(cmd.argv)): + cmd.argv[argI] = self._subst_arg(cmd.argv[argI], None, namespace) + if cmd.env_vars is not None: + env_vars = dict() + for name, value in cmd.env_vars.iteritems(): + env_vars[name] = self._subst_arg(value, None, namespace) + cmd.env_vars = env_vars + elif isinstance(cmd, shellcmd.Chdir): + cmd.dir = self._subst_arg(cmd.dir, None, namespace) + return pipeline.run(verbose=(Options.options.verbose > 0)) + +@TaskGen.taskgen_method +@TaskGen.feature('command') +def init_command(self): + Utils.def_attrs(self, + # other variables that can be used in the command: ${VARIABLE} + variables = None, + rule='') + + +@TaskGen.taskgen_method +@TaskGen.feature('command') +@TaskGen.before_method('process_source') +def process_rule(self): + if not 'command' in self.features: + return + # now create one instance + tsk = self.create_task('command') + if getattr(self, 'target', None): + if isinstance(self.target, str): + self.target = self.target.split() + if not isinstance(self.target, list): + self.target = [self.target] + for x in self.target: + if isinstance(x, str): + tsk.outputs.append(self.path.find_or_declare(x)) + else: + x.parent.mkdir() # if a node was given, create the required folders + tsk.outputs.append(x) + if getattr(self, 'install_path', None): + # from waf 1.5 + # although convenient, it does not 1. allow to name the target file and 2. symlinks + # TODO remove in waf 1.7 + self.bld.install_files(self.install_path, tsk.outputs) + + if getattr(self, 'source', None): + tsk.inputs = self.to_nodes(self.source) + # bypass the execution of process_source by setting the source to an empty list + self.source = [] + + elif getattr(self, 'deps', None): + def scan(self): + nodes = [] + for x in self.generator.to_list(self.generator.deps): + node = self.generator.path.find_resource(x) + if not node: + self.generator.bld.fatal('Could not find %r (was it declared?)' % x) + nodes.append(node) + return [nodes, []] + cls.scan = scan + + setattr(tsk, "dep_vars", getattr(self, "dep_vars", None)) + + diff --git a/waf-tools/misc.py b/waf-tools/misc.py new file mode 100644 index 0000000..e8620fb --- /dev/null +++ b/waf-tools/misc.py @@ -0,0 +1,416 @@ +#!/usr/bin/env python +# encoding: utf-8 +# Thomas Nagy, 2006-2010 (ita) + +""" +This tool is totally deprecated + +Try using: + .pc.in files for .pc files + the feature intltool_in - see demos/intltool + make-like rules +""" + +import shutil, re, os +from waflib import TaskGen, Node, Task, Utils, Build, Errors +from waflib.TaskGen import feature, after_method, before_method +from waflib.Logs import debug + +def copy_attrs(orig, dest, names, only_if_set=False): + """ + copy class attributes from an object to another + """ + for a in Utils.to_list(names): + u = getattr(orig, a, ()) + if u or not only_if_set: + setattr(dest, a, u) + +def copy_func(tsk): + "Make a file copy. This might be used to make other kinds of file processing (even calling a compiler is possible)" + env = tsk.env + infile = tsk.inputs[0].abspath() + outfile = tsk.outputs[0].abspath() + try: + shutil.copy2(infile, outfile) + except (OSError, IOError): + return 1 + else: + if tsk.chmod: os.chmod(outfile, tsk.chmod) + return 0 + +def action_process_file_func(tsk): + "Ask the function attached to the task to process it" + if not tsk.fun: raise Errors.WafError('task must have a function attached to it for copy_func to work!') + return tsk.fun(tsk) + +@feature('cmd') +def apply_cmd(self): + "call a command everytime" + if not self.fun: raise Errors.WafError('cmdobj needs a function!') + tsk = Task.TaskBase() + tsk.fun = self.fun + tsk.env = self.env + self.tasks.append(tsk) + tsk.install_path = self.install_path + +@feature('copy') +@before_method('process_source') +def apply_copy(self): + Utils.def_attrs(self, fun=copy_func) + self.default_install_path = 0 + + lst = self.to_list(self.source) + self.meths.remove('process_source') + + for filename in lst: + node = self.path.find_resource(filename) + if not node: raise Errors.WafError('cannot find input file %s for processing' % filename) + + target = self.target + if not target or len(lst)>1: target = node.name + + # TODO the file path may be incorrect + newnode = self.path.find_or_declare(target) + + tsk = self.create_task('copy', node, newnode) + tsk.fun = self.fun + tsk.chmod = getattr(self, 'chmod', Utils.O644) + + if not tsk.env: + tsk.debug() + raise Errors.WafError('task without an environment') + +def subst_func(tsk): + "Substitutes variables in a .in file" + + m4_re = re.compile('@(\w+)@', re.M) + + code = tsk.inputs[0].read() #Utils.readf(infile) + + # replace all % by %% to prevent errors by % signs in the input file while string formatting + code = code.replace('%', '%%') + + s = m4_re.sub(r'%(\1)s', code) + + env = tsk.env + di = getattr(tsk, 'dict', {}) or getattr(tsk.generator, 'dict', {}) + if not di: + names = m4_re.findall(code) + for i in names: + di[i] = env.get_flat(i) or env.get_flat(i.upper()) + + tsk.outputs[0].write(s % di) + +@feature('subst') +@before_method('process_source') +def apply_subst(self): + Utils.def_attrs(self, fun=subst_func) + lst = self.to_list(self.source) + self.meths.remove('process_source') + + self.dict = getattr(self, 'dict', {}) + + for filename in lst: + node = self.path.find_resource(filename) + if not node: raise Errors.WafError('cannot find input file %s for processing' % filename) + + if self.target: + newnode = self.path.find_or_declare(self.target) + else: + newnode = node.change_ext('') + + try: + self.dict = self.dict.get_merged_dict() + except AttributeError: + pass + + if self.dict and not self.env['DICT_HASH']: + self.env = self.env.derive() + keys = list(self.dict.keys()) + keys.sort() + lst = [self.dict[x] for x in keys] + self.env['DICT_HASH'] = str(Utils.h_list(lst)) + + tsk = self.create_task('copy', node, newnode) + tsk.fun = self.fun + tsk.dict = self.dict + tsk.dep_vars = ['DICT_HASH'] + tsk.chmod = getattr(self, 'chmod', Utils.O644) + + if not tsk.env: + tsk.debug() + raise Errors.WafError('task without an environment') + +#################### +## command-output #### +#################### + +class cmd_arg(object): + """command-output arguments for representing files or folders""" + def __init__(self, name, template='%s'): + self.name = name + self.template = template + self.node = None + +class input_file(cmd_arg): + def find_node(self, base_path): + assert isinstance(base_path, Node.Node) + self.node = base_path.find_resource(self.name) + if self.node is None: + raise Errors.WafError("Input file %s not found in " % (self.name, base_path)) + + def get_path(self, env, absolute): + if absolute: + return self.template % self.node.abspath() + else: + return self.template % self.node.srcpath() + +class output_file(cmd_arg): + def find_node(self, base_path): + assert isinstance(base_path, Node.Node) + self.node = base_path.find_or_declare(self.name) + if self.node is None: + raise Errors.WafError("Output file %s not found in " % (self.name, base_path)) + + def get_path(self, env, absolute): + if absolute: + return self.template % self.node.abspath() + else: + return self.template % self.node.bldpath() + +class cmd_dir_arg(cmd_arg): + def find_node(self, base_path): + assert isinstance(base_path, Node.Node) + self.node = base_path.find_dir(self.name) + if self.node is None: + raise Errors.WafError("Directory %s not found in " % (self.name, base_path)) + +class input_dir(cmd_dir_arg): + def get_path(self, dummy_env, dummy_absolute): + return self.template % self.node.abspath() + +class output_dir(cmd_dir_arg): + def get_path(self, env, dummy_absolute): + return self.template % self.node.abspath() + + +class command_output(Task.Task): + color = "BLUE" + def __init__(self, env, command, command_node, command_args, stdin, stdout, cwd, os_env, stderr): + Task.Task.__init__(self, env=env) + assert isinstance(command, (str, Node.Node)) + self.command = command + self.command_args = command_args + self.stdin = stdin + self.stdout = stdout + self.cwd = cwd + self.os_env = os_env + self.stderr = stderr + + if command_node is not None: self.dep_nodes = [command_node] + self.dep_vars = [] # additional environment variables to look + + def run(self): + task = self + #assert len(task.inputs) > 0 + + def input_path(node, template): + if task.cwd is None: + return template % node.bldpath() + else: + return template % node.abspath() + def output_path(node, template): + fun = node.abspath + if task.cwd is None: fun = node.bldpath + return template % fun() + + if isinstance(task.command, Node.Node): + argv = [input_path(task.command, '%s')] + else: + argv = [task.command] + + for arg in task.command_args: + if isinstance(arg, str): + argv.append(arg) + else: + assert isinstance(arg, cmd_arg) + argv.append(arg.get_path(task.env, (task.cwd is not None))) + + if task.stdin: + stdin = open(input_path(task.stdin, '%s')) + else: + stdin = None + + if task.stdout: + stdout = open(output_path(task.stdout, '%s'), "w") + else: + stdout = None + + if task.stderr: + stderr = open(output_path(task.stderr, '%s'), "w") + else: + stderr = None + + if task.cwd is None: + cwd = ('None (actually %r)' % os.getcwd()) + else: + cwd = repr(task.cwd) + debug("command-output: cwd=%s, stdin=%r, stdout=%r, argv=%r" % + (cwd, stdin, stdout, argv)) + + if task.os_env is None: + os_env = os.environ + else: + os_env = task.os_env + command = Utils.subprocess.Popen(argv, stdin=stdin, stdout=stdout, stderr=stderr, cwd=task.cwd, env=os_env) + return command.wait() + +@feature('command-output') +def init_cmd_output(self): + Utils.def_attrs(self, + stdin = None, + stdout = None, + stderr = None, + # the command to execute + command = None, + + # whether it is an external command; otherwise it is assumed + # to be an executable binary or script that lives in the + # source or build tree. + command_is_external = False, + + # extra parameters (argv) to pass to the command (excluding + # the command itself) + argv = [], + + # dependencies to other objects -> this is probably not what you want (ita) + # values must be 'task_gen' instances (not names!) + dependencies = [], + + # dependencies on env variable contents + dep_vars = [], + + # input files that are implicit, i.e. they are not + # stdin, nor are they mentioned explicitly in argv + hidden_inputs = [], + + # output files that are implicit, i.e. they are not + # stdout, nor are they mentioned explicitly in argv + hidden_outputs = [], + + # change the subprocess to this cwd (must use obj.input_dir() or output_dir() here) + cwd = None, + + # OS environment variables to pass to the subprocess + # if None, use the default environment variables unchanged + os_env = None) + +@feature('command-output') +@after_method('init_cmd_output') +def apply_cmd_output(self): + if self.command is None: + raise Errors.WafError("command-output missing command") + if self.command_is_external: + cmd = self.command + cmd_node = None + else: + cmd_node = self.path.find_resource(self.command) + assert cmd_node is not None, ('''Could not find command '%s' in source tree. +Hint: if this is an external command, +use command_is_external=True''') % (self.command,) + cmd = cmd_node + + if self.cwd is None: + cwd = None + else: + assert isinstance(cwd, CmdDirArg) + self.cwd.find_node(self.path) + + args = [] + inputs = [] + outputs = [] + + for arg in self.argv: + if isinstance(arg, cmd_arg): + arg.find_node(self.path) + if isinstance(arg, input_file): + inputs.append(arg.node) + if isinstance(arg, output_file): + outputs.append(arg.node) + + if self.stdout is None: + stdout = None + else: + assert isinstance(self.stdout, str) + stdout = self.path.find_or_declare(self.stdout) + if stdout is None: + raise Errors.WafError("File %s not found" % (self.stdout,)) + outputs.append(stdout) + + if self.stderr is None: + stderr = None + else: + assert isinstance(self.stderr, str) + stderr = self.path.find_or_declare(self.stderr) + if stderr is None: + raise Errors.WafError("File %s not found" % (self.stderr,)) + outputs.append(stderr) + + if self.stdin is None: + stdin = None + else: + assert isinstance(self.stdin, str) + stdin = self.path.find_resource(self.stdin) + if stdin is None: + raise Errors.WafError("File %s not found" % (self.stdin,)) + inputs.append(stdin) + + for hidden_input in self.to_list(self.hidden_inputs): + node = self.path.find_resource(hidden_input) + if node is None: + raise Errors.WafError("File %s not found in dir %s" % (hidden_input, self.path)) + inputs.append(node) + + for hidden_output in self.to_list(self.hidden_outputs): + node = self.path.find_or_declare(hidden_output) + if node is None: + raise Errors.WafError("File %s not found in dir %s" % (hidden_output, self.path)) + outputs.append(node) + + if not (inputs or getattr(self, 'no_inputs', None)): + raise Errors.WafError('command-output objects must have at least one input file or give self.no_inputs') + if not (outputs or getattr(self, 'no_outputs', None)): + raise Errors.WafError('command-output objects must have at least one output file or give self.no_outputs') + + cwd = self.bld.variant_dir + task = command_output(self.env, cmd, cmd_node, self.argv, stdin, stdout, cwd, self.os_env, stderr) + task.generator = self + copy_attrs(self, task, 'before after ext_in ext_out', only_if_set=True) + self.tasks.append(task) + + task.inputs = inputs + task.outputs = outputs + task.dep_vars = self.to_list(self.dep_vars) + + for dep in self.dependencies: + assert dep is not self + dep.post() + for dep_task in dep.tasks: + task.set_run_after(dep_task) + + if not task.inputs: + # the case for svnversion, always run, and update the output nodes + task.runnable_status = type(Task.TaskBase.run)(runnable_status, task, task.__class__) # always run + task.post_run = type(Task.TaskBase.run)(post_run, task, task.__class__) + + # TODO the case with no outputs? + +def post_run(self): + for x in self.outputs: + x.sig = Utils.h_file(x.abspath()) + +def runnable_status(self): + return self.RUN_ME + +Task.task_factory('copy', vars=[], func=action_process_file_func) + diff --git a/waf-tools/pkgconfig.py b/waf-tools/pkgconfig.py new file mode 100644 index 0000000..bc75727 --- /dev/null +++ b/waf-tools/pkgconfig.py @@ -0,0 +1,78 @@ +# -*- mode: python; encoding: utf-8 -*- +# Gustavo Carneiro (gjamc) 2008 + +import Options +import Configure +import subprocess +import config_c +import sys + +def configure(conf): + pkg_config = conf.find_program('pkg-config', var='PKG_CONFIG') + if not pkg_config: return + +@Configure.conf +def pkg_check_modules(conf, uselib_name, expression, mandatory=True): + pkg_config = conf.env['PKG_CONFIG'] + if not pkg_config: + if mandatory: + conf.fatal("pkg-config is not available") + else: + return False + + if Options.options.verbose: + extra_msg = ' (%s)' % expression + else: + extra_msg = '' + + conf.start_msg('Checking for pkg-config flags for %s%s' % (uselib_name, extra_msg)) + + argv = [pkg_config, '--cflags', '--libs', expression] + cmd = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = cmd.communicate() + retval = cmd.wait() + + conf.to_log('%r: %r (exit code %i)\n%s' % (argv, out, retval, err)) + + if retval != 0: + conf.end_msg(False) + sys.stderr.write(err) + else: + if Options.options.verbose: + conf.end_msg(out) + else: + conf.end_msg(True) + + if retval == 0: + conf.parse_flags(out, uselib_name, conf.env) + conf.env[uselib_name] = True + return True + + else: + + conf.env[uselib_name] = False + if mandatory: + raise Configure.ConfigurationError('pkg-config check failed') + else: + return False + +@Configure.conf +def pkg_check_module_variable(conf, module, variable): + pkg_config = conf.env['PKG_CONFIG'] + if not pkg_config: + conf.fatal("pkg-config is not available") + + argv = [pkg_config, '--variable', variable, module] + cmd = subprocess.Popen(argv, stdout=subprocess.PIPE) + out, dummy = cmd.communicate() + retval = cmd.wait() + out = out.rstrip() # strip the trailing newline + + msg_checking = ("Checking for pkg-config variable %r in %s" % (variable, module,)) + conf.check_message_custom(msg_checking, '', out) + conf.log.write('%r: %r (exit code %i)\n' % (argv, out, retval)) + + if retval == 0: + return out + else: + raise Configure.ConfigurationError('pkg-config check failed') diff --git a/waf-tools/relocation.py b/waf-tools/relocation.py new file mode 100644 index 0000000..ab8dd36 --- /dev/null +++ b/waf-tools/relocation.py @@ -0,0 +1,85 @@ +#! /usr/bin/env python +# encoding: utf-8 + +""" +Waf 1.6 + +Try to detect if the project directory was relocated, and if it was, +change the node representing the project directory. Just call: + + waf configure build + +Note that if the project directory name changes, the signatures for the tasks using +files in that directory will change, causing a partial build. +""" + +import os +from waflib import Build, ConfigSet, Task, Utils, Errors +from waflib.TaskGen import feature, before_method, after_method + +EXTRA_LOCK = '.old_srcdir' + +old1 = Build.BuildContext.store +def store(self): + old1(self) + db = os.path.join(self.variant_dir, EXTRA_LOCK) + env = ConfigSet.ConfigSet() + env.SRCDIR = self.srcnode.abspath() + env.store(db) +Build.BuildContext.store = store + +old2 = Build.BuildContext.init_dirs +def init_dirs(self): + + if not (os.path.isabs(self.top_dir) and os.path.isabs(self.out_dir)): + raise Errors.WafError('The project was not configured: run "waf configure" first!') + + srcdir = None + db = os.path.join(self.variant_dir, EXTRA_LOCK) + env = ConfigSet.ConfigSet() + try: + env.load(db) + srcdir = env.SRCDIR + except: + pass + + if srcdir: + d = self.root.find_node(srcdir) + if d and srcdir != self.top_dir and getattr(d, 'children', ''): + srcnode = self.root.make_node(self.top_dir) + print("relocating the source directory %r -> %r" % (srcdir, self.top_dir)) + srcnode.children = {} + + for (k, v) in d.children.items(): + srcnode.children[k] = v + v.parent = srcnode + d.children = {} + + old2(self) + +Build.BuildContext.init_dirs = init_dirs + + +def uid(self): + try: + return self.uid_ + except AttributeError: + # this is not a real hot zone, but we want to avoid surprizes here + m = Utils.md5() + up = m.update + up(self.__class__.__name__.encode()) + for x in self.inputs + self.outputs: + up(x.path_from(x.ctx.srcnode).encode()) + self.uid_ = m.digest() + return self.uid_ +Task.Task.uid = uid + +@feature('c', 'cxx', 'd', 'go', 'asm', 'fc', 'includes') +@after_method('propagate_uselib_vars', 'process_source') +def apply_incpaths(self): + lst = self.to_incnodes(self.to_list(getattr(self, 'includes', [])) + self.env['INCLUDES']) + self.includes_nodes = lst + bld = self.bld + self.env['INCPATHS'] = [x.is_child_of(bld.srcnode) and x.path_from(bld.srcnode) or x.abspath() for x in lst] + + diff --git a/waf-tools/shellcmd.py b/waf-tools/shellcmd.py new file mode 100644 index 0000000..36575b3 --- /dev/null +++ b/waf-tools/shellcmd.py @@ -0,0 +1,356 @@ +# Copyright (C) 2008 Gustavo J. A. M. Carneiro + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +import shlex +import subprocess +import sys +import re +import os + +env_var_rx = re.compile(r"^([a-zA-Z0-9_]+)=(\S+)$") + +def debug(message): + print >> sys.stderr, message + + +if sys.platform == 'win32': + dev_null = open("NUL:", "w") +else: + dev_null = open("/dev/null", "w") + +fcntl = fd = fl = None +try: + import fcntl +except ImportError: + pass +else: + fd = dev_null.fileno() + fl = fcntl.fcntl(fd, fcntl.F_GETFD) + fcntl.fcntl(fd, fcntl.F_SETFD, fl | fcntl.FD_CLOEXEC) +del fcntl, fd, fl + +def _open_out_file(filename): + if filename in ['NUL:', '/dev/null']: + return dev_null + else: + return open(filename, 'wb') + + +class Node(object): + pass + +class Op(Node): + pass + +class Pipe(Op): + pass + +class And(Op): + pass + +class Or(Op): + pass + +class Command(Node): + class PIPE(object): + pass # PIPE is a constant + class STDOUT(object): + pass # PIPE is a constant + + def __init__(self, name): + super(Command, self).__init__() + self.name = name # command name + self.argv = [name] # command argv + self.stdin = None + self.stdout = None + self.stderr = None + self.env_vars = None + + def __repr__(self): + return "Command(%r, argv=%r, stdin=%r, stdout=%r, stderr=%r)" \ + % (self.name, self.argv, self.stdin, self.stdout, self.stderr) + +class Chdir(Node): + def __init__(self): + super(Chdir, self).__init__() + self.dir = None + + def __repr__(self): + return "Chdir(%r)" \ + % (self.dir) + +class Pipeline(object): + def __init__(self): + self.current_command = None + self.pipeline = [] + + def _commit_command(self): + assert self.current_command is not None + self.pipeline.append(self.current_command) + self.current_command = None + + def get_abbreviated_command(self): + l = [] + for node in self.pipeline: + if isinstance(node, Command): + l.append(node.name) + if isinstance(node, Chdir): + l.append('cd %s' % node.dir) + elif isinstance(node, Pipe): + l.append('|') + elif isinstance(node, And): + l.append('&&') + elif isinstance(node, And): + l.append('||') + return ' '.join(l) + + def parse(self, command): + self.current_command = None + self.pipeline = [] + + if isinstance(command, list): + tokens = list(command) + else: + tokens = shlex.split(command) + debug("command: shlex: %r" % (tokens,)) + + BEGIN, COMMAND, CHDIR, STDERR, STDOUT, STDIN = range(6) + state = BEGIN + self.current_command = None + env_vars = dict() + + while tokens: + token = tokens.pop(0) + if state == BEGIN: + env_var_match = env_var_rx.match(token) + if env_var_match is not None: + env_vars[env_var_match.group(1)] = env_var_match.group(2) + else: + assert self.current_command is None + if token == 'cd': + self.current_command = Chdir() + assert not env_vars + state = CHDIR + else: + self.current_command = Command(token) + if env_vars: + self.current_command.env_vars = env_vars + env_vars = dict() + state = COMMAND + elif state == COMMAND: + if token == '>': + state = STDOUT + elif token == '2>': + state = STDERR + elif token == '2>&1': + assert self.current_command.stderr is None + self.current_command.stderr = Command.STDOUT + elif token == '<': + state = STDIN + elif token == '|': + assert self.current_command.stdout is None + self.current_command.stdout = Command.PIPE + self._commit_command() + self.pipeline.append(Pipe()) + state = BEGIN + elif token == '&&': + self._commit_command() + self.pipeline.append(And()) + state = BEGIN + elif token == '||': + self._commit_command() + self.pipeline.append(Or()) + state = BEGIN + else: + self.current_command.argv.append(token) + elif state == CHDIR: + if token == '&&': + self._commit_command() + self.pipeline.append(And()) + state = BEGIN + else: + assert self.current_command.dir is None + self.current_command.dir = token + elif state == STDOUT: + assert self.current_command.stdout is None + self.current_command.stdout = token + state = COMMAND + elif state == STDERR: + assert self.current_command.stderr is None + self.current_command.stderr = token + state = COMMAND + elif state == STDIN: + assert self.current_command.stdin is None + self.current_command.stdin = token + state = COMMAND + self._commit_command() + return self.pipeline + + def _exec_piped_commands(self, commands): + retvals = [] + for cmd in commands: + retvals.append(cmd.wait()) + retval = 0 + for r in retvals: + if r: + retval = retvals[-1] + break + return retval + + def run(self, verbose=False): + pipeline = list(self.pipeline) + files_to_close = [] + piped_commands = [] + piped_commands_display = [] + BEGIN, PIPE = range(2) + state = BEGIN + cwd = '.' + while pipeline: + node = pipeline.pop(0) + + if isinstance(node, Chdir): + next_op = pipeline.pop(0) + assert isinstance(next_op, And) + cwd = os.path.join(cwd, node.dir) + if verbose: + piped_commands_display.append("cd %s &&" % node.dir) + continue + + assert isinstance(node, (Command, Chdir)) + cmd = node + if verbose: + if cmd.env_vars: + env_vars_str = ' '.join(['%s=%s' % (key, val) for key, val in cmd.env_vars.iteritems()]) + piped_commands_display.append("%s %s" % (env_vars_str, ' '.join(cmd.argv))) + else: + piped_commands_display.append(' '.join(cmd.argv)) + + if state == PIPE: + stdin = piped_commands[-1].stdout + elif cmd.stdin is not None: + stdin = open(cmd.stdin, "r") + if verbose: + piped_commands_display.append('< %s' % cmd.stdin) + files_to_close.append(stdin) + else: + stdin = None + + if cmd.stdout is None: + stdout = None + elif cmd.stdout is Command.PIPE: + stdout = subprocess.PIPE + else: + stdout = _open_out_file(cmd.stdout) + files_to_close.append(stdout) + if verbose: + piped_commands_display.append('> %s' % cmd.stdout) + + if cmd.stderr is None: + stderr = None + elif cmd.stderr is Command.PIPE: + stderr = subprocess.PIPE + elif cmd.stderr is Command.STDOUT: + stderr = subprocess.STDOUT + if verbose: + piped_commands_display.append('2>&1') + else: + stderr = _open_out_file(cmd.stderr) + files_to_close.append(stderr) + if verbose: + piped_commands_display.append('2> %s' % cmd.stderr) + + if cmd.env_vars: + env = dict(os.environ) + env.update(cmd.env_vars) + else: + env = None + + if cwd == '.': + proc_cwd = None + else: + proc_cwd = cwd + + debug("command: subprocess.Popen(argv=%r, stdin=%r, stdout=%r, stderr=%r, env_vars=%r, cwd=%r)" + % (cmd.argv, stdin, stdout, stderr, cmd.env_vars, proc_cwd)) + proc = subprocess.Popen(cmd.argv, stdin=stdin, stdout=stdout, stderr=stderr, env=env, cwd=proc_cwd) + del stdin, stdout, stderr + piped_commands.append(proc) + + try: + next_node = pipeline.pop(0) + except IndexError: + try: + retval = self._exec_piped_commands(piped_commands) + if verbose: + print "%s: exit code %i" % (' '.join(piped_commands_display), retval) + finally: + for f in files_to_close: + if f is not dev_null: + f.close() + files_to_close = [] + return retval + else: + + if isinstance(next_node, Pipe): + state = PIPE + piped_commands_display.append('|') + + elif isinstance(next_node, Or): + try: + this_retval = self._exec_piped_commands(piped_commands) + finally: + for f in files_to_close: + if f is not dev_null: + f.close() + files_to_close = [] + if this_retval == 0: + if verbose: + print "%s: exit code %i (|| is short-circuited)" % (' '.join(piped_commands_display), retval) + return this_retval + if verbose: + print "%s: exit code %i (|| proceeds)" % (' '.join(piped_commands_display), retval) + state = BEGIN + piped_commands = [] + piped_commands_display = [] + + elif isinstance(next_node, And): + try: + this_retval = self._exec_piped_commands(piped_commands) + finally: + for f in files_to_close: + if f is not dev_null: + f.close() + files_to_close = [] + if this_retval != 0: + if verbose: + print "%s: exit code %i (&& is short-circuited)" % (' '.join(piped_commands_display), retval) + return this_retval + if verbose: + print "%s: exit code %i (&& proceeds)" % (' '.join(piped_commands_display), retval) + state = BEGIN + piped_commands = [] + piped_commands_display = [] + + + +def _main(): + pipeline = Pipeline() + pipeline.parse('./foo.py 2>&1 < xxx | cat && ls') + print pipeline.run() + +if __name__ == '__main__': + _main() + diff --git a/wscript b/wscript index de321ef..7ae9b6a 100644 --- a/wscript +++ b/wscript @@ -1,22 +1,22 @@ ## -*- python -*- -## (C) 2007,2008 Gustavo J. A. M. Carneiro +## (C) 2007-2012 Gustavo J. A. M. Carneiro -import Options -import Build +from waflib import Options +from waflib import Build import Scripting -Scripting.excludes.remove('Makefile') +# Scripting.excludes.remove('Makefile') Scripting.dist_format = 'zip' -import Configure -Configure.autoconfig = True +from waflib import Configure +#Configure.autoconfig = True -import Logs +from waflib import Logs #from Params import fatal import os -import pproc as subprocess +import subprocess import shutil import sys import Configure @@ -24,13 +24,13 @@ import tarfile import re import types -import Task -Task.file_deps = Task.extract_deps +#import Task +#Task.file_deps = Task.extract_deps APPNAME='pybindgen' -srcdir = '.' -blddir = 'build' +top = '.' +out = 'build' @@ -197,11 +197,11 @@ def dist_hook(): pass -def set_options(opt): +def options(opt): opt.tool_options('python') opt.tool_options('compiler_cc') opt.tool_options('compiler_cxx') - opt.tool_options('cflags') + opt.tool_options('cflags', tooldir="waf-tools") opt.sub_options('examples') @@ -230,33 +230,65 @@ def set_options(opt): action="store_true", default=False, dest='valgrind') -def configure(conf): - def _check_compilation_flag(conf, flag): - """ - Checks if the C++ compiler accepts a certain compilation flag or flags - flag: can be a string or a list of strings - """ - env = conf.env.copy() +def _check_compilation_flag(conf, flag, mode='cxx', linkflags=None): + """ + Checks if the C++ compiler accepts a certain compilation flag or flags + flag: can be a string or a list of strings + """ + l = [] + if flag: + l.append(flag) + if isinstance(linkflags, list): + l.extend(linkflags) + else: + if linkflags: + l.append(linkflags) + if len(l) > 1: + flag_str = 'flags ' + ' '.join(l) + else: + flag_str = 'flag ' + ' '.join(l) + if flag_str > 28: + flag_str = flag_str[:28] + "..." + + conf.start_msg('Checking for compilation %s support' % (flag_str,)) + env = conf.env.copy() + + if mode == 'cc': + mode = 'c' + + if mode == 'cxx': + fname = 'test.cc' env.append_value('CXXFLAGS', flag) - try: - retval = conf.run_c_code(code='#include \nint main() { return 0; }\n', - env=env, compile_filename='test.cc', - compile_mode='cxx',type='cprogram', execute=False) - except Configure.ConfigurationError: - ok = False - else: - ok = (retval == 0) - conf.check_message_custom(flag, 'support', (ok and 'yes' or 'no')) - return ok + else: + fname = 'test.c' + env.append_value('CFLAGS', flag) + + if linkflags is not None: + env.append_value("LINKFLAGS", linkflags) + + try: + retval = conf.run_c_code(code='#include \nint main() { return 0; }\n', + env=env, compile_filename=fname, + features=[mode, mode+'program'], execute=False) + except Configure.ConfigurationError: + ok = False + else: + ok = (retval == 0) + conf.end_msg(ok) + return ok + + + +def configure(conf): conf.check_compilation_flag = types.MethodType(_check_compilation_flag, conf) ## Write a pybindgen/version.py file containing the project version generate_version_py() - conf.check_tool('command') + conf.check_tool('command', tooldir="waf-tools") conf.check_tool('python') conf.check_python_version((2,3)) @@ -297,19 +329,23 @@ def configure(conf): def build(bld): - global g_bld - g_bld = bld + #global g_bld + #g_bld = bld if getattr(Options.options, 'generate_version', False): generate_version_py(force=True) bld.add_subdirs('pybindgen') - if Options.options.examples: - bld.add_subdirs('examples') - if Options.commands['check'] or Options.commands['clean']: + + if bld.cmd == 'check': bld.add_subdirs('tests') - if Options.commands.get('bench', False) or Options.commands['clean']: - bld.add_subdirs('benchmarks') + + if 0: # FIXME + if Options.options.examples: + bld.add_subdirs('examples') + + if Options.commands.get('bench', False) or Options.commands['clean']: + bld.add_subdirs('benchmarks') check_context = Build.BuildContext @@ -332,55 +368,65 @@ def bench(bld): raise SystemExit(retval) -check_context = Build.BuildContext -def check(bld): - "run the unit tests; add option -v for verbose mode" - Scripting.build(bld) +from waflib import Context, Build +class CheckContext(Context.Context): + """run the unit tests""" + cmd = 'check' - if Options.options.verbose: - verbosity = ['-v'] - else: - verbosity = [] + def execute(self): - if Options.options.valgrind: - valgrind = ['valgrind', '--leak-check=full', '--leak-resolution=low'] - else: - valgrind = [] + # first we execute the build + bld = Context.create_context("build") + bld.options = Options.options # provided for convenience + bld.cmd = "check" + bld.execute() - print "Running pure python unit tests..." - retval1 = subprocess.Popen([Build.bld.env['PYTHON'], 'tests/test.py'] + verbosity).wait() - env = g_bld.env + if Options.options.verbose: + verbosity = ['-v'] + else: + verbosity = [] - if env['CXX']: - print "Running manual module generation unit tests (module foo)..." - retval2 = subprocess.Popen(valgrind + [env['PYTHON'], 'tests/footest.py', '1'] + verbosity).wait() - else: - print "Skipping manual module generation unit tests (no C/C++ compiler)..." - retval2 = 0 + if Options.options.valgrind: + valgrind = ['valgrind', '--leak-check=full', '--leak-resolution=low'] + else: + valgrind = [] - if env['ENABLE_PYGCCXML']: - print "Running automatically scanned module generation unit tests (module foo2)..." - retval3 = subprocess.Popen(valgrind + [env['PYTHON'], 'tests/footest.py', '2'] + verbosity).wait() + print "Running pure python unit tests..." + python = bld.env['PYTHON'][0] + retval1 = subprocess.Popen([python, 'tests/test.py'] + verbosity).wait() - print "Running module generated by automatically generated python script unit tests (module foo3)..." - retval3b = subprocess.Popen(valgrind + [env['PYTHON'], 'tests/footest.py', '3'] + verbosity).wait() + env = bld.env - print "Running module generated by generated and split python script unit tests (module foo4)..." - retval3c = subprocess.Popen(valgrind + [env['PYTHON'], 'tests/footest.py', '4'] + verbosity).wait() + if env['CXX']: + print "Running manual module generation unit tests (module foo)..." + retval2 = subprocess.Popen(valgrind + [python, 'tests/footest.py', '1'] + verbosity).wait() + else: + print "Skipping manual module generation unit tests (no C/C++ compiler)..." + retval2 = 0 - print "Running semi-automatically scanned c-hello module ('hello')..." - retval4 = subprocess.Popen(valgrind + [env['PYTHON'], 'tests/c-hello/hellotest.py'] + verbosity).wait() - else: - print "Skipping automatically scanned module generation unit tests (pygccxml missing)..." - print "Skipping module generated by automatically generated python script unit tests (pygccxml missing)..." - print "Skipping module generated by generated and split python script unit tests (pygccxml missing)..." - print "Skipping semi-automatically scanned c-hello module (pygccxml missing)..." - retval3 = retval3b = retval3c = retval4 = 0 + if env['ENABLE_PYGCCXML']: + print "Running automatically scanned module generation unit tests (module foo2)..." + retval3 = subprocess.Popen(valgrind + [python, 'tests/footest.py', '2'] + verbosity).wait() - if retval1 or retval2 or retval3 or retval3b or retval3c or retval4: - Logs.error("Unit test failures") - raise SystemExit(2) + print "Running module generated by automatically generated python script unit tests (module foo3)..." + retval3b = subprocess.Popen(valgrind + [python, 'tests/footest.py', '3'] + verbosity).wait() + + print "Running module generated by generated and split python script unit tests (module foo4)..." + retval3c = subprocess.Popen(valgrind + [python, 'tests/footest.py', '4'] + verbosity).wait() + + print "Running semi-automatically scanned c-hello module ('hello')..." + retval4 = subprocess.Popen(valgrind + [python, 'tests/c-hello/hellotest.py'] + verbosity).wait() + else: + print "Skipping automatically scanned module generation unit tests (pygccxml missing)..." + print "Skipping module generated by automatically generated python script unit tests (pygccxml missing)..." + print "Skipping module generated by generated and split python script unit tests (pygccxml missing)..." + print "Skipping semi-automatically scanned c-hello module (pygccxml missing)..." + retval3 = retval3b = retval3c = retval4 = 0 + + if retval1 or retval2 or retval3 or retval3b or retval3c or retval4: + Logs.error("Unit test failures") + raise SystemExit(2) def docs(ctx): @@ -391,3 +437,29 @@ def docs(ctx): Logs.error("make returned with code %i" % retval) raise SystemExit(2) + +# +# FIXME: Remove this when upgrading beyond WAF 1.6.11; this here is +# only to fix a bug in WAF... +# +from waflib.Tools import python +from waflib import TaskGen +@TaskGen.feature('pyext') +@TaskGen.before_method('propagate_uselib_vars', 'apply_link') +@TaskGen.after_method('apply_bundle') +def init_pyext(self): + """ + Change the values of *cshlib_PATTERN* and *cxxshlib_PATTERN* to remove the + *lib* prefix from library names. + """ + self.uselib = self.to_list(getattr(self, 'uselib', [])) + if not 'PYEXT' in self.uselib: + self.uselib.append('PYEXT') + # override shlib_PATTERN set by the osx module + self.env['cshlib_PATTERN'] = self.env['cxxshlib_PATTERN'] = self.env['macbundle_PATTERN'] = self.env['pyext_PATTERN'] + + try: + if not self.install_path: + return + except AttributeError: + self.install_path = '${PYTHONARCHDIR}'