Exemplo n.º 1
0
    def ensure_build_location(self, build_dir, autodelete):
        # type: (str, bool) -> str
        assert build_dir is not None
        if self._temp_build_dir is not None:
            assert self._temp_build_dir.path
            return self._temp_build_dir.path
        if self.req is None:
            # Some systems have /tmp as a symlink which confuses custom
            # builds (such as numpy). Thus, we ensure that the real path
            # is returned.
            self._temp_build_dir = TempDirectory(
                kind=tempdir_kinds.REQ_BUILD, globally_managed=True
            )

            return self._temp_build_dir.path
        if self.editable:
            name = self.name.lower()
        else:
            name = self.name
        # FIXME: Is there a better place to create the build_dir? (hg and bzr
        # need this)
        if not os.path.exists(build_dir):
            logger.debug('Creating directory %s', build_dir)
            os.makedirs(build_dir)
        actual_build_dir = os.path.join(build_dir, name)
        # `None` indicates that we respect the globally-configured deletion
        # settings, which is what we actually want when auto-deleting.
        delete_arg = None if autodelete else False
        return TempDirectory(
            path=actual_build_dir,
            delete=delete_arg,
            kind=tempdir_kinds.REQ_BUILD,
            globally_managed=True,
        ).path
Exemplo n.º 2
0
    def _get_file_stash(self, path):
        # type: (str) -> str
        """Stashes a file.

        If no root has been provided, one will be created for the directory
        in the user's temp directory."""
        path = os.path.normcase(path)
        head, old_head = os.path.dirname(path), None
        save_dir = None

        while head != old_head:
            try:
                save_dir = self._save_dirs[head]
                break
            except KeyError:
                pass
            head, old_head = os.path.dirname(head), head
        else:
            # Did not find any suitable root
            head = os.path.dirname(path)
            save_dir = TempDirectory(kind='uninstall')
            self._save_dirs[head] = save_dir

        relpath = os.path.relpath(path, head)
        if relpath and relpath != os.path.curdir:
            return os.path.join(save_dir.path, relpath)
        return save_dir.path
Exemplo n.º 3
0
def install_wheel(
    name,  # type: str
    wheel_path,  # type: str
    scheme,  # type: Scheme
    req_description,  # type: str
    pycompile=True,  # type: bool
    warn_script_location=True,  # type: bool
    _temp_dir_for_testing=None,  # type: Optional[str]
    direct_url=None,  # type: Optional[DirectUrl]
):
    # type: (...) -> None
    with TempDirectory(
        path=_temp_dir_for_testing, kind="unpacked-wheel"
    ) as unpacked_dir, ZipFile(wheel_path, allowZip64=True) as z:
        unpack_file(wheel_path, unpacked_dir.path)
        install_unpacked_wheel(
            name=name,
            wheeldir=unpacked_dir.path,
            wheel_zip=z,
            scheme=scheme,
            req_description=req_description,
            pycompile=pycompile,
            warn_script_location=warn_script_location,
            direct_url=direct_url,
        )
Exemplo n.º 4
0
    def __init__(self, format_control):
        # type: (FormatControl) -> None
        self._temp_dir = TempDirectory(
            kind=tempdir_kinds.EPHEM_WHEEL_CACHE,
            globally_managed=True,
        )

        super(EphemWheelCache, self).__init__(self._temp_dir.path,
                                              format_control)
Exemplo n.º 5
0
    def export(self, location, url):
        # type: (str, HiddenText) -> None
        """Export the Hg repository at the url to the destination location"""
        with TempDirectory(kind="export") as temp_dir:
            self.unpack(temp_dir.path, url=url)

            self.run_command(['archive', location],
                             show_stdout=False,
                             cwd=temp_dir.path)
