Beispiel #1
0
 def run(self):
     create_rpm.run(self, False)
     # we have one dir under BUILDROOT
     # we move under the buildroot/pkg-name dir as we do not want then to be part of remote sync
     _cwd = os.path.join(
         self.rpm_top_dir, 'BUILDROOT',
         os.listdir(os.path.join(self.rpm_top_dir, 'BUILDROOT'))[0])
     _cmd = (
         '/usr/bin/rsync', '-rltvz', '--no-times', '-e',
         'ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null',
         '--progress', '.', 'opc@%s:/tmp/rsynced' % str(self.remote_ip))
     ec = subprocess.call(_cmd, cwd=_cwd)
     if ec != 0:
         raise DistutilsExecError("rpmbuild execution failed")
Beispiel #2
0
 def run(self):
     # sphinx-build -b html docs build\docs_html
     # defer import so not all setups require sphinx
     from sphinx.application import Sphinx
     from sphinx.util.console import nocolor, color_terminal
     nocolor()
     source_dir = os.path.join(MYPATH, 'docs')
     target_dir = os.path.join(MYPATH, 'build', 'docs_html')
     doctree_dir = os.path.join(target_dir, '.doctree')
     app = Sphinx(source_dir, source_dir, target_dir, doctree_dir, 'html')
     app.build()
     if app.statuscode:
         raise DistutilsExecError(
             'caused by %s builder.' % app.builder.name)
Beispiel #3
0
def _spawn_nt(cmd, search_path=1, verbose=0, dry_run=0):
    executable = cmd[0]
    cmd = _nt_quote_args(cmd)
    if search_path:
        # either we find one or it stays the same
        executable = find_executable(executable) or executable
    log.info(' '.join([executable] + cmd[1:]))
    if not dry_run:
        # spawn for NT requires a full path to the .exe
        try:
            rc = os.spawnv(os.P_WAIT, executable, cmd)
        except OSError as exc:
            # this seems to happen when the command isn't found
            if not DEBUG:
                cmd = executable
            raise DistutilsExecError("command %r failed: %s" %
                                     (cmd, exc.args[-1]))
        if rc != 0:
            # and this reflects the command running but failing
            if not DEBUG:
                cmd = executable
            raise DistutilsExecError("command %r failed with exit status %d" %
                                     (cmd, rc))
Beispiel #4
0
    def run(self):
        try:
            from pylint import lint
        except ImportError:
            raise DistutilsExecError('pylint is not installed')

        lint_args = [MODULEDIR]
        rcfile = os.path.join(TOPDIR, '.pylintrc')
        if os.path.exists(rcfile):
            lint_args.extend(['--rcfile', rcfile])
        if self.errors_only:
            lint_args.append('-E')
        lint_args.extend(['--output-format', self.output_format])
        lint.Run(lint_args)
Beispiel #5
0
    def run(self):
        # type: () -> None
        if not color_terminal():
            nocolor()
        if not self.verbose:  # type: ignore
            status_stream = StringIO()
        else:
            status_stream = sys.stdout  # type: ignore
        confoverrides = {}
        if self.project:
            confoverrides['project'] = self.project
        if self.version:
            confoverrides['version'] = self.version
        if self.release:
            confoverrides['release'] = self.release
        if self.today:
            confoverrides['today'] = self.today
        if self.copyright:
            confoverrides['copyright'] = self.copyright

        for builder, builder_target_dir in self.builder_target_dirs:
            app = None

            try:
                confdir = self.config_dir or self.source_dir
                with patch_docutils(confdir), docutils_namespace():
                    app = Sphinx(self.source_dir,
                                 self.config_dir,
                                 builder_target_dir,
                                 self.doctree_dir,
                                 builder,
                                 confoverrides,
                                 status_stream,
                                 freshenv=self.fresh_env,
                                 warningiserror=self.warning_is_error)
                    app.build(force_all=self.all_files)
                    if app.statuscode:
                        raise DistutilsExecError('caused by %s builder.' %
                                                 app.builder.name)
            except Exception as exc:
                handle_exception(app, self, exc, sys.stderr)
                if not self.pdb:
                    raise SystemExit(1)

            if not self.link_index:
                continue

            src = app.config.master_doc + app.builder.out_suffix  # type: ignore
            dst = app.builder.get_outfilename('index')  # type: ignore
            os.symlink(src, dst)
