id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
175,562
from __future__ import absolute_import import errno import logging import operator import os import shutil import site from optparse import SUPPRESS_HELP from pip._vendor import pkg_resources from pip._vendor.packaging.utils import canonicalize_name from pip._internal.cache import WheelCache from pip._internal.cli import cmdoptions from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.req_command import RequirementCommand, with_cleanup from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.exceptions import CommandError, InstallationError from pip._internal.locations import distutils_scheme from pip._internal.operations.check import check_install_conflicts from pip._internal.req import install_given_reqs from pip._internal.req.req_tracker import get_requirement_tracker from pip._internal.utils.datetime import today_is_later_than from pip._internal.utils.distutils_args import parse_distutils_args from pip._internal.utils.filesystem import test_writable_dir from pip._internal.utils.misc import ( ensure_dir, get_installed_version, get_pip_version, protect_pip_from_modification_on_windows, write_output, ) from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.virtualenv import virtualenv_no_global from pip._internal.wheel_builder import build, should_build_for_install_command logger = logging.getLogger(__name__) def site_packages_writable(root, isolated): # type: (Optional[str], bool) -> bool return all( test_writable_dir(d) for d in set( get_lib_location_guesses(root=root, isolated=isolated)) ) class InstallationError(PipError): """General exception during installation""" class CommandError(PipError): """Raised when there is an error in command-line arguments""" def virtualenv_no_global(): # type: () -> bool """Returns a boolean, whether running in venv with no system site-packages. """ # PEP 405 compliance needs to be checked first since virtualenv >=20 would # return True for both checks, but is only able to use the PEP 405 config. if _running_under_venv(): return _no_global_under_venv() if _running_under_regular_virtualenv(): return _no_global_under_regular_virtualenv() return False The provided code snippet includes necessary dependencies for implementing the `decide_user_install` function. Write a Python function `def decide_user_install( use_user_site, # type: Optional[bool] prefix_path=None, # type: Optional[str] target_dir=None, # type: Optional[str] root_path=None, # type: Optional[str] isolated_mode=False, # type: bool )` to solve the following problem: Determine whether to do a user install based on the input options. If use_user_site is False, no additional checks are done. If use_user_site is True, it is checked for compatibility with other options. If use_user_site is None, the default behaviour depends on the environment, which is provided by the other arguments. Here is the function: def decide_user_install( use_user_site, # type: Optional[bool] prefix_path=None, # type: Optional[str] target_dir=None, # type: Optional[str] root_path=None, # type: Optional[str] isolated_mode=False, # type: bool ): # type: (...) -> bool """Determine whether to do a user install based on the input options. If use_user_site is False, no additional checks are done. If use_user_site is True, it is checked for compatibility with other options. If use_user_site is None, the default behaviour depends on the environment, which is provided by the other arguments. """ # In some cases (config from tox), use_user_site can be set to an integer # rather than a bool, which 'use_user_site is False' wouldn't catch. if (use_user_site is not None) and (not use_user_site): logger.debug("Non-user install by explicit request") return False if use_user_site: if prefix_path: raise CommandError( "Can not combine '--user' and '--prefix' as they imply " "different installation locations" ) if virtualenv_no_global(): raise InstallationError( "Can not perform a '--user' install. User site-packages " "are not visible in this virtualenv." ) logger.debug("User install by explicit request") return True # If we are here, user installs have not been explicitly requested/avoided assert use_user_site is None # user install incompatible with --prefix/--target if prefix_path or target_dir: logger.debug("Non-user install due to --prefix or --target option") return False # If user installs are not enabled, choose a non-user install if not site.ENABLE_USER_SITE: logger.debug("Non-user install because user site-packages disabled") return False # If we have permission for a non-user install, do that, # otherwise do a user install. if site_packages_writable(root=root_path, isolated=isolated_mode): logger.debug("Non-user install because site-packages writeable") return False logger.info("Defaulting to user installation because normal site-packages " "is not writeable") return True
Determine whether to do a user install based on the input options. If use_user_site is False, no additional checks are done. If use_user_site is True, it is checked for compatibility with other options. If use_user_site is None, the default behaviour depends on the environment, which is provided by the other arguments.
175,563
from __future__ import absolute_import import errno import logging import operator import os import shutil import site from optparse import SUPPRESS_HELP from pip._vendor import pkg_resources from pip._vendor.packaging.utils import canonicalize_name from pip._internal.cache import WheelCache from pip._internal.cli import cmdoptions from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.req_command import RequirementCommand, with_cleanup from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.exceptions import CommandError, InstallationError from pip._internal.locations import distutils_scheme from pip._internal.operations.check import check_install_conflicts from pip._internal.req import install_given_reqs from pip._internal.req.req_tracker import get_requirement_tracker from pip._internal.utils.datetime import today_is_later_than from pip._internal.utils.distutils_args import parse_distutils_args from pip._internal.utils.filesystem import test_writable_dir from pip._internal.utils.misc import ( ensure_dir, get_installed_version, get_pip_version, protect_pip_from_modification_on_windows, write_output, ) from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.virtualenv import virtualenv_no_global from pip._internal.wheel_builder import build, should_build_for_install_command class CommandError(PipError): """Raised when there is an error in command-line arguments""" def parse_distutils_args(args): # type: (List[str]) -> Dict[str, str] """Parse provided arguments, returning an object that has the matched arguments. Any unknown arguments are ignored. """ result = {} for arg in args: try: _, match = _distutils_getopt.getopt(args=[arg]) except DistutilsArgError: # We don't care about any other options, which here may be # considered unrecognized since our option list is not # exhaustive. pass else: result.update(match.__dict__) return result The provided code snippet includes necessary dependencies for implementing the `reject_location_related_install_options` function. Write a Python function `def reject_location_related_install_options(requirements, options)` to solve the following problem: If any location-changing --install-option arguments were passed for requirements or on the command-line, then show a deprecation warning. Here is the function: def reject_location_related_install_options(requirements, options): # type: (List[InstallRequirement], Optional[List[str]]) -> None """If any location-changing --install-option arguments were passed for requirements or on the command-line, then show a deprecation warning. """ def format_options(option_names): # type: (Iterable[str]) -> List[str] return ["--{}".format(name.replace("_", "-")) for name in option_names] offenders = [] for requirement in requirements: install_options = requirement.install_options location_options = parse_distutils_args(install_options) if location_options: offenders.append( "{!r} from {}".format( format_options(location_options.keys()), requirement ) ) if options: location_options = parse_distutils_args(options) if location_options: offenders.append( "{!r} from command line".format( format_options(location_options.keys()) ) ) if not offenders: return raise CommandError( "Location-changing options found in --install-option: {}." " This is unsupported, use pip-level options like --user," " --prefix, --root, and --target instead.".format( "; ".join(offenders) ) )
If any location-changing --install-option arguments were passed for requirements or on the command-line, then show a deprecation warning.
175,564
from __future__ import absolute_import import errno import logging import operator import os import shutil import site from optparse import SUPPRESS_HELP from pip._vendor import pkg_resources from pip._vendor.packaging.utils import canonicalize_name from pip._internal.cache import WheelCache from pip._internal.cli import cmdoptions from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.req_command import RequirementCommand, with_cleanup from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.exceptions import CommandError, InstallationError from pip._internal.locations import distutils_scheme from pip._internal.operations.check import check_install_conflicts from pip._internal.req import install_given_reqs from pip._internal.req.req_tracker import get_requirement_tracker from pip._internal.utils.datetime import today_is_later_than from pip._internal.utils.distutils_args import parse_distutils_args from pip._internal.utils.filesystem import test_writable_dir from pip._internal.utils.misc import ( ensure_dir, get_installed_version, get_pip_version, protect_pip_from_modification_on_windows, write_output, ) from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.virtualenv import virtualenv_no_global from pip._internal.wheel_builder import build, should_build_for_install_command The provided code snippet includes necessary dependencies for implementing the `create_env_error_message` function. Write a Python function `def create_env_error_message(error, show_traceback, using_user_site)` to solve the following problem: Format an error message for an EnvironmentError It may occur anytime during the execution of the install command. Here is the function: def create_env_error_message(error, show_traceback, using_user_site): # type: (EnvironmentError, bool, bool) -> str """Format an error message for an EnvironmentError It may occur anytime during the execution of the install command. """ parts = [] # Mention the error if we are not going to show a traceback parts.append("Could not install packages due to an EnvironmentError") if not show_traceback: parts.append(": ") parts.append(str(error)) else: parts.append(".") # Spilt the error indication from a helper message (if any) parts[-1] += "\n" # Suggest useful actions to the user: # (1) using user site-packages or (2) verifying the permissions if error.errno == errno.EACCES: user_option_part = "Consider using the `--user` option" permissions_part = "Check the permissions" if not using_user_site: parts.extend([ user_option_part, " or ", permissions_part.lower(), ]) else: parts.append(permissions_part) parts.append(".\n") return "".join(parts).strip() + "\n"
Format an error message for an EnvironmentError It may occur anytime during the execution of the install command.
175,565
from __future__ import absolute_import import logging import sys import textwrap from collections import OrderedDict from pip._vendor import pkg_resources from pip._vendor.packaging.version import parse as parse_version from pip._vendor.six.moves import xmlrpc_client from pip._internal.cli.base_command import Command from pip._internal.cli.req_command import SessionCommandMixin from pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESS from pip._internal.exceptions import CommandError from pip._internal.models.index import PyPI from pip._internal.network.xmlrpc import PipXmlrpcTransport from pip._internal.utils.compat import get_terminal_size from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import get_distribution, write_output from pip._internal.utils.typing import MYPY_CHECK_RUNNING def highest_version(versions): # type: (List[str]) -> str return max(versions, key=parse_version) class OrderedDict(dict): def __init__(self, data=None, **kwargs): self._keys = self.keys(data, kwargs.get("keys")) self._default_factory = kwargs.get("default_factory") if data is None: dict.__init__(self) else: dict.__init__(self, data) def __delitem__(self, key): dict.__delitem__(self, key) self._keys.remove(key) def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.__missing__(key) def __iter__(self): return (key for key in self.keys()) def __missing__(self, key): if not self._default_factory and key not in self._keys: raise KeyError() return self._default_factory() def __setitem__(self, key, item): dict.__setitem__(self, key, item) if key not in self._keys: self._keys.append(key) def clear(self): dict.clear(self) self._keys.clear() def copy(self): d = dict.copy(self) d._keys = self._keys return d def items(self): # returns iterator under python 3 and list under python 2 return zip(self.keys(), self.values()) def keys(self, data=None, keys=None): if data: if keys: assert isinstance(keys, list) assert len(data) == len(keys) return keys else: assert ( isinstance(data, dict) or isinstance(data, OrderedDict) or isinstance(data, list) ) if isinstance(data, dict) or isinstance(data, OrderedDict): return data.keys() elif isinstance(data, list): return [key for (key, value) in data] elif "_keys" in self.__dict__: return self._keys else: return [] def popitem(self): if not self._keys: raise KeyError() key = self._keys.pop() value = self[key] del self[key] return (key, value) def setdefault(self, key, failobj=None): dict.setdefault(self, key, failobj) if key not in self._keys: self._keys.append(key) def update(self, data): dict.update(self, data) for key in self.keys(data): if key not in self._keys: self._keys.append(key) def values(self): # returns iterator under python 3 return map(self.get, self._keys) The provided code snippet includes necessary dependencies for implementing the `transform_hits` function. Write a Python function `def transform_hits(hits)` to solve the following problem: The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use. Here is the function: def transform_hits(hits): # type: (List[Dict[str, str]]) -> List[TransformedHit] """ The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use. """ packages = OrderedDict() # type: OrderedDict[str, TransformedHit] for hit in hits: name = hit['name'] summary = hit['summary'] version = hit['version'] if name not in packages.keys(): packages[name] = { 'name': name, 'summary': summary, 'versions': [version], } else: packages[name]['versions'].append(version) # if this is the highest version, replace summary and score if version == highest_version(packages[name]['versions']): packages[name]['summary'] = summary return list(packages.values())
The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use.
175,566
from __future__ import absolute_import import logging import sys import textwrap from collections import OrderedDict from pip._vendor import pkg_resources from pip._vendor.packaging.version import parse as parse_version from pip._vendor.six.moves import xmlrpc_client from pip._internal.cli.base_command import Command from pip._internal.cli.req_command import SessionCommandMixin from pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESS from pip._internal.exceptions import CommandError from pip._internal.models.index import PyPI from pip._internal.network.xmlrpc import PipXmlrpcTransport from pip._internal.utils.compat import get_terminal_size from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import get_distribution, write_output from pip._internal.utils.typing import MYPY_CHECK_RUNNING def highest_version(versions): def indent_log(num=2): def get_distribution(req_name): def write_output(msg, *args): def print_results(hits, name_column_width=None, terminal_width=None): # type: (List[TransformedHit], Optional[int], Optional[int]) -> None if not hits: return if name_column_width is None: name_column_width = max([ len(hit['name']) + len(highest_version(hit.get('versions', ['-']))) for hit in hits ]) + 4 installed_packages = [p.project_name for p in pkg_resources.working_set] for hit in hits: name = hit['name'] summary = hit['summary'] or '' latest = highest_version(hit.get('versions', ['-'])) if terminal_width is not None: target_width = terminal_width - name_column_width - 5 if target_width > 10: # wrap and indent summary to fit terminal summary_lines = textwrap.wrap(summary, target_width) summary = ('\n' + ' ' * (name_column_width + 3)).join( summary_lines) line = '{name_latest:{name_column_width}} - {summary}'.format( name_latest='{name} ({latest})'.format(**locals()), **locals()) try: write_output(line) if name in installed_packages: dist = get_distribution(name) assert dist is not None with indent_log(): if dist.version == latest: write_output('INSTALLED: %s (latest)', dist.version) else: write_output('INSTALLED: %s', dist.version) if parse_version(latest).pre: write_output('LATEST: %s (pre-release; install' ' with "pip install --pre")', latest) else: write_output('LATEST: %s', latest) except UnicodeEncodeError: pass
null
175,567
from __future__ import absolute_import import locale import logging import os import sys import pip._vendor from pip._vendor import pkg_resources from pip._vendor.certifi import where from pip import __file__ as pip_location from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.status_codes import SUCCESS from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import get_pip_version from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) def show_value(name, value): # type: (str, Optional[str]) -> None logger.info('%s: %s', name, value) def indent_log(num=2): """ A context manager which will cause the log output to be indented for any log messages emitted inside it. """ # For thread-safety _log_state.indentation = get_indentation() _log_state.indentation += num try: yield finally: _log_state.indentation -= num def show_sys_implementation(): # type: () -> None logger.info('sys.implementation:') if hasattr(sys, 'implementation'): implementation = sys.implementation # type: ignore implementation_name = implementation.name else: implementation_name = '' with indent_log(): show_value('name', implementation_name)
null
175,568
from __future__ import absolute_import import locale import logging import os import sys import pip._vendor from pip._vendor import pkg_resources from pip._vendor.certifi import where from pip import __file__ as pip_location from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.status_codes import SUCCESS from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import get_pip_version from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) def create_vendor_txt_map(): # type: () -> Dict[str, str] vendor_txt_path = os.path.join( os.path.dirname(pip_location), '_vendor', 'vendor.txt' ) with open(vendor_txt_path) as f: # Purge non version specifying lines. # Also, remove any space prefix or suffixes (including comments). lines = [line.strip().split(' ', 1)[0] for line in f.readlines() if '==' in line] # Transform into "module" -> version dict. return dict(line.split('==', 1) for line in lines) # type: ignore def show_actual_vendor_versions(vendor_txt_versions): # type: (Dict[str, str]) -> None """Log the actual version and print extra info if there is a conflict or if the actual version could not be imported. """ for module_name, expected_version in vendor_txt_versions.items(): extra_message = '' actual_version = get_vendor_version_from_module(module_name) if not actual_version: extra_message = ' (Unable to locate actual module version, using'\ ' vendor.txt specified version)' actual_version = expected_version elif actual_version != expected_version: extra_message = ' (CONFLICT: vendor.txt suggests version should'\ ' be {})'.format(expected_version) logger.info('%s==%s%s', module_name, actual_version, extra_message) def indent_log(num=2): """ A context manager which will cause the log output to be indented for any log messages emitted inside it. """ # For thread-safety _log_state.indentation = get_indentation() _log_state.indentation += num try: yield finally: _log_state.indentation -= num def show_vendor_versions(): # type: () -> None logger.info('vendored library versions:') vendor_txt_versions = create_vendor_txt_map() with indent_log(): show_actual_vendor_versions(vendor_txt_versions)
null
175,569
from __future__ import absolute_import import locale import logging import os import sys import pip._vendor from pip._vendor import pkg_resources from pip._vendor.certifi import where from pip import __file__ as pip_location from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.status_codes import SUCCESS from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import get_pip_version from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) def make_target_python(options): def indent_log(num=2): def show_tags(options): # type: (Values) -> None tag_limit = 10 target_python = make_target_python(options) tags = target_python.get_tags() # Display the target options that were explicitly provided. formatted_target = target_python.format_given() suffix = '' if formatted_target: suffix = ' (target: {})'.format(formatted_target) msg = 'Compatible tags: {}{}'.format(len(tags), suffix) logger.info(msg) if options.verbose < 1 and len(tags) > tag_limit: tags_limited = True tags = tags[:tag_limit] else: tags_limited = False with indent_log(): for tag in tags: logger.info(str(tag)) if tags_limited: msg = ( '...\n' '[First {tag_limit} tags shown. Pass --verbose to show all.]' ).format(tag_limit=tag_limit) logger.info(msg)
null
175,570
from __future__ import absolute_import import locale import logging import os import sys import pip._vendor from pip._vendor import pkg_resources from pip._vendor.certifi import where from pip import __file__ as pip_location from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.status_codes import SUCCESS from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import get_pip_version from pip._internal.utils.typing import MYPY_CHECK_RUNNING def ca_bundle_info(config): # type: (Configuration) -> str levels = set() for key, _ in config.items(): levels.add(key.split('.')[0]) if not levels: return "Not specified" levels_that_override_global = ['install', 'wheel', 'download'] global_overriding_level = [ level for level in levels if level in levels_that_override_global ] if not global_overriding_level: return 'global' if 'global' in levels: levels.remove('global') return ", ".join(levels)
null
175,571
from __future__ import absolute_import import json import logging from pip._vendor import six from pip._internal.cli import cmdoptions from pip._internal.cli.req_command import IndexGroupCommand from pip._internal.cli.status_codes import SUCCESS from pip._internal.exceptions import CommandError from pip._internal.index.collector import LinkCollector from pip._internal.index.package_finder import PackageFinder from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.utils.misc import ( dist_is_editable, get_installed_distributions, tabulate, write_output, ) from pip._internal.utils.packaging import get_installer from pip._internal.utils.parallel import map_multithread from pip._internal.utils.typing import MYPY_CHECK_RUNNING def dist_is_editable(dist): # type: (Distribution) -> bool """ Return True if given Distribution is an editable install. """ for path_item in sys.path: egg_link = os.path.join(path_item, dist.project_name + '.egg-link') if os.path.isfile(egg_link): return True return False def get_installer(dist): # type: (Distribution) -> str if dist.has_metadata('INSTALLER'): for line in dist.get_metadata_lines('INSTALLER'): if line.strip(): return line.strip() return '' The provided code snippet includes necessary dependencies for implementing the `format_for_columns` function. Write a Python function `def format_for_columns(pkgs, options)` to solve the following problem: Convert the package data into something usable by output_package_listing_columns. Here is the function: def format_for_columns(pkgs, options): # type: (List[Distribution], Values) -> Tuple[List[List[str]], List[str]] """ Convert the package data into something usable by output_package_listing_columns. """ running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", "Type"] else: header = ["Package", "Version"] data = [] if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs): header.append("Location") if options.verbose >= 1: header.append("Installer") for proj in pkgs: # if we're working on the 'outdated' list, separate out the # latest_version and type row = [proj.project_name, proj.version] if running_outdated: row.append(proj.latest_version) row.append(proj.latest_filetype) if options.verbose >= 1 or dist_is_editable(proj): row.append(proj.location) if options.verbose >= 1: row.append(get_installer(proj)) data.append(row) return data, header
Convert the package data into something usable by output_package_listing_columns.
175,572
from __future__ import absolute_import import json import logging from pip._vendor import six from pip._internal.cli import cmdoptions from pip._internal.cli.req_command import IndexGroupCommand from pip._internal.cli.status_codes import SUCCESS from pip._internal.exceptions import CommandError from pip._internal.index.collector import LinkCollector from pip._internal.index.package_finder import PackageFinder from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.utils.misc import ( dist_is_editable, get_installed_distributions, tabulate, write_output, ) from pip._internal.utils.packaging import get_installer from pip._internal.utils.parallel import map_multithread from pip._internal.utils.typing import MYPY_CHECK_RUNNING def get_installer(dist): # type: (Distribution) -> str if dist.has_metadata('INSTALLER'): for line in dist.get_metadata_lines('INSTALLER'): if line.strip(): return line.strip() return '' def format_for_json(packages, options): # type: (List[Distribution], Values) -> str data = [] for dist in packages: info = { 'name': dist.project_name, 'version': six.text_type(dist.version), } if options.verbose >= 1: info['location'] = dist.location info['installer'] = get_installer(dist) if options.outdated: info['latest_version'] = six.text_type(dist.latest_version) info['latest_filetype'] = dist.latest_filetype data.append(info) return json.dumps(data)
null
175,573
from __future__ import absolute_import import errno import logging import os import shutil import subprocess import sys from pip._vendor import pkg_resources from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.exceptions import ( BadCommand, InstallationError, SubProcessError, ) from pip._internal.utils.compat import console_to_str, samefile from pip._internal.utils.logging import subprocess_logger from pip._internal.utils.misc import ( ask_path_exists, backup_dir, display_path, hide_url, hide_value, rmtree, ) from pip._internal.utils.subprocess import ( format_command_args, make_command, make_subprocess_output_error, reveal_command_args, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import get_url_scheme vcs = VcsSupport() def get_url_scheme(url): # type: (Union[str, Text]) -> Optional[Text] if ':' not in url: return None return url.split(':', 1)[0].lower() The provided code snippet includes necessary dependencies for implementing the `is_url` function. Write a Python function `def is_url(name)` to solve the following problem: Return true if the name looks like a URL. Here is the function: def is_url(name): # type: (Union[str, Text]) -> bool """ Return true if the name looks like a URL. """ scheme = get_url_scheme(name) if scheme is None: return False return scheme in ['http', 'https', 'file', 'ftp'] + vcs.all_schemes
Return true if the name looks like a URL.
175,574
from __future__ import absolute_import import errno import logging import os import shutil import subprocess import sys from pip._vendor import pkg_resources from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.exceptions import ( BadCommand, InstallationError, SubProcessError, ) from pip._internal.utils.compat import console_to_str, samefile from pip._internal.utils.logging import subprocess_logger from pip._internal.utils.misc import ( ask_path_exists, backup_dir, display_path, hide_url, hide_value, rmtree, ) from pip._internal.utils.subprocess import ( format_command_args, make_command, make_subprocess_output_error, reveal_command_args, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import get_url_scheme The provided code snippet includes necessary dependencies for implementing the `make_vcs_requirement_url` function. Write a Python function `def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None)` to solve the following problem: Return the URL for a VCS requirement. Args: repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+"). project_name: the (unescaped) project name. Here is the function: def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None): # type: (str, str, str, Optional[str]) -> str """ Return the URL for a VCS requirement. Args: repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+"). project_name: the (unescaped) project name. """ egg_project_name = pkg_resources.to_filename(project_name) req = '{}@{}#egg={}'.format(repo_url, rev, egg_project_name) if subdir: req += '&subdirectory={}'.format(subdir) return req
Return the URL for a VCS requirement. Args: repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+"). project_name: the (unescaped) project name.
175,575
from __future__ import absolute_import import errno import logging import os import shutil import subprocess import sys from pip._vendor import pkg_resources from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.exceptions import ( BadCommand, InstallationError, SubProcessError, ) from pip._internal.utils.compat import console_to_str, samefile from pip._internal.utils.logging import subprocess_logger from pip._internal.utils.misc import ( ask_path_exists, backup_dir, display_path, hide_url, hide_value, rmtree, ) from pip._internal.utils.subprocess import ( format_command_args, make_command, make_subprocess_output_error, reveal_command_args, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import get_url_scheme class SubProcessError(PipError): """Raised when there is an error raised while executing a command in subprocess""" def console_to_str(data): # type: (bytes) -> Text """Return a string, safe for output, of subprocess output. """ return str_to_display(data, desc='Subprocess output') subprocess_logger = getLogger('pip.subprocessor') def format_command_args(args): # type: (Union[List[str], CommandArgs]) -> str """ Format command arguments for display. """ # For HiddenText arguments, display the redacted form by calling str(). # Also, we don't apply str() to arguments that aren't HiddenText since # this can trigger a UnicodeDecodeError in Python 2 if the argument # has type unicode and includes a non-ascii character. (The type # checker doesn't ensure the annotations are correct in all cases.) return ' '.join( shlex_quote(str(arg)) if isinstance(arg, HiddenText) else shlex_quote(arg) for arg in args ) def reveal_command_args(args): # type: (Union[List[str], CommandArgs]) -> List[str] """ Return the arguments in their raw, unredacted form. """ return [ arg.secret if isinstance(arg, HiddenText) else arg for arg in args ] def make_subprocess_output_error( cmd_args, # type: Union[List[str], CommandArgs] cwd, # type: Optional[str] lines, # type: List[Text] exit_status, # type: int ): # type: (...) -> Text """ Create and return the error message to use to log a subprocess error with command output. :param lines: A list of lines, each ending with a newline. """ command = format_command_args(cmd_args) # Convert `command` and `cwd` to text (unicode in Python 2) so we can use # them as arguments in the unicode format string below. This avoids # "UnicodeDecodeError: 'ascii' codec can't decode byte ..." in Python 2 # if either contains a non-ascii character. command_display = str_to_display(command, desc='command bytes') cwd_display = path_to_display(cwd) # We know the joined output value ends in a newline. output = ''.join(lines) msg = ( # Use a unicode string to avoid "UnicodeEncodeError: 'ascii' # codec can't encode character ..." in Python 2 when a format # argument (e.g. `output`) has a non-ascii character. u'Command errored out with exit status {exit_status}:\n' ' command: {command_display}\n' ' cwd: {cwd_display}\n' 'Complete output ({line_count} lines):\n{output}{divider}' ).format( exit_status=exit_status, command_display=command_display, cwd_display=cwd_display, line_count=len(lines), output=output, divider=LOG_DIVIDER, ) return msg The provided code snippet includes necessary dependencies for implementing the `call_subprocess` function. Write a Python function `def call_subprocess( cmd, # type: Union[List[str], CommandArgs] cwd=None, # type: Optional[str] extra_environ=None, # type: Optional[Mapping[str, Any]] extra_ok_returncodes=None, # type: Optional[Iterable[int]] log_failed_cmd=True # type: Optional[bool] )` to solve the following problem: Args: extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. log_failed_cmd: if false, failed commands are not logged, only raised. Here is the function: def call_subprocess( cmd, # type: Union[List[str], CommandArgs] cwd=None, # type: Optional[str] extra_environ=None, # type: Optional[Mapping[str, Any]] extra_ok_returncodes=None, # type: Optional[Iterable[int]] log_failed_cmd=True # type: Optional[bool] ): # type: (...) -> Text """ Args: extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. log_failed_cmd: if false, failed commands are not logged, only raised. """ if extra_ok_returncodes is None: extra_ok_returncodes = [] # log the subprocess output at DEBUG level. log_subprocess = subprocess_logger.debug env = os.environ.copy() if extra_environ: env.update(extra_environ) # Whether the subprocess will be visible in the console. showing_subprocess = True command_desc = format_command_args(cmd) try: proc = subprocess.Popen( # Convert HiddenText objects to the underlying str. reveal_command_args(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd ) if proc.stdin: proc.stdin.close() except Exception as exc: if log_failed_cmd: subprocess_logger.critical( "Error %s while executing command %s", exc, command_desc, ) raise all_output = [] while True: # The "line" value is a unicode string in Python 2. line = None if proc.stdout: line = console_to_str(proc.stdout.readline()) if not line: break line = line.rstrip() all_output.append(line + '\n') # Show the line immediately. log_subprocess(line) try: proc.wait() finally: if proc.stdout: proc.stdout.close() proc_had_error = ( proc.returncode and proc.returncode not in extra_ok_returncodes ) if proc_had_error: if not showing_subprocess and log_failed_cmd: # Then the subprocess streams haven't been logged to the # console yet. msg = make_subprocess_output_error( cmd_args=cmd, cwd=cwd, lines=all_output, exit_status=proc.returncode, ) subprocess_logger.error(msg) exc_msg = ( 'Command errored out with exit status {}: {} ' 'Check the logs for full command output.' ).format(proc.returncode, command_desc) raise SubProcessError(exc_msg) return ''.join(all_output)
Args: extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. log_failed_cmd: if false, failed commands are not logged, only raised.
175,576
from __future__ import absolute_import import errno import logging import os import shutil import subprocess import sys from pip._vendor import pkg_resources from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.exceptions import ( BadCommand, InstallationError, SubProcessError, ) from pip._internal.utils.compat import console_to_str, samefile from pip._internal.utils.logging import subprocess_logger from pip._internal.utils.misc import ( ask_path_exists, backup_dir, display_path, hide_url, hide_value, rmtree, ) from pip._internal.utils.subprocess import ( format_command_args, make_command, make_subprocess_output_error, reveal_command_args, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import get_url_scheme logger = logging.getLogger(__name__) def samefile(file1, file2): # type: (str, str) -> bool """Provide an alternative for os.path.samefile on Windows/Python2""" if hasattr(os.path, 'samefile'): return os.path.samefile(file1, file2) else: path1 = os.path.normcase(os.path.abspath(file1)) path2 = os.path.normcase(os.path.abspath(file2)) return path1 == path2 The provided code snippet includes necessary dependencies for implementing the `find_path_to_setup_from_repo_root` function. Write a Python function `def find_path_to_setup_from_repo_root(location, repo_root)` to solve the following problem: Find the path to `setup.py` by searching up the filesystem from `location`. Return the path to `setup.py` relative to `repo_root`. Return None if `setup.py` is in `repo_root` or cannot be found. Here is the function: def find_path_to_setup_from_repo_root(location, repo_root): # type: (str, str) -> Optional[str] """ Find the path to `setup.py` by searching up the filesystem from `location`. Return the path to `setup.py` relative to `repo_root`. Return None if `setup.py` is in `repo_root` or cannot be found. """ # find setup.py orig_location = location while not os.path.exists(os.path.join(location, 'setup.py')): last_location = location location = os.path.dirname(location) if location == last_location: # We've traversed up to the root of the filesystem without # finding setup.py logger.warning( "Could not find setup.py for directory %s (tried all " "parent directories)", orig_location, ) return None if samefile(repo_root, location): return None return os.path.relpath(location, repo_root)
Find the path to `setup.py` by searching up the filesystem from `location`. Return the path to `setup.py` relative to `repo_root`. Return None if `setup.py` is in `repo_root` or cannot be found.
175,577
from __future__ import absolute_import import logging import os.path import re from pip._vendor.packaging.version import parse as parse_version from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.exceptions import BadCommand, SubProcessError from pip._internal.utils.misc import display_path, hide_url from pip._internal.utils.subprocess import make_command from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.vcs.versioncontrol import ( RemoteNotFoundError, VersionControl, find_path_to_setup_from_repo_root, vcs, ) HASH_REGEX = re.compile('^[a-fA-F0-9]{40}$') def looks_like_hash(sha): return bool(HASH_REGEX.match(sha))
null
175,578
from __future__ import absolute_import import io import os import sys from collections import namedtuple from pip._vendor import six, toml from pip._vendor.packaging.requirements import InvalidRequirement, Requirement from pip._internal.exceptions import InstallationError from pip._internal.utils.typing import MYPY_CHECK_RUNNING def _is_list_of_str(obj): # type: (Any) -> bool return ( isinstance(obj, list) and all(isinstance(item, six.string_types) for item in obj) ) BuildSystemDetails = namedtuple('BuildSystemDetails', [ 'requires', 'backend', 'check', 'backend_path' ]) class InvalidRequirement(ValueError): """ An invalid requirement was found, users should refer to PEP 508. """ class Requirement(object): """Parse a requirement. Parse a given requirement string into its parts, such as name, specifier, URL, and extras. Raises InvalidRequirement on a badly-formed requirement string. """ # TODO: Can we test whether something is contained within a requirement? # If so how do we do that? Do we need to test against the _name_ of # the thing as well as the version? What about the markers? # TODO: Can we normalize the name and extra name? def __init__(self, requirement_string): # type: (str) -> None try: req = REQUIREMENT.parseString(requirement_string) except ParseException as e: raise InvalidRequirement( 'Parse error at "{0!r}": {1}'.format( requirement_string[e.loc : e.loc + 8], e.msg ) ) self.name = req.name if req.url: parsed_url = urlparse.urlparse(req.url) if parsed_url.scheme == "file": if urlparse.urlunparse(parsed_url) != req.url: raise InvalidRequirement("Invalid URL given") elif not (parsed_url.scheme and parsed_url.netloc) or ( not parsed_url.scheme and not parsed_url.netloc ): raise InvalidRequirement("Invalid URL: {0}".format(req.url)) self.url = req.url else: self.url = None self.extras = set(req.extras.asList() if req.extras else []) self.specifier = SpecifierSet(req.specifier) self.marker = req.marker if req.marker else None def __str__(self): # type: () -> str parts = [self.name] # type: List[str] if self.extras: parts.append("[{0}]".format(",".join(sorted(self.extras)))) if self.specifier: parts.append(str(self.specifier)) if self.url: parts.append("@ {0}".format(self.url)) if self.marker: parts.append(" ") if self.marker: parts.append("; {0}".format(self.marker)) return "".join(parts) def __repr__(self): # type: () -> str return "<Requirement({0!r})>".format(str(self)) class InstallationError(PipError): """General exception during installation""" The provided code snippet includes necessary dependencies for implementing the `load_pyproject_toml` function. Write a Python function `def load_pyproject_toml( use_pep517, # type: Optional[bool] pyproject_toml, # type: str setup_py, # type: str req_name # type: str )` to solve the following problem: Load the pyproject.toml file. Parameters: use_pep517 - Has the user requested PEP 517 processing? None means the user hasn't explicitly specified. pyproject_toml - Location of the project's pyproject.toml file setup_py - Location of the project's setup.py file req_name - The name of the requirement we're processing (for error reporting) Returns: None if we should use the legacy code path, otherwise a tuple ( requirements from pyproject.toml, name of PEP 517 backend, requirements we should check are installed after setting up the build environment directory paths to import the backend from (backend-path), relative to the project root. ) Here is the function: def load_pyproject_toml( use_pep517, # type: Optional[bool] pyproject_toml, # type: str setup_py, # type: str req_name # type: str ): # type: (...) -> Optional[BuildSystemDetails] """Load the pyproject.toml file. Parameters: use_pep517 - Has the user requested PEP 517 processing? None means the user hasn't explicitly specified. pyproject_toml - Location of the project's pyproject.toml file setup_py - Location of the project's setup.py file req_name - The name of the requirement we're processing (for error reporting) Returns: None if we should use the legacy code path, otherwise a tuple ( requirements from pyproject.toml, name of PEP 517 backend, requirements we should check are installed after setting up the build environment directory paths to import the backend from (backend-path), relative to the project root. ) """ has_pyproject = os.path.isfile(pyproject_toml) has_setup = os.path.isfile(setup_py) if has_pyproject: with io.open(pyproject_toml, encoding="utf-8") as f: pp_toml = toml.load(f) build_system = pp_toml.get("build-system") else: build_system = None # The following cases must use PEP 517 # We check for use_pep517 being non-None and falsey because that means # the user explicitly requested --no-use-pep517. The value 0 as # opposed to False can occur when the value is provided via an # environment variable or config file option (due to the quirk of # strtobool() returning an integer in pip's configuration code). if has_pyproject and not has_setup: if use_pep517 is not None and not use_pep517: raise InstallationError( "Disabling PEP 517 processing is invalid: " "project does not have a setup.py" ) use_pep517 = True elif build_system and "build-backend" in build_system: if use_pep517 is not None and not use_pep517: raise InstallationError( "Disabling PEP 517 processing is invalid: " "project specifies a build backend of {} " "in pyproject.toml".format( build_system["build-backend"] ) ) use_pep517 = True # If we haven't worked out whether to use PEP 517 yet, # and the user hasn't explicitly stated a preference, # we do so if the project has a pyproject.toml file. elif use_pep517 is None: use_pep517 = has_pyproject # At this point, we know whether we're going to use PEP 517. assert use_pep517 is not None # If we're using the legacy code path, there is nothing further # for us to do here. if not use_pep517: return None if build_system is None: # Either the user has a pyproject.toml with no build-system # section, or the user has no pyproject.toml, but has opted in # explicitly via --use-pep517. # In the absence of any explicit backend specification, we # assume the setuptools backend that most closely emulates the # traditional direct setup.py execution, and require wheel and # a version of setuptools that supports that backend. build_system = { "requires": ["setuptools>=40.8.0", "wheel"], "build-backend": "setuptools.build_meta:__legacy__", } # If we're using PEP 517, we have build system information (either # from pyproject.toml, or defaulted by the code above). # Note that at this point, we do not know if the user has actually # specified a backend, though. assert build_system is not None # Ensure that the build-system section in pyproject.toml conforms # to PEP 518. error_template = ( "{package} has a pyproject.toml file that does not comply " "with PEP 518: {reason}" ) # Specifying the build-system table but not the requires key is invalid if "requires" not in build_system: raise InstallationError( error_template.format(package=req_name, reason=( "it has a 'build-system' table but not " "'build-system.requires' which is mandatory in the table" )) ) # Error out if requires is not a list of strings requires = build_system["requires"] if not _is_list_of_str(requires): raise InstallationError(error_template.format( package=req_name, reason="'build-system.requires' is not a list of strings.", )) # Each requirement must be valid as per PEP 508 for requirement in requires: try: Requirement(requirement) except InvalidRequirement: raise InstallationError( error_template.format( package=req_name, reason=( "'build-system.requires' contains an invalid " "requirement: {!r}".format(requirement) ), ) ) backend = build_system.get("build-backend") backend_path = build_system.get("backend-path", []) check = [] # type: List[str] if backend is None: # If the user didn't specify a backend, we assume they want to use # the setuptools backend. But we can't be sure they have included # a version of setuptools which supplies the backend, or wheel # (which is needed by the backend) in their requirements. So we # make a note to check that those requirements are present once # we have set up the environment. # This is quite a lot of work to check for a very specific case. But # the problem is, that case is potentially quite common - projects that # adopted PEP 518 early for the ability to specify requirements to # execute setup.py, but never considered needing to mention the build # tools themselves. The original PEP 518 code had a similar check (but # implemented in a different way). backend = "setuptools.build_meta:__legacy__" check = ["setuptools>=40.8.0", "wheel"] return BuildSystemDetails(requires, backend, check, backend_path)
Load the pyproject.toml file. Parameters: use_pep517 - Has the user requested PEP 517 processing? None means the user hasn't explicitly specified. pyproject_toml - Location of the project's pyproject.toml file setup_py - Location of the project's setup.py file req_name - The name of the requirement we're processing (for error reporting) Returns: None if we should use the legacy code path, otherwise a tuple ( requirements from pyproject.toml, name of PEP 517 backend, requirements we should check are installed after setting up the build environment directory paths to import the backend from (backend-path), relative to the project root. )
175,579
import cgi import functools import itertools import logging import mimetypes import os import re from collections import OrderedDict from pip._vendor import html5lib, requests from pip._vendor.distlib.compat import unescape from pip._vendor.requests.exceptions import RetryError, SSLError from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.link import Link from pip._internal.models.search_scope import SearchScope from pip._internal.network.utils import raise_for_status from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import pairwise, redact_auth_from_url from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url, url_to_path from pip._internal.vcs import is_url, vcs def noop_lru_cache(maxsize=None): # type: (Optional[int]) -> Callable[[F], F] def _wrapper(f): # type: (F) -> F return f return _wrapper
null
175,580
import cgi import functools import itertools import logging import mimetypes import os import re from collections import OrderedDict from pip._vendor import html5lib, requests from pip._vendor.distlib.compat import unescape from pip._vendor.requests.exceptions import RetryError, SSLError from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.link import Link from pip._internal.models.search_scope import SearchScope from pip._internal.network.utils import raise_for_status from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import pairwise, redact_auth_from_url from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url, url_to_path from pip._internal.vcs import is_url, vcs _lru_cache = getattr(functools, "lru_cache", noop_lru_cache) class CacheablePageContent(object): def __init__(self, page): # type: (HTMLPage) -> None assert page.cache_link_parsing self.page = page def __eq__(self, other): # type: (object) -> bool return (isinstance(other, type(self)) and self.page.url == other.page.url) def __hash__(self): # type: () -> int return hash(self.page.url) The provided code snippet includes necessary dependencies for implementing the `with_cached_html_pages` function. Write a Python function `def with_cached_html_pages( fn, # type: Callable[[HTMLPage], Iterable[Link]] )` to solve the following problem: Given a function that parses an Iterable[Link] from an HTMLPage, cache the function's result (keyed by CacheablePageContent), unless the HTMLPage `page` has `page.cache_link_parsing == False`. Here is the function: def with_cached_html_pages( fn, # type: Callable[[HTMLPage], Iterable[Link]] ): # type: (...) -> Callable[[HTMLPage], List[Link]] """ Given a function that parses an Iterable[Link] from an HTMLPage, cache the function's result (keyed by CacheablePageContent), unless the HTMLPage `page` has `page.cache_link_parsing == False`. """ @_lru_cache(maxsize=None) def wrapper(cacheable_page): # type: (CacheablePageContent) -> List[Link] return list(fn(cacheable_page.page)) @functools.wraps(fn) def wrapper_wrapper(page): # type: (HTMLPage) -> List[Link] if page.cache_link_parsing: return wrapper(CacheablePageContent(page)) return list(fn(page)) return wrapper_wrapper
Given a function that parses an Iterable[Link] from an HTMLPage, cache the function's result (keyed by CacheablePageContent), unless the HTMLPage `page` has `page.cache_link_parsing == False`.
175,581
import cgi import functools import itertools import logging import mimetypes import os import re from collections import OrderedDict from pip._vendor import html5lib, requests from pip._vendor.distlib.compat import unescape from pip._vendor.requests.exceptions import RetryError, SSLError from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.link import Link from pip._internal.models.search_scope import SearchScope from pip._internal.network.utils import raise_for_status from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import pairwise, redact_auth_from_url from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url, url_to_path from pip._internal.vcs import is_url, vcs def _determine_base_url(document, page_url): # type: (HTMLElement, str) -> str """Determine the HTML document's base URL. This looks for a ``<base>`` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the HTML file's URL is used as the base URL. :param document: An HTML document representation. The current implementation expects the result of ``html5lib.parse()``. :param page_url: The URL of the HTML document. """ for base in document.findall(".//base"): href = base.get("href") if href is not None: return href return page_url def _create_link_from_element( anchor, # type: HTMLElement page_url, # type: str base_url, # type: str ): # type: (...) -> Optional[Link] """ Convert an anchor element in a simple repository page to a Link. """ href = anchor.get("href") if not href: return None url = _clean_link(urllib_parse.urljoin(base_url, href)) pyrequire = anchor.get('data-requires-python') pyrequire = unescape(pyrequire) if pyrequire else None yanked_reason = anchor.get('data-yanked') if yanked_reason: # This is a unicode string in Python 2 (and 3). yanked_reason = unescape(yanked_reason) link = Link( url, comes_from=page_url, requires_python=pyrequire, yanked_reason=yanked_reason, ) return link The provided code snippet includes necessary dependencies for implementing the `parse_links` function. Write a Python function `def parse_links(page)` to solve the following problem: Parse an HTML document, and yield its anchor elements as Link objects. Here is the function: def parse_links(page): # type: (HTMLPage) -> Iterable[Link] """ Parse an HTML document, and yield its anchor elements as Link objects. """ document = html5lib.parse( page.content, transport_encoding=page.encoding, namespaceHTMLElements=False, ) url = page.url base_url = _determine_base_url(document, url) for anchor in document.findall(".//a"): link = _create_link_from_element( anchor, page_url=url, base_url=base_url, ) if link is None: continue yield link
Parse an HTML document, and yield its anchor elements as Link objects.
175,582
import cgi import functools import itertools import logging import mimetypes import os import re from collections import OrderedDict from pip._vendor import html5lib, requests from pip._vendor.distlib.compat import unescape from pip._vendor.requests.exceptions import RetryError, SSLError from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.link import Link from pip._internal.models.search_scope import SearchScope from pip._internal.network.utils import raise_for_status from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import pairwise, redact_auth_from_url from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url, url_to_path from pip._internal.vcs import is_url, vcs logger = logging.getLogger(__name__) def _match_vcs_scheme(url): # type: (str) -> Optional[str] """Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match. """ for scheme in vcs.schemes: if url.lower().startswith(scheme) and url[len(scheme)] in '+:': return scheme return None class _NotHTML(Exception): def __init__(self, content_type, request_desc): # type: (str, str) -> None super(_NotHTML, self).__init__(content_type, request_desc) self.content_type = content_type self.request_desc = request_desc class _NotHTTP(Exception): pass def _get_html_response(url, session): # type: (str, PipSession) -> Response """Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_NotHTML` if it is not HTML. 2. Actually perform the request. Raise HTTP exceptions on network failures. 3. Check the Content-Type header to make sure we got HTML, and raise `_NotHTML` otherwise. """ if _is_url_like_archive(url): _ensure_html_response(url, session=session) logger.debug('Getting page %s', redact_auth_from_url(url)) resp = session.get( url, headers={ "Accept": "text/html", # We don't want to blindly returned cached data for # /simple/, because authors generally expecting that # twine upload && pip install will function, but if # they've done a pip install in the last ~10 minutes # it won't. Thus by setting this to zero we will not # blindly use any cached data, however the benefit of # using max-age=0 instead of no-cache, is that we will # still support conditional requests, so we will still # minimize traffic sent in cases where the page hasn't # changed at all, we will just always incur the round # trip for the conditional GET now instead of only # once per 10 minutes. # For more information, please see pypa/pip#5670. "Cache-Control": "max-age=0", }, ) raise_for_status(resp) # The check for archives above only works if the url ends with # something that looks like an archive. However that is not a # requirement of an url. Unless we issue a HEAD request on every # url we cannot know ahead of time for sure if something is HTML # or not. However we can check after we've downloaded it. _ensure_html_header(resp) return resp def _handle_get_page_fail( link, # type: Link reason, # type: Union[str, Exception] meth=None # type: Optional[Callable[..., None]] ): # type: (...) -> None if meth is None: meth = logger.debug meth("Could not fetch URL %s: %s - skipping", link, reason) def _make_html_page(response, cache_link_parsing=True): # type: (Response, bool) -> HTMLPage encoding = _get_encoding_from_headers(response.headers) return HTMLPage( response.content, encoding=encoding, url=response.url, cache_link_parsing=cache_link_parsing) class SSLError(ConnectionError): """An SSL error occurred.""" class RetryError(RequestException): """Custom retries logic failed""" class NetworkConnectionError(PipError): """HTTP connection error""" def __init__(self, error_msg, response=None, request=None): # type: (Text, Response, Request) -> None """ Initialize NetworkConnectionError with `request` and `response` objects. """ self.response = response self.request = request self.error_msg = error_msg if (self.response is not None and not self.request and hasattr(response, 'request')): self.request = self.response.request super(NetworkConnectionError, self).__init__( error_msg, response, request) def __str__(self): # type: () -> str return str(self.error_msg) def _get_html_page(link, session=None): # type: (Link, Optional[PipSession]) -> Optional[HTMLPage] if session is None: raise TypeError( "_get_html_page() missing 1 required keyword argument: 'session'" ) url = link.url.split('#', 1)[0] # Check for VCS schemes that do not support lookup as web pages. vcs_scheme = _match_vcs_scheme(url) if vcs_scheme: logger.warning('Cannot look at %s URL %s because it does not support ' 'lookup as web pages.', vcs_scheme, link) return None # Tack index.html onto file:// URLs that point to directories scheme, _, path, _, _, _ = urllib_parse.urlparse(url) if (scheme == 'file' and os.path.isdir(urllib_request.url2pathname(path))): # add trailing slash if not present so urljoin doesn't trim # final segment if not url.endswith('/'): url += '/' url = urllib_parse.urljoin(url, 'index.html') logger.debug(' file: URL is directory, getting %s', url) try: resp = _get_html_response(url, session=session) except _NotHTTP: logger.warning( 'Skipping page %s because it looks like an archive, and cannot ' 'be checked by a HTTP HEAD request.', link, ) except _NotHTML as exc: logger.warning( 'Skipping page %s because the %s request got Content-Type: %s.' 'The only supported Content-Type is text/html', link, exc.request_desc, exc.content_type, ) except NetworkConnectionError as exc: _handle_get_page_fail(link, exc) except RetryError as exc: _handle_get_page_fail(link, exc) except SSLError as exc: reason = "There was a problem confirming the ssl certificate: " reason += str(exc) _handle_get_page_fail(link, reason, meth=logger.info) except requests.ConnectionError as exc: _handle_get_page_fail(link, "connection error: {}".format(exc)) except requests.Timeout: _handle_get_page_fail(link, "timed out") else: return _make_html_page(resp, cache_link_parsing=link.cache_link_parsing) return None
null
175,583
import cgi import functools import itertools import logging import mimetypes import os import re from collections import OrderedDict from pip._vendor import html5lib, requests from pip._vendor.distlib.compat import unescape from pip._vendor.requests.exceptions import RetryError, SSLError from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.link import Link from pip._internal.models.search_scope import SearchScope from pip._internal.network.utils import raise_for_status from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import pairwise, redact_auth_from_url from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url, url_to_path from pip._internal.vcs import is_url, vcs class OrderedDict(dict): def __init__(self, data=None, **kwargs): self._keys = self.keys(data, kwargs.get("keys")) self._default_factory = kwargs.get("default_factory") if data is None: dict.__init__(self) else: dict.__init__(self, data) def __delitem__(self, key): dict.__delitem__(self, key) self._keys.remove(key) def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.__missing__(key) def __iter__(self): return (key for key in self.keys()) def __missing__(self, key): if not self._default_factory and key not in self._keys: raise KeyError() return self._default_factory() def __setitem__(self, key, item): dict.__setitem__(self, key, item) if key not in self._keys: self._keys.append(key) def clear(self): dict.clear(self) self._keys.clear() def copy(self): d = dict.copy(self) d._keys = self._keys return d def items(self): # returns iterator under python 3 and list under python 2 return zip(self.keys(), self.values()) def keys(self, data=None, keys=None): if data: if keys: assert isinstance(keys, list) assert len(data) == len(keys) return keys else: assert ( isinstance(data, dict) or isinstance(data, OrderedDict) or isinstance(data, list) ) if isinstance(data, dict) or isinstance(data, OrderedDict): return data.keys() elif isinstance(data, list): return [key for (key, value) in data] elif "_keys" in self.__dict__: return self._keys else: return [] def popitem(self): if not self._keys: raise KeyError() key = self._keys.pop() value = self[key] del self[key] return (key, value) def setdefault(self, key, failobj=None): dict.setdefault(self, key, failobj) if key not in self._keys: self._keys.append(key) def update(self, data): dict.update(self, data) for key in self.keys(data): if key not in self._keys: self._keys.append(key) def values(self): # returns iterator under python 3 return map(self.get, self._keys) The provided code snippet includes necessary dependencies for implementing the `_remove_duplicate_links` function. Write a Python function `def _remove_duplicate_links(links)` to solve the following problem: Return a list of links, with duplicates removed and ordering preserved. Here is the function: def _remove_duplicate_links(links): # type: (Iterable[Link]) -> List[Link] """ Return a list of links, with duplicates removed and ordering preserved. """ # We preserve the ordering when removing duplicates because we can. return list(OrderedDict.fromkeys(links))
Return a list of links, with duplicates removed and ordering preserved.
175,584
import cgi import functools import itertools import logging import mimetypes import os import re from collections import OrderedDict from pip._vendor import html5lib, requests from pip._vendor.distlib.compat import unescape from pip._vendor.requests.exceptions import RetryError, SSLError from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.link import Link from pip._internal.models.search_scope import SearchScope from pip._internal.network.utils import raise_for_status from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import pairwise, redact_auth_from_url from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url, url_to_path from pip._internal.vcs import is_url, vcs logger = logging.getLogger(__name__) def path_to_url(path): # type: (Union[str, Text]) -> str """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) url = urllib_parse.urljoin('file:', urllib_request.pathname2url(path)) return url def url_to_path(url): # type: (str) -> str """ Convert a file: URL to a path. """ assert url.startswith('file:'), ( "You can only turn file: urls into filenames (not {url!r})" .format(**locals())) _, netloc, path, _, _ = urllib_parse.urlsplit(url) if not netloc or netloc == 'localhost': # According to RFC 8089, same as empty authority. netloc = '' elif sys.platform == 'win32': # If we have a UNC path, prepend UNC share notation. netloc = '\\\\' + netloc else: raise ValueError( 'non-local file URIs are not supported on this platform: {url!r}' .format(**locals()) ) path = urllib_request.url2pathname(netloc + path) return path The provided code snippet includes necessary dependencies for implementing the `group_locations` function. Write a Python function `def group_locations(locations, expand_dir=False)` to solve the following problem: Divide a list of locations into two groups: "files" (archives) and "urls." :return: A pair of lists (files, urls). Here is the function: def group_locations(locations, expand_dir=False): # type: (Sequence[str], bool) -> Tuple[List[str], List[str]] """ Divide a list of locations into two groups: "files" (archives) and "urls." :return: A pair of lists (files, urls). """ files = [] urls = [] # puts the url for the given file path into the appropriate list def sort_path(path): # type: (str) -> None url = path_to_url(path) if mimetypes.guess_type(url, strict=False)[0] == 'text/html': urls.append(url) else: files.append(url) for url in locations: is_local_path = os.path.exists(url) is_file_url = url.startswith('file:') if is_local_path or is_file_url: if is_local_path: path = url else: path = url_to_path(url) if os.path.isdir(path): if expand_dir: path = os.path.realpath(path) for item in os.listdir(path): sort_path(os.path.join(path, item)) elif is_file_url: urls.append(url) else: logger.warning( "Path '%s' is ignored: it is a directory.", path, ) elif os.path.isfile(path): sort_path(path) else: logger.warning( "Url '%s' is ignored: it is neither a file " "nor a directory.", url, ) elif is_url(url): # Only add url with clear scheme urls.append(url) else: logger.warning( "Url '%s' is ignored. It is either a non-existing " "path or lacks a specific scheme.", url, ) return files, urls
Divide a list of locations into two groups: "files" (archives) and "urls." :return: A pair of lists (files, urls).
175,585
from __future__ import absolute_import import logging import re from pip._vendor.packaging import specifiers from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import parse as parse_version from pip._internal.exceptions import ( BestVersionAlreadyInstalled, DistributionNotFound, InvalidWheelFilename, UnsupportedWheel, ) from pip._internal.index.collector import parse_links from pip._internal.models.candidate import InstallationCandidate from pip._internal.models.format_control import FormatControl from pip._internal.models.link import Link from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.models.target_python import TargetPython from pip._internal.models.wheel import Wheel from pip._internal.utils.filetypes import WHEEL_EXTENSION from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import build_netloc from pip._internal.utils.packaging import check_requires_python from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS from pip._internal.utils.urls import url_to_path logger = logging.getLogger(__name__) def check_requires_python(requires_python, version_info): # type: (Optional[str], Tuple[int, ...]) -> bool """ Check if the given Python version matches a "Requires-Python" specifier. :param version_info: A 3-tuple of ints representing a Python major-minor-micro version to check (e.g. `sys.version_info[:3]`). :return: `True` if the given Python version satisfies the requirement. Otherwise, return `False`. :raises InvalidSpecifier: If `requires_python` has an invalid format. """ if requires_python is None: # The package provides no information return True requires_python_specifier = specifiers.SpecifierSet(requires_python) python_version = version.parse('.'.join(map(str, version_info))) return python_version in requires_python_specifier The provided code snippet includes necessary dependencies for implementing the `_check_link_requires_python` function. Write a Python function `def _check_link_requires_python( link, # type: Link version_info, # type: Tuple[int, int, int] ignore_requires_python=False, # type: bool )` to solve the following problem: Return whether the given Python version is compatible with a link's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. Here is the function: def _check_link_requires_python( link, # type: Link version_info, # type: Tuple[int, int, int] ignore_requires_python=False, # type: bool ): # type: (...) -> bool """ Return whether the given Python version is compatible with a link's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. """ try: is_compatible = check_requires_python( link.requires_python, version_info=version_info, ) except specifiers.InvalidSpecifier: logger.debug( "Ignoring invalid Requires-Python (%r) for link: %s", link.requires_python, link, ) else: if not is_compatible: version = '.'.join(map(str, version_info)) if not ignore_requires_python: logger.debug( 'Link requires a different Python (%s not in: %r): %s', version, link.requires_python, link, ) return False logger.debug( 'Ignoring failed Requires-Python check (%s not in: %r) ' 'for link: %s', version, link.requires_python, link, ) return True
Return whether the given Python version is compatible with a link's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible.
175,586
from __future__ import absolute_import import logging import re from pip._vendor.packaging import specifiers from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import parse as parse_version from pip._internal.exceptions import ( BestVersionAlreadyInstalled, DistributionNotFound, InvalidWheelFilename, UnsupportedWheel, ) from pip._internal.index.collector import parse_links from pip._internal.models.candidate import InstallationCandidate from pip._internal.models.format_control import FormatControl from pip._internal.models.link import Link from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.models.target_python import TargetPython from pip._internal.models.wheel import Wheel from pip._internal.utils.filetypes import WHEEL_EXTENSION from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import build_netloc from pip._internal.utils.packaging import check_requires_python from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS from pip._internal.utils.urls import url_to_path logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `filter_unallowed_hashes` function. Write a Python function `def filter_unallowed_hashes( candidates, # type: List[InstallationCandidate] hashes, # type: Hashes project_name, # type: str )` to solve the following problem: Filter out candidates whose hashes aren't allowed, and return a new list of candidates. If at least one candidate has an allowed hash, then all candidates with either an allowed hash or no hash specified are returned. Otherwise, the given candidates are returned. Including the candidates with no hash specified when there is a match allows a warning to be logged if there is a more preferred candidate with no hash specified. Returning all candidates in the case of no matches lets pip report the hash of the candidate that would otherwise have been installed (e.g. permitting the user to more easily update their requirements file with the desired hash). Here is the function: def filter_unallowed_hashes( candidates, # type: List[InstallationCandidate] hashes, # type: Hashes project_name, # type: str ): # type: (...) -> List[InstallationCandidate] """ Filter out candidates whose hashes aren't allowed, and return a new list of candidates. If at least one candidate has an allowed hash, then all candidates with either an allowed hash or no hash specified are returned. Otherwise, the given candidates are returned. Including the candidates with no hash specified when there is a match allows a warning to be logged if there is a more preferred candidate with no hash specified. Returning all candidates in the case of no matches lets pip report the hash of the candidate that would otherwise have been installed (e.g. permitting the user to more easily update their requirements file with the desired hash). """ if not hashes: logger.debug( 'Given no hashes to check %s links for project %r: ' 'discarding no candidates', len(candidates), project_name, ) # Make sure we're not returning back the given value. return list(candidates) matches_or_no_digest = [] # Collect the non-matches for logging purposes. non_matches = [] match_count = 0 for candidate in candidates: link = candidate.link if not link.has_hash: pass elif link.is_hash_allowed(hashes=hashes): match_count += 1 else: non_matches.append(candidate) continue matches_or_no_digest.append(candidate) if match_count: filtered = matches_or_no_digest else: # Make sure we're not returning back the given value. filtered = list(candidates) if len(filtered) == len(candidates): discard_message = 'discarding no candidates' else: discard_message = 'discarding {} non-matches:\n {}'.format( len(non_matches), '\n '.join(str(candidate.link) for candidate in non_matches) ) logger.debug( 'Checked %s links for project %r against %s hashes ' '(%s matches, %s no digest): %s', len(candidates), project_name, hashes.digest_count, match_count, len(matches_or_no_digest) - match_count, discard_message ) return filtered
Filter out candidates whose hashes aren't allowed, and return a new list of candidates. If at least one candidate has an allowed hash, then all candidates with either an allowed hash or no hash specified are returned. Otherwise, the given candidates are returned. Including the candidates with no hash specified when there is a match allows a warning to be logged if there is a more preferred candidate with no hash specified. Returning all candidates in the case of no matches lets pip report the hash of the candidate that would otherwise have been installed (e.g. permitting the user to more easily update their requirements file with the desired hash).
175,587
from __future__ import absolute_import import logging import re from pip._vendor.packaging import specifiers from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import parse as parse_version from pip._internal.exceptions import ( BestVersionAlreadyInstalled, DistributionNotFound, InvalidWheelFilename, UnsupportedWheel, ) from pip._internal.index.collector import parse_links from pip._internal.models.candidate import InstallationCandidate from pip._internal.models.format_control import FormatControl from pip._internal.models.link import Link from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.models.target_python import TargetPython from pip._internal.models.wheel import Wheel from pip._internal.utils.filetypes import WHEEL_EXTENSION from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import build_netloc from pip._internal.utils.packaging import check_requires_python from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS from pip._internal.utils.urls import url_to_path def _find_name_version_sep(fragment, canonical_name): # type: (str, str) -> int """Find the separator's index based on the package's canonical name. :param fragment: A <package>+<version> filename "fragment" (stem) or egg fragment. :param canonical_name: The package's canonical name. This function is needed since the canonicalized name does not necessarily have the same length as the egg info's name part. An example:: >>> fragment = 'foo__bar-1.0' >>> canonical_name = 'foo-bar' >>> _find_name_version_sep(fragment, canonical_name) 8 """ # Project name and version must be separated by one single dash. Find all # occurrences of dashes; if the string in front of it matches the canonical # name, this is the one separating the name and version parts. for i, c in enumerate(fragment): if c != "-": continue if canonicalize_name(fragment[:i]) == canonical_name: return i raise ValueError("{} does not match {}".format(fragment, canonical_name)) The provided code snippet includes necessary dependencies for implementing the `_extract_version_from_fragment` function. Write a Python function `def _extract_version_from_fragment(fragment, canonical_name)` to solve the following problem: Parse the version string from a <package>+<version> filename "fragment" (stem) or egg fragment. :param fragment: The string to parse. E.g. foo-2.1 :param canonical_name: The canonicalized name of the package this belongs to. Here is the function: def _extract_version_from_fragment(fragment, canonical_name): # type: (str, str) -> Optional[str] """Parse the version string from a <package>+<version> filename "fragment" (stem) or egg fragment. :param fragment: The string to parse. E.g. foo-2.1 :param canonical_name: The canonicalized name of the package this belongs to. """ try: version_start = _find_name_version_sep(fragment, canonical_name) + 1 except ValueError: return None version = fragment[version_start:] if not version: return None return version
Parse the version string from a <package>+<version> filename "fragment" (stem) or egg fragment. :param fragment: The string to parse. E.g. foo-2.1 :param canonical_name: The canonicalized name of the package this belongs to.
175,588
import logging import os.path import re import shutil from pip._internal.models.link import Link from pip._internal.operations.build.wheel import build_wheel_pep517 from pip._internal.operations.build.wheel_legacy import build_wheel_legacy from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ensure_dir, hash_file, is_wheel_installed from pip._internal.utils.setuptools_build import make_setuptools_clean_args from pip._internal.utils.subprocess import call_subprocess from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url from pip._internal.vcs import vcs def _should_build( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate ): # type: (...) -> bool """Return whether an InstallRequirement should be built into a wheel.""" if req.constraint: # never build requirements that are merely constraints return False if req.is_wheel: if need_wheel: logger.info( 'Skipping %s, due to already being wheel.', req.name, ) return False if need_wheel: # i.e. pip wheel, not pip install return True # From this point, this concerns the pip install command only # (need_wheel=False). if req.editable or not req.source_dir: return False if not check_binary_allowed(req): logger.info( "Skipping wheel build for %s, due to binaries " "being disabled for it.", req.name, ) return False if not req.use_pep517 and not is_wheel_installed(): # we don't build legacy requirements if wheel is not installed logger.info( "Using legacy 'setup.py install' for %s, " "since package 'wheel' is not installed.", req.name, ) return False return True def _always_true(_): # type: (Any) -> bool return True def should_build_for_wheel_command( req, # type: InstallRequirement ): # type: (...) -> bool return _should_build( req, need_wheel=True, check_binary_allowed=_always_true )
null
175,589
import logging import os.path import re import shutil from pip._internal.models.link import Link from pip._internal.operations.build.wheel import build_wheel_pep517 from pip._internal.operations.build.wheel_legacy import build_wheel_legacy from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ensure_dir, hash_file, is_wheel_installed from pip._internal.utils.setuptools_build import make_setuptools_clean_args from pip._internal.utils.subprocess import call_subprocess from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url from pip._internal.vcs import vcs def _should_build( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate ): # type: (...) -> bool """Return whether an InstallRequirement should be built into a wheel.""" if req.constraint: # never build requirements that are merely constraints return False if req.is_wheel: if need_wheel: logger.info( 'Skipping %s, due to already being wheel.', req.name, ) return False if need_wheel: # i.e. pip wheel, not pip install return True # From this point, this concerns the pip install command only # (need_wheel=False). if req.editable or not req.source_dir: return False if not check_binary_allowed(req): logger.info( "Skipping wheel build for %s, due to binaries " "being disabled for it.", req.name, ) return False if not req.use_pep517 and not is_wheel_installed(): # we don't build legacy requirements if wheel is not installed logger.info( "Using legacy 'setup.py install' for %s, " "since package 'wheel' is not installed.", req.name, ) return False return True def should_build_for_install_command( req, # type: InstallRequirement check_binary_allowed, # type: BinaryAllowedPredicate ): # type: (...) -> bool return _should_build( req, need_wheel=False, check_binary_allowed=check_binary_allowed )
null
175,590
import logging import os.path import re import shutil from pip._internal.models.link import Link from pip._internal.operations.build.wheel import build_wheel_pep517 from pip._internal.operations.build.wheel_legacy import build_wheel_legacy from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ensure_dir, hash_file, is_wheel_installed from pip._internal.utils.setuptools_build import make_setuptools_clean_args from pip._internal.utils.subprocess import call_subprocess from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url from pip._internal.vcs import vcs logger = logging.getLogger(__name__) def _get_cache_dir( req, # type: InstallRequirement wheel_cache, # type: WheelCache ): # type: (...) -> str """Return the persistent or temporary cache directory where the built wheel need to be stored. """ cache_available = bool(wheel_cache.cache_dir) assert req.link if cache_available and _should_cache(req): cache_dir = wheel_cache.get_path_for_link(req.link) else: cache_dir = wheel_cache.get_ephem_path_for_link(req.link) return cache_dir def _build_one( req, # type: InstallRequirement output_dir, # type: str build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> Optional[str] """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ try: ensure_dir(output_dir) except OSError as e: logger.warning( "Building wheel for %s failed: %s", req.name, e, ) return None # Install build deps into temporary directory (PEP 518) with req.build_env: return _build_one_inside_env( req, output_dir, build_options, global_options ) class Link(KeyBasedCompareMixin): """Represents a parsed link from a Package Index's simple URL """ __slots__ = [ "_parsed_url", "_url", "comes_from", "requires_python", "yanked_reason", "cache_link_parsing", ] def __init__( self, url, # type: str comes_from=None, # type: Optional[Union[str, HTMLPage]] requires_python=None, # type: Optional[str] yanked_reason=None, # type: Optional[Text] cache_link_parsing=True, # type: bool ): # type: (...) -> None """ :param url: url of the resource pointed to (href of the link) :param comes_from: instance of HTMLPage where the link was found, or string. :param requires_python: String containing the `Requires-Python` metadata field, specified in PEP 345. This may be specified by a data-requires-python attribute in the HTML link tag, as described in PEP 503. :param yanked_reason: the reason the file has been yanked, if the file has been yanked, or None if the file hasn't been yanked. This is the value of the "data-yanked" attribute, if present, in a simple repository HTML link. If the file has been yanked but no reason was provided, this should be the empty string. See PEP 592 for more information and the specification. :param cache_link_parsing: A flag that is used elsewhere to determine whether resources retrieved from this link should be cached. PyPI index urls should generally have this set to False, for example. """ # url can be a UNC windows share if url.startswith('\\\\'): url = path_to_url(url) self._parsed_url = urllib_parse.urlsplit(url) # Store the url as a private attribute to prevent accidentally # trying to set a new value. self._url = url self.comes_from = comes_from self.requires_python = requires_python if requires_python else None self.yanked_reason = yanked_reason super(Link, self).__init__(key=url, defining_class=Link) self.cache_link_parsing = cache_link_parsing def __str__(self): # type: () -> str if self.requires_python: rp = ' (requires-python:{})'.format(self.requires_python) else: rp = '' if self.comes_from: return '{} (from {}){}'.format( redact_auth_from_url(self._url), self.comes_from, rp) else: return redact_auth_from_url(str(self._url)) def __repr__(self): # type: () -> str return '<Link {}>'.format(self) def url(self): # type: () -> str return self._url def filename(self): # type: () -> str path = self.path.rstrip('/') name = posixpath.basename(path) if not name: # Make sure we don't leak auth information if the netloc # includes a username and password. netloc, user_pass = split_auth_from_netloc(self.netloc) return netloc name = urllib_parse.unquote(name) assert name, ( 'URL {self._url!r} produced no filename'.format(**locals())) return name def file_path(self): # type: () -> str return url_to_path(self.url) def scheme(self): # type: () -> str return self._parsed_url.scheme def netloc(self): # type: () -> str """ This can contain auth information. """ return self._parsed_url.netloc def path(self): # type: () -> str return urllib_parse.unquote(self._parsed_url.path) def splitext(self): # type: () -> Tuple[str, str] return splitext(posixpath.basename(self.path.rstrip('/'))) def ext(self): # type: () -> str return self.splitext()[1] def url_without_fragment(self): # type: () -> str scheme, netloc, path, query, fragment = self._parsed_url return urllib_parse.urlunsplit((scheme, netloc, path, query, None)) _egg_fragment_re = re.compile(r'[#&]egg=([^&]*)') def egg_fragment(self): # type: () -> Optional[str] match = self._egg_fragment_re.search(self._url) if not match: return None return match.group(1) _subdirectory_fragment_re = re.compile(r'[#&]subdirectory=([^&]*)') def subdirectory_fragment(self): # type: () -> Optional[str] match = self._subdirectory_fragment_re.search(self._url) if not match: return None return match.group(1) _hash_re = re.compile( r'(sha1|sha224|sha384|sha256|sha512|md5)=([a-f0-9]+)' ) def hash(self): # type: () -> Optional[str] match = self._hash_re.search(self._url) if match: return match.group(2) return None def hash_name(self): # type: () -> Optional[str] match = self._hash_re.search(self._url) if match: return match.group(1) return None def show_url(self): # type: () -> str return posixpath.basename(self._url.split('#', 1)[0].split('?', 1)[0]) def is_file(self): # type: () -> bool return self.scheme == 'file' def is_existing_dir(self): # type: () -> bool return self.is_file and os.path.isdir(self.file_path) def is_wheel(self): # type: () -> bool return self.ext == WHEEL_EXTENSION def is_vcs(self): # type: () -> bool from pip._internal.vcs import vcs return self.scheme in vcs.all_schemes def is_yanked(self): # type: () -> bool return self.yanked_reason is not None def has_hash(self): # type: () -> bool return self.hash_name is not None def is_hash_allowed(self, hashes): # type: (Optional[Hashes]) -> bool """ Return True if the link has a hash and it is allowed. """ if hashes is None or not self.has_hash: return False # Assert non-None so mypy knows self.hash_name and self.hash are str. assert self.hash_name is not None assert self.hash is not None return hashes.is_hash_allowed(self.hash_name, hex_digest=self.hash) def indent_log(num=2): """ A context manager which will cause the log output to be indented for any log messages emitted inside it. """ # For thread-safety _log_state.indentation = get_indentation() _log_state.indentation += num try: yield finally: _log_state.indentation -= num def path_to_url(path): # type: (Union[str, Text]) -> str """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) url = urllib_parse.urljoin('file:', urllib_request.pathname2url(path)) return url The provided code snippet includes necessary dependencies for implementing the `build` function. Write a Python function `def build( requirements, # type: Iterable[InstallRequirement] wheel_cache, # type: WheelCache build_options, # type: List[str] global_options, # type: List[str] )` to solve the following problem: Build wheels. :return: The list of InstallRequirement that succeeded to build and the list of InstallRequirement that failed to build. Here is the function: def build( requirements, # type: Iterable[InstallRequirement] wheel_cache, # type: WheelCache build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> BuildResult """Build wheels. :return: The list of InstallRequirement that succeeded to build and the list of InstallRequirement that failed to build. """ if not requirements: return [], [] # Build the wheels. logger.info( 'Building wheels for collected packages: %s', ', '.join(req.name for req in requirements), # type: ignore ) with indent_log(): build_successes, build_failures = [], [] for req in requirements: cache_dir = _get_cache_dir(req, wheel_cache) wheel_file = _build_one( req, cache_dir, build_options, global_options ) if wheel_file: # Update the link for this. req.link = Link(path_to_url(wheel_file)) req.local_file_path = req.link.file_path assert req.link.is_wheel build_successes.append(req) else: build_failures.append(req) # notify success/failure if build_successes: logger.info( 'Successfully built %s', ' '.join([req.name for req in build_successes]), # type: ignore ) if build_failures: logger.info( 'Failed to build %s', ' '.join([req.name for req in build_failures]), # type: ignore ) # Return a list of requirements that failed to build return build_successes, build_failures
Build wheels. :return: The list of InstallRequirement that succeeded to build and the list of InstallRequirement that failed to build.
175,591
from pip._vendor.packaging.utils import canonicalize_name from pip._internal.utils.typing import MYPY_CHECK_RUNNING def canonicalize_name(name): # type: (str) -> NormalizedName # This is taken from PEP 503. value = _canonicalize_regex.sub("-", name).lower() return cast("NormalizedName", value) def format_name(project, extras): # type: (str, FrozenSet[str]) -> str if not extras: return project canonical_extras = sorted(canonicalize_name(e) for e in extras) return "{}[{}]".format(project, ",".join(canonical_extras))
null
175,592
import functools import logging from pip._vendor import six from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.resolvelib import BaseReporter, ResolutionImpossible from pip._vendor.resolvelib import Resolver as RLResolver from pip._internal.exceptions import InstallationError from pip._internal.req.req_install import check_invalid_constraint_type from pip._internal.req.req_set import RequirementSet from pip._internal.resolution.base import BaseResolver from pip._internal.resolution.resolvelib.provider import PipProvider from pip._internal.utils.misc import dist_is_editable from pip._internal.utils.typing import MYPY_CHECK_RUNNING from .factory import Factory The provided code snippet includes necessary dependencies for implementing the `get_topological_weights` function. Write a Python function `def get_topological_weights(graph)` to solve the following problem: Assign weights to each node based on how "deep" they are. This implementation may change at any point in the future without prior notice. We take the length for the longest path to any node from root, ignoring any paths that contain a single node twice (i.e. cycles). This is done through a depth-first search through the graph, while keeping track of the path to the node. Cycles in the graph result would result in node being revisited while also being it's own path. In this case, take no action. This helps ensure we don't get stuck in a cycle. When assigning weight, the longer path (i.e. larger length) is preferred. Here is the function: def get_topological_weights(graph): # type: (Graph) -> Dict[Optional[str], int] """Assign weights to each node based on how "deep" they are. This implementation may change at any point in the future without prior notice. We take the length for the longest path to any node from root, ignoring any paths that contain a single node twice (i.e. cycles). This is done through a depth-first search through the graph, while keeping track of the path to the node. Cycles in the graph result would result in node being revisited while also being it's own path. In this case, take no action. This helps ensure we don't get stuck in a cycle. When assigning weight, the longer path (i.e. larger length) is preferred. """ path = set() # type: Set[Optional[str]] weights = {} # type: Dict[Optional[str], int] def visit(node): # type: (Optional[str]) -> None if node in path: # We hit a cycle, so we'll break it here. return # Time to visit the children! path.add(node) for child in graph.iter_children(node): visit(child) path.remove(node) last_known_parent_count = weights.get(node, 0) weights[node] = max(last_known_parent_count, len(path)) # `None` is guaranteed to be the root node by resolvelib. visit(None) # Sanity checks assert weights[None] == 0 assert len(weights) == len(graph) return weights
Assign weights to each node based on how "deep" they are. This implementation may change at any point in the future without prior notice. We take the length for the longest path to any node from root, ignoring any paths that contain a single node twice (i.e. cycles). This is done through a depth-first search through the graph, while keeping track of the path to the node. Cycles in the graph result would result in node being revisited while also being it's own path. In this case, take no action. This helps ensure we don't get stuck in a cycle. When assigning weight, the longer path (i.e. larger length) is preferred.
175,593
import functools import logging from pip._vendor import six from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.resolvelib import BaseReporter, ResolutionImpossible from pip._vendor.resolvelib import Resolver as RLResolver from pip._internal.exceptions import InstallationError from pip._internal.req.req_install import check_invalid_constraint_type from pip._internal.req.req_set import RequirementSet from pip._internal.resolution.base import BaseResolver from pip._internal.resolution.resolvelib.provider import PipProvider from pip._internal.utils.misc import dist_is_editable from pip._internal.utils.typing import MYPY_CHECK_RUNNING from .factory import Factory def canonicalize_name(name): # type: (str) -> NormalizedName # This is taken from PEP 503. value = _canonicalize_regex.sub("-", name).lower() return cast("NormalizedName", value) The provided code snippet includes necessary dependencies for implementing the `_req_set_item_sorter` function. Write a Python function `def _req_set_item_sorter( item, # type: Tuple[str, InstallRequirement] weights, # type: Dict[Optional[str], int] )` to solve the following problem: Key function used to sort install requirements for installation. Based on the "weight" mapping calculated in ``get_installation_order()``. The canonical package name is returned as the second member as a tie- breaker to ensure the result is predictable, which is useful in tests. Here is the function: def _req_set_item_sorter( item, # type: Tuple[str, InstallRequirement] weights, # type: Dict[Optional[str], int] ): # type: (...) -> Tuple[int, str] """Key function used to sort install requirements for installation. Based on the "weight" mapping calculated in ``get_installation_order()``. The canonical package name is returned as the second member as a tie- breaker to ensure the result is predictable, which is useful in tests. """ name = canonicalize_name(item[0]) return weights[name], name
Key function used to sort install requirements for installation. Based on the "weight" mapping calculated in ``get_installation_order()``. The canonical package name is returned as the second member as a tie- breaker to ensure the result is predictable, which is useful in tests.
175,594
import logging import sys from pip._vendor.contextlib2 import suppress from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import Version from pip._internal.exceptions import HashError, MetadataInconsistent from pip._internal.network.lazy_wheel import ( HTTPRangeRequestUnsupported, dist_from_wheel_url, ) from pip._internal.req.constructors import ( install_req_from_editable, install_req_from_line, ) from pip._internal.req.req_install import InstallRequirement from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import dist_is_editable, normalize_version_info from pip._internal.utils.packaging import get_requires_python from pip._internal.utils.typing import MYPY_CHECK_RUNNING from .base import Candidate, format_name def install_req_from_line( name, # type: str comes_from=None, # type: Optional[Union[str, InstallRequirement]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool line_source=None, # type: Optional[str] user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. :param line_source: An optional string describing where the line is from, for logging purposes in case of an error. """ parts = parse_req_from_line(name, line_source) return InstallRequirement( parts.requirement, comes_from, link=parts.link, markers=parts.markers, use_pep517=use_pep517, isolated=isolated, install_options=options.get("install_options", []) if options else [], global_options=options.get("global_options", []) if options else [], hash_options=options.get("hashes", {}) if options else {}, constraint=constraint, extras=parts.extras, user_supplied=user_supplied, ) def make_install_req_from_link(link, template): # type: (Link, InstallRequirement) -> InstallRequirement assert not template.editable, "template is editable" if template.req: line = str(template.req) else: line = link.url ireq = install_req_from_line( line, user_supplied=template.user_supplied, comes_from=template.comes_from, use_pep517=template.use_pep517, isolated=template.isolated, constraint=template.constraint, options=dict( install_options=template.install_options, global_options=template.global_options, hashes=template.hash_options ), ) ireq.original_link = template.original_link ireq.link = link return ireq
null
175,595
import logging import sys from pip._vendor.contextlib2 import suppress from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import Version from pip._internal.exceptions import HashError, MetadataInconsistent from pip._internal.network.lazy_wheel import ( HTTPRangeRequestUnsupported, dist_from_wheel_url, ) from pip._internal.req.constructors import ( install_req_from_editable, install_req_from_line, ) from pip._internal.req.req_install import InstallRequirement from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import dist_is_editable, normalize_version_info from pip._internal.utils.packaging import get_requires_python from pip._internal.utils.typing import MYPY_CHECK_RUNNING from .base import Candidate, format_name def install_req_from_editable( editable_req, # type: str comes_from=None, # type: Optional[Union[InstallRequirement, str]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement parts = parse_req_from_editable(editable_req) return InstallRequirement( parts.requirement, comes_from=comes_from, user_supplied=user_supplied, editable=True, link=parts.link, constraint=constraint, use_pep517=use_pep517, isolated=isolated, install_options=options.get("install_options", []) if options else [], global_options=options.get("global_options", []) if options else [], hash_options=options.get("hashes", {}) if options else {}, extras=parts.extras, ) def make_install_req_from_editable(link, template): # type: (Link, InstallRequirement) -> InstallRequirement assert template.editable, "template not editable" return install_req_from_editable( link.url, user_supplied=template.user_supplied, comes_from=template.comes_from, use_pep517=template.use_pep517, isolated=template.isolated, constraint=template.constraint, options=dict( install_options=template.install_options, global_options=template.global_options, hashes=template.hash_options ), )
null
175,596
import logging import sys from pip._vendor.contextlib2 import suppress from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import Version from pip._internal.exceptions import HashError, MetadataInconsistent from pip._internal.network.lazy_wheel import ( HTTPRangeRequestUnsupported, dist_from_wheel_url, ) from pip._internal.req.constructors import ( install_req_from_editable, install_req_from_line, ) from pip._internal.req.req_install import InstallRequirement from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import dist_is_editable, normalize_version_info from pip._internal.utils.packaging import get_requires_python from pip._internal.utils.typing import MYPY_CHECK_RUNNING from .base import Candidate, format_name def canonicalize_name(name): # type: (str) -> NormalizedName # This is taken from PEP 503. value = _canonicalize_regex.sub("-", name).lower() return cast("NormalizedName", value) def install_req_from_line( name, # type: str comes_from=None, # type: Optional[Union[str, InstallRequirement]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool line_source=None, # type: Optional[str] user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. :param line_source: An optional string describing where the line is from, for logging purposes in case of an error. """ parts = parse_req_from_line(name, line_source) return InstallRequirement( parts.requirement, comes_from, link=parts.link, markers=parts.markers, use_pep517=use_pep517, isolated=isolated, install_options=options.get("install_options", []) if options else [], global_options=options.get("global_options", []) if options else [], hash_options=options.get("hashes", {}) if options else {}, constraint=constraint, extras=parts.extras, user_supplied=user_supplied, ) def make_install_req_from_dist(dist, template): # type: (Distribution, InstallRequirement) -> InstallRequirement project_name = canonicalize_name(dist.project_name) if template.req: line = str(template.req) elif template.link: line = "{} @ {}".format(project_name, template.link.url) else: line = "{}=={}".format(project_name, dist.parsed_version) ireq = install_req_from_line( line, user_supplied=template.user_supplied, comes_from=template.comes_from, use_pep517=template.use_pep517, isolated=template.isolated, constraint=template.constraint, options=dict( install_options=template.install_options, global_options=template.global_options, hashes=template.hash_options ), ) ireq.satisfied_by = dist return ireq
null
175,597
import logging import sys from collections import defaultdict from itertools import chain from pip._vendor.packaging import specifiers from pip._internal.exceptions import ( BestVersionAlreadyInstalled, DistributionNotFound, HashError, HashErrors, UnsupportedPythonVersion, ) from pip._internal.req.req_install import check_invalid_constraint_type from pip._internal.req.req_set import RequirementSet from pip._internal.resolution.base import BaseResolver from pip._internal.utils.compatibility_tags import get_supported from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import dist_in_usersite, normalize_version_info from pip._internal.utils.packaging import ( check_requires_python, get_requires_python, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) class UnsupportedPythonVersion(InstallationError): """Unsupported python version according to Requires-Python package metadata.""" def check_requires_python(requires_python, version_info): # type: (Optional[str], Tuple[int, ...]) -> bool """ Check if the given Python version matches a "Requires-Python" specifier. :param version_info: A 3-tuple of ints representing a Python major-minor-micro version to check (e.g. `sys.version_info[:3]`). :return: `True` if the given Python version satisfies the requirement. Otherwise, return `False`. :raises InvalidSpecifier: If `requires_python` has an invalid format. """ if requires_python is None: # The package provides no information return True requires_python_specifier = specifiers.SpecifierSet(requires_python) python_version = version.parse('.'.join(map(str, version_info))) return python_version in requires_python_specifier def get_requires_python(dist): # type: (pkg_resources.Distribution) -> Optional[str] """ Return the "Requires-Python" metadata for a distribution, or None if not present. """ pkg_info_dict = get_metadata(dist) requires_python = pkg_info_dict.get('Requires-Python') if requires_python is not None: # Convert to a str to satisfy the type checker, since requires_python # can be a Header object. requires_python = str(requires_python) return requires_python The provided code snippet includes necessary dependencies for implementing the `_check_dist_requires_python` function. Write a Python function `def _check_dist_requires_python( dist, # type: pkg_resources.Distribution version_info, # type: Tuple[int, int, int] ignore_requires_python=False, # type: bool )` to solve the following problem: Check whether the given Python version is compatible with a distribution's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. :raises UnsupportedPythonVersion: When the given Python version isn't compatible. Here is the function: def _check_dist_requires_python( dist, # type: pkg_resources.Distribution version_info, # type: Tuple[int, int, int] ignore_requires_python=False, # type: bool ): # type: (...) -> None """ Check whether the given Python version is compatible with a distribution's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. :raises UnsupportedPythonVersion: When the given Python version isn't compatible. """ requires_python = get_requires_python(dist) try: is_compatible = check_requires_python( requires_python, version_info=version_info, ) except specifiers.InvalidSpecifier as exc: logger.warning( "Package %r has an invalid Requires-Python: %s", dist.project_name, exc, ) return if is_compatible: return version = '.'.join(map(str, version_info)) if ignore_requires_python: logger.debug( 'Ignoring failed Requires-Python check for package %r: ' '%s not in %r', dist.project_name, version, requires_python, ) return raise UnsupportedPythonVersion( 'Package {!r} requires a different Python: {} not in {!r}'.format( dist.project_name, version, requires_python, ))
Check whether the given Python version is compatible with a distribution's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. :raises UnsupportedPythonVersion: When the given Python version isn't compatible.
175,598
import logging from collections import namedtuple from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.pkg_resources import RequirementParseError from pip._internal.distributions import ( make_distribution_for_install_requirement, ) from pip._internal.utils.misc import get_installed_distributions from pip._internal.utils.typing import MYPY_CHECK_RUNNING def create_package_set_from_installed(**kwargs): # type: (**Any) -> Tuple[PackageSet, bool] """Converts a list of distributions into a PackageSet. """ # Default to using all packages installed on the system if kwargs == {}: kwargs = {"local_only": False, "skip": ()} package_set = {} problems = False for dist in get_installed_distributions(**kwargs): name = canonicalize_name(dist.project_name) try: package_set[name] = PackageDetails(dist.version, dist.requires()) except RequirementParseError as e: # Don't crash on broken metadata logger.warning("Error parsing requirements for %s: %s", name, e) problems = True return package_set, problems def check_package_set(package_set, should_ignore=None): # type: (PackageSet, Optional[Callable[[str], bool]]) -> CheckResult """Check if a package set is consistent If should_ignore is passed, it should be a callable that takes a package name and returns a boolean. """ missing = {} conflicting = {} for package_name in package_set: # Info about dependencies of package_name missing_deps = set() # type: Set[Missing] conflicting_deps = set() # type: Set[Conflicting] if should_ignore and should_ignore(package_name): continue for req in package_set[package_name].requires: name = canonicalize_name(req.project_name) # type: str # Check if it's missing if name not in package_set: missed = True if req.marker is not None: missed = req.marker.evaluate() if missed: missing_deps.add((name, req)) continue # Check if there's a conflict version = package_set[name].version # type: str if not req.specifier.contains(version, prereleases=True): conflicting_deps.add((name, version, req)) if missing_deps: missing[package_name] = sorted(missing_deps, key=str) if conflicting_deps: conflicting[package_name] = sorted(conflicting_deps, key=str) return missing, conflicting def _simulate_installation_of(to_install, package_set): # type: (List[InstallRequirement], PackageSet) -> Set[str] """Computes the version of packages after installing to_install. """ # Keep track of packages that were installed installed = set() # Modify it as installing requirement_set would (assuming no errors) for inst_req in to_install: abstract_dist = make_distribution_for_install_requirement(inst_req) dist = abstract_dist.get_pkg_resources_distribution() assert dist is not None name = canonicalize_name(dist.key) package_set[name] = PackageDetails(dist.version, dist.requires()) installed.add(name) return installed def _create_whitelist(would_be_installed, package_set): # type: (Set[str], PackageSet) -> Set[str] packages_affected = set(would_be_installed) for package_name in package_set: if package_name in packages_affected: continue for req in package_set[package_name].requires: if canonicalize_name(req.name) in packages_affected: packages_affected.add(package_name) break return packages_affected The provided code snippet includes necessary dependencies for implementing the `check_install_conflicts` function. Write a Python function `def check_install_conflicts(to_install)` to solve the following problem: For checking if the dependency graph would be consistent after \ installing given requirements Here is the function: def check_install_conflicts(to_install): # type: (List[InstallRequirement]) -> ConflictDetails """For checking if the dependency graph would be consistent after \ installing given requirements """ # Start from the current state package_set, _ = create_package_set_from_installed() # Install packages would_be_installed = _simulate_installation_of(to_install, package_set) # Only warn about directly-dependent packages; create a whitelist of them whitelist = _create_whitelist(would_be_installed, package_set) return ( package_set, check_package_set( package_set, should_ignore=lambda name: name not in whitelist ) )
For checking if the dependency graph would be consistent after \ installing given requirements
175,599
import logging import os import sys from distutils.util import change_root from pip._internal.exceptions import InstallationError from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ensure_dir from pip._internal.utils.setuptools_build import make_setuptools_install_args from pip._internal.utils.subprocess import runner_with_spinner_message from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) class LegacyInstallFailure(Exception): def __init__(self): class InstallationError(PipError): def indent_log(num=2): def ensure_dir(path): def make_setuptools_install_args( setup_py_path, # type: str global_options, # type: Sequence[str] install_options, # type: Sequence[str] record_filename, # type: str root, # type: Optional[str] prefix, # type: Optional[str] header_dir, # type: Optional[str] home, # type: Optional[str] use_user_site, # type: bool no_user_config, # type: bool pycompile # type: bool ): def runner_with_spinner_message(message): class TempDirectory(object): def __init__( self, path=None, # type: Optional[str] delete=_default, # type: Union[bool, None, _Default] kind="temp", # type: str globally_managed=False, # type: bool ): def path(self): def __repr__(self): def __enter__(self): def __exit__(self, exc, value, tb): def _create(self, kind): def cleanup(self): 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: message = ( "{} did not indicate that it installed an " ".egg-info directory. Only setup.py projects " "generating .egg-info directories are supported." ).format(req_description) raise InstallationError(message) 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
null
175,600
import logging from pip._internal.utils.logging import indent_log from pip._internal.utils.setuptools_build import make_setuptools_develop_args from pip._internal.utils.subprocess import call_subprocess from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) def indent_log(num=2): """ A context manager which will cause the log output to be indented for any log messages emitted inside it. """ # For thread-safety _log_state.indentation = get_indentation() _log_state.indentation += num try: yield finally: _log_state.indentation -= num def make_setuptools_develop_args( setup_py_path, # type: str global_options, # type: Sequence[str] install_options, # type: Sequence[str] no_user_config, # type: bool prefix, # type: Optional[str] home, # type: Optional[str] use_user_site, # type: bool ): # type: (...) -> List[str] assert not (use_user_site and prefix) args = make_setuptools_shim_args( setup_py_path, global_options=global_options, no_user_config=no_user_config, ) args += ["develop", "--no-deps"] args += install_options if prefix: args += ["--prefix", prefix] if home is not None: args += ["--home", home] if use_user_site: args += ["--user", "--prefix="] return args def call_subprocess( cmd, # type: Union[List[str], CommandArgs] show_stdout=False, # type: bool cwd=None, # type: Optional[str] on_returncode='raise', # type: str extra_ok_returncodes=None, # type: Optional[Iterable[int]] command_desc=None, # type: Optional[str] extra_environ=None, # type: Optional[Mapping[str, Any]] unset_environ=None, # type: Optional[Iterable[str]] spinner=None, # type: Optional[SpinnerInterface] log_failed_cmd=True # type: Optional[bool] ): # type: (...) -> Text """ Args: show_stdout: if true, use INFO to log the subprocess's stderr and stdout streams. Otherwise, use DEBUG. Defaults to False. extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. unset_environ: an iterable of environment variable names to unset prior to calling subprocess.Popen(). log_failed_cmd: if false, failed commands are not logged, only raised. """ if extra_ok_returncodes is None: extra_ok_returncodes = [] if unset_environ is None: unset_environ = [] # Most places in pip use show_stdout=False. What this means is-- # # - We connect the child's output (combined stderr and stdout) to a # single pipe, which we read. # - We log this output to stderr at DEBUG level as it is received. # - If DEBUG logging isn't enabled (e.g. if --verbose logging wasn't # requested), then we show a spinner so the user can still see the # subprocess is in progress. # - If the subprocess exits with an error, we log the output to stderr # at ERROR level if it hasn't already been displayed to the console # (e.g. if --verbose logging wasn't enabled). This way we don't log # the output to the console twice. # # If show_stdout=True, then the above is still done, but with DEBUG # replaced by INFO. if show_stdout: # Then log the subprocess output at INFO level. log_subprocess = subprocess_logger.info used_level = logging.INFO else: # Then log the subprocess output using DEBUG. This also ensures # it will be logged to the log file (aka user_log), if enabled. log_subprocess = subprocess_logger.debug used_level = logging.DEBUG # Whether the subprocess will be visible in the console. showing_subprocess = subprocess_logger.getEffectiveLevel() <= used_level # Only use the spinner if we're not showing the subprocess output # and we have a spinner. use_spinner = not showing_subprocess and spinner is not None if command_desc is None: command_desc = format_command_args(cmd) log_subprocess("Running command %s", command_desc) env = os.environ.copy() if extra_environ: env.update(extra_environ) for name in unset_environ: env.pop(name, None) try: proc = subprocess.Popen( # Convert HiddenText objects to the underlying str. reveal_command_args(cmd), stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=cwd, env=env, ) assert proc.stdin assert proc.stdout proc.stdin.close() except Exception as exc: if log_failed_cmd: subprocess_logger.critical( "Error %s while executing command %s", exc, command_desc, ) raise all_output = [] while True: # The "line" value is a unicode string in Python 2. line = console_to_str(proc.stdout.readline()) if not line: break line = line.rstrip() all_output.append(line + '\n') # Show the line immediately. log_subprocess(line) # Update the spinner. if use_spinner: assert spinner spinner.spin() try: proc.wait() finally: if proc.stdout: proc.stdout.close() proc_had_error = ( proc.returncode and proc.returncode not in extra_ok_returncodes ) if use_spinner: assert spinner if proc_had_error: spinner.finish("error") else: spinner.finish("done") if proc_had_error: if on_returncode == 'raise': if not showing_subprocess and log_failed_cmd: # Then the subprocess streams haven't been logged to the # console yet. msg = make_subprocess_output_error( cmd_args=cmd, cwd=cwd, lines=all_output, exit_status=proc.returncode, ) subprocess_logger.error(msg) exc_msg = ( 'Command errored out with exit status {}: {} ' 'Check the logs for full command output.' ).format(proc.returncode, command_desc) raise InstallationError(exc_msg) elif on_returncode == 'warn': subprocess_logger.warning( 'Command "%s" had error code %s in %s', command_desc, proc.returncode, cwd, ) elif on_returncode == 'ignore': pass else: raise ValueError('Invalid value: on_returncode={!r}'.format( on_returncode)) return ''.join(all_output) The provided code snippet includes necessary dependencies for implementing the `install_editable` function. Write a Python function `def install_editable( install_options, # type: List[str] global_options, # type: Sequence[str] prefix, # type: Optional[str] home, # type: Optional[str] use_user_site, # type: bool name, # type: str setup_py_path, # type: str isolated, # type: bool build_env, # type: BuildEnvironment unpacked_source_directory, # type: str )` to solve the following problem: Install a package in editable mode. Most arguments are pass-through to setuptools. Here is the function: def install_editable( install_options, # type: List[str] global_options, # type: Sequence[str] prefix, # type: Optional[str] home, # type: Optional[str] use_user_site, # type: bool name, # type: str setup_py_path, # type: str isolated, # type: bool build_env, # type: BuildEnvironment unpacked_source_directory, # type: str ): # type: (...) -> None """Install a package in editable mode. Most arguments are pass-through to setuptools. """ logger.info('Running setup.py develop for %s', name) args = make_setuptools_develop_args( setup_py_path, global_options=global_options, install_options=install_options, no_user_config=isolated, prefix=prefix, home=home, use_user_site=use_user_site, ) with indent_log(): with build_env: call_subprocess( args, cwd=unpacked_source_directory, )
Install a package in editable mode. Most arguments are pass-through to setuptools.
175,601
from __future__ import absolute_import import collections import compileall import contextlib import csv import importlib import logging import os.path import re import shutil import sys import warnings from base64 import urlsafe_b64encode from itertools import chain, starmap from zipfile import ZipFile from pip._vendor import pkg_resources from pip._vendor.distlib.scripts import ScriptMaker from pip._vendor.distlib.util import get_export_entry from pip._vendor.six import ( PY2, ensure_str, ensure_text, itervalues, reraise, text_type, ) from pip._vendor.six.moves import filterfalse, map from pip._internal.exceptions import InstallationError from pip._internal.locations import get_major_minor_version from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl from pip._internal.models.scheme import SCHEME_KEYS from pip._internal.utils.filesystem import adjacent_tmp_file, replace from pip._internal.utils.misc import ( captured_stdout, ensure_dir, hash_file, partition, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import ( current_umask, is_within_directory, set_extracted_file_to_default_mode_plus_executable, zip_item_is_executable, ) from pip._internal.utils.wheel import ( parse_wheel, pkg_resources_distribution_for_wheel, ) import sys if 'setuptools' in sys.modules: import setuptools.command.install as old_install_mod have_setuptools = True else: import distutils.command.install as old_install_mod have_setuptools = False The provided code snippet includes necessary dependencies for implementing the `fix_script` function. Write a Python function `def fix_script(path)` to solve the following problem: Replace #!python with #!/path/to/python Return True if file was changed. Here is the function: def fix_script(path): # type: (text_type) -> bool """Replace #!python with #!/path/to/python Return True if file was changed. """ # XXX RECORD hashes will need to be updated assert os.path.isfile(path) with open(path, 'rb') as script: firstline = script.readline() if not firstline.startswith(b'#!python'): return False exename = sys.executable.encode(sys.getfilesystemencoding()) firstline = b'#!' + exename + os.linesep.encode("ascii") rest = script.read() with open(path, 'wb') as script: script.write(firstline) script.write(rest) return True
Replace #!python with #!/path/to/python Return True if file was changed.
175,602
from __future__ import absolute_import import collections import compileall import contextlib import csv import importlib import logging import os.path import re import shutil import sys import warnings from base64 import urlsafe_b64encode from itertools import chain, starmap from zipfile import ZipFile from pip._vendor import pkg_resources from pip._vendor.distlib.scripts import ScriptMaker from pip._vendor.distlib.util import get_export_entry from pip._vendor.six import ( PY2, ensure_str, ensure_text, itervalues, reraise, text_type, ) from pip._vendor.six.moves import filterfalse, map from pip._internal.exceptions import InstallationError from pip._internal.locations import get_major_minor_version from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl from pip._internal.models.scheme import SCHEME_KEYS from pip._internal.utils.filesystem import adjacent_tmp_file, replace from pip._internal.utils.misc import ( captured_stdout, ensure_dir, hash_file, partition, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import ( current_umask, is_within_directory, set_extracted_file_to_default_mode_plus_executable, zip_item_is_executable, ) from pip._internal.utils.wheel import ( parse_wheel, pkg_resources_distribution_for_wheel, ) class MissingCallableSuffix(InstallationError): def __init__(self, entry_point): # type: (str) -> None super(MissingCallableSuffix, self).__init__( "Invalid script entry point: {} - A callable " "suffix is required. Cf https://packaging.python.org/" "specifications/entry-points/#use-for-scripts for more " "information.".format(entry_point) ) def get_export_entry(specification): m = ENTRY_RE.search(specification) if not m: result = None if '[' in specification or ']' in specification: raise DistlibException("Invalid specification " "'%s'" % specification) else: d = m.groupdict() name = d['name'] path = d['callable'] colons = path.count(':') if colons == 0: prefix, suffix = path, None else: if colons != 1: raise DistlibException("Invalid specification " "'%s'" % specification) prefix, suffix = path.split(':') flags = d['flags'] if flags is None: if '[' in specification or ']' in specification: raise DistlibException("Invalid specification " "'%s'" % specification) flags = [] else: flags = [f.strip() for f in flags.split(',')] result = ExportEntry(name, prefix, suffix, flags) return result def _raise_for_invalid_entrypoint(specification): # type: (str) -> None entry = get_export_entry(specification) if entry is not None and entry.suffix is None: raise MissingCallableSuffix(str(entry))
null
175,603
from __future__ import absolute_import import collections import compileall import contextlib import csv import importlib import logging import os.path import re import shutil import sys import warnings from base64 import urlsafe_b64encode from itertools import chain, starmap from zipfile import ZipFile from pip._vendor import pkg_resources from pip._vendor.distlib.scripts import ScriptMaker from pip._vendor.distlib.util import get_export_entry from pip._vendor.six import ( PY2, ensure_str, ensure_text, itervalues, reraise, text_type, ) from pip._vendor.six.moves import filterfalse, map from pip._internal.exceptions import InstallationError from pip._internal.locations import get_major_minor_version from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl from pip._internal.models.scheme import SCHEME_KEYS from pip._internal.utils.filesystem import adjacent_tmp_file, replace from pip._internal.utils.misc import ( captured_stdout, ensure_dir, hash_file, partition, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import ( current_umask, is_within_directory, set_extracted_file_to_default_mode_plus_executable, zip_item_is_executable, ) from pip._internal.utils.wheel import ( parse_wheel, pkg_resources_distribution_for_wheel, ) def _install_wheel( name, # type: str wheel_zip, # type: ZipFile wheel_path, # type: str scheme, # type: Scheme pycompile=True, # type: bool warn_script_location=True, # type: bool direct_url=None, # type: Optional[DirectUrl] requested=False, # type: bool ): # type: (...) -> None """Install a wheel. :param name: Name of the project to install :param wheel_zip: open ZipFile for wheel being installed :param scheme: Distutils scheme dictating the install directories :param req_description: String used in place of the requirement, for logging :param pycompile: Whether to byte-compile installed Python files :param warn_script_location: Whether to check that scripts are installed into a directory on PATH :raises UnsupportedWheel: * when the directory holds an unpacked wheel with incompatible Wheel-Version * when the .dist-info dir does not match the wheel """ info_dir, metadata = parse_wheel(wheel_zip, name) if wheel_root_is_purelib(metadata): lib_dir = scheme.purelib else: lib_dir = scheme.platlib # Record details of the files moved # installed = files copied from the wheel to the destination # changed = files changed while installing (scripts #! line typically) # generated = files newly generated during the install (script wrappers) installed = {} # type: Dict[RecordPath, RecordPath] changed = set() # type: Set[RecordPath] generated = [] # type: List[str] def record_installed(srcfile, destfile, modified=False): # type: (RecordPath, text_type, bool) -> None """Map archive RECORD paths to installation RECORD paths.""" newpath = _fs_to_record_path(destfile, lib_dir) installed[srcfile] = newpath if modified: changed.add(_fs_to_record_path(destfile)) def all_paths(): # type: () -> Iterable[RecordPath] names = wheel_zip.namelist() # If a flag is set, names may be unicode in Python 2. We convert to # text explicitly so these are valid for lookup in RECORD. decoded_names = map(ensure_text, names) for name in decoded_names: yield cast("RecordPath", name) def is_dir_path(path): # type: (RecordPath) -> bool return path.endswith("/") def assert_no_path_traversal(dest_dir_path, target_path): # type: (text_type, text_type) -> None if not is_within_directory(dest_dir_path, target_path): message = ( "The wheel {!r} has a file {!r} trying to install" " outside the target directory {!r}" ) raise InstallationError( message.format(wheel_path, target_path, dest_dir_path) ) def root_scheme_file_maker(zip_file, dest): # type: (ZipFile, text_type) -> Callable[[RecordPath], File] def make_root_scheme_file(record_path): # type: (RecordPath) -> File normed_path = os.path.normpath(record_path) dest_path = os.path.join(dest, normed_path) assert_no_path_traversal(dest, dest_path) return ZipBackedFile(record_path, dest_path, zip_file) return make_root_scheme_file def data_scheme_file_maker(zip_file, scheme): # type: (ZipFile, Scheme) -> Callable[[RecordPath], File] scheme_paths = {} for key in SCHEME_KEYS: encoded_key = ensure_text(key) scheme_paths[encoded_key] = ensure_text( getattr(scheme, key), encoding=sys.getfilesystemencoding() ) def make_data_scheme_file(record_path): # type: (RecordPath) -> File normed_path = os.path.normpath(record_path) try: _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2) except ValueError: message = ( "Unexpected file in {}: {!r}. .data directory contents" " should be named like: '<scheme key>/<path>'." ).format(wheel_path, record_path) raise InstallationError(message) try: scheme_path = scheme_paths[scheme_key] except KeyError: valid_scheme_keys = ", ".join(sorted(scheme_paths)) message = ( "Unknown scheme key used in {}: {} (for file {!r}). .data" " directory contents should be in subdirectories named" " with a valid scheme key ({})" ).format( wheel_path, scheme_key, record_path, valid_scheme_keys ) raise InstallationError(message) dest_path = os.path.join(scheme_path, dest_subpath) assert_no_path_traversal(scheme_path, dest_path) return ZipBackedFile(record_path, dest_path, zip_file) return make_data_scheme_file def is_data_scheme_path(path): # type: (RecordPath) -> bool return path.split("/", 1)[0].endswith(".data") paths = all_paths() file_paths = filterfalse(is_dir_path, paths) root_scheme_paths, data_scheme_paths = partition( is_data_scheme_path, file_paths ) make_root_scheme_file = root_scheme_file_maker( wheel_zip, ensure_text(lib_dir, encoding=sys.getfilesystemencoding()), ) files = map(make_root_scheme_file, root_scheme_paths) def is_script_scheme_path(path): # type: (RecordPath) -> bool parts = path.split("/", 2) return ( len(parts) > 2 and parts[0].endswith(".data") and parts[1] == "scripts" ) other_scheme_paths, script_scheme_paths = partition( is_script_scheme_path, data_scheme_paths ) make_data_scheme_file = data_scheme_file_maker(wheel_zip, scheme) other_scheme_files = map(make_data_scheme_file, other_scheme_paths) files = chain(files, other_scheme_files) # Get the defined entry points distribution = pkg_resources_distribution_for_wheel( wheel_zip, name, wheel_path ) console, gui = get_entrypoints(distribution) def is_entrypoint_wrapper(file): # type: (File) -> bool # EP, EP.exe and EP-script.py are scripts generated for # entry point EP by setuptools path = file.dest_path name = os.path.basename(path) if name.lower().endswith('.exe'): matchname = name[:-4] elif name.lower().endswith('-script.py'): matchname = name[:-10] elif name.lower().endswith(".pya"): matchname = name[:-4] else: matchname = name # Ignore setuptools-generated scripts return (matchname in console or matchname in gui) script_scheme_files = map(make_data_scheme_file, script_scheme_paths) script_scheme_files = filterfalse( is_entrypoint_wrapper, script_scheme_files ) script_scheme_files = map(ScriptFile, script_scheme_files) files = chain(files, script_scheme_files) for file in files: file.save() record_installed(file.src_record_path, file.dest_path, file.changed) def pyc_source_file_paths(): # type: () -> Iterator[text_type] # We de-duplicate installation paths, since there can be overlap (e.g. # file in .data maps to same location as file in wheel root). # Sorting installation paths makes it easier to reproduce and debug # issues related to permissions on existing files. for installed_path in sorted(set(installed.values())): full_installed_path = os.path.join(lib_dir, installed_path) if not os.path.isfile(full_installed_path): continue if not full_installed_path.endswith('.py'): continue yield full_installed_path def pyc_output_path(path): # type: (text_type) -> text_type """Return the path the pyc file would have been written to. """ if PY2: if sys.flags.optimize: return path + 'o' else: return path + 'c' else: return importlib.util.cache_from_source(path) # Compile all of the pyc files for the installed files if pycompile: with captured_stdout() as stdout: with warnings.catch_warnings(): warnings.filterwarnings('ignore') for path in pyc_source_file_paths(): # Python 2's `compileall.compile_file` requires a str in # error cases, so we must convert to the native type. path_arg = ensure_str( path, encoding=sys.getfilesystemencoding() ) success = compileall.compile_file( path_arg, force=True, quiet=True ) if success: pyc_path = pyc_output_path(path) assert os.path.exists(pyc_path) pyc_record_path = cast( "RecordPath", pyc_path.replace(os.path.sep, "/") ) record_installed(pyc_record_path, pyc_path) logger.debug(stdout.getvalue()) maker = PipScriptMaker(None, scheme.scripts) # Ensure old scripts are overwritten. # See https://github.com/pypa/pip/issues/1800 maker.clobber = True # Ensure we don't generate any variants for scripts because this is almost # never what somebody wants. # See https://bitbucket.org/pypa/distlib/issue/35/ maker.variants = {''} # This is required because otherwise distlib creates scripts that are not # executable. # See https://bitbucket.org/pypa/distlib/issue/32/ maker.set_mode = True # Generate the console and GUI entry points specified in the wheel scripts_to_generate = get_console_script_specs(console) gui_scripts_to_generate = list(starmap('{} = {}'.format, gui.items())) generated_console_scripts = maker.make_multiple(scripts_to_generate) generated.extend(generated_console_scripts) generated.extend( maker.make_multiple(gui_scripts_to_generate, {'gui': True}) ) if warn_script_location: msg = message_about_scripts_not_on_PATH(generated_console_scripts) if msg is not None: logger.warning(msg) generated_file_mode = 0o666 & ~current_umask() def _generate_file(path, **kwargs): # type: (str, **Any) -> Iterator[NamedTemporaryFileResult] with adjacent_tmp_file(path, **kwargs) as f: yield f os.chmod(f.name, generated_file_mode) replace(f.name, path) dest_info_dir = os.path.join(lib_dir, info_dir) # Record pip as the installer installer_path = os.path.join(dest_info_dir, 'INSTALLER') with _generate_file(installer_path) as installer_file: installer_file.write(b'pip\n') generated.append(installer_path) # Record the PEP 610 direct URL reference if direct_url is not None: direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME) with _generate_file(direct_url_path) as direct_url_file: direct_url_file.write(direct_url.to_json().encode("utf-8")) generated.append(direct_url_path) # Record the REQUESTED file if requested: requested_path = os.path.join(dest_info_dir, 'REQUESTED') with open(requested_path, "w"): pass generated.append(requested_path) record_text = distribution.get_metadata('RECORD') record_rows = list(csv.reader(record_text.splitlines())) rows = get_csv_rows_for_installed( record_rows, installed=installed, changed=changed, generated=generated, lib_dir=lib_dir) # Record details of all files installed record_path = os.path.join(dest_info_dir, 'RECORD') with _generate_file(record_path, **csv_io_kwargs('w')) as record_file: # The type mypy infers for record_file is different for Python 3 # (typing.IO[Any]) and Python 2 (typing.BinaryIO). We explicitly # cast to typing.IO[str] as a workaround. writer = csv.writer(cast('IO[str]', record_file)) writer.writerows(_normalized_outrows(rows)) def req_error_context(req_description): # type: (str) -> Iterator[None] try: yield except InstallationError as e: message = "For req: {}. {}".format(req_description, e.args[0]) reraise( InstallationError, InstallationError(message), sys.exc_info()[2] ) class ZipFile: filename: Optional[Text] debug: int comment: bytes filelist: List[ZipInfo] fp: Optional[IO[bytes]] NameToInfo: Dict[Text, ZipInfo] start_dir: int # undocumented if sys.version_info >= (3, 8): def __init__( self, file: Union[StrPath, IO[bytes]], mode: str = ..., compression: int = ..., allowZip64: bool = ..., compresslevel: Optional[int] = ..., *, strict_timestamps: bool = ..., ) -> None: ... elif sys.version_info >= (3, 7): def __init__( self, file: Union[StrPath, IO[bytes]], mode: str = ..., compression: int = ..., allowZip64: bool = ..., compresslevel: Optional[int] = ..., ) -> None: ... else: def __init__( self, file: Union[StrPath, IO[bytes]], mode: Text = ..., compression: int = ..., allowZip64: bool = ... ) -> None: ... def __enter__(self) -> ZipFile: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... def close(self) -> None: ... def getinfo(self, name: Text) -> ZipInfo: ... def infolist(self) -> List[ZipInfo]: ... def namelist(self) -> List[Text]: ... def open(self, name: _SZI, mode: Text = ..., pwd: Optional[bytes] = ..., *, force_zip64: bool = ...) -> IO[bytes]: ... def extract(self, member: _SZI, path: Optional[StrPath] = ..., pwd: Optional[bytes] = ...) -> str: ... def extractall( self, path: Optional[StrPath] = ..., members: Optional[Iterable[Text]] = ..., pwd: Optional[bytes] = ... ) -> None: ... if sys.version_info >= (3,): def printdir(self, file: Optional[_Writer] = ...) -> None: ... else: def printdir(self) -> None: ... def setpassword(self, pwd: bytes) -> None: ... def read(self, name: _SZI, pwd: Optional[bytes] = ...) -> bytes: ... def testzip(self) -> Optional[str]: ... if sys.version_info >= (3, 7): def write( self, filename: StrPath, arcname: Optional[StrPath] = ..., compress_type: Optional[int] = ..., compresslevel: Optional[int] = ..., ) -> None: ... else: def write(self, filename: StrPath, arcname: Optional[StrPath] = ..., compress_type: Optional[int] = ...) -> None: ... if sys.version_info >= (3, 7): def writestr( self, zinfo_or_arcname: _SZI, data: Union[bytes, str], compress_type: Optional[int] = ..., compresslevel: Optional[int] = ..., ) -> None: ... elif sys.version_info >= (3,): def writestr(self, zinfo_or_arcname: _SZI, data: Union[bytes, str], compress_type: Optional[int] = ...) -> None: ... else: def writestr(self, zinfo_or_arcname: _SZI, bytes: bytes, compress_type: Optional[int] = ...) -> None: ... 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 direct_url=None, # type: Optional[DirectUrl] requested=False, # type: bool ): # type: (...) -> None with ZipFile(wheel_path, allowZip64=True) as z: with req_error_context(req_description): _install_wheel( name=name, wheel_zip=z, wheel_path=wheel_path, scheme=scheme, pycompile=pycompile, warn_script_location=warn_script_location, direct_url=direct_url, requested=requested, )
null
175,604
from __future__ import absolute_import import collections import logging import os from pip._vendor import six from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.pkg_resources import RequirementParseError from pip._internal.exceptions import BadCommand, InstallationError from pip._internal.req.constructors import ( install_req_from_editable, install_req_from_line, ) from pip._internal.req.req_file import COMMENT_RE from pip._internal.utils.direct_url_helpers import ( direct_url_as_pep440_direct_reference, dist_get_direct_url, ) from pip._internal.utils.misc import ( dist_is_editable, get_installed_distributions, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) class FrozenRequirement(object): def __init__(self, name, req, editable, comments=()): # type: (str, Union[str, Requirement], bool, Iterable[str]) -> None self.name = name self.canonical_name = canonicalize_name(name) self.req = req self.editable = editable self.comments = comments def from_dist(cls, dist): # type: (Distribution) -> FrozenRequirement # TODO `get_requirement_info` is taking care of editable requirements. # TODO This should be refactored when we will add detection of # editable that provide .dist-info metadata. req, editable, comments = get_requirement_info(dist) if req is None and not editable: # if PEP 610 metadata is present, attempt to use it direct_url = dist_get_direct_url(dist) if direct_url: req = direct_url_as_pep440_direct_reference( direct_url, dist.project_name ) comments = [] if req is None: # name==version requirement req = dist.as_requirement() return cls(dist.project_name, req, editable, comments=comments) def __str__(self): # type: () -> str req = self.req if self.editable: req = '-e {}'.format(req) return '\n'.join(list(self.comments) + [str(req)]) + '\n' def canonicalize_name(name): # type: (str) -> NormalizedName # This is taken from PEP 503. value = _canonicalize_regex.sub("-", name).lower() return cast("NormalizedName", value) class RequirementParseError(ValueError): def __str__(self): return ' '.join(self.args) def install_req_from_editable( editable_req, # type: str comes_from=None, # type: Optional[Union[InstallRequirement, str]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement parts = parse_req_from_editable(editable_req) return InstallRequirement( parts.requirement, comes_from=comes_from, user_supplied=user_supplied, editable=True, link=parts.link, constraint=constraint, use_pep517=use_pep517, isolated=isolated, install_options=options.get("install_options", []) if options else [], global_options=options.get("global_options", []) if options else [], hash_options=options.get("hashes", {}) if options else {}, extras=parts.extras, ) def install_req_from_line( name, # type: str comes_from=None, # type: Optional[Union[str, InstallRequirement]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool line_source=None, # type: Optional[str] user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. :param line_source: An optional string describing where the line is from, for logging purposes in case of an error. """ parts = parse_req_from_line(name, line_source) return InstallRequirement( parts.requirement, comes_from, link=parts.link, markers=parts.markers, use_pep517=use_pep517, isolated=isolated, install_options=options.get("install_options", []) if options else [], global_options=options.get("global_options", []) if options else [], hash_options=options.get("hashes", {}) if options else {}, constraint=constraint, extras=parts.extras, user_supplied=user_supplied, ) COMMENT_RE = re.compile(r'(^|\s+)#.*$') def get_installed_distributions( local_only=True, # type: bool skip=stdlib_pkgs, # type: Container[str] include_editables=True, # type: bool editables_only=False, # type: bool user_only=False, # type: bool paths=None # type: Optional[List[str]] ): # type: (...) -> List[Distribution] """ Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs If ``include_editables`` is False, don't report editables. If ``editables_only`` is True , only report editables. If ``user_only`` is True , only report installations in the user site directory. If ``paths`` is set, only report the distributions present at the specified list of locations. """ if paths: working_set = pkg_resources.WorkingSet(paths) else: working_set = pkg_resources.working_set if local_only: local_test = dist_is_local else: def local_test(d): return True if include_editables: def editable_test(d): return True else: def editable_test(d): return not dist_is_editable(d) if editables_only: def editables_only_test(d): return dist_is_editable(d) else: def editables_only_test(d): return True if user_only: user_test = dist_in_usersite else: def user_test(d): return True return [d for d in working_set if local_test(d) and d.key not in skip and editable_test(d) and editables_only_test(d) and user_test(d) ] def freeze( requirement=None, # type: Optional[List[str]] find_links=None, # type: Optional[List[str]] local_only=False, # type: bool user_only=False, # type: bool paths=None, # type: Optional[List[str]] isolated=False, # type: bool wheel_cache=None, # type: Optional[WheelCache] exclude_editable=False, # type: bool skip=() # type: Container[str] ): # type: (...) -> Iterator[str] find_links = find_links or [] for link in find_links: yield '-f {}'.format(link) installations = {} # type: Dict[str, FrozenRequirement] for dist in get_installed_distributions( local_only=local_only, skip=(), user_only=user_only, paths=paths ): try: req = FrozenRequirement.from_dist(dist) except RequirementParseError as exc: # We include dist rather than dist.project_name because the # dist string includes more information, like the version and # location. We also include the exception message to aid # troubleshooting. logger.warning( 'Could not generate requirement for distribution %r: %s', dist, exc ) continue if exclude_editable and req.editable: continue installations[req.canonical_name] = req if requirement: # the options that don't get turned into an InstallRequirement # should only be emitted once, even if the same option is in multiple # requirements files, so we need to keep track of what has been emitted # so that we don't emit it again if it's seen again emitted_options = set() # type: Set[str] # keep track of which files a requirement is in so that we can # give an accurate warning if a requirement appears multiple times. req_files = collections.defaultdict(list) # type: Dict[str, List[str]] for req_file_path in requirement: with open(req_file_path) as req_file: for line in req_file: if (not line.strip() or line.strip().startswith('#') or line.startswith(( '-r', '--requirement', '-f', '--find-links', '-i', '--index-url', '--pre', '--trusted-host', '--process-dependency-links', '--extra-index-url', '--use-feature'))): line = line.rstrip() if line not in emitted_options: emitted_options.add(line) yield line continue if line.startswith('-e') or line.startswith('--editable'): if line.startswith('-e'): line = line[2:].strip() else: line = line[len('--editable'):].strip().lstrip('=') line_req = install_req_from_editable( line, isolated=isolated, ) else: line_req = install_req_from_line( COMMENT_RE.sub('', line).strip(), isolated=isolated, ) if not line_req.name: logger.info( "Skipping line in requirement file [%s] because " "it's not clear what it would install: %s", req_file_path, line.strip(), ) logger.info( " (add #egg=PackageName to the URL to avoid" " this warning)" ) else: line_req_canonical_name = canonicalize_name( line_req.name) if line_req_canonical_name not in installations: # either it's not installed, or it is installed # but has been processed already if not req_files[line_req.name]: logger.warning( "Requirement file [%s] contains %s, but " "package %r is not installed", req_file_path, COMMENT_RE.sub('', line).strip(), line_req.name ) else: req_files[line_req.name].append(req_file_path) else: yield str(installations[ line_req_canonical_name]).rstrip() del installations[line_req_canonical_name] req_files[line_req.name].append(req_file_path) # Warn about requirements that were included multiple times (in a # single requirements file or in different requirements files). for name, files in six.iteritems(req_files): if len(files) > 1: logger.warning("Requirement %s included multiple times [%s]", name, ', '.join(sorted(set(files)))) yield( '## The following requirements were added by ' 'pip freeze:' ) for installation in sorted( installations.values(), key=lambda x: x.name.lower()): if installation.canonical_name not in skip: yield str(installation).rstrip()
null
175,605
from __future__ import absolute_import import collections import logging import os from pip._vendor import six from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.pkg_resources import RequirementParseError from pip._internal.exceptions import BadCommand, InstallationError from pip._internal.req.constructors import ( install_req_from_editable, install_req_from_line, ) from pip._internal.req.req_file import COMMENT_RE from pip._internal.utils.direct_url_helpers import ( direct_url_as_pep440_direct_reference, dist_get_direct_url, ) from pip._internal.utils.misc import ( dist_is_editable, get_installed_distributions, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) class InstallationError(PipError): """General exception during installation""" class BadCommand(PipError): """Raised when virtualenv or a command is not found""" def dist_is_editable(dist): # type: (Distribution) -> bool """ Return True if given Distribution is an editable install. """ for path_item in sys.path: egg_link = os.path.join(path_item, dist.project_name + '.egg-link') if os.path.isfile(egg_link): return True return False The provided code snippet includes necessary dependencies for implementing the `get_requirement_info` function. Write a Python function `def get_requirement_info(dist)` to solve the following problem: Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist(). Here is the function: def get_requirement_info(dist): # type: (Distribution) -> RequirementInfo """ Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist(). """ if not dist_is_editable(dist): return (None, False, []) location = os.path.normcase(os.path.abspath(dist.location)) from pip._internal.vcs import vcs, RemoteNotFoundError vcs_backend = vcs.get_backend_for_dir(location) if vcs_backend is None: req = dist.as_requirement() logger.debug( 'No VCS found for editable requirement "%s" in: %r', req, location, ) comments = [ '# Editable install with no version control ({})'.format(req) ] return (location, True, comments) try: req = vcs_backend.get_src_requirement(location, dist.project_name) except RemoteNotFoundError: req = dist.as_requirement() comments = [ '# Editable {} install with no remote ({})'.format( type(vcs_backend).__name__, req, ) ] return (location, True, comments) except BadCommand: logger.warning( 'cannot determine version of editable source in %s ' '(%s command not found in path)', location, vcs_backend.name, ) return (None, True, []) except InstallationError as exc: logger.warning( "Error when trying to get requirement for VCS system %s, " "falling back to uneditable format", exc ) else: if req is not None: return (req, True, []) logger.warning( 'Could not determine repository location of %s', location ) comments = ['## !! Could not determine repository location'] return (None, False, comments)
Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist().
175,606
import logging import mimetypes import os import shutil from pip._vendor.six import PY2 from pip._internal.distributions import ( make_distribution_for_install_requirement, ) from pip._internal.distributions.installed import InstalledDistribution from pip._internal.exceptions import ( DirectoryUrlHashUnsupported, HashMismatch, HashUnpinned, InstallationError, NetworkConnectionError, PreviousBuildDirError, VcsHashUnsupported, ) from pip._internal.utils.filesystem import copy2_fixed from pip._internal.utils.hashes import MissingHashes from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( display_path, hide_url, path_to_display, rmtree, ) from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import unpack_file from pip._internal.vcs import vcs def make_distribution_for_install_requirement(install_req): # type: (InstallRequirement) -> AbstractDistribution """Returns a Distribution for the given InstallRequirement """ # Editable requirements will always be source distributions. They use the # legacy logic until we create a modern standard for them. if install_req.editable: return SourceDistribution(install_req) # If it's a wheel, it's a WheelDistribution if install_req.is_wheel: return WheelDistribution(install_req) # Otherwise, a SourceDistribution return SourceDistribution(install_req) The provided code snippet includes necessary dependencies for implementing the `_get_prepared_distribution` function. Write a Python function `def _get_prepared_distribution( req, # type: InstallRequirement req_tracker, # type: RequirementTracker finder, # type: PackageFinder build_isolation # type: bool )` to solve the following problem: Prepare a distribution for installation. Here is the function: def _get_prepared_distribution( req, # type: InstallRequirement req_tracker, # type: RequirementTracker finder, # type: PackageFinder build_isolation # type: bool ): # type: (...) -> AbstractDistribution """Prepare a distribution for installation. """ abstract_dist = make_distribution_for_install_requirement(req) with req_tracker.track(req): abstract_dist.prepare_distribution_metadata(finder, build_isolation) return abstract_dist
Prepare a distribution for installation.
175,607
import logging import mimetypes import os import shutil from pip._vendor.six import PY2 from pip._internal.distributions import ( make_distribution_for_install_requirement, ) from pip._internal.distributions.installed import InstalledDistribution from pip._internal.exceptions import ( DirectoryUrlHashUnsupported, HashMismatch, HashUnpinned, InstallationError, NetworkConnectionError, PreviousBuildDirError, VcsHashUnsupported, ) from pip._internal.utils.filesystem import copy2_fixed from pip._internal.utils.hashes import MissingHashes from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( display_path, hide_url, path_to_display, rmtree, ) from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import unpack_file from pip._internal.vcs import vcs def unpack_vcs_link(link, location): # type: (Link, str) -> None vcs_backend = vcs.get_backend_for_scheme(link.scheme) assert vcs_backend is not None vcs_backend.unpack(location, url=hide_url(link.url)) 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) def _copy_source_tree(source, target): # type: (str, str) -> None target_abspath = os.path.abspath(target) target_basename = os.path.basename(target_abspath) target_dirname = os.path.dirname(target_abspath) def ignore(d, names): # type: (str, List[str]) -> List[str] skipped = [] # type: List[str] if d == source: # Pulling in those directories can potentially be very slow, # exclude the following directories if they appear in the top # level dir (and only it). # See discussion at https://github.com/pypa/pip/pull/6770 skipped += ['.tox', '.nox'] if os.path.abspath(d) == target_dirname: # Prevent an infinite recursion if the target is in source. # This can happen when TMPDIR is set to ${PWD}/... # and we copy PWD to TMPDIR. skipped += [target_basename] return skipped kwargs = dict(ignore=ignore, symlinks=True) # type: CopytreeKwargs if not PY2: # Python 2 does not support copy_function, so we only ignore # errors on special file copy in Python 3. kwargs['copy_function'] = _copy2_ignoring_special_files shutil.copytree(source, target, **kwargs) def get_file_url( link, # type: Link download_dir=None, # type: Optional[str] hashes=None # type: Optional[Hashes] ): # type: (...) -> File """Get file and optionally check its hash. """ # If a download dir is specified, is the file already there and valid? 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 else: from_path = link.file_path # If --require-hashes is off, `hashes` is either empty, the # link's embedded hash, or MissingHashes; it is required to # match. If --require-hashes is on, we are satisfied by any # hash in `hashes` matching: a URL-based or an option-based # one; no internet-sourced hash will be in `hashes`. if hashes: hashes.check_against_path(from_path) content_type = mimetypes.guess_type(from_path)[0] return File(from_path, content_type) def rmtree(dir, ignore_errors=False): # type: (Text, bool) -> None shutil.rmtree(dir, ignore_errors=ignore_errors, onerror=rmtree_errorhandler) def unpack_file( filename, # type: str location, # type: str content_type=None, # type: Optional[str] ): # type: (...) -> None filename = os.path.realpath(filename) if ( content_type == 'application/zip' or filename.lower().endswith(ZIP_EXTENSIONS) or zipfile.is_zipfile(filename) ): unzip_file( filename, location, flatten=not filename.endswith('.whl') ) elif ( content_type == 'application/x-gzip' or tarfile.is_tarfile(filename) or filename.lower().endswith( TAR_EXTENSIONS + BZ2_EXTENSIONS + XZ_EXTENSIONS ) ): untar_file(filename, location) else: # FIXME: handle? # FIXME: magic signatures? logger.critical( 'Cannot unpack file %s (downloaded from %s, content-type: %s); ' 'cannot detect archive format', filename, location, content_type, ) raise InstallationError( 'Cannot determine archive format of {}'.format(location) ) The provided code snippet includes necessary dependencies for implementing the `unpack_url` function. Write a Python function `def unpack_url( link, # type: Link location, # type: str downloader, # type: Downloader download_dir=None, # type: Optional[str] hashes=None, # type: Optional[Hashes] )` to solve the following problem: Unpack link into location, downloading if required. :param hashes: A Hashes object, one of whose embedded hashes must match, or HashMismatch will be raised. If the Hashes is empty, no matches are required, and unhashable types of requirements (like VCS ones, which would ordinarily raise HashUnsupported) are allowed. Here is the function: def unpack_url( link, # type: Link location, # type: str downloader, # type: Downloader download_dir=None, # type: Optional[str] hashes=None, # type: Optional[Hashes] ): # type: (...) -> Optional[File] """Unpack link into location, downloading if required. :param hashes: A Hashes object, one of whose embedded hashes must match, or HashMismatch will be raised. If the Hashes is empty, no matches are required, and unhashable types of requirements (like VCS ones, which would ordinarily raise HashUnsupported) are allowed. """ # non-editable vcs urls if link.is_vcs: unpack_vcs_link(link, location) return None # If it's a url to a local directory if link.is_existing_dir(): if os.path.isdir(location): rmtree(location) _copy_source_tree(link.file_path, location) return None # file urls if link.is_file: file = get_file_url(link, download_dir, hashes=hashes) # http urls else: file = get_http_url( link, downloader, download_dir, hashes=hashes, ) # unpack the archive to the build dir location. even when only downloading # archives, they have to be unpacked to parse dependencies, except wheels if not link.is_wheel: unpack_file(file.path, location, file.content_type) return file
Unpack link into location, downloading if required. :param hashes: A Hashes object, one of whose embedded hashes must match, or HashMismatch will be raised. If the Hashes is empty, no matches are required, and unhashable types of requirements (like VCS ones, which would ordinarily raise HashUnsupported) are allowed.
175,608
import logging import os from pip._internal.exceptions import InstallationError from pip._internal.utils.setuptools_build import make_setuptools_egg_info_args from pip._internal.utils.subprocess import call_subprocess from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) def _find_egg_info(directory): # type: (str) -> str """Find an .egg-info subdirectory in `directory`. """ filenames = [ f for f in os.listdir(directory) if f.endswith(".egg-info") ] if not filenames: raise InstallationError( "No .egg-info directory found in {}".format(directory) ) if len(filenames) > 1: raise InstallationError( "More than one .egg-info directory found in {}".format( directory ) ) return os.path.join(directory, filenames[0]) def make_setuptools_egg_info_args( setup_py_path, # type: str egg_info_dir, # type: Optional[str] no_user_config, # type: bool ): # type: (...) -> List[str] args = make_setuptools_shim_args( setup_py_path, no_user_config=no_user_config ) args += ["egg_info"] if egg_info_dir: args += ["--egg-base", egg_info_dir] return args def call_subprocess( cmd, # type: Union[List[str], CommandArgs] show_stdout=False, # type: bool cwd=None, # type: Optional[str] on_returncode='raise', # type: str extra_ok_returncodes=None, # type: Optional[Iterable[int]] command_desc=None, # type: Optional[str] extra_environ=None, # type: Optional[Mapping[str, Any]] unset_environ=None, # type: Optional[Iterable[str]] spinner=None, # type: Optional[SpinnerInterface] log_failed_cmd=True # type: Optional[bool] ): # type: (...) -> Text """ Args: show_stdout: if true, use INFO to log the subprocess's stderr and stdout streams. Otherwise, use DEBUG. Defaults to False. extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. unset_environ: an iterable of environment variable names to unset prior to calling subprocess.Popen(). log_failed_cmd: if false, failed commands are not logged, only raised. """ if extra_ok_returncodes is None: extra_ok_returncodes = [] if unset_environ is None: unset_environ = [] # Most places in pip use show_stdout=False. What this means is-- # # - We connect the child's output (combined stderr and stdout) to a # single pipe, which we read. # - We log this output to stderr at DEBUG level as it is received. # - If DEBUG logging isn't enabled (e.g. if --verbose logging wasn't # requested), then we show a spinner so the user can still see the # subprocess is in progress. # - If the subprocess exits with an error, we log the output to stderr # at ERROR level if it hasn't already been displayed to the console # (e.g. if --verbose logging wasn't enabled). This way we don't log # the output to the console twice. # # If show_stdout=True, then the above is still done, but with DEBUG # replaced by INFO. if show_stdout: # Then log the subprocess output at INFO level. log_subprocess = subprocess_logger.info used_level = logging.INFO else: # Then log the subprocess output using DEBUG. This also ensures # it will be logged to the log file (aka user_log), if enabled. log_subprocess = subprocess_logger.debug used_level = logging.DEBUG # Whether the subprocess will be visible in the console. showing_subprocess = subprocess_logger.getEffectiveLevel() <= used_level # Only use the spinner if we're not showing the subprocess output # and we have a spinner. use_spinner = not showing_subprocess and spinner is not None if command_desc is None: command_desc = format_command_args(cmd) log_subprocess("Running command %s", command_desc) env = os.environ.copy() if extra_environ: env.update(extra_environ) for name in unset_environ: env.pop(name, None) try: proc = subprocess.Popen( # Convert HiddenText objects to the underlying str. reveal_command_args(cmd), stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=cwd, env=env, ) assert proc.stdin assert proc.stdout proc.stdin.close() except Exception as exc: if log_failed_cmd: subprocess_logger.critical( "Error %s while executing command %s", exc, command_desc, ) raise all_output = [] while True: # The "line" value is a unicode string in Python 2. line = console_to_str(proc.stdout.readline()) if not line: break line = line.rstrip() all_output.append(line + '\n') # Show the line immediately. log_subprocess(line) # Update the spinner. if use_spinner: assert spinner spinner.spin() try: proc.wait() finally: if proc.stdout: proc.stdout.close() proc_had_error = ( proc.returncode and proc.returncode not in extra_ok_returncodes ) if use_spinner: assert spinner if proc_had_error: spinner.finish("error") else: spinner.finish("done") if proc_had_error: if on_returncode == 'raise': if not showing_subprocess and log_failed_cmd: # Then the subprocess streams haven't been logged to the # console yet. msg = make_subprocess_output_error( cmd_args=cmd, cwd=cwd, lines=all_output, exit_status=proc.returncode, ) subprocess_logger.error(msg) exc_msg = ( 'Command errored out with exit status {}: {} ' 'Check the logs for full command output.' ).format(proc.returncode, command_desc) raise InstallationError(exc_msg) elif on_returncode == 'warn': subprocess_logger.warning( 'Command "%s" had error code %s in %s', command_desc, proc.returncode, cwd, ) elif on_returncode == 'ignore': pass else: raise ValueError('Invalid value: on_returncode={!r}'.format( on_returncode)) return ''.join(all_output) class TempDirectory(object): """Helper class that owns and cleans up a temporary directory. This class can be used as a context manager or as an OO representation of a temporary directory. Attributes: path Location to the created temporary directory delete Whether the directory should be deleted when exiting (when used as a contextmanager) Methods: cleanup() Deletes the temporary directory When used as a context manager, if the delete attribute is True, on exiting the context the temporary directory is deleted. """ def __init__( self, path=None, # type: Optional[str] delete=_default, # type: Union[bool, None, _Default] kind="temp", # type: str globally_managed=False, # type: bool ): super(TempDirectory, self).__init__() if delete is _default: if path is not None: # If we were given an explicit directory, resolve delete option # now. delete = False else: # Otherwise, we wait until cleanup and see what # tempdir_registry says. delete = None if path is None: path = self._create(kind) self._path = path self._deleted = False self.delete = delete self.kind = kind if globally_managed: assert _tempdir_manager is not None _tempdir_manager.enter_context(self) def path(self): # type: () -> str assert not self._deleted, ( "Attempted to access deleted path: {}".format(self._path) ) return self._path def __repr__(self): # type: () -> str return "<{} {!r}>".format(self.__class__.__name__, self.path) def __enter__(self): # type: (_T) -> _T return self def __exit__(self, exc, value, tb): # type: (Any, Any, Any) -> None if self.delete is not None: delete = self.delete elif _tempdir_registry: delete = _tempdir_registry.get_delete(self.kind) else: delete = True if delete: self.cleanup() def _create(self, kind): # type: (str) -> str """Create a temporary directory and store its path in self.path """ # We realpath here because some systems have their default tmpdir # symlinked to another directory. This tends to confuse build # scripts, so we canonicalize the path by traversing potential # symlinks here. path = os.path.realpath( tempfile.mkdtemp(prefix="pip-{}-".format(kind)) ) logger.debug("Created temporary directory: %s", path) return path def cleanup(self): # type: () -> None """Remove the temporary directory created and reset state """ self._deleted = True if os.path.exists(self._path): # Make sure to pass unicode on Python 2 to make the contents also # use unicode, ensuring non-ASCII names and can be represented. rmtree(ensure_text(self._path)) The provided code snippet includes necessary dependencies for implementing the `generate_metadata` function. Write a Python function `def generate_metadata( build_env, # type: BuildEnvironment setup_py_path, # type: str source_dir, # type: str isolated, # type: bool details, # type: str )` to solve the following problem: Generate metadata using setup.py-based defacto mechanisms. Returns the generated metadata directory. Here is the function: def generate_metadata( build_env, # type: BuildEnvironment setup_py_path, # type: str source_dir, # type: str isolated, # type: bool details, # type: str ): # type: (...) -> str """Generate metadata using setup.py-based defacto mechanisms. Returns the generated metadata directory. """ logger.debug( 'Running setup.py (path:%s) egg_info for package %s', setup_py_path, details, ) egg_info_dir = TempDirectory( kind="pip-egg-info", globally_managed=True ).path args = make_setuptools_egg_info_args( setup_py_path, egg_info_dir=egg_info_dir, no_user_config=isolated, ) with build_env: call_subprocess( args, cwd=source_dir, command_desc='python setup.py egg_info', ) # Return the .egg-info directory. return _find_egg_info(egg_info_dir)
Generate metadata using setup.py-based defacto mechanisms. Returns the generated metadata directory.
175,609
import os from pip._internal.utils.subprocess import runner_with_spinner_message from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING def runner_with_spinner_message(message): # type: (str) -> Callable[..., None] """Provide a subprocess_runner that shows a spinner message. Intended for use with for pep517's Pep517HookCaller. Thus, the runner has an API that matches what's expected by Pep517HookCaller.subprocess_runner. """ def runner( cmd, # type: List[str] cwd=None, # type: Optional[str] extra_environ=None # type: Optional[Mapping[str, Any]] ): # type: (...) -> None with open_spinner(message) as spinner: call_subprocess( cmd, cwd=cwd, extra_environ=extra_environ, spinner=spinner, ) return runner class TempDirectory(object): """Helper class that owns and cleans up a temporary directory. This class can be used as a context manager or as an OO representation of a temporary directory. Attributes: path Location to the created temporary directory delete Whether the directory should be deleted when exiting (when used as a contextmanager) Methods: cleanup() Deletes the temporary directory When used as a context manager, if the delete attribute is True, on exiting the context the temporary directory is deleted. """ def __init__( self, path=None, # type: Optional[str] delete=_default, # type: Union[bool, None, _Default] kind="temp", # type: str globally_managed=False, # type: bool ): super(TempDirectory, self).__init__() if delete is _default: if path is not None: # If we were given an explicit directory, resolve delete option # now. delete = False else: # Otherwise, we wait until cleanup and see what # tempdir_registry says. delete = None if path is None: path = self._create(kind) self._path = path self._deleted = False self.delete = delete self.kind = kind if globally_managed: assert _tempdir_manager is not None _tempdir_manager.enter_context(self) def path(self): # type: () -> str assert not self._deleted, ( "Attempted to access deleted path: {}".format(self._path) ) return self._path def __repr__(self): # type: () -> str return "<{} {!r}>".format(self.__class__.__name__, self.path) def __enter__(self): # type: (_T) -> _T return self def __exit__(self, exc, value, tb): # type: (Any, Any, Any) -> None if self.delete is not None: delete = self.delete elif _tempdir_registry: delete = _tempdir_registry.get_delete(self.kind) else: delete = True if delete: self.cleanup() def _create(self, kind): # type: (str) -> str """Create a temporary directory and store its path in self.path """ # We realpath here because some systems have their default tmpdir # symlinked to another directory. This tends to confuse build # scripts, so we canonicalize the path by traversing potential # symlinks here. path = os.path.realpath( tempfile.mkdtemp(prefix="pip-{}-".format(kind)) ) logger.debug("Created temporary directory: %s", path) return path def cleanup(self): # type: () -> None """Remove the temporary directory created and reset state """ self._deleted = True if os.path.exists(self._path): # Make sure to pass unicode on Python 2 to make the contents also # use unicode, ensuring non-ASCII names and can be represented. rmtree(ensure_text(self._path)) The provided code snippet includes necessary dependencies for implementing the `generate_metadata` function. Write a Python function `def generate_metadata(build_env, backend)` to solve the following problem: Generate metadata using mechanisms described in PEP 517. Returns the generated metadata directory. Here is the function: def generate_metadata(build_env, backend): # type: (BuildEnvironment, Pep517HookCaller) -> str """Generate metadata using mechanisms described in PEP 517. Returns the generated metadata directory. """ metadata_tmpdir = TempDirectory( kind="modern-metadata", globally_managed=True ) metadata_dir = metadata_tmpdir.path with build_env: # Note that Pep517HookCaller implements a fallback for # prepare_metadata_for_build_wheel, so we don't have to # consider the possibility that this hook doesn't exist. runner = runner_with_spinner_message("Preparing wheel metadata") with backend.subprocess_runner(runner): distinfo_dir = backend.prepare_metadata_for_build_wheel( metadata_dir ) return os.path.join(metadata_dir, distinfo_dir)
Generate metadata using mechanisms described in PEP 517. Returns the generated metadata directory.
175,610
from __future__ import absolute_import import logging import os import shutil import sys import uuid import zipfile from pip._vendor import pkg_resources, six from pip._vendor.packaging.requirements import Requirement from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import Version from pip._vendor.packaging.version import parse as parse_version from pip._vendor.pep517.wrappers import Pep517HookCaller from pip._internal.build_env import NoOpBuildEnvironment from pip._internal.exceptions import InstallationError from pip._internal.locations import get_scheme from pip._internal.models.link import Link from pip._internal.operations.build.metadata import generate_metadata from pip._internal.operations.build.metadata_legacy import \ generate_metadata as generate_metadata_legacy from pip._internal.operations.install.editable_legacy import \ install_editable as install_editable_legacy from pip._internal.operations.install.legacy import LegacyInstallFailure from pip._internal.operations.install.legacy import install as install_legacy from pip._internal.operations.install.wheel import install_wheel from pip._internal.pyproject import load_pyproject_toml, make_pyproject_path from pip._internal.req.req_uninstall import UninstallPathSet from pip._internal.utils.deprecation import deprecated from pip._internal.utils.direct_url_helpers import direct_url_from_link from pip._internal.utils.hashes import Hashes from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( ask_path_exists, backup_dir, display_path, dist_in_site_packages, dist_in_usersite, get_distribution, get_installed_version, hide_url, redact_auth_from_url, ) from pip._internal.utils.packaging import get_metadata from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.virtualenv import running_under_virtualenv from pip._internal.vcs import vcs class Distribution: """Wrap an actual or potential sys.path entry w/metadata""" PKG_INFO = 'PKG-INFO' def __init__( self, location=None, metadata=None, project_name=None, version=None, py_version=PY_MAJOR, platform=None, precedence=EGG_DIST): self.project_name = safe_name(project_name or 'Unknown') if version is not None: self._version = safe_version(version) self.py_version = py_version self.platform = platform self.location = location self.precedence = precedence self._provider = metadata or empty_provider def from_location(cls, location, basename, metadata=None, **kw): project_name, version, py_version, platform = [None] * 4 basename, ext = os.path.splitext(basename) if ext.lower() in _distributionImpl: cls = _distributionImpl[ext.lower()] match = EGG_NAME(basename) if match: project_name, version, py_version, platform = match.group( 'name', 'ver', 'pyver', 'plat' ) return cls( location, metadata, project_name=project_name, version=version, py_version=py_version, platform=platform, **kw )._reload_version() def _reload_version(self): return self def hashcmp(self): return ( self.parsed_version, self.precedence, self.key, _remove_md5_fragment(self.location), self.py_version or '', self.platform or '', ) def __hash__(self): return hash(self.hashcmp) def __lt__(self, other): return self.hashcmp < other.hashcmp def __le__(self, other): return self.hashcmp <= other.hashcmp def __gt__(self, other): return self.hashcmp > other.hashcmp def __ge__(self, other): return self.hashcmp >= other.hashcmp def __eq__(self, other): if not isinstance(other, self.__class__): # It's not a Distribution, so they are not equal return False return self.hashcmp == other.hashcmp def __ne__(self, other): return not self == other # These properties have to be lazy so that we don't have to load any # metadata until/unless it's actually needed. (i.e., some distributions # may not know their name or version without loading PKG-INFO) def key(self): try: return self._key except AttributeError: self._key = key = self.project_name.lower() return key def parsed_version(self): if not hasattr(self, "_parsed_version"): self._parsed_version = parse_version(self.version) return self._parsed_version def _warn_legacy_version(self): LV = packaging.version.LegacyVersion is_legacy = isinstance(self._parsed_version, LV) if not is_legacy: return # While an empty version is technically a legacy version and # is not a valid PEP 440 version, it's also unlikely to # actually come from someone and instead it is more likely that # it comes from setuptools attempting to parse a filename and # including it in the list. So for that we'll gate this warning # on if the version is anything at all or not. if not self.version: return tmpl = textwrap.dedent(""" '{project_name} ({version})' is being parsed as a legacy, non PEP 440, version. You may find odd behavior and sort order. In particular it will be sorted as less than 0.0. It is recommended to migrate to PEP 440 compatible versions. """).strip().replace('\n', ' ') warnings.warn(tmpl.format(**vars(self)), PEP440Warning) def version(self): try: return self._version except AttributeError: version = self._get_version() if version is None: path = self._get_metadata_path_for_display(self.PKG_INFO) msg = ( "Missing 'Version:' header and/or {} file at path: {}" ).format(self.PKG_INFO, path) raise ValueError(msg, self) return version def _dep_map(self): """ A map of extra to its list of (direct) requirements for this distribution, including the null extra. """ try: return self.__dep_map except AttributeError: self.__dep_map = self._filter_extras(self._build_dep_map()) return self.__dep_map def _filter_extras(dm): """ Given a mapping of extras to dependencies, strip off environment markers and filter out any dependencies not matching the markers. """ for extra in list(filter(None, dm)): new_extra = extra reqs = dm.pop(extra) new_extra, _, marker = extra.partition(':') fails_marker = marker and ( invalid_marker(marker) or not evaluate_marker(marker) ) if fails_marker: reqs = [] new_extra = safe_extra(new_extra) or None dm.setdefault(new_extra, []).extend(reqs) return dm def _build_dep_map(self): dm = {} for name in 'requires.txt', 'depends.txt': for extra, reqs in split_sections(self._get_metadata(name)): dm.setdefault(extra, []).extend(parse_requirements(reqs)) return dm def requires(self, extras=()): """List of Requirements needed for this distro if `extras` are used""" dm = self._dep_map deps = [] deps.extend(dm.get(None, ())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra( "%s has no such extra feature %r" % (self, ext) ) return deps def _get_metadata_path_for_display(self, name): """ Return the path to the given metadata file, if available. """ try: # We need to access _get_metadata_path() on the provider object # directly rather than through this class's __getattr__() # since _get_metadata_path() is marked private. path = self._provider._get_metadata_path(name) # Handle exceptions e.g. in case the distribution's metadata # provider doesn't support _get_metadata_path(). except Exception: return '[could not detect]' return path def _get_metadata(self, name): if self.has_metadata(name): for line in self.get_metadata_lines(name): yield line def _get_version(self): lines = self._get_metadata(self.PKG_INFO) version = _version_from_file(lines) return version def activate(self, path=None, replace=False): """Ensure distribution is importable on `path` (default=sys.path)""" if path is None: path = sys.path self.insert_on(path, replace=replace) if path is sys.path: fixup_namespace_packages(self.location) for pkg in self._get_metadata('namespace_packages.txt'): if pkg in sys.modules: declare_namespace(pkg) def egg_name(self): """Return what this distribution's standard .egg filename should be""" filename = "%s-%s-py%s" % ( to_filename(self.project_name), to_filename(self.version), self.py_version or PY_MAJOR ) if self.platform: filename += '-' + self.platform return filename def __repr__(self): if self.location: return "%s (%s)" % (self, self.location) else: return str(self) def __str__(self): try: version = getattr(self, 'version', None) except ValueError: version = None version = version or "[unknown version]" return "%s %s" % (self.project_name, version) def __getattr__(self, attr): """Delegate all unrecognized public attributes to .metadata provider""" if attr.startswith('_'): raise AttributeError(attr) return getattr(self._provider, attr) def __dir__(self): return list( set(super(Distribution, self).__dir__()) | set( attr for attr in self._provider.__dir__() if not attr.startswith('_') ) ) if not hasattr(object, '__dir__'): # python 2.7 not supported del __dir__ def from_filename(cls, filename, metadata=None, **kw): return cls.from_location( _normalize_cached(filename), os.path.basename(filename), metadata, **kw ) def as_requirement(self): """Return a ``Requirement`` that matches this distribution exactly""" if isinstance(self.parsed_version, packaging.version.Version): spec = "%s==%s" % (self.project_name, self.parsed_version) else: spec = "%s===%s" % (self.project_name, self.parsed_version) return Requirement.parse(spec) def load_entry_point(self, group, name): """Return the `name` entry point of `group` or raise ImportError""" ep = self.get_entry_info(group, name) if ep is None: raise ImportError("Entry point %r not found" % ((group, name),)) return ep.load() def get_entry_map(self, group=None): """Return the entry point map for `group`, or the full entry map""" try: ep_map = self._ep_map except AttributeError: ep_map = self._ep_map = EntryPoint.parse_map( self._get_metadata('entry_points.txt'), self ) if group is not None: return ep_map.get(group, {}) return ep_map def get_entry_info(self, group, name): """Return the EntryPoint object for `group`+`name`, or ``None``""" return self.get_entry_map(group).get(name) def insert_on(self, path, loc=None, replace=False): """Ensure self.location is on path If replace=False (default): - If location is already in path anywhere, do nothing. - Else: - If it's an egg and its parent directory is on path, insert just ahead of the parent. - Else: add to the end of path. If replace=True: - If location is already on path anywhere (not eggs) or higher priority than its parent (eggs) do nothing. - Else: - If it's an egg and its parent directory is on path, insert just ahead of the parent, removing any lower-priority entries. - Else: add it to the front of path. """ loc = loc or self.location if not loc: return nloc = _normalize_cached(loc) bdir = os.path.dirname(nloc) npath = [(p and _normalize_cached(p) or p) for p in path] for p, item in enumerate(npath): if item == nloc: if replace: break else: # don't modify path (even removing duplicates) if # found and not replace return elif item == bdir and self.precedence == EGG_DIST: # if it's an .egg, give it precedence over its directory # UNLESS it's already been added to sys.path and replace=False if (not replace) and nloc in npath[p:]: return if path is sys.path: self.check_version_conflict() path.insert(p, loc) npath.insert(p, nloc) break else: if path is sys.path: self.check_version_conflict() if replace: path.insert(0, loc) else: path.append(loc) return # p is the spot where we found or inserted loc; now remove duplicates while True: try: np = npath.index(nloc, p + 1) except ValueError: break else: del npath[np], path[np] # ha! p = np return def check_version_conflict(self): if self.key == 'setuptools': # ignore the inevitable setuptools self-conflicts :( return nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt')) loc = normalize_path(self.location) for modname in self._get_metadata('top_level.txt'): if (modname not in sys.modules or modname in nsp or modname in _namespace_packages): continue if modname in ('pkg_resources', 'setuptools', 'site'): continue fn = getattr(sys.modules[modname], '__file__', None) if fn and (normalize_path(fn).startswith(loc) or fn.startswith(self.location)): continue issue_warning( "Module %s was already imported from %s, but %s is being added" " to sys.path" % (modname, fn, self.location), ) def has_version(self): try: self.version except ValueError: issue_warning("Unbuilt egg for " + repr(self)) return False return True def clone(self, **kw): """Copy this distribution, substituting in any changed keyword args""" names = 'project_name version py_version platform location precedence' for attr in names.split(): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provider) return self.__class__(**kw) def extras(self): return [dep for dep in self._dep_map if dep] The provided code snippet includes necessary dependencies for implementing the `_get_dist` function. Write a Python function `def _get_dist(metadata_directory)` to solve the following problem: Return a pkg_resources.Distribution for the provided metadata directory. Here is the function: def _get_dist(metadata_directory): # type: (str) -> Distribution """Return a pkg_resources.Distribution for the provided metadata directory. """ dist_dir = metadata_directory.rstrip(os.sep) # Build a PathMetadata object, from path to metadata. :wink: base_dir, dist_dir_name = os.path.split(dist_dir) metadata = pkg_resources.PathMetadata(base_dir, dist_dir) # Determine the correct Distribution object type. if dist_dir.endswith(".egg-info"): dist_cls = pkg_resources.Distribution dist_name = os.path.splitext(dist_dir_name)[0] else: assert dist_dir.endswith(".dist-info") dist_cls = pkg_resources.DistInfoDistribution dist_name = os.path.splitext(dist_dir_name)[0].split("-")[0] return dist_cls( base_dir, project_name=dist_name, metadata=metadata, )
Return a pkg_resources.Distribution for the provided metadata directory.
175,611
from __future__ import absolute_import import logging import os import shutil import sys import uuid import zipfile from pip._vendor import pkg_resources, six from pip._vendor.packaging.requirements import Requirement from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import Version from pip._vendor.packaging.version import parse as parse_version from pip._vendor.pep517.wrappers import Pep517HookCaller from pip._internal.build_env import NoOpBuildEnvironment from pip._internal.exceptions import InstallationError from pip._internal.locations import get_scheme from pip._internal.models.link import Link from pip._internal.operations.build.metadata import generate_metadata from pip._internal.operations.build.metadata_legacy import \ generate_metadata as generate_metadata_legacy from pip._internal.operations.install.editable_legacy import \ install_editable as install_editable_legacy from pip._internal.operations.install.legacy import LegacyInstallFailure from pip._internal.operations.install.legacy import install as install_legacy from pip._internal.operations.install.wheel import install_wheel from pip._internal.pyproject import load_pyproject_toml, make_pyproject_path from pip._internal.req.req_uninstall import UninstallPathSet from pip._internal.utils.deprecation import deprecated from pip._internal.utils.direct_url_helpers import direct_url_from_link from pip._internal.utils.hashes import Hashes from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( ask_path_exists, backup_dir, display_path, dist_in_site_packages, dist_in_usersite, get_distribution, get_installed_version, hide_url, redact_auth_from_url, ) from pip._internal.utils.packaging import get_metadata from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.virtualenv import running_under_virtualenv from pip._internal.vcs import vcs def deprecated(reason, replacement, gone_in, issue=None): # type: (str, Optional[str], Optional[str], Optional[int]) -> None """Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site. """ # Construct a nice message. # This is eagerly formatted as we want it to get logged as if someone # typed this entire message out. sentences = [ (reason, DEPRECATION_MSG_PREFIX + "{}"), (gone_in, "pip {} will remove support for this functionality."), (replacement, "A possible replacement is {}."), (issue, ( "You can find discussion regarding this at " "https://github.com/pypa/pip/issues/{}." )), ] message = " ".join( template.format(val) for val, template in sentences if val is not None ) # Raise as an error if it has to be removed. if gone_in is not None and parse(current_version) >= parse(gone_in): raise PipDeprecationWarning(message) warnings.warn(message, category=PipDeprecationWarning, stacklevel=2) def check_invalid_constraint_type(req): # type: (InstallRequirement) -> str # Check for unsupported forms problem = "" if not req.name: problem = "Unnamed requirements are not allowed as constraints" elif req.link: problem = "Links are not allowed as constraints" elif req.extras: problem = "Constraints cannot have extras" if problem: deprecated( reason=( "Constraints are only allowed to take the form of a package " "name and a version specifier. Other forms were originally " "permitted as an accident of the implementation, but were " "undocumented. The new implementation of the resolver no " "longer supports these forms." ), replacement=( "replacing the constraint with a requirement." ), # No plan yet for when the new resolver becomes default gone_in=None, issue=8210 ) return problem
null
175,612
import logging import os import re from pip._vendor.packaging.markers import Marker from pip._vendor.packaging.requirements import InvalidRequirement, Requirement from pip._vendor.packaging.specifiers import Specifier from pip._vendor.pkg_resources import RequirementParseError, parse_requirements from pip._internal.exceptions import InstallationError from pip._internal.models.index import PyPI, TestPyPI from pip._internal.models.link import Link from pip._internal.models.wheel import Wheel from pip._internal.pyproject import make_pyproject_path from pip._internal.req.req_install import InstallRequirement from pip._internal.utils.deprecation import deprecated from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import is_installable_dir, splitext from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url from pip._internal.vcs import is_url, vcs class InvalidRequirement(ValueError): """ An invalid requirement was found, users should refer to PEP 508. """ class Requirement(object): """Parse a requirement. Parse a given requirement string into its parts, such as name, specifier, URL, and extras. Raises InvalidRequirement on a badly-formed requirement string. """ # TODO: Can we test whether something is contained within a requirement? # If so how do we do that? Do we need to test against the _name_ of # the thing as well as the version? What about the markers? # TODO: Can we normalize the name and extra name? def __init__(self, requirement_string): # type: (str) -> None try: req = REQUIREMENT.parseString(requirement_string) except ParseException as e: raise InvalidRequirement( 'Parse error at "{0!r}": {1}'.format( requirement_string[e.loc : e.loc + 8], e.msg ) ) self.name = req.name if req.url: parsed_url = urlparse.urlparse(req.url) if parsed_url.scheme == "file": if urlparse.urlunparse(parsed_url) != req.url: raise InvalidRequirement("Invalid URL given") elif not (parsed_url.scheme and parsed_url.netloc) or ( not parsed_url.scheme and not parsed_url.netloc ): raise InvalidRequirement("Invalid URL: {0}".format(req.url)) self.url = req.url else: self.url = None self.extras = set(req.extras.asList() if req.extras else []) self.specifier = SpecifierSet(req.specifier) self.marker = req.marker if req.marker else None def __str__(self): # type: () -> str parts = [self.name] # type: List[str] if self.extras: parts.append("[{0}]".format(",".join(sorted(self.extras)))) if self.specifier: parts.append(str(self.specifier)) if self.url: parts.append("@ {0}".format(self.url)) if self.marker: parts.append(" ") if self.marker: parts.append("; {0}".format(self.marker)) return "".join(parts) def __repr__(self): # type: () -> str return "<Requirement({0!r})>".format(str(self)) class InstallationError(PipError): """General exception during installation""" PyPI = PackageIndex( 'https://pypi.org/', file_storage_domain='files.pythonhosted.org' ) TestPyPI = PackageIndex( 'https://test.pypi.org/', file_storage_domain='test-files.pythonhosted.org' ) class InstallRequirement(object): """ Represents something that may be installed later on, may have information about where to fetch the relevant requirement and also contains logic for installing the said requirement. """ def __init__( self, req, # type: Optional[Requirement] comes_from, # type: Optional[Union[str, InstallRequirement]] editable=False, # type: bool link=None, # type: Optional[Link] markers=None, # type: Optional[Marker] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool install_options=None, # type: Optional[List[str]] global_options=None, # type: Optional[List[str]] hash_options=None, # type: Optional[Dict[str, List[str]]] constraint=False, # type: bool extras=(), # type: Iterable[str] user_supplied=False, # type: bool ): # type: (...) -> None assert req is None or isinstance(req, Requirement), req self.req = req self.comes_from = comes_from self.constraint = constraint self.editable = editable self.legacy_install_reason = None # type: Optional[int] # source_dir is the local directory where the linked requirement is # located, or unpacked. In case unpacking is needed, creating and # populating source_dir is done by the RequirementPreparer. Note this # is not necessarily the directory where pyproject.toml or setup.py is # located - that one is obtained via unpacked_source_directory. self.source_dir = None # type: Optional[str] if self.editable: assert link if link.is_file: self.source_dir = os.path.normpath( os.path.abspath(link.file_path) ) if link is None and req and req.url: # PEP 508 URL requirement link = Link(req.url) self.link = self.original_link = link self.original_link_is_in_wheel_cache = False # Path to any downloaded or already-existing package. self.local_file_path = None # type: Optional[str] if self.link and self.link.is_file: self.local_file_path = self.link.file_path if extras: self.extras = extras elif req: self.extras = { pkg_resources.safe_extra(extra) for extra in req.extras } else: self.extras = set() if markers is None and req: markers = req.marker self.markers = markers # This holds the pkg_resources.Distribution object if this requirement # is already available: self.satisfied_by = None # type: Optional[Distribution] # Whether the installation process should try to uninstall an existing # distribution before installing this requirement. self.should_reinstall = False # Temporary build location self._temp_build_dir = None # type: Optional[TempDirectory] # Set to True after successful installation self.install_succeeded = None # type: Optional[bool] # Supplied options self.install_options = install_options if install_options else [] self.global_options = global_options if global_options else [] self.hash_options = hash_options if hash_options else {} # Set to True after successful preparation of this requirement self.prepared = False # User supplied requirement are explicitly requested for installation # by the user via CLI arguments or requirements files, as opposed to, # e.g. dependencies, extras or constraints. self.user_supplied = user_supplied # Set by the legacy resolver when the requirement has been downloaded # TODO: This introduces a strong coupling between the resolver and the # requirement (the coupling was previously between the resolver # and the requirement set). This should be refactored to allow # the requirement to decide for itself when it has been # successfully downloaded - but that is more tricky to get right, # se we are making the change in stages. self.successfully_downloaded = False self.isolated = isolated self.build_env = NoOpBuildEnvironment() # type: BuildEnvironment # For PEP 517, the directory where we request the project metadata # gets stored. We need this to pass to build_wheel, so the backend # can ensure that the wheel matches the metadata (see the PEP for # details). self.metadata_directory = None # type: Optional[str] # The static build requirements (from pyproject.toml) self.pyproject_requires = None # type: Optional[List[str]] # Build requirements that we will check are available self.requirements_to_check = [] # type: List[str] # The PEP 517 backend we should use to build the project self.pep517_backend = None # type: Optional[Pep517HookCaller] # Are we using PEP 517 for this requirement? # After pyproject.toml has been loaded, the only valid values are True # and False. Before loading, None is valid (meaning "use the default"). # Setting an explicit value before loading pyproject.toml is supported, # but after loading this flag should be treated as read only. self.use_pep517 = use_pep517 def __str__(self): # type: () -> str if self.req: s = str(self.req) if self.link: s += ' from {}'.format(redact_auth_from_url(self.link.url)) elif self.link: s = redact_auth_from_url(self.link.url) else: s = '<InstallRequirement>' if self.satisfied_by is not None: s += ' in {}'.format(display_path(self.satisfied_by.location)) if self.comes_from: if isinstance(self.comes_from, six.string_types): comes_from = self.comes_from # type: Optional[str] else: comes_from = self.comes_from.from_path() if comes_from: s += ' (from {})'.format(comes_from) return s def __repr__(self): # type: () -> str return '<{} object: {} editable={!r}>'.format( self.__class__.__name__, str(self), self.editable) def format_debug(self): # type: () -> str """An un-tested helper for getting state, for debugging. """ attributes = vars(self) names = sorted(attributes) state = ( "{}={!r}".format(attr, attributes[attr]) for attr in sorted(names) ) return '<{name} object: {{{state}}}>'.format( name=self.__class__.__name__, state=", ".join(state), ) # Things that are valid for all kinds of requirements? def name(self): # type: () -> Optional[str] if self.req is None: return None return six.ensure_str(pkg_resources.safe_name(self.req.name)) def specifier(self): # type: () -> SpecifierSet return self.req.specifier def is_pinned(self): # type: () -> bool """Return whether I am pinned to an exact version. For example, some-package==1.2 is pinned; some-package>1.2 is not. """ specifiers = self.specifier return (len(specifiers) == 1 and next(iter(specifiers)).operator in {'==', '==='}) def installed_version(self): # type: () -> Optional[str] return get_installed_version(self.name) def match_markers(self, extras_requested=None): # type: (Optional[Iterable[str]]) -> bool if not extras_requested: # Provide an extra to safely evaluate the markers # without matching any extra extras_requested = ('',) if self.markers is not None: return any( self.markers.evaluate({'extra': extra}) for extra in extras_requested) else: return True def has_hash_options(self): # type: () -> bool """Return whether any known-good hashes are specified as options. These activate --require-hashes mode; hashes specified as part of a URL do not. """ return bool(self.hash_options) def hashes(self, trust_internet=True): # type: (bool) -> Hashes """Return a hash-comparer that considers my option- and URL-based hashes to be known-good. Hashes in URLs--ones embedded in the requirements file, not ones downloaded from an index server--are almost peers with ones from flags. They satisfy --require-hashes (whether it was implicitly or explicitly activated) but do not activate it. md5 and sha224 are not allowed in flags, which should nudge people toward good algos. We always OR all hashes together, even ones from URLs. :param trust_internet: Whether to trust URL-based (#md5=...) hashes downloaded from the internet, as by populate_link() """ good_hashes = self.hash_options.copy() link = self.link if trust_internet else self.original_link if link and link.hash: good_hashes.setdefault(link.hash_name, []).append(link.hash) return Hashes(good_hashes) def from_path(self): # type: () -> Optional[str] """Format a nice indicator to show where this "comes from" """ if self.req is None: return None s = str(self.req) if self.comes_from: if isinstance(self.comes_from, six.string_types): comes_from = self.comes_from else: comes_from = self.comes_from.from_path() if comes_from: s += '->' + comes_from return s def ensure_build_location(self, build_dir, autodelete, parallel_builds): # type: (str, bool, 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 # When parallel builds are enabled, add a UUID to the build directory # name so multiple builds do not interfere with each other. dir_name = canonicalize_name(self.name) if parallel_builds: dir_name = "{}_{}".format(dir_name, uuid.uuid4().hex) # 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, 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 def _set_requirement(self): # type: () -> None """Set requirement after generating metadata. """ assert self.req is None assert self.metadata is not None assert self.source_dir is not None # Construct a Requirement object from the generated metadata if isinstance(parse_version(self.metadata["Version"]), Version): op = "==" else: op = "===" self.req = Requirement( "".join([ self.metadata["Name"], op, self.metadata["Version"], ]) ) def warn_on_mismatching_name(self): # type: () -> None metadata_name = canonicalize_name(self.metadata["Name"]) if canonicalize_name(self.req.name) == metadata_name: # Everything is fine. return # If we're here, there's a mismatch. Log a warning about it. logger.warning( 'Generating metadata for package %s ' 'produced metadata for project name %s. Fix your ' '#egg=%s fragments.', self.name, metadata_name, self.name ) self.req = Requirement(metadata_name) def check_if_exists(self, use_user_site): # type: (bool) -> None """Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.should_reinstall appropriately. """ if self.req is None: return existing_dist = get_distribution(self.req.name) if not existing_dist: return existing_version = existing_dist.parsed_version if not self.req.specifier.contains(existing_version, prereleases=True): self.satisfied_by = None if use_user_site: if dist_in_usersite(existing_dist): self.should_reinstall = True elif (running_under_virtualenv() and dist_in_site_packages(existing_dist)): raise InstallationError( "Will not install to the user site because it will " "lack sys.path precedence to {} in {}".format( existing_dist.project_name, existing_dist.location) ) else: self.should_reinstall = True else: if self.editable: self.should_reinstall = True # when installing editables, nothing pre-existing should ever # satisfy self.satisfied_by = None else: self.satisfied_by = existing_dist # Things valid for wheels def is_wheel(self): # type: () -> bool if not self.link: return False return self.link.is_wheel # Things valid for sdists def unpacked_source_directory(self): # type: () -> str return os.path.join( self.source_dir, self.link and self.link.subdirectory_fragment or '') def setup_py_path(self): # type: () -> str assert self.source_dir, "No source dir for {}".format(self) setup_py = os.path.join(self.unpacked_source_directory, 'setup.py') # Python2 __file__ should not be unicode if six.PY2 and isinstance(setup_py, six.text_type): setup_py = setup_py.encode(sys.getfilesystemencoding()) return setup_py def pyproject_toml_path(self): # type: () -> str assert self.source_dir, "No source dir for {}".format(self) return make_pyproject_path(self.unpacked_source_directory) def load_pyproject_toml(self): # type: () -> None """Load the pyproject.toml file. After calling this routine, all of the attributes related to PEP 517 processing for this requirement have been set. In particular, the use_pep517 attribute can be used to determine whether we should follow the PEP 517 or legacy (setup.py) code path. """ pyproject_toml_data = load_pyproject_toml( self.use_pep517, self.pyproject_toml_path, self.setup_py_path, str(self) ) if pyproject_toml_data is None: self.use_pep517 = False return self.use_pep517 = True requires, backend, check, backend_path = pyproject_toml_data self.requirements_to_check = check self.pyproject_requires = requires self.pep517_backend = Pep517HookCaller( self.unpacked_source_directory, backend, backend_path=backend_path, ) def _generate_metadata(self): # type: () -> str """Invokes metadata generator functions, with the required arguments. """ if not self.use_pep517: assert self.unpacked_source_directory return generate_metadata_legacy( build_env=self.build_env, setup_py_path=self.setup_py_path, source_dir=self.unpacked_source_directory, isolated=self.isolated, details=self.name or "from {}".format(self.link) ) assert self.pep517_backend is not None return generate_metadata( build_env=self.build_env, backend=self.pep517_backend, ) def prepare_metadata(self): # type: () -> None """Ensure that project metadata is available. Under PEP 517, call the backend hook to prepare the metadata. Under legacy processing, call setup.py egg-info. """ assert self.source_dir with indent_log(): self.metadata_directory = self._generate_metadata() # Act on the newly generated metadata, based on the name and version. if not self.name: self._set_requirement() else: self.warn_on_mismatching_name() self.assert_source_matches_version() def metadata(self): # type: () -> Any if not hasattr(self, '_metadata'): self._metadata = get_metadata(self.get_dist()) return self._metadata def get_dist(self): # type: () -> Distribution return _get_dist(self.metadata_directory) def assert_source_matches_version(self): # type: () -> None assert self.source_dir version = self.metadata['version'] if self.req.specifier and version not in self.req.specifier: logger.warning( 'Requested %s, but installing version %s', self, version, ) else: logger.debug( 'Source in %s has version %s, which satisfies requirement %s', display_path(self.source_dir), version, self, ) # For both source distributions and editables def ensure_has_source_dir( self, parent_dir, autodelete=False, parallel_builds=False, ): # type: (str, bool, bool) -> None """Ensure that a source_dir is set. This will create a temporary build dir if the name of the requirement isn't known yet. :param parent_dir: The ideal pip parent_dir for the source_dir. Generally src_dir for editables and build_dir for sdists. :return: self.source_dir """ if self.source_dir is None: self.source_dir = self.ensure_build_location( parent_dir, autodelete=autodelete, parallel_builds=parallel_builds, ) # For editable installations def update_editable(self, obtain=True): # type: (bool) -> None if not self.link: logger.debug( "Cannot update repository at %s; repository location is " "unknown", self.source_dir, ) return assert self.editable assert self.source_dir if self.link.scheme == 'file': # Static paths don't get updated return assert '+' in self.link.url, \ "bad url: {self.link.url!r}".format(**locals()) vc_type, url = self.link.url.split('+', 1) vcs_backend = vcs.get_backend(vc_type) if vcs_backend: if not self.link.is_vcs: reason = ( "This form of VCS requirement is being deprecated: {}." ).format( self.link.url ) replacement = None if self.link.url.startswith("git+git@"): replacement = ( "git+https://git@example.com/..., " "git+ssh://git@example.com/..., " "or the insecure git+git://git@example.com/..." ) deprecated(reason, replacement, gone_in="21.0", issue=7554) hidden_url = hide_url(self.link.url) if obtain: vcs_backend.obtain(self.source_dir, url=hidden_url) else: vcs_backend.export(self.source_dir, url=hidden_url) else: assert 0, ( 'Unexpected version control type (in {}): {}'.format( self.link, vc_type)) # Top-level Actions def uninstall(self, auto_confirm=False, verbose=False): # type: (bool, bool) -> Optional[UninstallPathSet] """ Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virtual environment, even if the virtualenv is linked to global site-packages. """ assert self.req dist = get_distribution(self.req.name) if not dist: logger.warning("Skipping %s as it is not installed.", self.name) return None logger.info('Found existing installation: %s', dist) uninstalled_pathset = UninstallPathSet.from_dist(dist) uninstalled_pathset.remove(auto_confirm, verbose) return uninstalled_pathset def _get_archive_name(self, path, parentdir, rootdir): # type: (str, str, str) -> str def _clean_zip_name(name, prefix): # type: (str, str) -> str assert name.startswith(prefix + os.path.sep), ( "name {name!r} doesn't start with prefix {prefix!r}" .format(**locals()) ) name = name[len(prefix) + 1:] name = name.replace(os.path.sep, '/') return name path = os.path.join(parentdir, path) name = _clean_zip_name(path, rootdir) return self.name + '/' + name def archive(self, build_dir): # type: (str) -> None """Saves archive to provided build_dir. Used for saving downloaded VCS requirements as part of `pip download`. """ assert self.source_dir create_archive = True archive_name = '{}-{}.zip'.format(self.name, self.metadata["version"]) archive_path = os.path.join(build_dir, archive_name) if os.path.exists(archive_path): response = ask_path_exists( 'The file {} exists. (i)gnore, (w)ipe, ' '(b)ackup, (a)bort '.format( display_path(archive_path)), ('i', 'w', 'b', 'a')) if response == 'i': create_archive = False elif response == 'w': logger.warning('Deleting %s', display_path(archive_path)) os.remove(archive_path) elif response == 'b': dest_file = backup_dir(archive_path) logger.warning( 'Backing up %s to %s', display_path(archive_path), display_path(dest_file), ) shutil.move(archive_path, dest_file) elif response == 'a': sys.exit(-1) if not create_archive: return zip_output = zipfile.ZipFile( archive_path, 'w', zipfile.ZIP_DEFLATED, allowZip64=True, ) with zip_output: dir = os.path.normcase( os.path.abspath(self.unpacked_source_directory) ) for dirpath, dirnames, filenames in os.walk(dir): for dirname in dirnames: dir_arcname = self._get_archive_name( dirname, parentdir=dirpath, rootdir=dir, ) zipdir = zipfile.ZipInfo(dir_arcname + '/') zipdir.external_attr = 0x1ED << 16 # 0o755 zip_output.writestr(zipdir, '') for filename in filenames: file_arcname = self._get_archive_name( filename, parentdir=dirpath, rootdir=dir, ) filename = os.path.join(dirpath, filename) zip_output.write(filename, file_arcname) logger.info('Saved %s', display_path(archive_path)) def install( self, install_options, # type: List[str] global_options=None, # type: Optional[Sequence[str]] root=None, # type: Optional[str] home=None, # type: Optional[str] prefix=None, # type: Optional[str] warn_script_location=True, # type: bool use_user_site=False, # type: bool pycompile=True # type: bool ): # type: (...) -> None scheme = get_scheme( self.name, user=use_user_site, home=home, root=root, isolated=self.isolated, prefix=prefix, ) global_options = global_options if global_options is not None else [] if self.editable: install_editable_legacy( install_options, global_options, prefix=prefix, home=home, use_user_site=use_user_site, name=self.name, setup_py_path=self.setup_py_path, isolated=self.isolated, build_env=self.build_env, unpacked_source_directory=self.unpacked_source_directory, ) self.install_succeeded = True return if self.is_wheel: assert self.local_file_path direct_url = None if self.original_link: direct_url = direct_url_from_link( self.original_link, self.source_dir, self.original_link_is_in_wheel_cache, ) install_wheel( self.name, self.local_file_path, scheme=scheme, req_description=str(self.req), pycompile=pycompile, warn_script_location=warn_script_location, direct_url=direct_url, requested=self.user_supplied, ) self.install_succeeded = True return # TODO: Why don't we do this for editable installs? # Extend the list of global and install options passed on to # the setup.py call with the ones from the requirements file. # Options specified in requirements file override those # specified on the command line, since the last option given # to setup.py is the one that is used. global_options = list(global_options) + self.global_options install_options = list(install_options) + self.install_options try: success = install_legacy( install_options=install_options, global_options=global_options, root=root, home=home, prefix=prefix, use_user_site=use_user_site, pycompile=pycompile, scheme=scheme, setup_py_path=self.setup_py_path, isolated=self.isolated, req_name=self.name, build_env=self.build_env, unpacked_source_directory=self.unpacked_source_directory, req_description=str(self.req), ) except LegacyInstallFailure as exc: self.install_succeeded = False six.reraise(*exc.parent) except Exception: self.install_succeeded = True raise self.install_succeeded = success if success and self.legacy_install_reason == 8368: deprecated( reason=( "{} was installed using the legacy 'setup.py install' " "method, because a wheel could not be built for it.". format(self.name) ), replacement="to fix the wheel build issue reported above", gone_in="21.0", issue=8368, ) def install_req_from_req_string( req_string, # type: str comes_from=None, # type: Optional[InstallRequirement] isolated=False, # type: bool use_pep517=None, # type: Optional[bool] user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement try: req = Requirement(req_string) except InvalidRequirement: raise InstallationError("Invalid requirement: '{}'".format(req_string)) domains_not_allowed = [ PyPI.file_storage_domain, TestPyPI.file_storage_domain, ] if (req.url and comes_from and comes_from.link and comes_from.link.netloc in domains_not_allowed): # Explicitly disallow pypi packages that depend on external urls raise InstallationError( "Packages installed from PyPI cannot depend on packages " "which are not also hosted on PyPI.\n" "{} depends on {} ".format(comes_from.name, req) ) return InstallRequirement( req, comes_from, isolated=isolated, use_pep517=use_pep517, user_supplied=user_supplied, )
null
175,613
import logging import os import re from pip._vendor.packaging.markers import Marker from pip._vendor.packaging.requirements import InvalidRequirement, Requirement from pip._vendor.packaging.specifiers import Specifier from pip._vendor.pkg_resources import RequirementParseError, parse_requirements from pip._internal.exceptions import InstallationError from pip._internal.models.index import PyPI, TestPyPI from pip._internal.models.link import Link from pip._internal.models.wheel import Wheel from pip._internal.pyproject import make_pyproject_path from pip._internal.req.req_install import InstallRequirement from pip._internal.utils.deprecation import deprecated from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import is_installable_dir, splitext from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url from pip._internal.vcs import is_url, vcs def install_req_from_editable( editable_req, # type: str comes_from=None, # type: Optional[Union[InstallRequirement, str]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement parts = parse_req_from_editable(editable_req) return InstallRequirement( parts.requirement, comes_from=comes_from, user_supplied=user_supplied, editable=True, link=parts.link, constraint=constraint, use_pep517=use_pep517, isolated=isolated, install_options=options.get("install_options", []) if options else [], global_options=options.get("global_options", []) if options else [], hash_options=options.get("hashes", {}) if options else {}, extras=parts.extras, ) def install_req_from_line( name, # type: str comes_from=None, # type: Optional[Union[str, InstallRequirement]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool line_source=None, # type: Optional[str] user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. :param line_source: An optional string describing where the line is from, for logging purposes in case of an error. """ parts = parse_req_from_line(name, line_source) return InstallRequirement( parts.requirement, comes_from, link=parts.link, markers=parts.markers, use_pep517=use_pep517, isolated=isolated, install_options=options.get("install_options", []) if options else [], global_options=options.get("global_options", []) if options else [], hash_options=options.get("hashes", {}) if options else {}, constraint=constraint, extras=parts.extras, user_supplied=user_supplied, ) def install_req_from_parsed_requirement( parsed_req, # type: ParsedRequirement isolated=False, # type: bool use_pep517=None, # type: Optional[bool] user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement if parsed_req.is_editable: req = install_req_from_editable( parsed_req.requirement, comes_from=parsed_req.comes_from, use_pep517=use_pep517, constraint=parsed_req.constraint, isolated=isolated, user_supplied=user_supplied, ) else: req = install_req_from_line( parsed_req.requirement, comes_from=parsed_req.comes_from, use_pep517=use_pep517, isolated=isolated, options=parsed_req.options, constraint=parsed_req.constraint, line_source=parsed_req.line_source, user_supplied=user_supplied, ) return req
null
175,614
from __future__ import absolute_import import csv import functools import logging import os import sys import sysconfig from pip._vendor import pkg_resources from pip._internal.exceptions import UninstallationError from pip._internal.locations import bin_py, bin_user from pip._internal.utils.compat import WINDOWS, cache_from_source, uses_pycache from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( FakeFile, ask, dist_in_usersite, dist_is_local, egg_link_path, is_local, normalize_path, renames, rmtree, ) from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING WINDOWS = (sys.platform.startswith("win") or (sys.platform == 'cli' and os.name == 'nt')) def dist_in_usersite(dist): # type: (Distribution) -> bool """ Return True if given Distribution is installed in user site. """ return dist_location(dist).startswith(normalize_path(user_site)) The provided code snippet includes necessary dependencies for implementing the `_script_names` function. Write a Python function `def _script_names(dist, script_name, is_gui)` to solve the following problem: Create the fully qualified name of the files created by {console,gui}_scripts for the given ``dist``. Returns the list of file names Here is the function: def _script_names(dist, script_name, is_gui): # type: (Distribution, str, bool) -> List[str] """Create the fully qualified name of the files created by {console,gui}_scripts for the given ``dist``. Returns the list of file names """ if dist_in_usersite(dist): bin_dir = bin_user else: bin_dir = bin_py exe_name = os.path.join(bin_dir, script_name) paths_to_remove = [exe_name] if WINDOWS: paths_to_remove.append(exe_name + '.exe') paths_to_remove.append(exe_name + '.exe.manifest') if is_gui: paths_to_remove.append(exe_name + '-script.pyw') else: paths_to_remove.append(exe_name + '-script.py') return paths_to_remove
Create the fully qualified name of the files created by {console,gui}_scripts for the given ``dist``. Returns the list of file names
175,615
from __future__ import absolute_import import csv import functools import logging import os import sys import sysconfig from pip._vendor import pkg_resources from pip._internal.exceptions import UninstallationError from pip._internal.locations import bin_py, bin_user from pip._internal.utils.compat import WINDOWS, cache_from_source, uses_pycache from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( FakeFile, ask, dist_in_usersite, dist_is_local, egg_link_path, is_local, normalize_path, renames, rmtree, ) from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING def _unique(fn): # type: (Callable[..., Iterator[Any]]) -> Callable[..., Iterator[Any]] @functools.wraps(fn) def unique(*args, **kw): # type: (Any, Any) -> Iterator[Any] seen = set() # type: Set[Any] for item in fn(*args, **kw): if item not in seen: seen.add(item) yield item return unique
null
175,616
from __future__ import absolute_import import csv import functools import logging import os import sys import sysconfig from pip._vendor import pkg_resources from pip._internal.exceptions import UninstallationError from pip._internal.locations import bin_py, bin_user from pip._internal.utils.compat import WINDOWS, cache_from_source, uses_pycache from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( FakeFile, ask, dist_in_usersite, dist_is_local, egg_link_path, is_local, normalize_path, renames, rmtree, ) from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING class FakeFile(object): """Wrap a list of lines in an object with readline() to make ConfigParser happy.""" def __init__(self, lines): self._gen = iter(lines) def readline(self): try: return next(self._gen) except StopIteration: return '' def __iter__(self): return self._gen The provided code snippet includes necessary dependencies for implementing the `uninstallation_paths` function. Write a Python function `def uninstallation_paths(dist)` to solve the following problem: Yield all the uninstallation paths for dist based on RECORD-without-.py[co] Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc and .pyo in the same directory. UninstallPathSet.add() takes care of the __pycache__ .py[co]. Here is the function: def uninstallation_paths(dist): # type: (Distribution) -> Iterator[str] """ Yield all the uninstallation paths for dist based on RECORD-without-.py[co] Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc and .pyo in the same directory. UninstallPathSet.add() takes care of the __pycache__ .py[co]. """ r = csv.reader(FakeFile(dist.get_metadata_lines('RECORD'))) for row in r: path = os.path.join(dist.location, row[0]) yield path if path.endswith('.py'): dn, fn = os.path.split(path) base = fn[:-3] path = os.path.join(dn, base + '.pyc') yield path path = os.path.join(dn, base + '.pyo') yield path
Yield all the uninstallation paths for dist based on RECORD-without-.py[co] Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc and .pyo in the same directory. UninstallPathSet.add() takes care of the __pycache__ .py[co].
175,617
from __future__ import absolute_import import csv import functools import logging import os import sys import sysconfig from pip._vendor import pkg_resources from pip._internal.exceptions import UninstallationError from pip._internal.locations import bin_py, bin_user from pip._internal.utils.compat import WINDOWS, cache_from_source, uses_pycache from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( FakeFile, ask, dist_in_usersite, dist_is_local, egg_link_path, is_local, normalize_path, renames, rmtree, ) from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING The provided code snippet includes necessary dependencies for implementing the `compress_for_rename` function. Write a Python function `def compress_for_rename(paths)` to solve the following problem: Returns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk. Here is the function: def compress_for_rename(paths): # type: (Iterable[str]) -> Set[str] """Returns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk. """ case_map = dict((os.path.normcase(p), p) for p in paths) remaining = set(case_map) unchecked = sorted(set(os.path.split(p)[0] for p in case_map.values()), key=len) wildcards = set() # type: Set[str] def norm_join(*a): # type: (str) -> str return os.path.normcase(os.path.join(*a)) for root in unchecked: if any(os.path.normcase(root).startswith(w) for w in wildcards): # This directory has already been handled. continue all_files = set() # type: Set[str] all_subdirs = set() # type: Set[str] for dirname, subdirs, files in os.walk(root): all_subdirs.update(norm_join(root, dirname, d) for d in subdirs) all_files.update(norm_join(root, dirname, f) for f in files) # If all the files we found are in our remaining set of files to # remove, then remove them from the latter set and add a wildcard # for the directory. if not (all_files - remaining): remaining.difference_update(all_files) wildcards.add(root + os.sep) return set(map(case_map.__getitem__, remaining)) | wildcards
Returns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk.
175,618
from __future__ import absolute_import import csv import functools import logging import os import sys import sysconfig from pip._vendor import pkg_resources from pip._internal.exceptions import UninstallationError from pip._internal.locations import bin_py, bin_user from pip._internal.utils.compat import WINDOWS, cache_from_source, uses_pycache from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( FakeFile, ask, dist_in_usersite, dist_is_local, egg_link_path, is_local, normalize_path, renames, rmtree, ) from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING def compact(paths): # type: (Iterable[str]) -> Set[str] """Compact a path set to contain the minimal number of paths necessary to contain all paths in the set. If /a/path/ and /a/path/to/a/file.txt are both in the set, leave only the shorter path.""" sep = os.path.sep short_paths = set() # type: Set[str] for path in sorted(paths, key=len): should_skip = any( path.startswith(shortpath.rstrip("*")) and path[len(shortpath.rstrip("*").rstrip(sep))] == sep for shortpath in short_paths ) if not should_skip: short_paths.add(path) return short_paths The provided code snippet includes necessary dependencies for implementing the `compress_for_output_listing` function. Write a Python function `def compress_for_output_listing(paths)` to solve the following problem: Returns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders. Here is the function: def compress_for_output_listing(paths): # type: (Iterable[str]) -> Tuple[Set[str], Set[str]] """Returns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders. """ will_remove = set(paths) will_skip = set() # Determine folders and files folders = set() files = set() for path in will_remove: if path.endswith(".pyc"): continue if path.endswith("__init__.py") or ".dist-info" in path: folders.add(os.path.dirname(path)) files.add(path) # probably this one https://github.com/python/mypy/issues/390 _normcased_files = set(map(os.path.normcase, files)) # type: ignore folders = compact(folders) # This walks the tree using os.walk to not miss extra folders # that might get added. for folder in folders: for dirpath, _, dirfiles in os.walk(folder): for fname in dirfiles: if fname.endswith(".pyc"): continue file_ = os.path.join(dirpath, fname) if (os.path.isfile(file_) and os.path.normcase(file_) not in _normcased_files): # We are skipping this file. Add it to the set. will_skip.add(file_) will_remove = files | { os.path.join(folder, "*") for folder in folders } return will_remove, will_skip
Returns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders.
175,619
from __future__ import absolute_import import contextlib import errno import hashlib import logging import os from pip._vendor import contextlib2 from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) def update_env_context_manager(**changes): # type: (str) -> Iterator[None] target = os.environ # Save values from the target and change them. non_existent_marker = object() saved_values = {} # type: Dict[str, Union[object, str]] for name, new_value in changes.items(): try: saved_values[name] = target[name] except KeyError: saved_values[name] = non_existent_marker target[name] = new_value try: yield finally: # Restore original values in the target. for name, original_value in saved_values.items(): if original_value is non_existent_marker: del target[name] else: assert isinstance(original_value, str) # for mypy target[name] = original_value class RequirementTracker(object): def __init__(self, root): # type: (str) -> None self._root = root self._entries = set() # type: Set[InstallRequirement] logger.debug("Created build tracker: %s", self._root) def __enter__(self): # type: () -> RequirementTracker logger.debug("Entered build tracker: %s", self._root) return self def __exit__( self, exc_type, # type: Optional[Type[BaseException]] exc_val, # type: Optional[BaseException] exc_tb # type: Optional[TracebackType] ): # type: (...) -> None self.cleanup() def _entry_path(self, link): # type: (Link) -> str hashed = hashlib.sha224(link.url_without_fragment.encode()).hexdigest() return os.path.join(self._root, hashed) def add(self, req): # type: (InstallRequirement) -> None """Add an InstallRequirement to build tracking. """ assert req.link # Get the file to write information about this requirement. entry_path = self._entry_path(req.link) # Try reading from the file. If it exists and can be read from, a build # is already in progress, so a LookupError is raised. try: with open(entry_path) as fp: contents = fp.read() except IOError as e: # if the error is anything other than "file does not exist", raise. if e.errno != errno.ENOENT: raise else: message = '{} is already being built: {}'.format( req.link, contents) raise LookupError(message) # If we're here, req should really not be building already. assert req not in self._entries # Start tracking this requirement. with open(entry_path, 'w') as fp: fp.write(str(req)) self._entries.add(req) logger.debug('Added %s to build tracker %r', req, self._root) def remove(self, req): # type: (InstallRequirement) -> None """Remove an InstallRequirement from build tracking. """ assert req.link # Delete the created file and the corresponding entries. os.unlink(self._entry_path(req.link)) self._entries.remove(req) logger.debug('Removed %s from build tracker %r', req, self._root) def cleanup(self): # type: () -> None for req in set(self._entries): self.remove(req) logger.debug("Removed build tracker: %r", self._root) def track(self, req): # type: (InstallRequirement) -> Iterator[None] self.add(req) yield self.remove(req) class TempDirectory(object): """Helper class that owns and cleans up a temporary directory. This class can be used as a context manager or as an OO representation of a temporary directory. Attributes: path Location to the created temporary directory delete Whether the directory should be deleted when exiting (when used as a contextmanager) Methods: cleanup() Deletes the temporary directory When used as a context manager, if the delete attribute is True, on exiting the context the temporary directory is deleted. """ def __init__( self, path=None, # type: Optional[str] delete=_default, # type: Union[bool, None, _Default] kind="temp", # type: str globally_managed=False, # type: bool ): super(TempDirectory, self).__init__() if delete is _default: if path is not None: # If we were given an explicit directory, resolve delete option # now. delete = False else: # Otherwise, we wait until cleanup and see what # tempdir_registry says. delete = None if path is None: path = self._create(kind) self._path = path self._deleted = False self.delete = delete self.kind = kind if globally_managed: assert _tempdir_manager is not None _tempdir_manager.enter_context(self) def path(self): # type: () -> str assert not self._deleted, ( "Attempted to access deleted path: {}".format(self._path) ) return self._path def __repr__(self): # type: () -> str return "<{} {!r}>".format(self.__class__.__name__, self.path) def __enter__(self): # type: (_T) -> _T return self def __exit__(self, exc, value, tb): # type: (Any, Any, Any) -> None if self.delete is not None: delete = self.delete elif _tempdir_registry: delete = _tempdir_registry.get_delete(self.kind) else: delete = True if delete: self.cleanup() def _create(self, kind): # type: (str) -> str """Create a temporary directory and store its path in self.path """ # We realpath here because some systems have their default tmpdir # symlinked to another directory. This tends to confuse build # scripts, so we canonicalize the path by traversing potential # symlinks here. path = os.path.realpath( tempfile.mkdtemp(prefix="pip-{}-".format(kind)) ) logger.debug("Created temporary directory: %s", path) return path def cleanup(self): # type: () -> None """Remove the temporary directory created and reset state """ self._deleted = True if os.path.exists(self._path): # Make sure to pass unicode on Python 2 to make the contents also # use unicode, ensuring non-ASCII names and can be represented. rmtree(ensure_text(self._path)) 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
null
175,620
from __future__ import absolute_import import optparse import os import re import shlex import sys from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.cli import cmdoptions from pip._internal.exceptions import ( InstallationError, RequirementsFileParseError, ) from pip._internal.models.search_scope import SearchScope from pip._internal.network.utils import raise_for_status from pip._internal.utils.encoding import auto_decode from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import get_url_scheme def join_lines(lines_enum): # type: (ReqFileLines) -> ReqFileLines """Joins a line ending in '\' with the previous line (except when following comments). The joined line takes on the index of the first line. """ primary_line_number = None new_line = [] # type: List[Text] for line_number, line in lines_enum: if not line.endswith('\\') or COMMENT_RE.match(line): if COMMENT_RE.match(line): # this ensures comments are always matched later line = ' ' + line if new_line: new_line.append(line) assert primary_line_number is not None yield primary_line_number, ''.join(new_line) new_line = [] else: yield line_number, line else: if not new_line: primary_line_number = line_number new_line.append(line.strip('\\')) # last line contains \ if new_line: assert primary_line_number is not None yield primary_line_number, ''.join(new_line) # TODO: handle space after '\'. def ignore_comments(lines_enum): # type: (ReqFileLines) -> ReqFileLines """ Strips comments and filter empty lines. """ for line_number, line in lines_enum: line = COMMENT_RE.sub('', line) line = line.strip() if line: yield line_number, line def expand_env_variables(lines_enum): # type: (ReqFileLines) -> ReqFileLines """Replace all environment variables that can be retrieved via `os.getenv`. The only allowed format for environment variables defined in the requirement file is `${MY_VARIABLE_1}` to ensure two things: 1. Strings that contain a `$` aren't accidentally (partially) expanded. 2. Ensure consistency across platforms for requirement files. These points are the result of a discussion on the `github pull request #3514 <https://github.com/pypa/pip/pull/3514>`_. Valid characters in variable names follow the `POSIX standard <http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited to uppercase letter, digits and the `_` (underscore). """ for line_number, line in lines_enum: for env_var, var_name in ENV_VAR_RE.findall(line): value = os.getenv(var_name) if not value: continue line = line.replace(env_var, value) yield line_number, line The provided code snippet includes necessary dependencies for implementing the `preprocess` function. Write a Python function `def preprocess(content)` to solve the following problem: Split, filter, and join lines, and return a line iterator :param content: the content of the requirements file Here is the function: def preprocess(content): # type: (Text) -> ReqFileLines """Split, filter, and join lines, and return a line iterator :param content: the content of the requirements file """ lines_enum = enumerate(content.splitlines(), start=1) # type: ReqFileLines lines_enum = join_lines(lines_enum) lines_enum = ignore_comments(lines_enum) lines_enum = expand_env_variables(lines_enum) return lines_enum
Split, filter, and join lines, and return a line iterator :param content: the content of the requirements file
175,621
from __future__ import absolute_import import optparse import os import re import shlex import sys from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.cli import cmdoptions from pip._internal.exceptions import ( InstallationError, RequirementsFileParseError, ) from pip._internal.models.search_scope import SearchScope from pip._internal.network.utils import raise_for_status from pip._internal.utils.encoding import auto_decode from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import get_url_scheme _url_slash_drive_re = re.compile(r'/*([a-z])\|', re.I) class InstallationError(PipError): """General exception during installation""" def raise_for_status(resp): # type: (Response) -> None http_error_msg = u'' if isinstance(resp.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8, we fall back to iso-8859-1 for all other # encodings. try: reason = resp.reason.decode('utf-8') except UnicodeDecodeError: reason = resp.reason.decode('iso-8859-1') else: reason = resp.reason if 400 <= resp.status_code < 500: http_error_msg = u'%s Client Error: %s for url: %s' % ( resp.status_code, reason, resp.url) elif 500 <= resp.status_code < 600: http_error_msg = u'%s Server Error: %s for url: %s' % ( resp.status_code, reason, resp.url) if http_error_msg: raise NetworkConnectionError(http_error_msg, response=resp) def auto_decode(data): # type: (bytes) -> Text """Check a bytes string for a BOM to correctly detect the encoding Fallback to locale.getpreferredencoding(False) like open() on Python3""" for bom, encoding in BOMS: if data.startswith(bom): return data[len(bom):].decode(encoding) # Lets check the first two lines as in PEP263 for line in data.split(b'\n')[:2]: if line[0:1] == b'#' and ENCODING_RE.search(line): result = ENCODING_RE.search(line) assert result is not None encoding = result.groups()[0].decode('ascii') return data.decode(encoding) return data.decode( locale.getpreferredencoding(False) or sys.getdefaultencoding(), ) def get_url_scheme(url): # type: (Union[str, Text]) -> Optional[Text] if ':' not in url: return None return url.split(':', 1)[0].lower() The provided code snippet includes necessary dependencies for implementing the `get_file_content` function. Write a Python function `def get_file_content(url, session, comes_from=None)` to solve the following problem: Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode. Respects # -*- coding: declarations on the retrieved files. :param url: File path or url. :param session: PipSession instance. :param comes_from: Origin description of requirements. Here is the function: def get_file_content(url, session, comes_from=None): # type: (str, PipSession, Optional[str]) -> Tuple[str, Text] """Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode. Respects # -*- coding: declarations on the retrieved files. :param url: File path or url. :param session: PipSession instance. :param comes_from: Origin description of requirements. """ scheme = get_url_scheme(url) if scheme in ['http', 'https']: # FIXME: catch some errors resp = session.get(url) raise_for_status(resp) return resp.url, resp.text elif scheme == 'file': if comes_from and comes_from.startswith('http'): raise InstallationError( 'Requirements file {} references URL {}, ' 'which is local'.format(comes_from, url) ) path = url.split(':', 1)[1] path = path.replace('\\', '/') match = _url_slash_drive_re.match(path) if match: path = match.group(1) + ':' + path.split('|', 1)[1] path = urllib_parse.unquote(path) if path.startswith('/'): path = '/' + path.lstrip('/') url = path try: with open(url, 'rb') as f: content = auto_decode(f.read()) except IOError as exc: raise InstallationError( 'Could not open requirements file: {}'.format(exc) ) return url, content
Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode. Respects # -*- coding: declarations on the retrieved files. :param url: File path or url. :param session: PipSession instance. :param comes_from: Origin description of requirements.
175,622
import hashlib import json import logging import os from pip._vendor.packaging.tags import interpreter_name, interpreter_version from pip._vendor.packaging.utils import canonicalize_name from pip._internal.exceptions import InvalidWheelFilename from pip._internal.models.link import Link from pip._internal.models.wheel import Wheel from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url The provided code snippet includes necessary dependencies for implementing the `_hash_dict` function. Write a Python function `def _hash_dict(d)` to solve the following problem: Return a stable sha224 of a dictionary. Here is the function: def _hash_dict(d): # type: (Dict[str, str]) -> str """Return a stable sha224 of a dictionary.""" s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True) return hashlib.sha224(s.encode("ascii")).hexdigest()
Return a stable sha224 of a dictionary.
175,623
from __future__ import absolute_import import logging import optparse import sys import textwrap from distutils.util import strtobool from pip._vendor.six import string_types from pip._internal.cli.status_codes import UNKNOWN_ERROR from pip._internal.configuration import Configuration, ConfigurationError from pip._internal.utils.compat import get_terminal_size The provided code snippet includes necessary dependencies for implementing the `invalid_config_error_message` function. Write a Python function `def invalid_config_error_message(action, key, val)` to solve the following problem: Returns a better error message when invalid configuration option is provided. Here is the function: def invalid_config_error_message(action, key, val): """Returns a better error message when invalid configuration option is provided.""" if action in ('store_true', 'store_false'): return ("{0} is not a valid value for {1} option, " "please specify a boolean value like yes/no, " "true/false or 1/0 instead.").format(val, key) return ("{0} is not a valid value for {1} option, " "please specify a numerical value like 1/0 " "instead.").format(val, key)
Returns a better error message when invalid configuration option is provided.
175,624
import logging import os from functools import partial from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.cli.command_context import CommandContextMixIn from pip._internal.exceptions import CommandError, PreviousBuildDirError from pip._internal.index.collector import LinkCollector from pip._internal.index.package_finder import PackageFinder from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.network.download import Downloader from pip._internal.network.session import PipSession from pip._internal.operations.prepare import RequirementPreparer from pip._internal.req.constructors import ( install_req_from_editable, install_req_from_line, install_req_from_parsed_requirement, install_req_from_req_string, ) from pip._internal.req.req_file import parse_requirements from pip._internal.self_outdated_check import pip_self_version_check from pip._internal.utils.temp_dir import tempdir_kinds from pip._internal.utils.typing import MYPY_CHECK_RUNNING KEEPABLE_TEMPDIR_TYPES = [ tempdir_kinds.BUILD_ENV, tempdir_kinds.EPHEM_WHEEL_CACHE, tempdir_kinds.REQ_BUILD, ] class PreviousBuildDirError(PipError): """Raised when there's a previous conflicting build directory""" The provided code snippet includes necessary dependencies for implementing the `with_cleanup` function. Write a Python function `def with_cleanup(func)` to solve the following problem: Decorator for common logic related to managing temporary directories. Here is the function: def with_cleanup(func): # type: (Any) -> Any """Decorator for common logic related to managing temporary directories. """ def configure_tempdir_registry(registry): # type: (TempDirectoryTypeRegistry) -> None for t in KEEPABLE_TEMPDIR_TYPES: registry.set_delete(t, False) def wrapper(self, options, args): # type: (RequirementCommand, Values, List[Any]) -> Optional[int] assert self.tempdir_registry is not None if options.no_clean: configure_tempdir_registry(self.tempdir_registry) try: return func(self, options, args) except PreviousBuildDirError: # This kind of conflict can occur when the user passes an explicit # build directory with a pre-existing folder. In that case we do # not want to accidentally remove it. configure_tempdir_registry(self.tempdir_registry) raise return wrapper
Decorator for common logic related to managing temporary directories.
175,625
from __future__ import division import itertools import sys from signal import SIGINT, default_int_handler, signal from pip._vendor import six from pip._vendor.progress.bar import Bar, FillingCirclesBar, IncrementalBar from pip._vendor.progress.spinner import Spinner from pip._internal.utils.compat import WINDOWS from pip._internal.utils.logging import get_indentation from pip._internal.utils.misc import format_size from pip._internal.utils.typing import MYPY_CHECK_RUNNING def _select_progress_class(preferred, fallback): # type: (Bar, Bar) -> Bar encoding = getattr(preferred.file, "encoding", None) # If we don't know what encoding this file is in, then we'll just assume # that it doesn't support unicode and use the ASCII bar. if not encoding: return fallback # Collect all of the possible characters we want to use with the preferred # bar. characters = [ getattr(preferred, "empty_fill", six.text_type()), getattr(preferred, "fill", six.text_type()), ] characters += list(getattr(preferred, "phases", [])) # Try to decode the characters we're using for the bar using the encoding # of the given file, if this works then we'll assume that we can use the # fancier bar and if not we'll fall back to the plaintext bar. try: six.text_type().join(characters).encode(encoding) except UnicodeEncodeError: return fallback else: return preferred
null
175,626
import optparse import os import sys from itertools import chain from pip._internal.cli.main_parser import create_main_parser from pip._internal.commands import commands_dict, create_command from pip._internal.utils.misc import get_installed_distributions from pip._internal.utils.typing import MYPY_CHECK_RUNNING def get_path_completion_type(cwords, cword, opts): # type: (List[str], int, Iterable[Any]) -> Optional[str] """Get the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None) """ if cword < 2 or not cwords[cword - 2].startswith('-'): return None for opt in opts: if opt.help == optparse.SUPPRESS_HELP: continue for o in str(opt).split('/'): if cwords[cword - 2].split('=')[0] == o: if not opt.metavar or any( x in ('path', 'file', 'dir') for x in opt.metavar.split('/')): return opt.metavar return None def auto_complete_paths(current, completion_type): # type: (str, str) -> Iterable[str] """If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A generator of regular files and/or directories """ directory, filename = os.path.split(current) current_path = os.path.abspath(directory) # Don't complete paths if they can't be accessed if not os.access(current_path, os.R_OK): return filename = os.path.normcase(filename) # list all files that start with ``filename`` file_list = (x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)) for f in file_list: opt = os.path.join(current_path, f) comp_file = os.path.normcase(os.path.join(directory, f)) # complete regular files when there is not ``<dir>`` after option # complete directories when there is ``<file>``, ``<path>`` or # ``<dir>``after option if completion_type != 'dir' and os.path.isfile(opt): yield comp_file elif os.path.isdir(opt): yield os.path.join(comp_file, '') import sys assert "pydevd" in sys.modules class chain(Iterator[_T], Generic[_T]): def __init__(self, *iterables: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... def __iter__(self) -> Iterator[_T]: ... def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... def create_main_parser(): # type: () -> ConfigOptionParser """Creates and returns the main parser for pip's CLI """ parser_kw = { 'usage': '\n%prog <command> [options]', 'add_help_option': False, 'formatter': UpdatingDefaultsHelpFormatter(), 'name': 'global', 'prog': get_prog(), } parser = ConfigOptionParser(**parser_kw) parser.disable_interspersed_args() parser.version = get_pip_version() # add the general options gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser) parser.add_option_group(gen_opts) # so the help formatter knows parser.main = True # type: ignore # create command listing for description description = [''] + [ '{name:27} {command_info.summary}'.format(**locals()) for name, command_info in commands_dict.items() ] parser.description = '\n'.join(description) return parser commands_dict = OrderedDict([ ('install', CommandInfo( 'pip._internal.commands.install', 'InstallCommand', 'Install packages.', )), ('download', CommandInfo( 'pip._internal.commands.download', 'DownloadCommand', 'Download packages.', )), ('uninstall', CommandInfo( 'pip._internal.commands.uninstall', 'UninstallCommand', 'Uninstall packages.', )), ('freeze', CommandInfo( 'pip._internal.commands.freeze', 'FreezeCommand', 'Output installed packages in requirements format.', )), ('list', CommandInfo( 'pip._internal.commands.list', 'ListCommand', 'List installed packages.', )), ('show', CommandInfo( 'pip._internal.commands.show', 'ShowCommand', 'Show information about installed packages.', )), ('check', CommandInfo( 'pip._internal.commands.check', 'CheckCommand', 'Verify installed packages have compatible dependencies.', )), ('config', CommandInfo( 'pip._internal.commands.configuration', 'ConfigurationCommand', 'Manage local and global configuration.', )), ('search', CommandInfo( 'pip._internal.commands.search', 'SearchCommand', 'Search PyPI for packages.', )), ('cache', CommandInfo( 'pip._internal.commands.cache', 'CacheCommand', "Inspect and manage pip's wheel cache.", )), ('wheel', CommandInfo( 'pip._internal.commands.wheel', 'WheelCommand', 'Build wheels from your requirements.', )), ('hash', CommandInfo( 'pip._internal.commands.hash', 'HashCommand', 'Compute hashes of package archives.', )), ('completion', CommandInfo( 'pip._internal.commands.completion', 'CompletionCommand', 'A helper command used for command completion.', )), ('debug', CommandInfo( 'pip._internal.commands.debug', 'DebugCommand', 'Show information useful for debugging.', )), ('help', CommandInfo( 'pip._internal.commands.help', 'HelpCommand', 'Show help for commands.', )), ]) def create_command(name, **kwargs): # type: (str, **Any) -> Command """ Create an instance of the Command class with the given name. """ module_path, class_name, summary = commands_dict[name] module = importlib.import_module(module_path) command_class = getattr(module, class_name) command = command_class(name=name, summary=summary, **kwargs) return command def get_installed_distributions( local_only=True, # type: bool skip=stdlib_pkgs, # type: Container[str] include_editables=True, # type: bool editables_only=False, # type: bool user_only=False, # type: bool paths=None # type: Optional[List[str]] ): # type: (...) -> List[Distribution] """ Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs If ``include_editables`` is False, don't report editables. If ``editables_only`` is True , only report editables. If ``user_only`` is True , only report installations in the user site directory. If ``paths`` is set, only report the distributions present at the specified list of locations. """ if paths: working_set = pkg_resources.WorkingSet(paths) else: working_set = pkg_resources.working_set if local_only: local_test = dist_is_local else: def local_test(d): return True if include_editables: def editable_test(d): return True else: def editable_test(d): return not dist_is_editable(d) if editables_only: def editables_only_test(d): return dist_is_editable(d) else: def editables_only_test(d): return True if user_only: user_test = dist_in_usersite else: def user_test(d): return True return [d for d in working_set if local_test(d) and d.key not in skip and editable_test(d) and editables_only_test(d) and user_test(d) ] The provided code snippet includes necessary dependencies for implementing the `autocomplete` function. Write a Python function `def autocomplete()` to solve the following problem: Entry Point for completion of main and subcommand options. Here is the function: def autocomplete(): # type: () -> None """Entry Point for completion of main and subcommand options. """ # Don't complete if user hasn't sourced bash_completion file. if 'PIP_AUTO_COMPLETE' not in os.environ: return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: current = cwords[cword - 1] except IndexError: current = '' parser = create_main_parser() subcommands = list(commands_dict) options = [] # subcommand subcommand_name = None # type: Optional[str] for word in cwords: if word in subcommands: subcommand_name = word break # subcommand options if subcommand_name is not None: # special case: 'help' subcommand has no options if subcommand_name == 'help': sys.exit(1) # special case: list locally installed dists for show and uninstall should_list_installed = ( subcommand_name in ['show', 'uninstall'] and not current.startswith('-') ) if should_list_installed: installed = [] lc = current.lower() for dist in get_installed_distributions(local_only=True): if dist.key.startswith(lc) and dist.key not in cwords[1:]: installed.append(dist.key) # if there are no dists installed, fall back to option completion if installed: for dist in installed: print(dist) sys.exit(1) subcommand = create_command(subcommand_name) for opt in subcommand.parser.option_list_all: if opt.help != optparse.SUPPRESS_HELP: for opt_str in opt._long_opts + opt._short_opts: options.append((opt_str, opt.nargs)) # filter out previously specified options from available options prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]] options = [(x, v) for (x, v) in options if x not in prev_opts] # filter options by current input options = [(k, v) for k, v in options if k.startswith(current)] # get completion type given cwords and available subcommand options completion_type = get_path_completion_type( cwords, cword, subcommand.parser.option_list_all, ) # get completion files and directories if ``completion_type`` is # ``<file>``, ``<dir>`` or ``<path>`` if completion_type: paths = auto_complete_paths(current, completion_type) options = [(path, 0) for path in paths] for option in options: opt_label = option[0] # append '=' to options which require args if option[1] and option[0][:2] == "--": opt_label += '=' print(opt_label) else: # show main parser options only when necessary opts = [i.option_list for i in parser.option_groups] opts.append(parser.option_list) flattened_opts = chain.from_iterable(opts) if current.startswith('-'): for opt in flattened_opts: if opt.help != optparse.SUPPRESS_HELP: subcommands += opt._long_opts + opt._short_opts else: # get completion type given cwords and all available options completion_type = get_path_completion_type(cwords, cword, flattened_opts) if completion_type: subcommands = list(auto_complete_paths(current, completion_type)) print(' '.join([x for x in subcommands if x.startswith(current)])) sys.exit(1)
Entry Point for completion of main and subcommand options.
175,627
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING platform = partial( Option, '--platform', dest='platform', metavar='platform', default=None, help=("Only use wheels compatible with <platform>. " "Defaults to the platform of the running system."), ) python_version = partial( Option, '--python-version', dest='python_version', metavar='python_version', action='callback', callback=_handle_python_version, type='str', default=None, help=dedent("""\ The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0). """), ) implementation = partial( Option, '--implementation', dest='implementation', metavar='implementation', default=None, help=("Only use wheels compatible with Python " "implementation <implementation>, e.g. 'pp', 'jy', 'cp', " " or 'ip'. If not specified, then the current " "interpreter implementation is used. Use 'py' to force " "implementation-agnostic wheels."), ) abi = partial( Option, '--abi', dest='abi', metavar='abi', default=None, help=("Only use wheels compatible with Python " "abi <abi>, e.g. 'pypy_41'. If not specified, then the " "current interpreter abi tag is used. Generally " "you will need to specify --implementation, " "--platform, and --python-version when using " "this option."), ) class CommandError(PipError): """Raised when there is an error in command-line arguments""" class FormatControl(object): """Helper for managing formats from which a package can be installed. """ __slots__ = ["no_binary", "only_binary"] def __init__(self, no_binary=None, only_binary=None): # type: (Optional[Set[str]], Optional[Set[str]]) -> None if no_binary is None: no_binary = set() if only_binary is None: only_binary = set() self.no_binary = no_binary self.only_binary = only_binary def __eq__(self, other): # type: (object) -> bool if not isinstance(other, self.__class__): return NotImplemented if self.__slots__ != other.__slots__: return False return all( getattr(self, k) == getattr(other, k) for k in self.__slots__ ) def __ne__(self, other): # type: (object) -> bool return not self.__eq__(other) def __repr__(self): # type: () -> str return "{}({}, {})".format( self.__class__.__name__, self.no_binary, self.only_binary ) def handle_mutual_excludes(value, target, other): # type: (str, Set[str], Set[str]) -> None if value.startswith('-'): raise CommandError( "--no-binary / --only-binary option requires 1 argument." ) new = value.split(',') while ':all:' in new: other.clear() target.clear() target.add(':all:') del new[:new.index(':all:') + 1] # Without a none, we want to discard everything as :all: covers it if ':none:' not in new: return for name in new: if name == ':none:': target.clear() continue name = canonicalize_name(name) other.discard(name) target.add(name) def get_allowed_formats(self, canonical_name): # type: (str) -> FrozenSet[str] result = {"binary", "source"} if canonical_name in self.only_binary: result.discard('source') elif canonical_name in self.no_binary: result.discard('binary') elif ':all:' in self.only_binary: result.discard('source') elif ':all:' in self.no_binary: result.discard('binary') return frozenset(result) def disallow_binaries(self): # type: () -> None self.handle_mutual_excludes( ':all:', self.no_binary, self.only_binary, ) The provided code snippet includes necessary dependencies for implementing the `check_dist_restriction` function. Write a Python function `def check_dist_restriction(options, check_target=False)` to solve the following problem: Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. Here is the function: def check_dist_restriction(options, check_target=False): # type: (Values, bool) -> None """Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. """ dist_restriction_set = any([ options.python_version, options.platform, options.abi, options.implementation, ]) binary_only = FormatControl(set(), {':all:'}) sdist_dependencies_allowed = ( options.format_control != binary_only and not options.ignore_dependencies ) # Installations or downloads using dist restrictions must not combine # source distributions and dist-specific wheels, as they are not # guaranteed to be locally compatible. if dist_restriction_set and sdist_dependencies_allowed: raise CommandError( "When restricting platform and interpreter constraints using " "--python-version, --platform, --abi, or --implementation, " "either --no-deps must be set, or --only-binary=:all: must be " "set and --no-binary must not be set (or must be set to " ":none:)." ) if check_target: if dist_restriction_set and not options.target_dir: raise CommandError( "Can not use any platform or abi specific options unless " "installing via '--target'" )
Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used.
175,628
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING def _path_option_check(option, opt, value): # type: (Option, str, str) -> str return os.path.expanduser(value)
null
175,629
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING class Option: ACTIONS: Tuple[_Text, ...] ALWAYS_TYPED_ACTIONS: Tuple[_Text, ...] ATTRS: List[_Text] CHECK_METHODS: Optional[List[Callable[..., Any]]] CONST_ACTIONS: Tuple[_Text, ...] STORE_ACTIONS: Tuple[_Text, ...] TYPED_ACTIONS: Tuple[_Text, ...] TYPES: Tuple[_Text, ...] TYPE_CHECKER: Dict[_Text, Callable[..., Any]] _long_opts: List[_Text] _short_opts: List[_Text] action: _Text dest: Optional[_Text] nargs: int type: Any def __init__(self, *opts: Optional[_Text], **attrs: Any) -> None: ... def _check_action(self) -> None: ... def _check_callback(self) -> None: ... def _check_choice(self) -> None: ... def _check_const(self) -> None: ... def _check_dest(self) -> None: ... def _check_nargs(self) -> None: ... def _check_opt_strings(self, opts: Iterable[Optional[_Text]]) -> List[_Text]: ... def _check_type(self) -> None: ... def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: ... def _set_opt_strings(self, opts: Iterable[_Text]) -> None: ... def check_value(self, opt: Any, value: Any) -> Any: ... def convert_value(self, opt: Any, value: Any) -> Any: ... def get_opt_string(self) -> _Text: ... def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... def take_action(self, action: _Text, dest: _Text, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... def takes_value(self) -> bool: ... def exists_action(): # type: () -> Option return Option( # Option when path already exist '--exists-action', dest='exists_action', type='choice', choices=['s', 'i', 'w', 'b', 'a'], default=[], action='append', metavar='action', help="Default action when a path already exists: " "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.", )
null
175,630
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING class Option: ACTIONS: Tuple[_Text, ...] ALWAYS_TYPED_ACTIONS: Tuple[_Text, ...] ATTRS: List[_Text] CHECK_METHODS: Optional[List[Callable[..., Any]]] CONST_ACTIONS: Tuple[_Text, ...] STORE_ACTIONS: Tuple[_Text, ...] TYPED_ACTIONS: Tuple[_Text, ...] TYPES: Tuple[_Text, ...] TYPE_CHECKER: Dict[_Text, Callable[..., Any]] _long_opts: List[_Text] _short_opts: List[_Text] action: _Text dest: Optional[_Text] nargs: int type: Any def __init__(self, *opts: Optional[_Text], **attrs: Any) -> None: ... def _check_action(self) -> None: ... def _check_callback(self) -> None: ... def _check_choice(self) -> None: ... def _check_const(self) -> None: ... def _check_dest(self) -> None: ... def _check_nargs(self) -> None: ... def _check_opt_strings(self, opts: Iterable[Optional[_Text]]) -> List[_Text]: ... def _check_type(self) -> None: ... def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: ... def _set_opt_strings(self, opts: Iterable[_Text]) -> None: ... def check_value(self, opt: Any, value: Any) -> Any: ... def convert_value(self, opt: Any, value: Any) -> Any: ... def get_opt_string(self) -> _Text: ... def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... def take_action(self, action: _Text, dest: _Text, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... def takes_value(self) -> bool: ... def extra_index_url(): # type: () -> Option return Option( '--extra-index-url', dest='extra_index_urls', metavar='URL', action='append', default=[], help="Extra URLs of package indexes to use in addition to " "--index-url. Should follow the same rules as " "--index-url.", )
null
175,631
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING class Option: ACTIONS: Tuple[_Text, ...] ALWAYS_TYPED_ACTIONS: Tuple[_Text, ...] ATTRS: List[_Text] CHECK_METHODS: Optional[List[Callable[..., Any]]] CONST_ACTIONS: Tuple[_Text, ...] STORE_ACTIONS: Tuple[_Text, ...] TYPED_ACTIONS: Tuple[_Text, ...] TYPES: Tuple[_Text, ...] TYPE_CHECKER: Dict[_Text, Callable[..., Any]] _long_opts: List[_Text] _short_opts: List[_Text] action: _Text dest: Optional[_Text] nargs: int type: Any def __init__(self, *opts: Optional[_Text], **attrs: Any) -> None: ... def _check_action(self) -> None: ... def _check_callback(self) -> None: ... def _check_choice(self) -> None: ... def _check_const(self) -> None: ... def _check_dest(self) -> None: ... def _check_nargs(self) -> None: ... def _check_opt_strings(self, opts: Iterable[Optional[_Text]]) -> List[_Text]: ... def _check_type(self) -> None: ... def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: ... def _set_opt_strings(self, opts: Iterable[_Text]) -> None: ... def check_value(self, opt: Any, value: Any) -> Any: ... def convert_value(self, opt: Any, value: Any) -> Any: ... def get_opt_string(self) -> _Text: ... def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... def take_action(self, action: _Text, dest: _Text, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... def takes_value(self) -> bool: ... def trusted_host(): # type: () -> Option return Option( "--trusted-host", dest="trusted_hosts", action="append", metavar="HOSTNAME", default=[], help="Mark this host or host:port pair as trusted, even though it " "does not have valid or any HTTPS.", )
null
175,632
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING class Option: ACTIONS: Tuple[_Text, ...] ALWAYS_TYPED_ACTIONS: Tuple[_Text, ...] ATTRS: List[_Text] CHECK_METHODS: Optional[List[Callable[..., Any]]] CONST_ACTIONS: Tuple[_Text, ...] STORE_ACTIONS: Tuple[_Text, ...] TYPED_ACTIONS: Tuple[_Text, ...] TYPES: Tuple[_Text, ...] TYPE_CHECKER: Dict[_Text, Callable[..., Any]] _long_opts: List[_Text] _short_opts: List[_Text] action: _Text dest: Optional[_Text] nargs: int type: Any def __init__(self, *opts: Optional[_Text], **attrs: Any) -> None: ... def _check_action(self) -> None: ... def _check_callback(self) -> None: ... def _check_choice(self) -> None: ... def _check_const(self) -> None: ... def _check_dest(self) -> None: ... def _check_nargs(self) -> None: ... def _check_opt_strings(self, opts: Iterable[Optional[_Text]]) -> List[_Text]: ... def _check_type(self) -> None: ... def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: ... def _set_opt_strings(self, opts: Iterable[_Text]) -> None: ... def check_value(self, opt: Any, value: Any) -> Any: ... def convert_value(self, opt: Any, value: Any) -> Any: ... def get_opt_string(self) -> _Text: ... def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... def take_action(self, action: _Text, dest: _Text, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... def takes_value(self) -> bool: ... def constraints(): # type: () -> Option return Option( '-c', '--constraint', dest='constraints', action='append', default=[], metavar='file', help='Constrain versions using the given constraints file. ' 'This option can be used multiple times.' )
null
175,633
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING class Option: def __init__(self, *opts: Optional[_Text], **attrs: Any) -> None: def _check_action(self) -> None: def _check_callback(self) -> None: def _check_choice(self) -> None: def _check_const(self) -> None: def _check_dest(self) -> None: def _check_nargs(self) -> None: def _check_opt_strings(self, opts: Iterable[Optional[_Text]]) -> List[_Text]: def _check_type(self) -> None: def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: def _set_opt_strings(self, opts: Iterable[_Text]) -> None: def check_value(self, opt: Any, value: Any) -> Any: def convert_value(self, opt: Any, value: Any) -> Any: def get_opt_string(self) -> _Text: def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: def take_action(self, action: _Text, dest: _Text, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: def takes_value(self) -> bool: def requirements(): # type: () -> Option return Option( '-r', '--requirement', dest='requirements', action='append', default=[], metavar='file', help='Install from the given requirements file. ' 'This option can be used multiple times.' )
null
175,634
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING class Option: ACTIONS: Tuple[_Text, ...] ALWAYS_TYPED_ACTIONS: Tuple[_Text, ...] ATTRS: List[_Text] CHECK_METHODS: Optional[List[Callable[..., Any]]] CONST_ACTIONS: Tuple[_Text, ...] STORE_ACTIONS: Tuple[_Text, ...] TYPED_ACTIONS: Tuple[_Text, ...] TYPES: Tuple[_Text, ...] TYPE_CHECKER: Dict[_Text, Callable[..., Any]] _long_opts: List[_Text] _short_opts: List[_Text] action: _Text dest: Optional[_Text] nargs: int type: Any def __init__(self, *opts: Optional[_Text], **attrs: Any) -> None: ... def _check_action(self) -> None: ... def _check_callback(self) -> None: ... def _check_choice(self) -> None: ... def _check_const(self) -> None: ... def _check_dest(self) -> None: ... def _check_nargs(self) -> None: ... def _check_opt_strings(self, opts: Iterable[Optional[_Text]]) -> List[_Text]: ... def _check_type(self) -> None: ... def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: ... def _set_opt_strings(self, opts: Iterable[_Text]) -> None: ... def check_value(self, opt: Any, value: Any) -> Any: ... def convert_value(self, opt: Any, value: Any) -> Any: ... def get_opt_string(self) -> _Text: ... def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... def take_action(self, action: _Text, dest: _Text, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... def takes_value(self) -> bool: ... def editable(): # type: () -> Option return Option( '-e', '--editable', dest='editables', action='append', default=[], metavar='path/url', help=('Install a project in editable mode (i.e. setuptools ' '"develop mode") from a local project path or a VCS url.'), )
null
175,635
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING def _handle_src(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None value = os.path.abspath(value) setattr(parser.values, option.dest, value)
null
175,636
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING def raise_option_error(parser, option, msg): # type: (OptionParser, Option, str) -> None """ Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. """ msg = '{} error: {}'.format(option, msg) msg = textwrap.fill(' '.join(msg.split())) parser.error(msg) def _convert_python_version(value): # type: (str) -> Tuple[Tuple[int, ...], Optional[str]] """ Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. :return: A 2-tuple (version_info, error_msg), where `error_msg` is non-None if and only if there was a parsing error. """ if not value: # The empty string is the same as not providing a value. return (None, None) parts = value.split('.') if len(parts) > 3: return ((), 'at most three version parts are allowed') if len(parts) == 1: # Then we are in the case of "3" or "37". value = parts[0] if len(value) > 1: parts = [value[0], value[1:]] try: version_info = tuple(int(part) for part in parts) except ValueError: return ((), 'each version part must be an integer') return (version_info, None) python_version = partial( Option, '--python-version', dest='python_version', metavar='python_version', action='callback', callback=_handle_python_version, type='str', default=None, help=dedent("""\ The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0). """), ) The provided code snippet includes necessary dependencies for implementing the `_handle_python_version` function. Write a Python function `def _handle_python_version(option, opt_str, value, parser)` to solve the following problem: Handle a provided --python-version value. Here is the function: def _handle_python_version(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """ Handle a provided --python-version value. """ version_info, error_msg = _convert_python_version(value) if error_msg is not None: msg = ( 'invalid --python-version value: {!r}: {}'.format( value, error_msg, ) ) raise_option_error(parser, option=option, msg=msg) parser.values.python_version = version_info
Handle a provided --python-version value.
175,637
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING platform = partial( Option, '--platform', dest='platform', metavar='platform', default=None, help=("Only use wheels compatible with <platform>. " "Defaults to the platform of the running system."), ) python_version = partial( Option, '--python-version', dest='python_version', metavar='python_version', action='callback', callback=_handle_python_version, type='str', default=None, help=dedent("""\ The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0). """), ) implementation = partial( Option, '--implementation', dest='implementation', metavar='implementation', default=None, help=("Only use wheels compatible with Python " "implementation <implementation>, e.g. 'pp', 'jy', 'cp', " " or 'ip'. If not specified, then the current " "interpreter implementation is used. Use 'py' to force " "implementation-agnostic wheels."), ) abi = partial( Option, '--abi', dest='abi', metavar='abi', default=None, help=("Only use wheels compatible with Python " "abi <abi>, e.g. 'pypy_41'. If not specified, then the " "current interpreter abi tag is used. Generally " "you will need to specify --implementation, " "--platform, and --python-version when using " "this option."), ) def add_target_python_options(cmd_opts): # type: (OptionGroup) -> None cmd_opts.add_option(platform()) cmd_opts.add_option(python_version()) cmd_opts.add_option(implementation()) cmd_opts.add_option(abi())
null
175,638
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING def raise_option_error(parser, option, msg): # type: (OptionParser, Option, str) -> None """ Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. """ msg = '{} error: {}'.format(option, msg) msg = textwrap.fill(' '.join(msg.split())) parser.error(msg) cache_dir = partial( PipOption, "--cache-dir", dest="cache_dir", default=USER_CACHE_DIR, metavar="dir", type='path', help="Store the cache data in <dir>." ) The provided code snippet includes necessary dependencies for implementing the `_handle_no_cache_dir` function. Write a Python function `def _handle_no_cache_dir(option, opt, value, parser)` to solve the following problem: Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. Here is the function: def _handle_no_cache_dir(option, opt, value, parser): # type: (Option, str, str, OptionParser) -> None """ Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. """ # The value argument will be None if --no-cache-dir is passed via the # command-line, since the option doesn't accept arguments. However, # the value can be non-None if the option is triggered e.g. by an # environment variable, like PIP_NO_CACHE_DIR=true. if value is not None: # Then parse the string value to get argument error-checking. try: strtobool(value) except ValueError as exc: raise_option_error(parser, option=option, msg=str(exc)) # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() # converted to 0 (like "false" or "no") caused cache_dir to be disabled # rather than enabled (logic would say the latter). Thus, we disable # the cache directory not just on values that parse to True, but (for # backwards compatibility reasons) also on values that parse to False. # In other words, always set it to False if the option is provided in # some (valid) form. parser.values.cache_dir = False
Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option.
175,639
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING def _handle_build_dir(option, opt, value, parser): # type: (Option, str, str, OptionParser) -> None if value: value = os.path.abspath(value) setattr(parser.values, option.dest, value)
null
175,640
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING def raise_option_error(parser, option, msg): # type: (OptionParser, Option, str) -> None """ Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. """ msg = '{} error: {}'.format(option, msg) msg = textwrap.fill(' '.join(msg.split())) parser.error(msg) use_pep517 = partial( Option, '--use-pep517', dest='use_pep517', action='store_true', default=None, help='Use PEP 517 for building source distributions ' '(use --no-use-pep517 to force legacy behaviour).' ) The provided code snippet includes necessary dependencies for implementing the `_handle_no_use_pep517` function. Write a Python function `def _handle_no_use_pep517(option, opt, value, parser)` to solve the following problem: Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. Here is the function: def _handle_no_use_pep517(option, opt, value, parser): # type: (Option, str, str, OptionParser) -> None """ Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. """ # Since --no-use-pep517 doesn't accept arguments, the value argument # will be None if --no-use-pep517 is passed via the command-line. # However, the value can be non-None if the option is triggered e.g. # by an environment variable, for example "PIP_NO_USE_PEP517=true". if value is not None: msg = """A value was passed for --no-use-pep517, probably using either the PIP_NO_USE_PEP517 environment variable or the "no-use-pep517" config file option. Use an appropriate value of the PIP_USE_PEP517 environment variable or the "use-pep517" config file option instead. """ raise_option_error(parser, option=option, msg=msg) # Otherwise, --no-use-pep517 was passed via the command-line. parser.values.use_pep517 = False
Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option.
175,641
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING STRONG_HASHES = ['sha256', 'sha384', 'sha512'] The provided code snippet includes necessary dependencies for implementing the `_handle_merge_hash` function. Write a Python function `def _handle_merge_hash(option, opt_str, value, parser)` to solve the following problem: Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name. Here is the function: def _handle_merge_hash(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.""" if not parser.values.hashes: parser.values.hashes = {} try: algo, digest = value.split(':', 1) except ValueError: parser.error('Arguments to {} must be a hash name ' # noqa 'followed by a value, like --hash=sha256:' 'abcde...'.format(opt_str)) if algo not in STRONG_HASHES: parser.error('Allowed hash algorithms for {} are {}.'.format( # noqa opt_str, ', '.join(STRONG_HASHES))) parser.values.hashes.setdefault(algo, []).append(digest)
Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.
175,642
from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING class CommandError(PipError): """Raised when there is an error in command-line arguments""" def check_list_path_option(options): # type: (Values) -> None if options.path and (options.user or options.local): raise CommandError( "Cannot combine '--path' with '--user' or '--local'" )
null
175,643
import os import sys from pip._internal.cli import cmdoptions from pip._internal.cli.parser import ( ConfigOptionParser, UpdatingDefaultsHelpFormatter, ) from pip._internal.commands import commands_dict, get_similar_commands from pip._internal.exceptions import CommandError from pip._internal.utils.misc import get_pip_version, get_prog from pip._internal.utils.typing import MYPY_CHECK_RUNNING def create_main_parser(): # type: () -> ConfigOptionParser """Creates and returns the main parser for pip's CLI """ parser_kw = { 'usage': '\n%prog <command> [options]', 'add_help_option': False, 'formatter': UpdatingDefaultsHelpFormatter(), 'name': 'global', 'prog': get_prog(), } parser = ConfigOptionParser(**parser_kw) parser.disable_interspersed_args() parser.version = get_pip_version() # add the general options gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser) parser.add_option_group(gen_opts) # so the help formatter knows parser.main = True # type: ignore # create command listing for description description = [''] + [ '{name:27} {command_info.summary}'.format(**locals()) for name, command_info in commands_dict.items() ] parser.description = '\n'.join(description) return parser import sys assert "pydevd" in sys.modules commands_dict = OrderedDict([ ('install', CommandInfo( 'pip._internal.commands.install', 'InstallCommand', 'Install packages.', )), ('download', CommandInfo( 'pip._internal.commands.download', 'DownloadCommand', 'Download packages.', )), ('uninstall', CommandInfo( 'pip._internal.commands.uninstall', 'UninstallCommand', 'Uninstall packages.', )), ('freeze', CommandInfo( 'pip._internal.commands.freeze', 'FreezeCommand', 'Output installed packages in requirements format.', )), ('list', CommandInfo( 'pip._internal.commands.list', 'ListCommand', 'List installed packages.', )), ('show', CommandInfo( 'pip._internal.commands.show', 'ShowCommand', 'Show information about installed packages.', )), ('check', CommandInfo( 'pip._internal.commands.check', 'CheckCommand', 'Verify installed packages have compatible dependencies.', )), ('config', CommandInfo( 'pip._internal.commands.configuration', 'ConfigurationCommand', 'Manage local and global configuration.', )), ('search', CommandInfo( 'pip._internal.commands.search', 'SearchCommand', 'Search PyPI for packages.', )), ('cache', CommandInfo( 'pip._internal.commands.cache', 'CacheCommand', "Inspect and manage pip's wheel cache.", )), ('wheel', CommandInfo( 'pip._internal.commands.wheel', 'WheelCommand', 'Build wheels from your requirements.', )), ('hash', CommandInfo( 'pip._internal.commands.hash', 'HashCommand', 'Compute hashes of package archives.', )), ('completion', CommandInfo( 'pip._internal.commands.completion', 'CompletionCommand', 'A helper command used for command completion.', )), ('debug', CommandInfo( 'pip._internal.commands.debug', 'DebugCommand', 'Show information useful for debugging.', )), ('help', CommandInfo( 'pip._internal.commands.help', 'HelpCommand', 'Show help for commands.', )), ]) def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False class CommandError(PipError): """Raised when there is an error in command-line arguments""" def parse_command(args): # type: (List[str]) -> Tuple[str, List[str]] parser = create_main_parser() # Note: parser calls disable_interspersed_args(), so the result of this # call is to split the initial args into the general options before the # subcommand and everything else. # For example: # args: ['--timeout=5', 'install', '--user', 'INITools'] # general_options: ['--timeout==5'] # args_else: ['install', '--user', 'INITools'] general_options, args_else = parser.parse_args(args) # --version if general_options.version: sys.stdout.write(parser.version) # type: ignore sys.stdout.write(os.linesep) sys.exit() # pip || pip help -> print_help() if not args_else or (args_else[0] == 'help' and len(args_else) == 1): parser.print_help() sys.exit() # the subcommand name cmd_name = args_else[0] if cmd_name not in commands_dict: guess = get_similar_commands(cmd_name) msg = ['unknown command "{}"'.format(cmd_name)] if guess: msg.append('maybe you meant "{}"'.format(guess)) raise CommandError(' - '.join(msg)) # all the args without the subcommand cmd_args = args[:] cmd_args.remove(cmd_name) return cmd_name, cmd_args
null
175,644
from __future__ import absolute_import import os import os.path import platform import site import sys import sysconfig from distutils import sysconfig as distutils_sysconfig from distutils.command.install import SCHEME_KEYS from distutils.command.install import install as distutils_install_command from pip._internal.models.scheme import Scheme from pip._internal.utils import appdirs from pip._internal.utils.compat import WINDOWS from pip._internal.utils.typing import MYPY_CHECK_RUNNING, cast from pip._internal.utils.virtualenv import running_under_virtualenv import sys if sys.byteorder == 'little': _nbo = '<' else: _nbo = '>' def running_under_virtualenv(): # type: () -> bool """Return True if we're running inside a virtualenv, False otherwise. """ return _running_under_venv() or _running_under_regular_virtualenv() def get_src_prefix(): # type: () -> str if running_under_virtualenv(): src_prefix = os.path.join(sys.prefix, 'src') else: # FIXME: keep src in cwd for now (it is not a temporary folder) try: src_prefix = os.path.join(os.getcwd(), 'src') except OSError: # In case the current working directory has been renamed or deleted sys.exit( "The folder you are executing pip from can no longer be found." ) # under macOS + virtualenv sys.prefix is not properly resolved # it is something like /path/to/python/bin/.. return os.path.abspath(src_prefix)
null
175,645
from __future__ import absolute_import import os import os.path import platform import site import sys import sysconfig from distutils import sysconfig as distutils_sysconfig from distutils.command.install import SCHEME_KEYS from distutils.command.install import install as distutils_install_command from pip._internal.models.scheme import Scheme from pip._internal.utils import appdirs from pip._internal.utils.compat import WINDOWS from pip._internal.utils.typing import MYPY_CHECK_RUNNING, cast from pip._internal.utils.virtualenv import running_under_virtualenv def distutils_scheme( dist_name, user=False, home=None, root=None, isolated=False, prefix=None ): # type:(str, bool, str, str, bool, str) -> Dict[str, str] """ Return a distutils install scheme """ from distutils.dist import Distribution dist_args = {'name': dist_name} # type: Dict[str, Union[str, List[str]]] if isolated: dist_args["script_args"] = ["--no-user-cfg"] d = Distribution(dist_args) d.parse_config_files() obj = None # type: Optional[DistutilsCommand] obj = d.get_command_obj('install', create=True) assert obj is not None i = cast(distutils_install_command, obj) # NOTE: setting user or home has the side-effect of creating the home dir # or user base for installations during finalize_options() # ideally, we'd prefer a scheme class that has no side-effects. assert not (user and prefix), "user={} prefix={}".format(user, prefix) assert not (home and prefix), "home={} prefix={}".format(home, prefix) i.user = user or i.user if user or home: i.prefix = "" i.prefix = prefix or i.prefix i.home = home or i.home i.root = root or i.root i.finalize_options() scheme = {} for key in SCHEME_KEYS: scheme[key] = getattr(i, 'install_' + key) # install_lib specified in setup.cfg should install *everything* # into there (i.e. it takes precedence over both purelib and # platlib). Note, i.install_lib is *always* set after # finalize_options(); we only want to override here if the user # has explicitly requested it hence going back to the config if 'install_lib' in d.get_option_dict('install'): scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib)) if running_under_virtualenv(): scheme['headers'] = os.path.join( i.prefix, 'include', 'site', 'python{}'.format(get_major_minor_version()), dist_name, ) if root is not None: path_no_drive = os.path.splitdrive( os.path.abspath(scheme["headers"]))[1] scheme["headers"] = os.path.join( root, path_no_drive[1:], ) return scheme class Scheme(object): """A Scheme holds paths which are used as the base directories for artifacts associated with a Python package. """ __slots__ = SCHEME_KEYS def __init__( self, platlib, # type: str purelib, # type: str headers, # type: str scripts, # type: str data, # type: str ): self.platlib = platlib self.purelib = purelib self.headers = headers self.scripts = scripts self.data = data The provided code snippet includes necessary dependencies for implementing the `get_scheme` function. Write a Python function `def get_scheme( dist_name, # type: str user=False, # type: bool home=None, # type: Optional[str] root=None, # type: Optional[str] isolated=False, # type: bool prefix=None, # type: Optional[str] )` to solve the following problem: Get the "scheme" corresponding to the input parameters. The distutils documentation provides the context for the available schemes: https://docs.python.org/3/install/index.html#alternate-installation :param dist_name: the name of the package to retrieve the scheme for, used in the headers scheme path :param user: indicates to use the "user" scheme :param home: indicates to use the "home" scheme and provides the base directory for the same :param root: root under which other directories are re-based :param isolated: equivalent to --no-user-cfg, i.e. do not consider ~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for scheme paths :param prefix: indicates to use the "prefix" scheme and provides the base directory for the same Here is the function: def get_scheme( dist_name, # type: str user=False, # type: bool home=None, # type: Optional[str] root=None, # type: Optional[str] isolated=False, # type: bool prefix=None, # type: Optional[str] ): # type: (...) -> Scheme """ Get the "scheme" corresponding to the input parameters. The distutils documentation provides the context for the available schemes: https://docs.python.org/3/install/index.html#alternate-installation :param dist_name: the name of the package to retrieve the scheme for, used in the headers scheme path :param user: indicates to use the "user" scheme :param home: indicates to use the "home" scheme and provides the base directory for the same :param root: root under which other directories are re-based :param isolated: equivalent to --no-user-cfg, i.e. do not consider ~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for scheme paths :param prefix: indicates to use the "prefix" scheme and provides the base directory for the same """ scheme = distutils_scheme( dist_name, user, home, root, isolated, prefix ) return Scheme( platlib=scheme["platlib"], purelib=scheme["purelib"], headers=scheme["headers"], scripts=scheme["scripts"], data=scheme["data"], )
Get the "scheme" corresponding to the input parameters. The distutils documentation provides the context for the available schemes: https://docs.python.org/3/install/index.html#alternate-installation :param dist_name: the name of the package to retrieve the scheme for, used in the headers scheme path :param user: indicates to use the "user" scheme :param home: indicates to use the "home" scheme and provides the base directory for the same :param root: root under which other directories are re-based :param isolated: equivalent to --no-user-cfg, i.e. do not consider ~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for scheme paths :param prefix: indicates to use the "prefix" scheme and provides the base directory for the same
175,646
from bisect import bisect_left, bisect_right from contextlib import contextmanager from tempfile import NamedTemporaryFile from zipfile import BadZipfile, ZipFile from pip._vendor.requests.models import CONTENT_CHUNK_SIZE from pip._vendor.six.moves import range from pip._internal.network.utils import ( HEADERS, raise_for_status, response_chunks, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.wheel import pkg_resources_distribution_for_wheel class LazyZipOverHTTP(object): """File-like object mapped to a ZIP file over HTTP. This uses HTTP range requests to lazily fetch the file's content, which is supposed to be fed to ZipFile. If such requests are not supported by the server, raise HTTPRangeRequestUnsupported during initialization. """ def __init__(self, url, session, chunk_size=CONTENT_CHUNK_SIZE): # type: (str, PipSession, int) -> None head = session.head(url, headers=HEADERS) raise_for_status(head) assert head.status_code == 200 self._session, self._url, self._chunk_size = session, url, chunk_size self._length = int(head.headers['Content-Length']) self._file = NamedTemporaryFile() self.truncate(self._length) self._left = [] # type: List[int] self._right = [] # type: List[int] if 'bytes' not in head.headers.get('Accept-Ranges', 'none'): raise HTTPRangeRequestUnsupported('range request is not supported') self._check_zip() def mode(self): # type: () -> str """Opening mode, which is always rb.""" return 'rb' def name(self): # type: () -> str """Path to the underlying file.""" return self._file.name def seekable(self): # type: () -> bool """Return whether random access is supported, which is True.""" return True def close(self): # type: () -> None """Close the file.""" self._file.close() def closed(self): # type: () -> bool """Whether the file is closed.""" return self._file.closed def read(self, size=-1): # type: (int) -> bytes """Read up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Fewer than size bytes may be returned if EOF is reached. """ download_size = max(size, self._chunk_size) start, length = self.tell(), self._length stop = length if size < 0 else min(start+download_size, length) start = max(0, stop-download_size) self._download(start, stop-1) return self._file.read(size) def readable(self): # type: () -> bool """Return whether the file is readable, which is True.""" return True def seek(self, offset, whence=0): # type: (int, int) -> int """Change stream position and return the new absolute position. Seek to offset relative position indicated by whence: * 0: Start of stream (the default). pos should be >= 0; * 1: Current position - pos may be negative; * 2: End of stream - pos usually negative. """ return self._file.seek(offset, whence) def tell(self): # type: () -> int """Return the current possition.""" return self._file.tell() def truncate(self, size=None): # type: (Optional[int]) -> int """Resize the stream to the given size in bytes. If size is unspecified resize to the current position. The current stream position isn't changed. Return the new file size. """ return self._file.truncate(size) def writable(self): # type: () -> bool """Return False.""" return False def __enter__(self): # type: () -> LazyZipOverHTTP self._file.__enter__() return self def __exit__(self, *exc): # type: (*Any) -> Optional[bool] return self._file.__exit__(*exc) def _stay(self): # type: ()-> Iterator[None] """Return a context manager keeping the position. At the end of the block, seek back to original position. """ pos = self.tell() try: yield finally: self.seek(pos) def _check_zip(self): # type: () -> None """Check and download until the file is a valid ZIP.""" end = self._length - 1 for start in reversed(range(0, end, self._chunk_size)): self._download(start, end) with self._stay(): try: # For read-only ZIP files, ZipFile only needs # methods read, seek, seekable and tell. ZipFile(self) # type: ignore except BadZipfile: pass else: break def _stream_response(self, start, end, base_headers=HEADERS): # type: (int, int, Dict[str, str]) -> Response """Return HTTP response to a range request from start to end.""" headers = base_headers.copy() headers['Range'] = 'bytes={}-{}'.format(start, end) # TODO: Get range requests to be correctly cached headers['Cache-Control'] = 'no-cache' return self._session.get(self._url, headers=headers, stream=True) def _merge(self, start, end, left, right): # type: (int, int, int, int) -> Iterator[Tuple[int, int]] """Return an iterator of intervals to be fetched. Args: start (int): Start of needed interval end (int): End of needed interval left (int): Index of first overlapping downloaded data right (int): Index after last overlapping downloaded data """ lslice, rslice = self._left[left:right], self._right[left:right] i = start = min([start]+lslice[:1]) end = max([end]+rslice[-1:]) for j, k in zip(lslice, rslice): if j > i: yield i, j-1 i = k + 1 if i <= end: yield i, end self._left[left:right], self._right[left:right] = [start], [end] def _download(self, start, end): # type: (int, int) -> None """Download bytes from start to end inclusively.""" with self._stay(): left = bisect_left(self._right, start) right = bisect_right(self._left, end) for start, end in self._merge(start, end, left, right): response = self._stream_response(start, end) response.raise_for_status() self.seek(start) for chunk in response_chunks(response, self._chunk_size): self._file.write(chunk) class ZipFile: filename: Optional[Text] debug: int comment: bytes filelist: List[ZipInfo] fp: Optional[IO[bytes]] NameToInfo: Dict[Text, ZipInfo] start_dir: int # undocumented if sys.version_info >= (3, 8): def __init__( self, file: Union[StrPath, IO[bytes]], mode: str = ..., compression: int = ..., allowZip64: bool = ..., compresslevel: Optional[int] = ..., *, strict_timestamps: bool = ..., ) -> None: ... elif sys.version_info >= (3, 7): def __init__( self, file: Union[StrPath, IO[bytes]], mode: str = ..., compression: int = ..., allowZip64: bool = ..., compresslevel: Optional[int] = ..., ) -> None: ... else: def __init__( self, file: Union[StrPath, IO[bytes]], mode: Text = ..., compression: int = ..., allowZip64: bool = ... ) -> None: ... def __enter__(self) -> ZipFile: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... def close(self) -> None: ... def getinfo(self, name: Text) -> ZipInfo: ... def infolist(self) -> List[ZipInfo]: ... def namelist(self) -> List[Text]: ... def open(self, name: _SZI, mode: Text = ..., pwd: Optional[bytes] = ..., *, force_zip64: bool = ...) -> IO[bytes]: ... def extract(self, member: _SZI, path: Optional[StrPath] = ..., pwd: Optional[bytes] = ...) -> str: ... def extractall( self, path: Optional[StrPath] = ..., members: Optional[Iterable[Text]] = ..., pwd: Optional[bytes] = ... ) -> None: ... if sys.version_info >= (3,): def printdir(self, file: Optional[_Writer] = ...) -> None: ... else: def printdir(self) -> None: ... def setpassword(self, pwd: bytes) -> None: ... def read(self, name: _SZI, pwd: Optional[bytes] = ...) -> bytes: ... def testzip(self) -> Optional[str]: ... if sys.version_info >= (3, 7): def write( self, filename: StrPath, arcname: Optional[StrPath] = ..., compress_type: Optional[int] = ..., compresslevel: Optional[int] = ..., ) -> None: ... else: def write(self, filename: StrPath, arcname: Optional[StrPath] = ..., compress_type: Optional[int] = ...) -> None: ... if sys.version_info >= (3, 7): def writestr( self, zinfo_or_arcname: _SZI, data: Union[bytes, str], compress_type: Optional[int] = ..., compresslevel: Optional[int] = ..., ) -> None: ... elif sys.version_info >= (3,): def writestr(self, zinfo_or_arcname: _SZI, data: Union[bytes, str], compress_type: Optional[int] = ...) -> None: ... else: def writestr(self, zinfo_or_arcname: _SZI, bytes: bytes, compress_type: Optional[int] = ...) -> None: ... def pkg_resources_distribution_for_wheel(wheel_zip, name, location): # type: (ZipFile, str, str) -> Distribution """Get a pkg_resources distribution given a wheel. :raises UnsupportedWheel: on any errors """ info_dir, _ = parse_wheel(wheel_zip, name) metadata_files = [ p for p in wheel_zip.namelist() if p.startswith("{}/".format(info_dir)) ] metadata_text = {} # type: Dict[str, bytes] for path in metadata_files: # If a flag is set, namelist entries may be unicode in Python 2. # We coerce them to native str type to match the types used in the rest # of the code. This cannot fail because unicode can always be encoded # with UTF-8. full_path = ensure_str(path) _, metadata_name = full_path.split("/", 1) try: metadata_text[metadata_name] = read_wheel_metadata_file( wheel_zip, full_path ) except UnsupportedWheel as e: raise UnsupportedWheel( "{} has an invalid wheel, {}".format(name, str(e)) ) metadata = WheelMetadata(metadata_text, location) return DistInfoDistribution( location=location, metadata=metadata, project_name=name ) The provided code snippet includes necessary dependencies for implementing the `dist_from_wheel_url` function. Write a Python function `def dist_from_wheel_url(name, url, session)` to solve the following problem: Return a pkg_resources.Distribution from the given wheel URL. This uses HTTP range requests to only fetch the potion of the wheel containing metadata, just enough for the object to be constructed. If such requests are not supported, HTTPRangeRequestUnsupported is raised. Here is the function: def dist_from_wheel_url(name, url, session): # type: (str, str, PipSession) -> Distribution """Return a pkg_resources.Distribution from the given wheel URL. This uses HTTP range requests to only fetch the potion of the wheel containing metadata, just enough for the object to be constructed. If such requests are not supported, HTTPRangeRequestUnsupported is raised. """ with LazyZipOverHTTP(url, session) as wheel: # For read-only ZIP files, ZipFile only needs methods read, # seek, seekable and tell, not the whole IO protocol. zip_file = ZipFile(wheel) # type: ignore # After context manager exit, wheel.name # is an invalid file by intention. return pkg_resources_distribution_for_wheel(zip_file, name, wheel.name)
Return a pkg_resources.Distribution from the given wheel URL. This uses HTTP range requests to only fetch the potion of the wheel containing metadata, just enough for the object to be constructed. If such requests are not supported, HTTPRangeRequestUnsupported is raised.
175,647
import email.utils import json import logging import mimetypes import os import platform import sys import warnings from pip._vendor import requests, six, urllib3 from pip._vendor.cachecontrol import CacheControlAdapter from pip._vendor.requests.adapters import BaseAdapter, HTTPAdapter from pip._vendor.requests.models import Response from pip._vendor.requests.structures import CaseInsensitiveDict from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.urllib3.exceptions import InsecureRequestWarning from pip import __version__ from pip._internal.network.auth import MultiDomainBasicAuth from pip._internal.network.cache import SafeFileCache from pip._internal.utils.compat import has_tls, ipaddress from pip._internal.utils.glibc import libc_ver from pip._internal.utils.misc import ( build_url_from_netloc, get_installed_version, parse_netloc, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import url_to_path def looks_like_ci(): # type: () -> bool """ Return whether it looks like pip is running under CI. """ # We don't use the method of checking for a tty (e.g. using isatty()) # because some CI systems mimic a tty (e.g. Travis CI). Thus that # method doesn't provide definitive information in either direction. return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES) __version__ = "20.2.3" def has_tls(): # type: () -> bool try: import _ssl # noqa: F401 # ignore unused return True except ImportError: pass from pip._vendor.urllib3.util import IS_PYOPENSSL return IS_PYOPENSSL def libc_ver(): # type: () -> Tuple[str, str] """Try to determine the glibc version Returns a tuple of strings (lib, version) which default to empty strings in case the lookup fails. """ glibc_version = glibc_version_string() if glibc_version is None: return ("", "") else: return ("glibc", glibc_version) def get_installed_version(dist_name, working_set=None): """Get the installed version of dist_name avoiding pkg_resources cache""" # Create a requirement that we'll look for inside of setuptools. req = pkg_resources.Requirement.parse(dist_name) if working_set is None: # We want to avoid having this cached, so we need to construct a new # working set each time. working_set = pkg_resources.WorkingSet() # Get the installed distribution from our working set dist = working_set.find(req) # Check to see if we got an installed distribution or not, if we did # we want to return it's version. return dist.version if dist else None The provided code snippet includes necessary dependencies for implementing the `user_agent` function. Write a Python function `def user_agent()` to solve the following problem: Return a string representing the user agent. Here is the function: def user_agent(): """ Return a string representing the user agent. """ data = { "installer": {"name": "pip", "version": __version__}, "python": platform.python_version(), "implementation": { "name": platform.python_implementation(), }, } if data["implementation"]["name"] == 'CPython': data["implementation"]["version"] = platform.python_version() elif data["implementation"]["name"] == 'PyPy': if sys.pypy_version_info.releaselevel == 'final': pypy_version_info = sys.pypy_version_info[:3] else: pypy_version_info = sys.pypy_version_info data["implementation"]["version"] = ".".join( [str(x) for x in pypy_version_info] ) elif data["implementation"]["name"] == 'Jython': # Complete Guess data["implementation"]["version"] = platform.python_version() elif data["implementation"]["name"] == 'IronPython': # Complete Guess data["implementation"]["version"] = platform.python_version() if sys.platform.startswith("linux"): from pip._vendor import distro distro_infos = dict(filter( lambda x: x[1], zip(["name", "version", "id"], distro.linux_distribution()), )) libc = dict(filter( lambda x: x[1], zip(["lib", "version"], libc_ver()), )) if libc: distro_infos["libc"] = libc if distro_infos: data["distro"] = distro_infos if sys.platform.startswith("darwin") and platform.mac_ver()[0]: data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]} if platform.system(): data.setdefault("system", {})["name"] = platform.system() if platform.release(): data.setdefault("system", {})["release"] = platform.release() if platform.machine(): data["cpu"] = platform.machine() if has_tls(): import _ssl as ssl data["openssl_version"] = ssl.OPENSSL_VERSION setuptools_version = get_installed_version("setuptools") if setuptools_version is not None: data["setuptools_version"] = setuptools_version # Use None rather than False so as not to give the impression that # pip knows it is not being run under CI. Rather, it is a null or # inconclusive result. Also, we include some value rather than no # value to make it easier to know that the check has been run. data["ci"] = True if looks_like_ci() else None user_data = os.environ.get("PIP_USER_AGENT_USER_DATA") if user_data is not None: data["user_data"] = user_data return "{data[installer][name]}/{data[installer][version]} {json}".format( data=data, json=json.dumps(data, separators=(",", ":"), sort_keys=True), )
Return a string representing the user agent.
175,648
import cgi import logging import mimetypes import os from pip._vendor.requests.models import CONTENT_CHUNK_SIZE from pip._internal.cli.progress_bars import DownloadProgressProvider from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.index import PyPI from pip._internal.network.cache import is_from_cache from pip._internal.network.utils import ( HEADERS, raise_for_status, response_chunks, ) from pip._internal.utils.misc import ( format_size, redact_auth_from_url, splitext, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) def _get_http_response_size(resp): # type: (Response) -> Optional[int] try: return int(resp.headers['content-length']) except (ValueError, KeyError, TypeError): return None CONTENT_CHUNK_SIZE = 10 * 1024 def DownloadProgressProvider(progress_bar, max=None): # type: ignore if max is None or max == 0: return BAR_TYPES[progress_bar][1]().iter else: return BAR_TYPES[progress_bar][0](max=max).iter PyPI = PackageIndex( 'https://pypi.org/', file_storage_domain='files.pythonhosted.org' ) def is_from_cache(response): # type: (Response) -> bool return getattr(response, "from_cache", False) def response_chunks(response, chunk_size=CONTENT_CHUNK_SIZE): # type: (Response, int) -> Iterator[bytes] """Given a requests Response, provide the data chunks. """ try: # Special case for urllib3. for chunk in response.raw.stream( chunk_size, # We use decode_content=False here because we don't # want urllib3 to mess with the raw bytes we get # from the server. If we decompress inside of # urllib3 then we cannot verify the checksum # because the checksum will be of the compressed # file. This breakage will only occur if the # server adds a Content-Encoding header, which # depends on how the server was configured: # - Some servers will notice that the file isn't a # compressible file and will leave the file alone # and with an empty Content-Encoding # - Some servers will notice that the file is # already compressed and will leave the file # alone and will add a Content-Encoding: gzip # header # - Some servers won't notice anything at all and # will take a file that's already been compressed # and compress it again and set the # Content-Encoding: gzip header # # By setting this not to decode automatically we # hope to eliminate problems with the second case. decode_content=False, ): yield chunk except AttributeError: # Standard file-like object. while True: chunk = response.raw.read(chunk_size) if not chunk: break yield chunk def format_size(bytes): # type: (float) -> str if bytes > 1000 * 1000: return '{:.1f} MB'.format(bytes / 1000.0 / 1000) elif bytes > 10 * 1000: return '{} kB'.format(int(bytes / 1000)) elif bytes > 1000: return '{:.1f} kB'.format(bytes / 1000.0) else: return '{} bytes'.format(int(bytes)) def redact_auth_from_url(url): # type: (str) -> str """Replace the password in a given url with ****.""" return _transform_url(url, _redact_netloc)[0] def _prepare_download( resp, # type: Response link, # type: Link progress_bar # type: str ): # type: (...) -> Iterable[bytes] total_length = _get_http_response_size(resp) if link.netloc == PyPI.file_storage_domain: url = link.show_url else: url = link.url_without_fragment logged_url = redact_auth_from_url(url) if total_length: logged_url = '{} ({})'.format(logged_url, format_size(total_length)) if is_from_cache(resp): logger.info("Using cached %s", logged_url) else: logger.info("Downloading %s", logged_url) if logger.getEffectiveLevel() > logging.INFO: show_progress = False elif is_from_cache(resp): show_progress = False elif not total_length: show_progress = True elif total_length > (40 * 1000): show_progress = True else: show_progress = False chunks = response_chunks(resp, CONTENT_CHUNK_SIZE) if not show_progress: return chunks return DownloadProgressProvider( progress_bar, max=total_length )(chunks)
null
175,649
import cgi import logging import mimetypes import os from pip._vendor.requests.models import CONTENT_CHUNK_SIZE from pip._internal.cli.progress_bars import DownloadProgressProvider from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.index import PyPI from pip._internal.network.cache import is_from_cache from pip._internal.network.utils import ( HEADERS, raise_for_status, response_chunks, ) from pip._internal.utils.misc import ( format_size, redact_auth_from_url, splitext, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING def parse_content_disposition(content_disposition, default_filename): # type: (str, str) -> str """ Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty. """ _type, params = cgi.parse_header(content_disposition) filename = params.get('filename') if filename: # We need to sanitize the filename to prevent directory traversal # in case the filename contains ".." path parts. filename = sanitize_content_filename(filename) return filename or default_filename def splitext(path): # type: (str) -> Tuple[str, str] """Like os.path.splitext, but take off .tar too""" base, ext = posixpath.splitext(path) if base.lower().endswith('.tar'): ext = base[-4:] + ext base = base[:-4] return base, ext The provided code snippet includes necessary dependencies for implementing the `_get_http_response_filename` function. Write a Python function `def _get_http_response_filename(resp, link)` to solve the following problem: Get an ideal filename from the given HTTP response, falling back to the link filename if not provided. Here is the function: def _get_http_response_filename(resp, link): # type: (Response, Link) -> str """Get an ideal filename from the given HTTP response, falling back to the link filename if not provided. """ filename = link.filename # fallback # Have a look at the Content-Disposition header for a better guess content_disposition = resp.headers.get('content-disposition') if content_disposition: filename = parse_content_disposition(content_disposition, filename) ext = splitext(filename)[1] # type: Optional[str] if not ext: ext = mimetypes.guess_extension( resp.headers.get('content-type', '') ) if ext: filename += ext if not ext and link.url != resp.url: ext = os.path.splitext(resp.url)[1] if ext: filename += ext return filename
Get an ideal filename from the given HTTP response, falling back to the link filename if not provided.
175,650
import cgi import logging import mimetypes import os from pip._vendor.requests.models import CONTENT_CHUNK_SIZE from pip._internal.cli.progress_bars import DownloadProgressProvider from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.index import PyPI from pip._internal.network.cache import is_from_cache from pip._internal.network.utils import ( HEADERS, raise_for_status, response_chunks, ) from pip._internal.utils.misc import ( format_size, redact_auth_from_url, splitext, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING HEADERS = {'Accept-Encoding': 'identity'} def raise_for_status(resp): # type: (Response) -> None http_error_msg = u'' if isinstance(resp.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8, we fall back to iso-8859-1 for all other # encodings. try: reason = resp.reason.decode('utf-8') except UnicodeDecodeError: reason = resp.reason.decode('iso-8859-1') else: reason = resp.reason if 400 <= resp.status_code < 500: http_error_msg = u'%s Client Error: %s for url: %s' % ( resp.status_code, reason, resp.url) elif 500 <= resp.status_code < 600: http_error_msg = u'%s Server Error: %s for url: %s' % ( resp.status_code, reason, resp.url) if http_error_msg: raise NetworkConnectionError(http_error_msg, response=resp) def _http_get_download(session, link): # type: (PipSession, Link) -> Response target_url = link.url.split('#', 1)[0] resp = session.get(target_url, headers=HEADERS, stream=True) raise_for_status(resp) return resp
null
175,651
import os from contextlib import contextmanager from pip._vendor.cachecontrol.cache import BaseCache from pip._vendor.cachecontrol.caches import FileCache from pip._vendor.requests.models import Response from pip._internal.utils.filesystem import adjacent_tmp_file, replace from pip._internal.utils.misc import ensure_dir from pip._internal.utils.typing import MYPY_CHECK_RUNNING The provided code snippet includes necessary dependencies for implementing the `suppressed_cache_errors` function. Write a Python function `def suppressed_cache_errors()` to solve the following problem: If we can't access the cache then we can just skip caching and process requests as if caching wasn't enabled. Here is the function: def suppressed_cache_errors(): # type: () -> Iterator[None] """If we can't access the cache then we can just skip caching and process requests as if caching wasn't enabled. """ try: yield except (OSError, IOError): pass
If we can't access the cache then we can just skip caching and process requests as if caching wasn't enabled.
175,652
import logging from pip._vendor.requests.auth import AuthBase, HTTPBasicAuth from pip._vendor.requests.utils import get_netrc_auth from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.utils.misc import ( ask, ask_input, ask_password, remove_auth_from_url, split_auth_netloc_from_url, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) try: import keyring # noqa except ImportError: keyring = None except Exception as exc: logger.warning( "Keyring is skipped due to an exception: %s", str(exc), ) keyring = None The provided code snippet includes necessary dependencies for implementing the `get_keyring_auth` function. Write a Python function `def get_keyring_auth(url, username)` to solve the following problem: Return the tuple auth for a given url from keyring. Here is the function: def get_keyring_auth(url, username): # type: (str, str) -> Optional[AuthInfo] """Return the tuple auth for a given url from keyring.""" global keyring if not url or not keyring: return None try: try: get_credential = keyring.get_credential except AttributeError: pass else: logger.debug("Getting credentials from keyring for %s", url) cred = get_credential(url, username) if cred is not None: return cred.username, cred.password return None if username: logger.debug("Getting password from keyring for %s", url) password = keyring.get_password(url, username) if password: return username, password except Exception as exc: logger.warning( "Keyring is skipped due to an exception: %s", str(exc), ) keyring = None return None
Return the tuple auth for a given url from keyring.
175,653
import locale import logging import os import sys from pip._vendor.six.moves import configparser from pip._internal.exceptions import ( ConfigurationError, ConfigurationFileCouldNotBeLoaded, ) from pip._internal.utils import appdirs from pip._internal.utils.compat import WINDOWS, expanduser from pip._internal.utils.misc import ensure_dir, enum from pip._internal.utils.typing import MYPY_CHECK_RUNNING The provided code snippet includes necessary dependencies for implementing the `_normalize_name` function. Write a Python function `def _normalize_name(name)` to solve the following problem: Make a name consistent regardless of source (environment or file) Here is the function: def _normalize_name(name): # type: (str) -> str """Make a name consistent regardless of source (environment or file) """ name = name.lower().replace('_', '-') if name.startswith('--'): name = name[2:] # only prefer long opts return name
Make a name consistent regardless of source (environment or file)
175,654
import locale import logging import os import sys from pip._vendor.six.moves import configparser from pip._internal.exceptions import ( ConfigurationError, ConfigurationFileCouldNotBeLoaded, ) from pip._internal.utils import appdirs from pip._internal.utils.compat import WINDOWS, expanduser from pip._internal.utils.misc import ensure_dir, enum from pip._internal.utils.typing import MYPY_CHECK_RUNNING class ConfigurationError(PipError): """General exception in configuration""" def _disassemble_key(name): # type: (str) -> List[str] if "." not in name: error_message = ( "Key does not contain dot separated section and key. " "Perhaps you wanted to use 'global.{}' instead?" ).format(name) raise ConfigurationError(error_message) return name.split(".", 1)
null
175,655
import locale import logging import os import sys from pip._vendor.six.moves import configparser from pip._internal.exceptions import ( ConfigurationError, ConfigurationFileCouldNotBeLoaded, ) from pip._internal.utils import appdirs from pip._internal.utils.compat import WINDOWS, expanduser from pip._internal.utils.misc import ensure_dir, enum from pip._internal.utils.typing import MYPY_CHECK_RUNNING kinds = enum( USER="user", # User Specific GLOBAL="global", # System Wide SITE="site", # [Virtual] Environment Specific ENV="env", # from PIP_CONFIG_FILE ENV_VAR="env-var", # from Environment Variables ) CONFIG_BASENAME = 'pip.ini' if WINDOWS else 'pip.conf' import sys if sys.byteorder == 'little': _nbo = '<' else: _nbo = '>' def expanduser(path): # type: (str) -> str """ Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path.startswith('~/') and expanded.startswith('//'): expanded = expanded[1:] return expanded WINDOWS = (sys.platform.startswith("win") or (sys.platform == 'cli' and os.name == 'nt')) def get_configuration_files(): # type: () -> Dict[Kind, List[str]] global_config_files = [ os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs('pip') ] site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME) legacy_config_file = os.path.join( expanduser('~'), 'pip' if WINDOWS else '.pip', CONFIG_BASENAME, ) new_config_file = os.path.join( appdirs.user_config_dir("pip"), CONFIG_BASENAME ) return { kinds.GLOBAL: global_config_files, kinds.SITE: [site_config_file], kinds.USER: [legacy_config_file, new_config_file], }
null
175,656
import json import re from pip._vendor import six from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.utils.typing import MYPY_CHECK_RUNNING class DirectUrlValidationError(Exception): pass def _get(d, expected_type, key, default=None): # type: (Dict[str, Any], Type[T], str, Optional[T]) -> Optional[T] """Get value from dictionary and verify expected type.""" if key not in d: return default value = d[key] if six.PY2 and expected_type is str: expected_type = six.string_types # type: ignore if not isinstance(value, expected_type): raise DirectUrlValidationError( "{!r} has unexpected type for {} (expected {})".format( value, key, expected_type ) ) return value def _get_required(d, expected_type, key, default=None): # type: (Dict[str, Any], Type[T], str, Optional[T]) -> T value = _get(d, expected_type, key, default) if value is None: raise DirectUrlValidationError("{} must have a value".format(key)) return value
null
175,657
import json import re from pip._vendor import six from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.utils.typing import MYPY_CHECK_RUNNING class DirectUrlValidationError(Exception): pass def _exactly_one_of(infos): # type: (Iterable[Optional[InfoType]]) -> InfoType infos = [info for info in infos if info is not None] if not infos: raise DirectUrlValidationError( "missing one of archive_info, dir_info, vcs_info" ) if len(infos) > 1: raise DirectUrlValidationError( "more than one of archive_info, dir_info, vcs_info" ) assert infos[0] is not None return infos[0]
null
175,658
import json import re from pip._vendor import six from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.utils.typing import MYPY_CHECK_RUNNING The provided code snippet includes necessary dependencies for implementing the `_filter_none` function. Write a Python function `def _filter_none(**kwargs)` to solve the following problem: Make dict excluding None values. Here is the function: def _filter_none(**kwargs): # type: (Any) -> Dict[str, Any] """Make dict excluding None values.""" return {k: v for k, v in kwargs.items() if v is not None}
Make dict excluding None values.
175,659
from __future__ import absolute_import import datetime import hashlib import json import logging import os.path import sys from pip._vendor.packaging import version as packaging_version from pip._vendor.six import ensure_binary from pip._internal.index.collector import LinkCollector from pip._internal.index.package_finder import PackageFinder from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.utils.filesystem import ( adjacent_tmp_file, check_path_owner, replace, ) from pip._internal.utils.misc import ( ensure_dir, get_distribution, get_installed_version, ) from pip._internal.utils.packaging import get_installer from pip._internal.utils.typing import MYPY_CHECK_RUNNING def ensure_binary(s, encoding='utf-8', errors='strict'): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, binary_type): return s if isinstance(s, text_type): return s.encode(encoding, errors) raise TypeError("not expecting type '%s'" % type(s)) def _get_statefile_name(key): # type: (Union[str, Text]) -> str key_bytes = ensure_binary(key) name = hashlib.sha224(key_bytes).hexdigest() return name
null
175,660
from __future__ import absolute_import import datetime import hashlib import json import logging import os.path import sys from pip._vendor.packaging import version as packaging_version from pip._vendor.six import ensure_binary from pip._internal.index.collector import LinkCollector from pip._internal.index.package_finder import PackageFinder from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.utils.filesystem import ( adjacent_tmp_file, check_path_owner, replace, ) from pip._internal.utils.misc import ( ensure_dir, get_distribution, get_installed_version, ) from pip._internal.utils.packaging import get_installer from pip._internal.utils.typing import MYPY_CHECK_RUNNING SELFCHECK_DATE_FMT = "%Y-%m-%dT%H:%M:%SZ" logger = logging.getLogger(__name__) class SelfCheckState(object): def __init__(self, cache_dir): # type: (str) -> None self.state = {} # type: Dict[str, Any] self.statefile_path = None # Try to load the existing state if cache_dir: self.statefile_path = os.path.join( cache_dir, "selfcheck", _get_statefile_name(self.key) ) try: with open(self.statefile_path) as statefile: self.state = json.load(statefile) except (IOError, ValueError, KeyError): # Explicitly suppressing exceptions, since we don't want to # error out if the cache file is invalid. pass def key(self): # type: () -> str return sys.prefix def save(self, pypi_version, current_time): # type: (str, datetime.datetime) -> None # If we do not have a path to cache in, don't bother saving. if not self.statefile_path: return # Check to make sure that we own the directory if not check_path_owner(os.path.dirname(self.statefile_path)): return # Now that we've ensured the directory is owned by this user, we'll go # ahead and make sure that all our directories are created. ensure_dir(os.path.dirname(self.statefile_path)) state = { # Include the key so it's easy to tell which pip wrote the # file. "key": self.key, "last_check": current_time.strftime(SELFCHECK_DATE_FMT), "pypi_version": pypi_version, } text = json.dumps(state, sort_keys=True, separators=(",", ":")) with adjacent_tmp_file(self.statefile_path) as f: f.write(ensure_binary(text)) try: # Since we have a prefix-specific state file, we can just # overwrite whatever is there, no need to check. replace(f.name, self.statefile_path) except OSError: # Best effort. pass def was_installed_by_pip(pkg): # type: (str) -> bool """Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. """ dist = get_distribution(pkg) if not dist: return False return "pip" == get_installer(dist) import sys if sys.byteorder == 'little': _nbo = '<' else: _nbo = '>' class LinkCollector(object): """ Responsible for collecting Link objects from all configured locations, making network requests as needed. The class's main method is its collect_links() method. """ def __init__( self, session, # type: PipSession search_scope, # type: SearchScope ): # type: (...) -> None self.search_scope = search_scope self.session = session def create(cls, session, options, suppress_no_index=False): # type: (PipSession, Values, bool) -> LinkCollector """ :param session: The Session to use to make requests. :param suppress_no_index: Whether to ignore the --no-index option when constructing the SearchScope object. """ index_urls = [options.index_url] + options.extra_index_urls if options.no_index and not suppress_no_index: logger.debug( 'Ignoring indexes: %s', ','.join(redact_auth_from_url(url) for url in index_urls), ) index_urls = [] # Make sure find_links is a list before passing to create(). find_links = options.find_links or [] search_scope = SearchScope.create( find_links=find_links, index_urls=index_urls, ) link_collector = LinkCollector( session=session, search_scope=search_scope, ) return link_collector def find_links(self): # type: () -> List[str] return self.search_scope.find_links def fetch_page(self, location): # type: (Link) -> Optional[HTMLPage] """ Fetch an HTML page containing package links. """ return _get_html_page(location, session=self.session) def collect_links(self, project_name): # type: (str) -> CollectedLinks """Find all available links for the given project name. :return: All the Link objects (unfiltered), as a CollectedLinks object. """ search_scope = self.search_scope index_locations = search_scope.get_index_urls_locations(project_name) index_file_loc, index_url_loc = group_locations(index_locations) fl_file_loc, fl_url_loc = group_locations( self.find_links, expand_dir=True, ) file_links = [ Link(url) for url in itertools.chain(index_file_loc, fl_file_loc) ] # We trust every directly linked archive in find_links find_link_links = [Link(url, '-f') for url in self.find_links] # We trust every url that the user has given us whether it was given # via --index-url or --find-links. # We want to filter out anything that does not have a secure origin. url_locations = [ link for link in itertools.chain( # Mark PyPI indices as "cache_link_parsing == False" -- this # will avoid caching the result of parsing the page for links. (Link(url, cache_link_parsing=False) for url in index_url_loc), (Link(url) for url in fl_url_loc), ) if self.session.is_secure_origin(link) ] url_locations = _remove_duplicate_links(url_locations) lines = [ '{} location(s) to search for versions of {}:'.format( len(url_locations), project_name, ), ] for link in url_locations: lines.append('* {}'.format(link)) logger.debug('\n'.join(lines)) return CollectedLinks( files=file_links, find_links=find_link_links, project_urls=url_locations, ) class PackageFinder(object): """This finds packages. This is meant to match easy_install's technique for looking for packages, by reading pages and looking for appropriate links. """ def __init__( self, link_collector, # type: LinkCollector target_python, # type: TargetPython allow_yanked, # type: bool format_control=None, # type: Optional[FormatControl] candidate_prefs=None, # type: CandidatePreferences ignore_requires_python=None, # type: Optional[bool] ): # type: (...) -> None """ This constructor is primarily meant to be used by the create() class method and from tests. :param format_control: A FormatControl object, used to control the selection of source packages / binary packages when consulting the index and links. :param candidate_prefs: Options to use when creating a CandidateEvaluator object. """ if candidate_prefs is None: candidate_prefs = CandidatePreferences() format_control = format_control or FormatControl(set(), set()) self._allow_yanked = allow_yanked self._candidate_prefs = candidate_prefs self._ignore_requires_python = ignore_requires_python self._link_collector = link_collector self._target_python = target_python self.format_control = format_control # These are boring links that have already been logged somehow. self._logged_links = set() # type: Set[Link] # Don't include an allow_yanked default value to make sure each call # site considers whether yanked releases are allowed. This also causes # that decision to be made explicit in the calling code, which helps # people when reading the code. def create( cls, link_collector, # type: LinkCollector selection_prefs, # type: SelectionPreferences target_python=None, # type: Optional[TargetPython] ): # type: (...) -> PackageFinder """Create a PackageFinder. :param selection_prefs: The candidate selection preferences, as a SelectionPreferences object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. """ if target_python is None: target_python = TargetPython() candidate_prefs = CandidatePreferences( prefer_binary=selection_prefs.prefer_binary, allow_all_prereleases=selection_prefs.allow_all_prereleases, ) return cls( candidate_prefs=candidate_prefs, link_collector=link_collector, target_python=target_python, allow_yanked=selection_prefs.allow_yanked, format_control=selection_prefs.format_control, ignore_requires_python=selection_prefs.ignore_requires_python, ) def target_python(self): # type: () -> TargetPython return self._target_python def search_scope(self): # type: () -> SearchScope return self._link_collector.search_scope def search_scope(self, search_scope): # type: (SearchScope) -> None self._link_collector.search_scope = search_scope def find_links(self): # type: () -> List[str] return self._link_collector.find_links def index_urls(self): # type: () -> List[str] return self.search_scope.index_urls def trusted_hosts(self): # type: () -> Iterable[str] for host_port in self._link_collector.session.pip_trusted_origins: yield build_netloc(*host_port) def allow_all_prereleases(self): # type: () -> bool return self._candidate_prefs.allow_all_prereleases def set_allow_all_prereleases(self): # type: () -> None self._candidate_prefs.allow_all_prereleases = True def prefer_binary(self): # type: () -> bool return self._candidate_prefs.prefer_binary def set_prefer_binary(self): # type: () -> None self._candidate_prefs.prefer_binary = True def make_link_evaluator(self, project_name): # type: (str) -> LinkEvaluator canonical_name = canonicalize_name(project_name) formats = self.format_control.get_allowed_formats(canonical_name) return LinkEvaluator( project_name=project_name, canonical_name=canonical_name, formats=formats, target_python=self._target_python, allow_yanked=self._allow_yanked, ignore_requires_python=self._ignore_requires_python, ) def _sort_links(self, links): # type: (Iterable[Link]) -> List[Link] """ Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates """ eggs, no_eggs = [], [] seen = set() # type: Set[Link] for link in links: if link not in seen: seen.add(link) if link.egg_fragment: eggs.append(link) else: no_eggs.append(link) return no_eggs + eggs def _log_skipped_link(self, link, reason): # type: (Link, Text) -> None if link not in self._logged_links: # Mark this as a unicode string to prevent "UnicodeEncodeError: # 'ascii' codec can't encode character" in Python 2 when # the reason contains non-ascii characters. # Also, put the link at the end so the reason is more visible # and because the link string is usually very long. logger.debug(u'Skipping link: %s: %s', reason, link) self._logged_links.add(link) def get_install_candidate(self, link_evaluator, link): # type: (LinkEvaluator, Link) -> Optional[InstallationCandidate] """ If the link is a candidate for install, convert it to an InstallationCandidate and return it. Otherwise, return None. """ is_candidate, result = link_evaluator.evaluate_link(link) if not is_candidate: if result: self._log_skipped_link(link, reason=result) return None return InstallationCandidate( name=link_evaluator.project_name, link=link, # Convert the Text result to str since InstallationCandidate # accepts str. version=str(result), ) def evaluate_links(self, link_evaluator, links): # type: (LinkEvaluator, Iterable[Link]) -> List[InstallationCandidate] """ Convert links that are candidates to InstallationCandidate objects. """ candidates = [] for link in self._sort_links(links): candidate = self.get_install_candidate(link_evaluator, link) if candidate is not None: candidates.append(candidate) return candidates def process_project_url(self, project_url, link_evaluator): # type: (Link, LinkEvaluator) -> List[InstallationCandidate] logger.debug( 'Fetching project page and analyzing links: %s', project_url, ) html_page = self._link_collector.fetch_page(project_url) if html_page is None: return [] page_links = list(parse_links(html_page)) with indent_log(): package_links = self.evaluate_links( link_evaluator, links=page_links, ) return package_links def find_all_candidates(self, project_name): # type: (str) -> List[InstallationCandidate] """Find all available InstallationCandidate for project_name This checks index_urls and find_links. All versions found are returned as an InstallationCandidate list. See LinkEvaluator.evaluate_link() for details on which files are accepted. """ collected_links = self._link_collector.collect_links(project_name) link_evaluator = self.make_link_evaluator(project_name) find_links_versions = self.evaluate_links( link_evaluator, links=collected_links.find_links, ) page_versions = [] for project_url in collected_links.project_urls: package_links = self.process_project_url( project_url, link_evaluator=link_evaluator, ) page_versions.extend(package_links) file_versions = self.evaluate_links( link_evaluator, links=collected_links.files, ) if file_versions: file_versions.sort(reverse=True) logger.debug( 'Local files found: %s', ', '.join([ url_to_path(candidate.link.url) for candidate in file_versions ]) ) # This is an intentional priority ordering return file_versions + find_links_versions + page_versions def make_candidate_evaluator( self, project_name, # type: str specifier=None, # type: Optional[specifiers.BaseSpecifier] hashes=None, # type: Optional[Hashes] ): # type: (...) -> CandidateEvaluator """Create a CandidateEvaluator object to use. """ candidate_prefs = self._candidate_prefs return CandidateEvaluator.create( project_name=project_name, target_python=self._target_python, prefer_binary=candidate_prefs.prefer_binary, allow_all_prereleases=candidate_prefs.allow_all_prereleases, specifier=specifier, hashes=hashes, ) def find_best_candidate( self, project_name, # type: str specifier=None, # type: Optional[specifiers.BaseSpecifier] hashes=None, # type: Optional[Hashes] ): # type: (...) -> BestCandidateResult """Find matches for the given project and specifier. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :return: A `BestCandidateResult` instance. """ candidates = self.find_all_candidates(project_name) candidate_evaluator = self.make_candidate_evaluator( project_name=project_name, specifier=specifier, hashes=hashes, ) return candidate_evaluator.compute_best_candidate(candidates) def find_requirement(self, req, upgrade): # type: (InstallRequirement, bool) -> Optional[InstallationCandidate] """Try to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a InstallationCandidate if found, Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise """ hashes = req.hashes(trust_internet=False) best_candidate_result = self.find_best_candidate( req.name, specifier=req.specifier, hashes=hashes, ) best_candidate = best_candidate_result.best_candidate installed_version = None # type: Optional[_BaseVersion] if req.satisfied_by is not None: installed_version = parse_version(req.satisfied_by.version) def _format_versions(cand_iter): # type: (Iterable[InstallationCandidate]) -> str # This repeated parse_version and str() conversion is needed to # handle different vendoring sources from pip and pkg_resources. # If we stop using the pkg_resources provided specifier and start # using our own, we can drop the cast to str(). return ", ".join(sorted( {str(c.version) for c in cand_iter}, key=parse_version, )) or "none" if installed_version is None and best_candidate is None: logger.critical( 'Could not find a version that satisfies the requirement %s ' '(from versions: %s)', req, _format_versions(best_candidate_result.iter_all()), ) raise DistributionNotFound( 'No matching distribution found for {}'.format( req) ) best_installed = False if installed_version and ( best_candidate is None or best_candidate.version <= installed_version): best_installed = True if not upgrade and installed_version is not None: if best_installed: logger.debug( 'Existing installed version (%s) is most up-to-date and ' 'satisfies requirement', installed_version, ) else: logger.debug( 'Existing installed version (%s) satisfies requirement ' '(most up-to-date version is %s)', installed_version, best_candidate.version, ) return None if best_installed: # We have an existing version, and its the best version logger.debug( 'Installed version (%s) is most up-to-date (past versions: ' '%s)', installed_version, _format_versions(best_candidate_result.iter_applicable()), ) raise BestVersionAlreadyInstalled logger.debug( 'Using version %s (newest of versions: %s)', best_candidate.version, _format_versions(best_candidate_result.iter_applicable()), ) return best_candidate class SelectionPreferences(object): """ Encapsulates the candidate selection preferences for downloading and installing files. """ __slots__ = ['allow_yanked', 'allow_all_prereleases', 'format_control', 'prefer_binary', 'ignore_requires_python'] # Don't include an allow_yanked default value to make sure each call # site considers whether yanked releases are allowed. This also causes # that decision to be made explicit in the calling code, which helps # people when reading the code. def __init__( self, allow_yanked, # type: bool allow_all_prereleases=False, # type: bool format_control=None, # type: Optional[FormatControl] prefer_binary=False, # type: bool ignore_requires_python=None, # type: Optional[bool] ): # type: (...) -> None """Create a SelectionPreferences object. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param format_control: A FormatControl object or None. Used to control the selection of source packages / binary packages when consulting the index and links. :param prefer_binary: Whether to prefer an old, but valid, binary dist over a new source dist. :param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False. """ if ignore_requires_python is None: ignore_requires_python = False self.allow_yanked = allow_yanked self.allow_all_prereleases = allow_all_prereleases self.format_control = format_control self.prefer_binary = prefer_binary self.ignore_requires_python = ignore_requires_python def get_installed_version(dist_name, working_set=None): """Get the installed version of dist_name avoiding pkg_resources cache""" # Create a requirement that we'll look for inside of setuptools. req = pkg_resources.Requirement.parse(dist_name) if working_set is None: # We want to avoid having this cached, so we need to construct a new # working set each time. working_set = pkg_resources.WorkingSet() # Get the installed distribution from our working set dist = working_set.find(req) # Check to see if we got an installed distribution or not, if we did # we want to return it's version. return dist.version if dist else None The provided code snippet includes necessary dependencies for implementing the `pip_self_version_check` function. Write a Python function `def pip_self_version_check(session, options)` to solve the following problem: Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. Here is the function: def pip_self_version_check(session, options): # type: (PipSession, optparse.Values) -> None """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if not installed_version: return pip_version = packaging_version.parse(installed_version) pypi_version = None try: state = SelfCheckState(cache_dir=options.cache_dir) current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime( state.state["last_check"], SELFCHECK_DATE_FMT ) if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: # Lets use PackageFinder to see what the latest pip version is link_collector = LinkCollector.create( session, options=options, suppress_no_index=True, ) # Pass allow_yanked=False so we don't suggest upgrading to a # yanked version. selection_prefs = SelectionPreferences( allow_yanked=False, allow_all_prereleases=False, # Explicitly set to False ) finder = PackageFinder.create( link_collector=link_collector, selection_prefs=selection_prefs, ) best_candidate = finder.find_best_candidate("pip").best_candidate if best_candidate is None: return pypi_version = str(best_candidate.version) # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) local_version_is_older = ( pip_version < remote_version and pip_version.base_version != remote_version.base_version and was_installed_by_pip('pip') ) # Determine if our pypi_version is older if not local_version_is_older: return # We cannot tell how the current pip is available in the current # command context, so be pragmatic here and suggest the command # that's always available. This does not accommodate spaces in # `sys.executable`. pip_cmd = "{} -m pip".format(sys.executable) logger.warning( "You are using pip version %s; however, version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, pypi_version, pip_cmd ) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path.
175,661
from __future__ import absolute_import import contextlib import errno import logging import logging.handlers import os import sys from logging import Filter, getLogger from pip._vendor.six import PY2 from pip._internal.utils.compat import WINDOWS from pip._internal.utils.deprecation import DEPRECATION_MSG_PREFIX from pip._internal.utils.misc import ensure_dir The provided code snippet includes necessary dependencies for implementing the `_is_broken_pipe_error` function. Write a Python function `def _is_broken_pipe_error(exc_class, exc)` to solve the following problem: See the docstring for non-Windows Python 3 below. Here is the function: def _is_broken_pipe_error(exc_class, exc): """See the docstring for non-Windows Python 3 below.""" return (exc_class is IOError and exc.errno in (errno.EINVAL, errno.EPIPE))
See the docstring for non-Windows Python 3 below.