Exemplo n.º 6
0
    def __init__(self):
        # type: () -> None
        temp_dir = TempDirectory(
            kind=tempdir_kinds.BUILD_ENV, globally_managed=True
        )

        self._prefixes = OrderedDict((
            (name, _Prefix(os.path.join(temp_dir.path, name)))
            for name in ('normal', 'overlay')
        ))

        self._bin_dirs = []  # type: List[str]
        self._lib_dirs = []  # type: List[str]
        for prefix in reversed(list(self._prefixes.values())):
            self._bin_dirs.append(prefix.bin_dir)
            self._lib_dirs.extend(prefix.lib_dirs)

        # Customize site to:
        # - ensure .pth files are honored
        # - prevent access to system site packages
        system_sites = {
            os.path.normcase(site) for site in (
                get_python_lib(plat_specific=False),
                get_python_lib(plat_specific=True),
            )
        }
        self._site_dir = os.path.join(temp_dir.path, 'site')
        if not os.path.exists(self._site_dir):
            os.mkdir(self._site_dir)
        with open(os.path.join(self._site_dir, 'sitecustomize.py'), 'w') as fp:
            fp.write(textwrap.dedent(
                '''
                import os, site, sys

                # First, drop system-sites related paths.
                original_sys_path = sys.path[:]
                known_paths = set()
                for path in {system_sites!r}:
                    site.addsitedir(path, known_paths=known_paths)
                system_paths = set(
                    os.path.normcase(path)
                    for path in sys.path[len(original_sys_path):]
                )
                original_sys_path = [
                    path for path in original_sys_path
                    if os.path.normcase(path) not in system_paths
                ]
                sys.path = original_sys_path

                # Second, add lib directories.
                # ensuring .pth file are processed.
                for path in {lib_dirs!r}:
                    assert not path in sys.path
                    site.addsitedir(path)
                '''
            ).format(system_sites=system_sites, lib_dirs=self._lib_dirs))
Exemplo n.º 7
0
def get_requirement_tracker():
    # type: () -> Iterator[RequirementTracker]
    root = os.environ.get('PIP_REQ_TRACKER')
    with contextlib2.ExitStack() as ctx:
        if root is None:
            root = ctx.enter_context(TempDirectory(kind='req-tracker')).path
            ctx.enter_context(update_env_context_manager(PIP_REQ_TRACKER=root))
            logger.debug("Initialized build tracking at %s", root)

        with RequirementTracker(root) as tracker:
            yield tracker
Exemplo n.º 8
0
    def export(self, location, url):
        # type: (str, HiddenText) -> None
        """Export the Git repository at the url to the destination location"""
        if not location.endswith('/'):
            location = location + '/'

        with TempDirectory(kind="export") as temp_dir:
            self.unpack(temp_dir.path, url=url)
            self.run_command(
                ['checkout-index', '-a', '-f', '--prefix', location],
                show_stdout=False,
                cwd=temp_dir.path)
Exemplo n.º 9
0
    def _get_directory_stash(self, path):
        # type: (str) -> str
        """Stashes a directory.

        Directories are stashed adjacent to their original location if
        possible, or else moved/copied into the user's temp dir."""

        try:
            save_dir = AdjacentTempDirectory(path)  # type: TempDirectory
        except OSError:
            save_dir = TempDirectory(kind="uninstall")
        self._save_dirs[os.path.normcase(path)] = save_dir

        return save_dir.path
Exemplo n.º 10
0
def _build_one_inside_env(
    req,  # type: InstallRequirement
    output_dir,  # type: str
    build_options,  # type: List[str]
    global_options,  # type: List[str]
):
    # type: (...) -> Optional[str]
    with TempDirectory(kind="wheel") as temp_dir:
        if req.use_pep517:
            wheel_path = build_wheel_pep517(
                name=req.name,
                backend=req.pep517_backend,
                metadata_directory=req.metadata_directory,
                build_options=build_options,
                tempd=temp_dir.path,
            )
        else:
            wheel_path = build_wheel_legacy(
                name=req.name,
                setup_py_path=req.setup_py_path,
                source_dir=req.unpacked_source_directory,
                global_options=global_options,
                build_options=build_options,
                tempd=temp_dir.path,
            )

        if wheel_path is not None:
            wheel_name = os.path.basename(wheel_path)
            dest_path = os.path.join(output_dir, wheel_name)
            try:
                wheel_hash, length = hash_file(wheel_path)
                shutil.move(wheel_path, dest_path)
                logger.info('Created wheel for %s: '
                            'filename=%s size=%d sha256=%s',
                            req.name, wheel_name, length,
                            wheel_hash.hexdigest())
                logger.info('Stored in directory: %s', output_dir)
                return dest_path
            except Exception as e:
                logger.warning(
                    "Building wheel for %s failed: %s",
                    req.name, e,
                )
        # Ignore return, we can't do anything else useful.
        if not req.use_pep517:
            _clean_one_legacy(req, global_options)
        return None