Beispiel #6
0
def write_pkgcore_ebd_funclists(root, target, scripts_dir, python_base='.'):
    "Generate bash function lists from ebd implementation for env filtering."""
    ebd_dir = target
    if root != '/':
        ebd_dir = os.path.join(root, target.lstrip('/'))
    log.info("Writing ebd function lists to %s" % os.path.join(ebd_dir, 'funcnames'))
    try:
        os.makedirs(os.path.join(ebd_dir, 'funcnames'))
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    # Add scripts dir to PATH and set the current python binary for filter-env
    # usage in global scope.
    env = {
        'PATH': os.pathsep.join([os.path.abspath(scripts_dir), os.environ.get('PATH', '')]),
        'PKGCORE_PYTHON_BINARY': sys.executable,
        'PKGCORE_PYTHONPATH': os.path.abspath(python_base),
    }

    # generate global function list
    with open(os.path.join(ebd_dir, 'funcnames', 'global'), 'w') as f:
        if subprocess.call(
                [os.path.join(pkgdist.TOPDIR, 'ebd', 'generate_global_func_list.bash')],
                cwd=ebd_dir, env=env, stdout=f):
            raise DistutilsExecError("generating global function list failed")

    # generate EAPI specific function lists
    eapis = (x.split('.')[0] for x in os.listdir(os.path.join(pkgdist.TOPDIR, 'ebd', 'eapi'))
             if x.split('.')[0].isdigit())
    for eapi in sorted(eapis):
        with open(os.path.join(ebd_dir, 'funcnames', eapi), 'w') as f:
            if subprocess.call(
                    [os.path.join(pkgdist.TOPDIR, 'ebd', 'generate_eapi_func_list.bash'), eapi],
                    cwd=ebd_dir, env=env, stdout=f):
                raise DistutilsExecError(
                    "generating EAPI %s function list failed" % eapi)
Beispiel #7
0
    def run(self):
        if not color_terminal():
            nocolor()
        if not self.verbose:
            status_stream = StringIO()
        else:
            status_stream = sys.stdout
        confoverrides = {}
        if self.project:
            confoverrides['project'] = self.project
        if self.version:
            confoverrides['version'] = self.version
        if self.release:
            confoverrides['release'] = self.release
        if self.today:
            confoverrides['today'] = self.today
        if self.copyright:
            confoverrides['copyright'] = self.copyright
        app = Sphinx(self.source_dir, self.config_dir,
                     self.builder_target_dir, self.doctree_dir,
                     self.builder, confoverrides, status_stream,
                     freshenv=self.fresh_env,
                     warningiserror=self.warning_is_error)

        try:
            app.build(force_all=self.all_files)
            if app.statuscode:
                raise DistutilsExecError(
                    'caused by %s builder.' % app.builder.name)
        except Exception as err:
            if self.pdb:
                import pdb
                print(darkred('Exception occurred while building, starting debugger:'),
                      file=sys.stderr)
                traceback.print_exc()
                pdb.post_mortem(sys.exc_info()[2])
            else:
                from docutils.utils import SystemMessage
                if isinstance(err, SystemMessage):
                    print(darkred('reST markup error:'), file=sys.stderr)
                    print(err.args[0].encode('ascii', 'backslashreplace'),
                          file=sys.stderr)
                else:
                    raise

        if self.link_index:
            src = app.config.master_doc + app.builder.out_suffix
            dst = app.builder.get_outfilename('index')
            os.symlink(src, dst)
