⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 boostbuild.py

📁 C++的一个好库。。。现在很流行
💻 PY
📖 第 1 页 / 共 2 页
字号:

import TestCmd
from tree import build_tree, trees_difference
import copy
import fnmatch
import os
import shutil
import string
import types
import time
import tempfile
import sys
import re

def get_toolset():
    toolset = None;
    for arg in sys.argv[1:]:
        if not arg.startswith('-'):
            toolset = arg
    return toolset or 'gcc'

windows = 0
if os.environ.get('OS','').lower().startswith('windows') or \
       os.__dict__.has_key('uname') and \
       os.uname()[0].lower().startswith('cygwin'):
    windows = 1

suffixes = {}

# Prepare the map of suffixes
def prepare_suffix_map(toolset):
    global windows, suffixes    
    suffixes = {'.exe': '', '.dll': '.so', '.lib': '.a', '.obj': '.o'}
    if windows:
        suffixes = {}
        if toolset in ["gcc"]:
            suffixes['.lib'] = '.a' # static libs have '.a' suffix with mingw...
            suffixes['.obj'] = '.o'
    if os.__dict__.has_key('uname') and os.uname()[0] == 'Darwin':
        suffixes['.dll'] = '.dylib'

lib_prefix = 1
if windows:
    lib_prefix = 0
        
    
    
#
# FIXME: this is copy-pasted from TestSCons.py
# Should be moved to TestCmd.py?
#
if os.name == 'posix':
    def _failed(self, status = 0):
        if self.status is None:
            return None
        if os.WIFSIGNALED(status):
            return None
        return _status(self) != status
    def _status(self):
        if os.WIFEXITED(self.status):
            return os.WEXITSTATUS(self.status)
        else:
            return None
elif os.name == 'nt':
    def _failed(self, status = 0):
        return not self.status is None and self.status != status
    def _status(self):
        return self.status