Exemplo n.º 11
0
def get_http_url(
        link,  # type: Link
        downloader,  # type: Downloader
        download_dir=None,  # type: Optional[str]
        hashes=None,  # type: Optional[Hashes]
):
    # type: (...) -> File
    temp_dir = TempDirectory(kind="unpack", globally_managed=True)
    # If a download dir is specified, is the file already downloaded there?
    already_downloaded_path = None
    if download_dir:
        already_downloaded_path = _check_download_dir(link, download_dir,
                                                      hashes)

    if already_downloaded_path:
        from_path = already_downloaded_path
        content_type = mimetypes.guess_type(from_path)[0]
    else:
        # let's download to a tmp dir
        from_path, content_type = _download_http_url(link, downloader,
                                                     temp_dir.path, hashes)

    return File(from_path, content_type)
Exemplo n.º 12
0
def install(
        install_options,  # type: List[str]
        global_options,  # type: Sequence[str]
        root,  # type: Optional[str]
        home,  # type: Optional[str]
        prefix,  # type: Optional[str]
        use_user_site,  # type: bool
        pycompile,  # type: bool
        scheme,  # type: Scheme
        setup_py_path,  # type: str
        isolated,  # type: bool
        req_name,  # type: str
        build_env,  # type: BuildEnvironment
        unpacked_source_directory,  # type: str
        req_description,  # type: str
):
    # type: (...) -> bool

    header_dir = scheme.headers

    with TempDirectory(kind="record") as temp_dir:
        try:
            record_filename = os.path.join(temp_dir.path, 'install-record.txt')
            install_args = make_setuptools_install_args(
                setup_py_path,
                global_options=global_options,
                install_options=install_options,
                record_filename=record_filename,
                root=root,
                prefix=prefix,
                header_dir=header_dir,
                home=home,
                use_user_site=use_user_site,
                no_user_config=isolated,
                pycompile=pycompile,
            )

            runner = runner_with_spinner_message(
                "Running setup.py install for {}".format(req_name))
            with indent_log(), build_env:
                runner(
                    cmd=install_args,
                    cwd=unpacked_source_directory,
                )

            if not os.path.exists(record_filename):
                logger.debug('Record file %s not found', record_filename)
                # Signal to the caller that we didn't install the new package
                return False

        except Exception:
            # Signal to the caller that we didn't install the new package
            raise LegacyInstallFailure

        # At this point, we have successfully installed the requirement.

        # We intentionally do not use any encoding to read the file because
        # setuptools writes the file using distutils.file_util.write_file,
        # which does not specify an encoding.
        with open(record_filename) as f:
            record_lines = f.read().splitlines()

    def prepend_root(path):
        # type: (str) -> str
        if root is None or not os.path.isabs(path):
            return path
        else:
            return change_root(root, path)

    for line in record_lines:
        directory = os.path.dirname(line)
        if directory.endswith('.egg-info'):
            egg_info_dir = prepend_root(directory)
            break
    else:
        deprecated(
            reason=("{} did not indicate that it installed an "
                    ".egg-info directory. Only setup.py projects "
                    "generating .egg-info directories are supported."
                    ).format(req_description),
            replacement=(
                "for maintainers: updating the setup.py of {0}. "
                "For users: contact the maintainers of {0} to let "
                "them know to update their setup.py.".format(req_name)),
            gone_in="20.2",
            issue=6998,
        )
        # FIXME: put the record somewhere
        return True

    new_lines = []
    for line in record_lines:
        filename = line.strip()
        if os.path.isdir(filename):
            filename += os.path.sep
        new_lines.append(os.path.relpath(prepend_root(filename), egg_info_dir))
    new_lines.sort()
    ensure_dir(egg_info_dir)
    inst_files_path = os.path.join(egg_info_dir, 'installed-files.txt')
    with open(inst_files_path, 'w') as f:
        f.write('\n'.join(new_lines) + '\n')

    return True
Exemplo n.º 13
0
    def run(self, options, args):
        options.ignore_installed = True
        # editable doesn't really make sense for `pip download`, but the bowels
        # of the RequirementSet code require that property.
        options.editables = []

        cmdoptions.check_dist_restriction(options)

        options.download_dir = normalize_path(options.download_dir)

        ensure_dir(options.download_dir)

        session = self.get_default_session(options)

        target_python = make_target_python(options)
        finder = self._build_package_finder(
            options=options,
            session=session,
            target_python=target_python,
        )
        build_delete = (not (options.no_clean or options.build_dir))

        req_tracker = self.enter_context(get_requirement_tracker())

        directory = TempDirectory(
            options.build_dir,
            delete=build_delete,
            kind="download",
            globally_managed=True,
        )

        reqs = self.get_requirements(args, options, finder, session)

        preparer = self.make_requirement_preparer(
            temp_build_dir=directory,
            options=options,
            req_tracker=req_tracker,
            session=session,
            finder=finder,
            download_dir=options.download_dir,
            use_user_site=False,
        )

        resolver = self.make_resolver(
            preparer=preparer,
            finder=finder,
            options=options,
            py_version_info=options.python_version,
        )

        self.trace_basic_info(finder)

        requirement_set = resolver.resolve(reqs, check_supported_wheels=True)

        downloaded = ' '.join([
            req.name for req in requirement_set.requirements.values()
            if req.successfully_downloaded
        ])
        if downloaded:
            write_output('Successfully downloaded %s', downloaded)

        return requirement_set
Exemplo n.º 14
0
    def run(self, options, args):
        # type: (Values, List[Any]) -> int
        if options.use_user_site and options.target_dir is not None:
            raise CommandError("Can not combine '--user' and '--target'")

        cmdoptions.check_install_build_global(options)
        upgrade_strategy = "to-satisfy-only"
        if options.upgrade:
            upgrade_strategy = options.upgrade_strategy

        cmdoptions.check_dist_restriction(options, check_target=True)

        install_options = options.install_options or []

        options.use_user_site = decide_user_install(
            options.use_user_site,
            prefix_path=options.prefix_path,
            target_dir=options.target_dir,
            root_path=options.root_path,
            isolated_mode=options.isolated_mode,
        )

        target_temp_dir = None  # type: Optional[TempDirectory]
        target_temp_dir_path = None  # type: Optional[str]
        if options.target_dir:
            options.ignore_installed = True
            options.target_dir = os.path.abspath(options.target_dir)
            if (os.path.exists(options.target_dir)
                    and not os.path.isdir(options.target_dir)):
                raise CommandError(
                    "Target path exists but is not a directory, will not "
                    "continue.")

            # Create a target directory for using with the target option
            target_temp_dir = TempDirectory(kind="target")
            target_temp_dir_path = target_temp_dir.path

        global_options = options.global_options or []

        session = self.get_default_session(options)

        target_python = make_target_python(options)
        finder = self._build_package_finder(
            options=options,
            session=session,
            target_python=target_python,
            ignore_requires_python=options.ignore_requires_python,
        )
        build_delete = (not (options.no_clean or options.build_dir))
        wheel_cache = WheelCache(options.cache_dir, options.format_control)

        req_tracker = self.enter_context(get_requirement_tracker())

        directory = TempDirectory(
            options.build_dir,
            delete=build_delete,
            kind="install",
            globally_managed=True,
        )

        try:
            reqs = self.get_requirements(
                args,
                options,
                finder,
                session,
                check_supported_wheels=not options.target_dir,
            )

            warn_deprecated_install_options(reqs, options.install_options)

            preparer = self.make_requirement_preparer(
                temp_build_dir=directory,
                options=options,
                req_tracker=req_tracker,
                session=session,
                finder=finder,
                use_user_site=options.use_user_site,
            )
            resolver = self.make_resolver(
                preparer=preparer,
                finder=finder,
                options=options,
                wheel_cache=wheel_cache,
                use_user_site=options.use_user_site,
                ignore_installed=options.ignore_installed,
                ignore_requires_python=options.ignore_requires_python,
                force_reinstall=options.force_reinstall,
                upgrade_strategy=upgrade_strategy,
                use_pep517=options.use_pep517,
            )

            self.trace_basic_info(finder)

            requirement_set = resolver.resolve(
                reqs, check_supported_wheels=not options.target_dir)

            try:
                pip_req = requirement_set.get_requirement("pip")
            except KeyError:
                modifying_pip = None
            else:
                # If we're not replacing an already installed pip,
                # we're not modifying it.
                modifying_pip = pip_req.satisfied_by is None
            protect_pip_from_modification_on_windows(
                modifying_pip=modifying_pip)

            check_binary_allowed = get_check_binary_allowed(
                finder.format_control)

            reqs_to_build = [
                r for r in requirement_set.requirements.values()
                if should_build_for_install_command(r, check_binary_allowed)
            ]

            _, build_failures = build(
                reqs_to_build,
                wheel_cache=wheel_cache,
                build_options=[],
                global_options=[],
            )

            # If we're using PEP 517, we cannot do a direct install
            # so we fail here.
            # We don't care about failures building legacy
            # requirements, as we'll fall through to a direct
            # install for those.
            pep517_build_failures = [r for r in build_failures if r.use_pep517]
            if pep517_build_failures:
                raise InstallationError(
                    "Could not build wheels for {} which use"
                    " PEP 517 and cannot be installed directly".format(
                        ", ".join(r.name for r in pep517_build_failures)))

            to_install = resolver.get_installation_order(requirement_set)

            # Consistency Checking of the package set we're installing.
            should_warn_about_conflicts = (not options.ignore_dependencies
                                           and options.warn_about_conflicts)
            if should_warn_about_conflicts:
                self._warn_about_conflicts(to_install)

            # Don't warn about script install locations if
            # --target has been specified
            warn_script_location = options.warn_script_location
            if options.target_dir:
                warn_script_location = False

            installed = install_given_reqs(
                to_install,
                install_options,
                global_options,
                root=options.root_path,
                home=target_temp_dir_path,
                prefix=options.prefix_path,
                pycompile=options.compile,
                warn_script_location=warn_script_location,
                use_user_site=options.use_user_site,
            )

            lib_locations = get_lib_location_guesses(
                user=options.use_user_site,
                home=target_temp_dir_path,
                root=options.root_path,
                prefix=options.prefix_path,
                isolated=options.isolated_mode,
            )
            working_set = pkg_resources.WorkingSet(lib_locations)

            installed.sort(key=operator.attrgetter('name'))
            items = []
            for result in installed:
                item = result.name
                try:
                    installed_version = get_installed_version(
                        result.name, working_set=working_set)
                    if installed_version:
                        item += '-' + installed_version
                except Exception:
                    pass
                items.append(item)
            installed_desc = ' '.join(items)
            if installed_desc:
                write_output(
                    'Successfully installed %s',
                    installed_desc,
                )
        except EnvironmentError as error:
            show_traceback = (self.verbosity >= 1)

            message = create_env_error_message(
                error,
                show_traceback,
                options.use_user_site,
            )
            logger.error(message, exc_info=show_traceback)

            return ERROR

        if options.target_dir:
            self._handle_target_dir(options.target_dir, target_temp_dir,
                                    options.upgrade)

        return SUCCESS
Exemplo n.º 15
0
    def run(self, options, args):
        # type: (Values, List[Any]) -> None
        cmdoptions.check_install_build_global(options)

        session = self.get_default_session(options)

        finder = self._build_package_finder(options, session)
        build_delete = (not (options.no_clean or options.build_dir))
        wheel_cache = WheelCache(options.cache_dir, options.format_control)

        options.wheel_dir = normalize_path(options.wheel_dir)
        ensure_dir(options.wheel_dir)

        req_tracker = self.enter_context(get_requirement_tracker())

        directory = TempDirectory(
            options.build_dir,
            delete=build_delete,
            kind="wheel",
            globally_managed=True,
        )

        reqs = self.get_requirements(args, options, finder, session)

        preparer = self.make_requirement_preparer(
            temp_build_dir=directory,
            options=options,
            req_tracker=req_tracker,
            session=session,
            finder=finder,
            wheel_download_dir=options.wheel_dir,
            use_user_site=False,
        )

        resolver = self.make_resolver(
            preparer=preparer,
            finder=finder,
            options=options,
            wheel_cache=wheel_cache,
            ignore_requires_python=options.ignore_requires_python,
            use_pep517=options.use_pep517,
        )

        self.trace_basic_info(finder)

        requirement_set = resolver.resolve(
            reqs, check_supported_wheels=True
        )

        reqs_to_build = [
            r for r in requirement_set.requirements.values()
            if should_build_for_wheel_command(r)
        ]

        # build wheels
        build_successes, build_failures = build(
            reqs_to_build,
            wheel_cache=wheel_cache,
            build_options=options.build_options or [],
            global_options=options.global_options or [],
        )
        for req in build_successes:
            assert req.link and req.link.is_wheel
            assert req.local_file_path
            # copy from cache to target directory
            try:
                shutil.copy(req.local_file_path, options.wheel_dir)
            except OSError as e:
                logger.warning(
                    "Building wheel for %s failed: %s",
                    req.name, e,
                )
                build_failures.append(req)
        if len(build_failures) != 0:
            raise CommandError(
                "Failed to build one or more wheels"
            )