def GetSetupSrcDir():
    ''' Get the original directory in which setup.py was located, even if setup.py is run through pip.
    "Platform-independent", though linux and windows untested.

    :return: setupSrcDir as a string
    '''
    dirVars = ['PWD', 'CD']
    for dirVar in dirVars:
        if os.environ[dirVar]:
            return os.environ[dirVar]

    # if we got here something went wrong, so raise an error
    DistutilsExecError(
        'While looking for the original setup.py directory, os.environ did not contain relevant variable: %s'
        % dirVars)
Beispiel #9
0
    def run(self):
        from snakeoil.dist import unittest_extensions

        build_ext = self.reinitialize_command('build_ext')
        build_py = self.reinitialize_command('build_py')
        build_ext.inplace = build_py.inplace = self.inplace
        build_ext.force = build_py.force = self.force
        build_ext.ensure_finalized()
        build_py.ensure_finalized()

        if self.include_dirs:
            build_ext.include_dirs = self.include_dirs

        if not self.pure_python:
            self.run_command('build_ext')
        if not self.inplace:
            self.run_command('build_py')

        syspath = sys.path[:]
        mods_to_wipe = ()
        if not self.inplace:
            cwd = os.getcwd()
            syspath = [x for x in sys.path if x != cwd]
            test_path = os.path.abspath(build_py.build_lib)
            syspath.insert(0, test_path)
            mods = build_py.find_all_modules()
            mods_to_wipe = set(x[0] for x in mods)
            mods_to_wipe.update('.'.join(x[:2]) for x in mods)

        namespaces = self.namespaces
        if not self.namespaces:
            namespaces = [self.default_test_namespace]

        retval = unittest_extensions.run_tests(namespaces,
                                               disable_fork=self.disable_fork,
                                               blacklist=self.blacklist,
                                               pythonpath=syspath,
                                               modules_to_wipe=mods_to_wipe)

        # remove temporary plugincache so it isn't installed
        plugincache = os.path.join(os.path.abspath(build_py.build_lib),
                                   build_py.package_namespace,
                                   'plugins/plugincache')
        if os.path.exists(plugincache):
            os.remove(plugincache)

        if retval:
            raise DistutilsExecError("tests failed; return %i" % (retval, ))
Beispiel #10
0
    def run(self):
        if os.path.exists(self._indexfilename):
            with open(self._indexfilename, 'w') as f:
                f.write('# empty\n')

        # here no extension enabled, disabled() lists up everything
        code = ('import pprint; from mercurial import extensions; '
                'pprint.pprint(extensions.disabled())')
        out, err = runcmd([sys.executable, '-c', code], env)
        if err:
            raise DistutilsExecError(err)

        with open(self._indexfilename, 'w') as f:
            f.write('# this file is autogenerated by setup.py\n')
            f.write('docs = ')
            f.write(out)
 def run(self):
     if self.uptodate():
         print("Nothing to do")
         return
     if not os.path.exists("autoconf"):
         os.makedirs("autoconf")
     if not os.path.exists("autoconf/m4"):
         os.makedirs("autoconf/m4")
     with open(os.path.join("autoconf", "configure.ac"), "w") as outfile:
         outfile.write(self.create_configure_ac())
     with open(os.path.join("autoconf", "Makefile.am"), "w") as outfile:
         outfile.write("print-dist-archives:\n\t@echo '$(DIST_ARCHIVES)'\n")
     res = os.system("cd autoconf; autoreconf -i")
     exit_code = res >> 8
     if exit_code:
         raise DistutilsExecError()
Beispiel #12
0
 def run(self):
     self.run_command('build')  # build if not alredy run
     orig_path = sys.path[:]
     try:
         build_path = abspath(self.build_lib)
         sys.path.insert(0, build_path)
         import ceygen.tests as t
         assert dirname(t.__file__) == join(build_path, 'ceygen', 'tests')
         suite = unittest.TestLoader().loadTestsFromModule(t)
         result = unittest.TextTestRunner(verbosity=self.verbose).run(suite)
         if not result.wasSuccessful():
             raise Exception("There were test failures")
     except Exception as e:
         raise DistutilsExecError(e)
     finally:
         sys.path = orig_path
Beispiel #13
0
    def build_extension(self, ext):
        if not isinstance(ext, Executable):
            build_ext.build_extension(self, ext)
            return

        cmd = [sys.executable, ext.script, ext.target]
        if self.force:
            cmd += ["--force"]
        log.debug("running '{}'".format(" ".join(cmd)))
        if not self.dry_run:
            env = self._compiler_env.copy()
            if ext.env:
                env.update(ext.env)
            p = subprocess.run(cmd, cwd=ext.cwd, env=env)
            if p.returncode != 0:
                from distutils.errors import DistutilsExecError

                raise DistutilsExecError("running '{}' script failed".format(
                    ext.script))

        exe_fullpath = os.path.join(ext.output_dir, ext.target)

        dest_path = self.get_ext_fullpath(ext.name)
        mkpath(os.path.dirname(dest_path),
               verbose=self.verbose,
               dry_run=self.dry_run)

        copy_file(exe_fullpath,
                  dest_path,
                  verbose=self.verbose,
                  dry_run=self.dry_run)
        dest_path = os.path.dirname(dest_path)
        # I have the impression that this is not the ideal place to declare
        # this list of files, but for now that's good enough.
        # I would appreciate some input form Cosimo here on a better approach.
        # -- Felipe Sanches
        for dll_filename in [
                "Compat.dll", "Glyph.dll", "IronPython.dll", "mono-webkit.dll",
                "OTFontFileVal.dll", "ValCommon.dll", "GMath.dll",
                "IronPython.Modules.dll", "OTFontFile.dll", "SharpFont.dll"
        ]:
            dll_fullpath = os.path.join(ext.output_dir, dll_filename)
            copy_file(dll_fullpath,
                      dest_path,
                      verbose=self.verbose,
                      dry_run=self.dry_run)
Beispiel #14
0
 def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
     compiler_so = self.compiler_so
     if sys.platform == 'darwin':
         compiler_so = _osx_support.compiler_fixup(compiler_so,
                                                   cc_args + extra_postargs)
     try:
         # iOS: since clang is not available, we send a nicer error message:
         if (sys.platform == 'darwin'
                 and os.uname().machine.startswith('iP')):
             raise DistutilsExecError(
                 "There are no compilers available on iOS, sorry. Command was: ",
                 cc_args)
         #
         self.spawn(compiler_so + cc_args + [src, '-o', obj] +
                    extra_postargs)
     except DistutilsExecError as msg:
         raise CompileError(msg)
Beispiel #15
0
    def __init__(self):
        _gsl_Location.__init__(self)
        try:
            import gsl_site
        except ImportError as des:
            msg = "I do not know how to run gsl-config \n"+\
               "on this system. Therefore you must provide me with the information\n" +\
               "where to find the GSL library. I could not import `gsl_site'.\n" +\
               "Reason: %s. Copy gsl_site_example.py to gsl_site.py.\n"+\
               "Edit the variables in that file to reflect your installation."
            raise DistutilsExecError(msg % des)

        self.prefix = gsl_site.prefix
        self.cflags = gsl_site.cflags
        self.libs = gsl_site.libs
        self.swig = gsl_site.swig
        self.version = self._split_version(gsl_site.version)
    def run(self):
        self.run_command('autoconf')
        if self.uptodate():
            print("Nothing to do")
            return

        toks = ['./configure']
        options = self.distribution.get_option_dict(self.__class__.__name__)
        for name, value in options.items():
            toks.append('--%s=%s' % (name.replace('_', '-'), value[1]))
        cmd = "export PYTHON=%s; cd autoconf; " % sys.executable \
            + " ".join(toks)
        print("Configure: %s" % cmd)
        res = os.system(cmd)
        exit_code = res >> 8
        if exit_code:
            raise DistutilsExecError()
 def create_configure_ac(self):
     """
     Create the `configure.ac` script from the configure_ac setup variable.
     """
     configure_ac = self.distribution.configure_ac
     for name in ('AC_PREREQ', 'AC_INIT', 'AC_CONFIG_MACRO_DIR',
                  'AM_INIT_AUTOMAKE', 'AC_CONFIG_FILES', 'AC_OUTPUT'):
         if name in configure_ac:
             raise DistutilsExecError("Don't provide `%s` in configure_ac" %
                                      name)
     autoconf_version = self.distribution.autoconf_version
     if autoconf_version is not None:
         prereq = "AC_PREREQ([%s])" % autoconf_version
     else:
         prereq = ""
     return self.configure_ac_tmpl % (
         prereq, self.distribution.metadata.name
         or "foo", self.distribution.metadata.version or "1", configure_ac)
Beispiel #18
0
    def run(self, do_cleanup=True):
        """
        Run the actual sdist command and create the tarball under tarball_dir.

        Returns
        -------
            No return value.

        Raises
        ------
            DistutilsExecError
                On any error.
        """
        log.info("running sdist command now...")
        self.run_command('sdist')
        log.info("tarball created, building the RPM now...")
        _cwd = os.path.dirname(os.path.abspath(__file__))
        log.info('current wd [%s]' % _cwd)
        redefined_top_dir = os.path.join(_cwd, self.rpm_top_dir)
        spec_file_abs_path = os.path.join(_cwd, self.spec_file_path)
        v_opt = '--quiet'
        if self.verbose:
            v_opt = '-v'

        if do_cleanup:
            rpmbuild_cmd = ('/bin/rpmbuild',
                            v_opt,
                            '--define',
                            '_topdir %s' % redefined_top_dir,
                            '-ba',
                            spec_file_abs_path)
        else:
            rpmbuild_cmd = ('/bin/rpmbuild',
                            v_opt,
                            '--define',
                            '_topdir %s' % redefined_top_dir,
                            '--noclean',
                            '-ba',
                            spec_file_abs_path)

        log.info('executing %s' % ' '.join(rpmbuild_cmd))
        ec = subprocess.call(rpmbuild_cmd)
        if ec != 0:
            raise DistutilsExecError("rpmbuild execution failed")
Beispiel #19
0
def write_pkgcore_lookup_configs(python_base,
                                 install_prefix,
                                 injected_bin_path=()):
    """Generate file of install path constants."""
    path = os.path.join(python_base, "pkgcore", "_const.py")
    log.info("writing lookup config to %r" % path)
    with open(path, "w") as f:
        os.chmod(path, 0o644)
        f.write("INSTALL_PREFIX=%r\n" % install_prefix)
        f.write("DATA_PATH=%r\n" %
                os.path.join(install_prefix, DATA_INSTALL_OFFSET))
        f.write("CONFIG_PATH=%r\n" %
                os.path.join(install_prefix, CONFIG_INSTALL_OFFSET))
        f.write("LIBDIR_PATH=%r\n" %
                os.path.join(install_prefix, LIBDIR_INSTALL_OFFSET))
        f.write("EBD_PATH=%r\n" %
                os.path.join(install_prefix, EBD_INSTALL_OFFSET))

        # This is added to suppress the default behaviour of looking
        # within the repo for a bin subdir.
        f.write("INJECTED_BIN_PATH=%r\n" % (tuple(injected_bin_path), ))

        # Static paths for various utilities.
        from snakeoil import process
        required_progs = ('bash', 'cp')
        try:
            for prog in required_progs:
                prog_path = process.find_binary(prog)
                f.write("%s_BINARY=%r\n" % (prog.upper(), prog_path))
        except process.CommandNotFound:
            raise DistutilsExecError(
                "generating lookup config failed: required utility %r missing from PATH"
                % (prog, ))

        extra_progs = ('sandbox', )
        for prog in extra_progs:
            try:
                prog_path = process.find_binary(prog)
            except process.CommandNotFound:
                prog_path = ''
            f.write("%s_BINARY=%r\n" % (prog.upper(), prog_path))

    byte_compile([path], prefix=python_base)
    byte_compile([path], optimize=2, prefix=python_base)
Beispiel #20
0
    def install(self):
        """Install docs to target dirs."""
        source_path = self.find_content()
        if source_path is None:
            raise DistutilsExecError('no generated sphinx content')

        # determine mapping from doc files to install paths
        content = self._map_paths(get_file_paths(source_path))

        # create directories
        directories = set(map(os.path.dirname, content.values()))
        directories.discard('')
        for x in sorted(directories):
            self.mkpath(os.path.join(self.install_dir, x))

        # copy docs over
        for src, dst in sorted(content.items()):
            self.copy_file(os.path.join(source_path, src),
                           os.path.join(self.install_dir, dst))
Beispiel #21
0
    def run(self):
        # Ensure the extension is built
        self.run_command('build')

        # test the uninstalled extensions
        libdir = os.path.join(os.getcwd(), self.build_lib)

        sys.path.insert(0, libdir)

        import testsuite

        try:
            failures = testsuite.run()

        except RuntimeError, msg:
            sys.stderr.write('error: %s\n' % msg)
            raise DistutilsExecError(
                'please consult the "Troubleshooting" section in the README file.'
            )
Beispiel #22
0
 def copy_file(self, src, dest, *args, **kwds):
     """
     Overridden to validate Python sources before copying them.
     """
     if src.endswith('.py') or (sys.platform == 'win32'
                                and src.endswith('.pyw')):
         try:
             # Python 2.3+
             f = open(src, 'rU')
         except:
             # Python 2.2
             f = open(src, 'r')
             codestring = f.read()
             codestring = codestring.replace("\r\n", "\n")
             codestring = codestring.replace("\r", "\n")
         else:
             codestring = f.read()
         f.close()
         if codestring and codestring[-1] != '\n':
             codestring = codestring + '\n'
         try:
             compile(codestring, src, 'exec')
         except SyntaxError, detail:
             msg, (filename, lineno, offset, line) = detail
             if not filename: filename = src
             L = [
                 'Syntax error in file "%s", line %d: %s' %
                 (filename, lineno, msg)
             ]
             if line is not None:
                 i = 0
                 while i < len(line) and line[i].isspace():
                     i = i + 1
                 L.append('    %s' % line.strip())
                 if offset is not None:
                     s = '    '
                     for c in line[i:offset - 1]:
                         if c.isspace():
                             s = s + c
                         else:
                             s = s + ' '
                     L.append('%s^' % s)
             raise DistutilsExecError('\n'.join(L))
def CCompiler_spawn(self, cmd, display=None):
    cmd = quote_args(cmd)
    """
    Execute a command in a sub-process.

    Parameters
    ----------
    cmd : str
        The command to execute.
    display : str or sequence of str, optional
        The text to add to the log file kept by `numpy.distutils`.
        If not given, `display` is equal to `cmd`.

    Returns
    -------
    None

    Raises
    ------
    DistutilsExecError
        If the command failed, i.e. the exit status was not 0.

    """
    if display is None:
        display = cmd
        if is_sequence(display):
            display = ' '.join(list(display))
    log.info(display)
    s, o = exec_command(cmd)
    if s:
        if is_sequence(cmd):
            cmd = ' '.join(list(cmd))
        try:
            print(o)
        except UnicodeError:
            # When installing through pip, `o` can contain non-ascii chars
            pass
        if re.search('Too many open files', o):
            msg = '\nTry rerunning setup command until build succeeds.'
        else:
            msg = ''
        raise DistutilsExecError('Command "%s" failed with exit status %d%s' %
                                 (cmd, s, msg))
def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
    """Create a zip file from all the files under 'base_dir'.

    The output zip file will be named 'base_name' + ".zip".  Uses either the
    "zipfile" Python module (if available) or the InfoZIP "zip" utility
    (if installed and found on the default search path).  If neither tool is
    available, raises DistutilsExecError.  Returns the name of the output zip
    file.
    """
    zip_filename = base_name + '.zip'
    mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
    if zipfile is None:
        if verbose:
            zipoptions = '-r'
        else:
            zipoptions = '-rq'
        try:
            spawn(['zip', zipoptions, zip_filename, base_dir], dry_run=dry_run)
        except DistutilsExecError:
            raise DistutilsExecError(
                "unable to create zip file '%s': could neither import the 'zipfile' module nor find a standalone zip utility"
                % zip_filename)
    else:
        log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
        if not dry_run:
            try:
                zip = zipfile.ZipFile(zip_filename,
                                      'w',
                                      compression=zipfile.ZIP_DEFLATED)
            except RuntimeError:
                zip = zipfile.ZipFile(zip_filename,
                                      'w',
                                      compression=zipfile.ZIP_STORED)
            for dirpath, dirnames, filenames in os.walk(base_dir):
                for name in filenames:
                    path = os.path.normpath(os.path.join(dirpath, name))
                    if os.path.isfile(path):
                        zip.write(path, path)
                        log.info("adding '%s'", path)
            zip.close()
    return zip_filename
Beispiel #25
0
 def run(self):
     self.run_command('build')  # build if not alredy run
     orig_path = sys.path[:]
     try:
         tests_path = abspath(self.build_lib)
         sys.path.insert(0, tests_path)
         import pybayes.stresses
         if dirname(pybayes.stresses.__file__) != join(
                 tests_path, 'pybayes', 'stresses'):
             raise Exception(
                 "Expected that imported pybayes.stresses would be from " +
                 "{0}, but it was from {1} instead".format(
                     tests_path, dirname(pybayes.tests.__file__)))
         suite = unittest.TestLoader().loadTestsFromModule(pybayes.stresses)
         result = unittest.TextTestRunner(verbosity=self.verbose).run(suite)
         if not result.wasSuccessful():
             raise Exception("There were test failures")
     except Exception as e:
         raise DistutilsExecError(e)
     finally:
         sys.path = orig_path
Beispiel #26
0
    def run(self, firstrun=True):
        self.source_path = self.find_content()
        if self.source_path is None:
            if not firstrun:
                raise DistutilsExecError(
                    "no pregenerated sphinx content, and sphinx isn't available "
                    "to generate it; bailing")
            self.run_command(self.build_command)
            return self.run(False)

        content = self.scan_content()

        content = self.content
        directories = set(map(os.path.dirname, content.values()))
        directories.discard('')
        for x in sorted(directories):
            self.mkpath(os.path.join(self.path, x))

        for src, dst in sorted(content.items()):
            self.copy_file(os.path.join(self.source_path, src),
                           os.path.join(self.path, dst))
Beispiel #27
0
class run_check(Command):
    """ Run all of the tests for the package using uninstalled (local)
    files """

    description = "Automatically run the test suite for the package."

    user_options = []

    def initialize_options(self):
        self.build_lib = None
        return

    def finalize_options(self):
        # Obtain the build_lib directory from the build command
        self.set_undefined_options('build', ('build_lib', 'build_lib'))
        return

    def run(self):
        # Ensure the extension is built
        self.run_command('build')

        # test the uninstalled extensions
        libdir = os.path.join(os.getcwd(), self.build_lib)

        sys.path.insert(0, libdir)

        import testsuite

        try:
            failures = testsuite.run()

        except RuntimeError, msg:
            sys.stderr.write('error: %s\n' % msg)
            raise DistutilsExecError(
                'please consult the "Troubleshooting" section in the README file.'
            )

        if failures > 0:
            raise DistutilsExecError('check failed.')
        return
    def msvc_spawn_and_write_d_file(obj, src, cmd, env, dry_run):
        '''
        Run command with /showIncludes and convert output to dependency (.d) file.
        '''
        log.info(' '.join(cmd))

        if dry_run:
            return

        process = subprocess.Popen(cmd + ['/showIncludes'],
                                   env=env,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.STDOUT,
                                   universal_newlines=True)
        out = process.communicate()[0]

        deps = set([src])

        for line in out.splitlines():
            if not line.startswith('Note: including file:'):
                sys.stderr.write(line + '\n')
                continue

            dep = line[21:].strip()
            dep_lower = dep.lower()
            if not (
                    # filter out system headers
                    'microsoft visual studio' in dep_lower
                    or 'windows kits' in dep_lower):
                deps.add(dep)

        if process.returncode != 0:
            raise DistutilsExecError("command %r failed with exit status %d" %
                                     (cmd, process.returncode))

        with open(os.path.splitext(obj)[0] + '.d', 'w') as handle:
            handle.write(': ')
            for dep in deps:
                handle.write(' \\\n')
                handle.write(dep.replace('\\', '\\\\').replace(' ', '\\ '))
Beispiel #29
0
    def run_for_extension(self, ext: RustExtension):
        # Make sure that if pythonXX-sys is used, it builds against the current
        # executing python interpreter.
        bindir = os.path.dirname(sys.executable)

        env = os.environ.copy()
        env.update({
            # disables rust's pkg-config seeking for specified packages,
            # which causes pythonXX-sys to fall back to detecting the
            # interpreter from the path.
            "PYTHON_2.7_NO_PKG_CONFIG": "1",
            "PATH": bindir + os.pathsep + os.environ.get("PATH", ""),
        })

        if not os.path.exists(ext.path):
            raise DistutilsFileError(
                f"can't find Rust extension project file: {ext.path}")

        features = set(ext.features)
        features.update(rust_features(ext=False, binding=ext.binding))

        # test cargo command
        feature_args = ["--features", " ".join(features)] if features else []
        args = (["cargo", "test", "--manifest-path", ext.path] + feature_args +
                list(ext.args or []))

        # Execute cargo command
        print(" ".join(args))
        try:
            subprocess.check_output(args, env=env)
        except subprocess.CalledProcessError as e:
            raise CompileError("cargo failed with code: %d\n%s" %
                               (e.returncode, e.output.decode("utf-8")))
        except OSError:
            raise DistutilsExecError(
                "Unable to execute 'cargo' - this package "
                "requires Rust to be installed and "
                "cargo to be on the PATH")
        else:
            print(f"test completed for '{ext.name}' extension")
Beispiel #30
0
    def run(self):
        if not color_terminal():
            # Windows' poor cmd box doesn't understand ANSI sequences
            nocolor()
        if not self.verbose:
            status_stream = StringIO()
        else:
            status_stream = sys.stdout
        confoverrides = {}
        if self.project:
            confoverrides['project'] = self.project
        if self.version:
            confoverrides['version'] = self.version
        if self.release:
            confoverrides['release'] = self.release
        if self.today:
            confoverrides['today'] = self.today
        app = Sphinx(self.source_dir,
                     self.config_dir,
                     self.builder_target_dir,
                     self.doctree_dir,
                     self.builder,
                     confoverrides,
                     status_stream,
                     freshenv=self.fresh_env)

        try:
            app.build(force_all=self.all_files)
            if app.statuscode:
                raise DistutilsExecError('caused by %s builder.' %
                                         app.builder.name)
        except Exception, err:
            from docutils.utils import SystemMessage
            if isinstance(err, SystemMessage):
                print >> sys.stderr, darkred('reST markup error:')
                print >> sys.stderr, err.args[0].encode(
                    'ascii', 'backslashreplace')
            else:
                raise