class Tester(TestCmd.TestCmd):
    """Class for testing Boost.Build.

    Optional argument `executable` indicates the name of the
    executable to invoke. Set this to "jam" to test Boost.Build v1
    behavior.

    Optional argument `work_dir` indicates an absolute directory, 
    where the test will run be run.
    """
    def __init__(self, arguments="", executable = 'bjam', match =
                 TestCmd.match_exact, boost_build_path = None,
                 translate_suffixes = 1, pass_toolset = 1,
                 workdir = '',
                 **keywords):

        self.original_workdir = os.getcwd()
        if workdir != '' and not os.path.isabs(workdir):
            raise "Parameter workdir <"+workdir+"> must point to a absolute directory: "

        self.last_build_time = 0
        self.translate_suffixes = translate_suffixes

        self.toolset = get_toolset()
        self.pass_toolset = pass_toolset
        
        prepare_suffix_map(pass_toolset and self.toolset or 'gcc')

        jam_build_dir = ""
        if os.name == 'nt':
            jam_build_dir = "bin.ntx86"
        elif os.name == 'posix' and os.__dict__.has_key('uname'):
            if os.uname()[0].lower().startswith('cygwin'):
                jam_build_dir = "bin.cygwinx86"
                if 'TMP' in os.environ and os.environ['TMP'].find('~') != -1:
                    print 'Setting $TMP to /tmp to get around problem with short path names'
                    os.environ['TMP'] = '/tmp'
            elif os.uname()[0] == 'Linux':
                cpu = os.uname()[4]
                if re.match("i.86", cpu):
                    jam_build_dir = "bin.linuxx86";
                else:
                    jam_build_dir = "bin.linux" + os.uname()[4]
            elif os.uname()[0] == 'SunOS':
                jam_build_dir = "bin.solaris"
            elif os.uname()[0] == 'Darwin':
                jam_build_dir = "bin.macosxppc"
            elif os.uname()[0] == "AIX":
                jam_build_dir = "bin.aix"
            elif os.uname()[0] == "IRIX64":
                jam_build_dir = "bin.irix"
            elif os.uname()[0] == "FreeBSD":
                jam_build_dir = "bin.freebsd"
            else:
                raise "Don't know directory where jam is build for this system: " + os.name + "/" + os.uname()[0]
        else:
            raise "Don't know directory where jam is build for this system: " + os.name

        if boost_build_path is None:
            boost_build_path = self.original_workdir
            

        verbosity = ['-d0', '--quiet']
        if '--verbose' in sys.argv:
            keywords['verbose'] = 1
            verbosity = ['-d+2']

        program_list = []

        # Find there jam_src is located.
        # try for the debug version if it's lying around

        dirs = [os.path.join('../../jam_src', jam_build_dir + '.debug'),
                os.path.join('../../jam_src', jam_build_dir),
                os.path.join('../jam_src', jam_build_dir + '.debug'),
                os.path.join('../jam_src', jam_build_dir),
                ]

        for d in dirs:
            if os.path.exists(d):
                jam_build_dir = d
                break
        else:
            print "Cannot find built Boost.Jam"
            os.exit(1)                                    
        
            
        program_list.append(os.path.join(jam_build_dir, executable))
        program_list.append('-sBOOST_BUILD_PATH=' + boost_build_path)
        if verbosity:
            program_list += verbosity
        if arguments:
            program_list += arguments.split(" ")

        TestCmd.TestCmd.__init__(
            self
            , program=program_list
            , match=match
            , workdir = workdir
            , **keywords)

        os.chdir(self.workdir)

    def cleanup(self):
        try:
            TestCmd.TestCmd.cleanup(self)
            os.chdir(self.original_workdir)
        except AttributeError:
            # Whe this is called during by TestCmd.TestCmd.__del__ we can have both
            # 'TestCmd' and 'os' unavailable in our scope. Do nothing in this case.
            pass
            
    #
    # Methods that change working directory's content
    #
    def set_tree(self, tree_location):
        # Seem like it's not possible to remove a directory which is
        # current.
        d = os.getcwd()
        os.chdir(os.path.dirname(self.workdir))
        shutil.rmtree(self.workdir, ignore_errors=0)

        if not os.path.isabs(tree_location):
                tree_location = os.path.join(self.original_workdir, tree_location)
        shutil.copytree(tree_location, self.workdir)

        os.chdir(d)

        def make_writable(unused, dir, entries):
            for e in entries:
                name = os.path.join(dir, e)
                os.chmod(name, os.stat(name)[0] | 0222)

        os.path.walk(".", make_writable, None)


    def write(self, file, content):
        self.wait_for_time_change()
        nfile = self.native_file_name(file)
        try:
            os.makedirs(os.path.dirname(nfile))
        except Exception, e:
            pass
        open(nfile, "wb").write(content)

    def rename(self, old, new):
        try:
            os.makedirs(os.path.dirname(new))
        except:
            pass
        
        try:
            os.remove(new)
        except:
            pass
        
        os.rename(old, new)
        self.touch(new);

    def copy(self, src, dst):
        self.wait_for_time_change()
        self.write(dst, self.read(src))

    def touch(self, names):
        self.wait_for_time_change()
        for name in self.adjust_names(names):
                os.utime(self.native_file_name(name), None)

    def rm(self, names):
        self.wait_for_time_change()
        if not type(names) == types.ListType:
            names = [names]

        # Avoid attempts to remove current dir
        os.chdir(self.original_workdir)
        for name in names:
            n = self.native_file_name(name)
            if os.path.isdir(n):
                shutil.rmtree(n, ignore_errors=0)
            else:
                os.unlink(n)

        # Create working dir root again, in case
        # we've removed it
        if not os.path.exists(self.workdir):
            os.mkdir(self.workdir)
        os.chdir(self.workdir)

    def expand_toolset(self, name):
        """Expands $toolset in the given file to tested toolset"""
        content = self.read(name)
        content = string.replace(content, "$toolset", self.toolset)
        self.write(name, content)
                                                        
    def dump_stdio(self):
        print "STDOUT ============"
        print self.stdout()    
        print "STDERR ============"
        print self.stderr()
        print "END ==============="
                    
    #
    #   FIXME: Large portion copied from TestSCons.py, should be moved?
    #
    def run_build_system(
        self, extra_args='', subdir='', stdout = None, stderr = '',
        status = 0, match = None, pass_toolset = None, **kw):

        if os.path.isabs(subdir):
            if stderr:
                print "You must pass a relative directory to subdir <"+subdir+">."
            status = 1
            return

        self.previous_tree = build_tree(self.workdir)

        if match is None:
            match = self.match

        if pass_toolset is None:
            pass_toolset = self.pass_toolset        

        try:
            kw['program'] = []
            kw['program'] += self.program
            if extra_args:
                kw['program'] += extra_args.split(" ")            
            if pass_toolset:
                kw['program'].append(self.toolset)
            kw['chdir'] = subdir
            apply(TestCmd.TestCmd.run, [self], kw)
        except:
            self.dump_stdio()
            raise

        if status != None and _failed(self, status):
            expect = ''
            if status != 0:
                expect = " (expected %d)" % status

            print '"%s" returned %d%s' % (
                kw['program'], _status(self), expect)

            self.fail_test(1)

        if not stdout is None and not match(self.stdout(), stdout):
            print "Expected STDOUT =========="
            print stdout
            print "Actual STDOUT ============"
            print self.stdout()
            stderr = self.stderr()
            if stderr:
                print "STDERR ==================="
                print stderr
            self.maybe_do_diff(self.stdout(), stdout)
            self.fail_test(1, dump_stdio = 0)

        # Intel tends to produce some message to stderr, which makes tests
        # fail
        intel_workaround = re.compile("^xi(link|lib): executing.*\n", re.M)
        actual_stderr = re.sub(intel_workaround, "", self.stderr())

        if not stderr is None and not match(actual_stderr, stderr):
            print "STDOUT ==================="

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -