1"""Support for installing and building the "wheel" binary package format.
2"""
3
4import collections
5import compileall
6import contextlib
7import csv
8import importlib
9import logging
10import os.path
11import re
12import shutil
13import sys
14import warnings
15from base64 import urlsafe_b64encode
16from email.message import Message
17from itertools import chain, filterfalse, starmap
18from typing import (
19    IO,
20    TYPE_CHECKING,
21    Any,
22    BinaryIO,
23    Callable,
24    Dict,
25    Iterable,
26    Iterator,
27    List,
28    NewType,
29    Optional,
30    Sequence,
31    Set,
32    Tuple,
33    Union,
34    cast,
35)
36from zipfile import ZipFile, ZipInfo
37
38from pip._vendor.distlib.scripts import ScriptMaker
39from pip._vendor.distlib.util import get_export_entry
40from pip._vendor.packaging.utils import canonicalize_name
41from pip._vendor.six import ensure_str, ensure_text, reraise
42
43from pip._internal.exceptions import InstallationError
44from pip._internal.locations import get_major_minor_version
45from pip._internal.metadata import BaseDistribution, get_wheel_distribution
46from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl
47from pip._internal.models.scheme import SCHEME_KEYS, Scheme
48from pip._internal.utils.filesystem import adjacent_tmp_file, replace
49from pip._internal.utils.misc import captured_stdout, ensure_dir, hash_file, partition
50from pip._internal.utils.unpacking import (
51    current_umask,
52    is_within_directory,
53    set_extracted_file_to_default_mode_plus_executable,
54    zip_item_is_executable,
55)
56from pip._internal.utils.wheel import parse_wheel
57
58if TYPE_CHECKING:
59    from typing import Protocol
60
61    class File(Protocol):
62        src_record_path = None  # type: RecordPath
63        dest_path = None  # type: str
64        changed = None  # type: bool
65
66        def save(self):
67            # type: () -> None
68            pass
69
70
71logger = logging.getLogger(__name__)
72
73RecordPath = NewType('RecordPath', str)
74InstalledCSVRow = Tuple[RecordPath, str, Union[int, str]]
75
76
77def rehash(path, blocksize=1 << 20):
78    # type: (str, int) -> Tuple[str, str]
79    """Return (encoded_digest, length) for path using hashlib.sha256()"""
80    h, length = hash_file(path, blocksize)
81    digest = 'sha256=' + urlsafe_b64encode(
82        h.digest()
83    ).decode('latin1').rstrip('=')
84    return (digest, str(length))
85
86
87def csv_io_kwargs(mode):
88    # type: (str) -> Dict[str, Any]
89    """Return keyword arguments to properly open a CSV file
90    in the given mode.
91    """
92    return {'mode': mode, 'newline': '', 'encoding': 'utf-8'}
93
94
95def fix_script(path):
96    # type: (str) -> bool
97    """Replace #!python with #!/path/to/python
98    Return True if file was changed.
99    """
100    # XXX RECORD hashes will need to be updated
101    assert os.path.isfile(path)
102
103    with open(path, 'rb') as script:
104        firstline = script.readline()
105        if not firstline.startswith(b'#!python'):
106            return False
107        exename = sys.executable.encode(sys.getfilesystemencoding())
108        firstline = b'#!' + exename + os.linesep.encode("ascii")
109        rest = script.read()
110    with open(path, 'wb') as script:
111        script.write(firstline)
112        script.write(rest)
113    return True
114
115
116def wheel_root_is_purelib(metadata):
117    # type: (Message) -> bool
118    return metadata.get("Root-Is-Purelib", "").lower() == "true"
119
120
121def get_entrypoints(dist: BaseDistribution) -> Tuple[Dict[str, str], Dict[str, str]]:
122    console_scripts = {}
123    gui_scripts = {}
124    for entry_point in dist.iter_entry_points():
125        if entry_point.group == "console_scripts":
126            console_scripts[entry_point.name] = entry_point.value
127        elif entry_point.group == "gui_scripts":
128            gui_scripts[entry_point.name] = entry_point.value
129    return console_scripts, gui_scripts
130
131
132def message_about_scripts_not_on_PATH(scripts):
133    # type: (Sequence[str]) -> Optional[str]
134    """Determine if any scripts are not on PATH and format a warning.
135    Returns a warning message if one or more scripts are not on PATH,
136    otherwise None.
137    """
138    if not scripts:
139        return None
140
141    # Group scripts by the path they were installed in
142    grouped_by_dir = collections.defaultdict(set)  # type: Dict[str, Set[str]]
143    for destfile in scripts:
144        parent_dir = os.path.dirname(destfile)
145        script_name = os.path.basename(destfile)
146        grouped_by_dir[parent_dir].add(script_name)
147
148    # We don't want to warn for directories that are on PATH.
149    not_warn_dirs = [
150        os.path.normcase(i).rstrip(os.sep) for i in
151        os.environ.get("PATH", "").split(os.pathsep)
152    ]
153    # If an executable sits with sys.executable, we don't warn for it.
154    #     This covers the case of venv invocations without activating the venv.
155    not_warn_dirs.append(os.path.normcase(os.path.dirname(sys.executable)))
156    warn_for = {
157        parent_dir: scripts for parent_dir, scripts in grouped_by_dir.items()
158        if os.path.normcase(parent_dir) not in not_warn_dirs
159    }  # type: Dict[str, Set[str]]
160    if not warn_for:
161        return None
162
163    # Format a message
164    msg_lines = []
165    for parent_dir, dir_scripts in warn_for.items():
166        sorted_scripts = sorted(dir_scripts)  # type: List[str]
167        if len(sorted_scripts) == 1:
168            start_text = "script {} is".format(sorted_scripts[0])
169        else:
170            start_text = "scripts {} are".format(
171                ", ".join(sorted_scripts[:-1]) + " and " + sorted_scripts[-1]
172            )
173
174        msg_lines.append(
175            "The {} installed in '{}' which is not on PATH."
176            .format(start_text, parent_dir)
177        )
178
179    last_line_fmt = (
180        "Consider adding {} to PATH or, if you prefer "
181        "to suppress this warning, use --no-warn-script-location."
182    )
183    if len(msg_lines) == 1:
184        msg_lines.append(last_line_fmt.format("this directory"))
185    else:
186        msg_lines.append(last_line_fmt.format("these directories"))
187
188    # Add a note if any directory starts with ~
189    warn_for_tilde = any(
190        i[0] == "~" for i in os.environ.get("PATH", "").split(os.pathsep) if i
191    )
192    if warn_for_tilde:
193        tilde_warning_msg = (
194            "NOTE: The current PATH contains path(s) starting with `~`, "
195            "which may not be expanded by all applications."
196        )
197        msg_lines.append(tilde_warning_msg)
198
199    # Returns the formatted multiline message
200    return "\n".join(msg_lines)
201
202
203def _normalized_outrows(outrows):
204    # type: (Iterable[InstalledCSVRow]) -> List[Tuple[str, str, str]]
205    """Normalize the given rows of a RECORD file.
206
207    Items in each row are converted into str. Rows are then sorted to make
208    the value more predictable for tests.
209
210    Each row is a 3-tuple (path, hash, size) and corresponds to a record of
211    a RECORD file (see PEP 376 and PEP 427 for details).  For the rows
212    passed to this function, the size can be an integer as an int or string,
213    or the empty string.
214    """
215    # Normally, there should only be one row per path, in which case the
216    # second and third elements don't come into play when sorting.
217    # However, in cases in the wild where a path might happen to occur twice,
218    # we don't want the sort operation to trigger an error (but still want
219    # determinism).  Since the third element can be an int or string, we
220    # coerce each element to a string to avoid a TypeError in this case.
221    # For additional background, see--
222    # https://github.com/pypa/pip/issues/5868
223    return sorted(
224        (ensure_str(record_path, encoding='utf-8'), hash_, str(size))
225        for record_path, hash_, size in outrows
226    )
227
228
229def _record_to_fs_path(record_path):
230    # type: (RecordPath) -> str
231    return record_path
232
233
234def _fs_to_record_path(path, relative_to=None):
235    # type: (str, Optional[str]) -> RecordPath
236    if relative_to is not None:
237        # On Windows, do not handle relative paths if they belong to different
238        # logical disks
239        if os.path.splitdrive(path)[0].lower() == \
240                os.path.splitdrive(relative_to)[0].lower():
241            path = os.path.relpath(path, relative_to)
242    path = path.replace(os.path.sep, '/')
243    return cast('RecordPath', path)
244
245
246def _parse_record_path(record_column):
247    # type: (str) -> RecordPath
248    p = ensure_text(record_column, encoding='utf-8')
249    return cast('RecordPath', p)
250
251
252def get_csv_rows_for_installed(
253    old_csv_rows,  # type: List[List[str]]
254    installed,  # type: Dict[RecordPath, RecordPath]
255    changed,  # type: Set[RecordPath]
256    generated,  # type: List[str]
257    lib_dir,  # type: str
258):
259    # type: (...) -> List[InstalledCSVRow]
260    """
261    :param installed: A map from archive RECORD path to installation RECORD
262        path.
263    """
264    installed_rows = []  # type: List[InstalledCSVRow]
265    for row in old_csv_rows:
266        if len(row) > 3:
267            logger.warning('RECORD line has more than three elements: %s', row)
268        old_record_path = _parse_record_path(row[0])
269        new_record_path = installed.pop(old_record_path, old_record_path)
270        if new_record_path in changed:
271            digest, length = rehash(_record_to_fs_path(new_record_path))
272        else:
273            digest = row[1] if len(row) > 1 else ''
274            length = row[2] if len(row) > 2 else ''
275        installed_rows.append((new_record_path, digest, length))
276    for f in generated:
277        path = _fs_to_record_path(f, lib_dir)
278        digest, length = rehash(f)
279        installed_rows.append((path, digest, length))
280    for installed_record_path in installed.values():
281        installed_rows.append((installed_record_path, '', ''))
282    return installed_rows
283
284
285def get_console_script_specs(console):
286    # type: (Dict[str, str]) -> List[str]
287    """
288    Given the mapping from entrypoint name to callable, return the relevant
289    console script specs.
290    """
291    # Don't mutate caller's version
292    console = console.copy()
293
294    scripts_to_generate = []
295
296    # Special case pip and setuptools to generate versioned wrappers
297    #
298    # The issue is that some projects (specifically, pip and setuptools) use
299    # code in setup.py to create "versioned" entry points - pip2.7 on Python
300    # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into
301    # the wheel metadata at build time, and so if the wheel is installed with
302    # a *different* version of Python the entry points will be wrong. The
303    # correct fix for this is to enhance the metadata to be able to describe
304    # such versioned entry points, but that won't happen till Metadata 2.0 is
305    # available.
306    # In the meantime, projects using versioned entry points will either have
307    # incorrect versioned entry points, or they will not be able to distribute
308    # "universal" wheels (i.e., they will need a wheel per Python version).
309    #
310    # Because setuptools and pip are bundled with _ensurepip and virtualenv,
311    # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we
312    # override the versioned entry points in the wheel and generate the
313    # correct ones. This code is purely a short-term measure until Metadata 2.0
314    # is available.
315    #
316    # To add the level of hack in this section of code, in order to support
317    # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment
318    # variable which will control which version scripts get installed.
319    #
320    # ENSUREPIP_OPTIONS=altinstall
321    #   - Only pipX.Y and easy_install-X.Y will be generated and installed
322    # ENSUREPIP_OPTIONS=install
323    #   - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note
324    #     that this option is technically if ENSUREPIP_OPTIONS is set and is
325    #     not altinstall
326    # DEFAULT
327    #   - The default behavior is to install pip, pipX, pipX.Y, easy_install
328    #     and easy_install-X.Y.
329    pip_script = console.pop('pip', None)
330    if pip_script:
331        if "ENSUREPIP_OPTIONS" not in os.environ:
332            scripts_to_generate.append('pip = ' + pip_script)
333
334        if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall":
335            scripts_to_generate.append(
336                'pip{} = {}'.format(sys.version_info[0], pip_script)
337            )
338
339        scripts_to_generate.append(
340            f'pip{get_major_minor_version()} = {pip_script}'
341        )
342        # Delete any other versioned pip entry points
343        pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)]
344        for k in pip_ep:
345            del console[k]
346    easy_install_script = console.pop('easy_install', None)
347    if easy_install_script:
348        if "ENSUREPIP_OPTIONS" not in os.environ:
349            scripts_to_generate.append(
350                'easy_install = ' + easy_install_script
351            )
352
353        scripts_to_generate.append(
354            'easy_install-{} = {}'.format(
355                get_major_minor_version(), easy_install_script
356            )
357        )
358        # Delete any other versioned easy_install entry points
359        easy_install_ep = [
360            k for k in console if re.match(r'easy_install(-\d\.\d)?$', k)
361        ]
362        for k in easy_install_ep:
363            del console[k]
364
365    # Generate the console entry points specified in the wheel
366    scripts_to_generate.extend(starmap('{} = {}'.format, console.items()))
367
368    return scripts_to_generate
369
370
371class ZipBackedFile:
372    def __init__(self, src_record_path, dest_path, zip_file):
373        # type: (RecordPath, str, ZipFile) -> None
374        self.src_record_path = src_record_path
375        self.dest_path = dest_path
376        self._zip_file = zip_file
377        self.changed = False
378
379    def _getinfo(self):
380        # type: () -> ZipInfo
381        return self._zip_file.getinfo(self.src_record_path)
382
383    def save(self):
384        # type: () -> None
385        # directory creation is lazy and after file filtering
386        # to ensure we don't install empty dirs; empty dirs can't be
387        # uninstalled.
388        parent_dir = os.path.dirname(self.dest_path)
389        ensure_dir(parent_dir)
390
391        # When we open the output file below, any existing file is truncated
392        # before we start writing the new contents. This is fine in most
393        # cases, but can cause a segfault if pip has loaded a shared
394        # object (e.g. from pyopenssl through its vendored urllib3)
395        # Since the shared object is mmap'd an attempt to call a
396        # symbol in it will then cause a segfault. Unlinking the file
397        # allows writing of new contents while allowing the process to
398        # continue to use the old copy.
399        if os.path.exists(self.dest_path):
400            os.unlink(self.dest_path)
401
402        zipinfo = self._getinfo()
403
404        with self._zip_file.open(zipinfo) as f:
405            with open(self.dest_path, "wb") as dest:
406                shutil.copyfileobj(f, dest)
407
408        if zip_item_is_executable(zipinfo):
409            set_extracted_file_to_default_mode_plus_executable(self.dest_path)
410
411
412class ScriptFile:
413    def __init__(self, file):
414        # type: (File) -> None
415        self._file = file
416        self.src_record_path = self._file.src_record_path
417        self.dest_path = self._file.dest_path
418        self.changed = False
419
420    def save(self):
421        # type: () -> None
422        self._file.save()
423        self.changed = fix_script(self.dest_path)
424
425
426class MissingCallableSuffix(InstallationError):
427    def __init__(self, entry_point):
428        # type: (str) -> None
429        super().__init__(
430            "Invalid script entry point: {} - A callable "
431            "suffix is required. Cf https://packaging.python.org/"
432            "specifications/entry-points/#use-for-scripts for more "
433            "information.".format(entry_point)
434        )
435
436
437def _raise_for_invalid_entrypoint(specification):
438    # type: (str) -> None
439    entry = get_export_entry(specification)
440    if entry is not None and entry.suffix is None:
441        raise MissingCallableSuffix(str(entry))
442
443
444class PipScriptMaker(ScriptMaker):
445    def make(self, specification, options=None):
446        # type: (str, Dict[str, Any]) -> List[str]
447        _raise_for_invalid_entrypoint(specification)
448        return super().make(specification, options)
449
450
451def _install_wheel(
452    name,  # type: str
453    wheel_zip,  # type: ZipFile
454    wheel_path,  # type: str
455    scheme,  # type: Scheme
456    pycompile=True,  # type: bool
457    warn_script_location=True,  # type: bool
458    direct_url=None,  # type: Optional[DirectUrl]
459    requested=False,  # type: bool
460):
461    # type: (...) -> None
462    """Install a wheel.
463
464    :param name: Name of the project to install
465    :param wheel_zip: open ZipFile for wheel being installed
466    :param scheme: Distutils scheme dictating the install directories
467    :param req_description: String used in place of the requirement, for
468        logging
469    :param pycompile: Whether to byte-compile installed Python files
470    :param warn_script_location: Whether to check that scripts are installed
471        into a directory on PATH
472    :raises UnsupportedWheel:
473        * when the directory holds an unpacked wheel with incompatible
474          Wheel-Version
475        * when the .dist-info dir does not match the wheel
476    """
477    info_dir, metadata = parse_wheel(wheel_zip, name)
478
479    if wheel_root_is_purelib(metadata):
480        lib_dir = scheme.purelib
481    else:
482        lib_dir = scheme.platlib
483
484    # Record details of the files moved
485    #   installed = files copied from the wheel to the destination
486    #   changed = files changed while installing (scripts #! line typically)
487    #   generated = files newly generated during the install (script wrappers)
488    installed = {}  # type: Dict[RecordPath, RecordPath]
489    changed = set()  # type: Set[RecordPath]
490    generated = []  # type: List[str]
491
492    def record_installed(srcfile, destfile, modified=False):
493        # type: (RecordPath, str, bool) -> None
494        """Map archive RECORD paths to installation RECORD paths."""
495        newpath = _fs_to_record_path(destfile, lib_dir)
496        installed[srcfile] = newpath
497        if modified:
498            changed.add(_fs_to_record_path(destfile))
499
500    def all_paths():
501        # type: () -> Iterable[RecordPath]
502        names = wheel_zip.namelist()
503        # If a flag is set, names may be unicode in Python 2. We convert to
504        # text explicitly so these are valid for lookup in RECORD.
505        decoded_names = map(ensure_text, names)
506        for name in decoded_names:
507            yield cast("RecordPath", name)
508
509    def is_dir_path(path):
510        # type: (RecordPath) -> bool
511        return path.endswith("/")
512
513    def assert_no_path_traversal(dest_dir_path, target_path):
514        # type: (str, str) -> None
515        if not is_within_directory(dest_dir_path, target_path):
516            message = (
517                "The wheel {!r} has a file {!r} trying to install"
518                " outside the target directory {!r}"
519            )
520            raise InstallationError(
521                message.format(wheel_path, target_path, dest_dir_path)
522            )
523
524    def root_scheme_file_maker(zip_file, dest):
525        # type: (ZipFile, str) -> Callable[[RecordPath], File]
526        def make_root_scheme_file(record_path):
527            # type: (RecordPath) -> File
528            normed_path = os.path.normpath(record_path)
529            dest_path = os.path.join(dest, normed_path)
530            assert_no_path_traversal(dest, dest_path)
531            return ZipBackedFile(record_path, dest_path, zip_file)
532
533        return make_root_scheme_file
534
535    def data_scheme_file_maker(zip_file, scheme):
536        # type: (ZipFile, Scheme) -> Callable[[RecordPath], File]
537        scheme_paths = {}
538        for key in SCHEME_KEYS:
539            encoded_key = ensure_text(key)
540            scheme_paths[encoded_key] = ensure_text(
541                getattr(scheme, key), encoding=sys.getfilesystemencoding()
542            )
543
544        def make_data_scheme_file(record_path):
545            # type: (RecordPath) -> File
546            normed_path = os.path.normpath(record_path)
547            try:
548                _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2)
549            except ValueError:
550                message = (
551                    "Unexpected file in {}: {!r}. .data directory contents"
552                    " should be named like: '<scheme key>/<path>'."
553                ).format(wheel_path, record_path)
554                raise InstallationError(message)
555
556            try:
557                scheme_path = scheme_paths[scheme_key]
558            except KeyError:
559                valid_scheme_keys = ", ".join(sorted(scheme_paths))
560                message = (
561                    "Unknown scheme key used in {}: {} (for file {!r}). .data"
562                    " directory contents should be in subdirectories named"
563                    " with a valid scheme key ({})"
564                ).format(
565                    wheel_path, scheme_key, record_path, valid_scheme_keys
566                )
567                raise InstallationError(message)
568
569            dest_path = os.path.join(scheme_path, dest_subpath)
570            assert_no_path_traversal(scheme_path, dest_path)
571            return ZipBackedFile(record_path, dest_path, zip_file)
572
573        return make_data_scheme_file
574
575    def is_data_scheme_path(path):
576        # type: (RecordPath) -> bool
577        return path.split("/", 1)[0].endswith(".data")
578
579    paths = all_paths()
580    file_paths = filterfalse(is_dir_path, paths)
581    root_scheme_paths, data_scheme_paths = partition(
582        is_data_scheme_path, file_paths
583    )
584
585    make_root_scheme_file = root_scheme_file_maker(
586        wheel_zip,
587        ensure_text(lib_dir, encoding=sys.getfilesystemencoding()),
588    )
589    files = map(make_root_scheme_file, root_scheme_paths)
590
591    def is_script_scheme_path(path):
592        # type: (RecordPath) -> bool
593        parts = path.split("/", 2)
594        return (
595            len(parts) > 2 and
596            parts[0].endswith(".data") and
597            parts[1] == "scripts"
598        )
599
600    other_scheme_paths, script_scheme_paths = partition(
601        is_script_scheme_path, data_scheme_paths
602    )
603
604    make_data_scheme_file = data_scheme_file_maker(wheel_zip, scheme)
605    other_scheme_files = map(make_data_scheme_file, other_scheme_paths)
606    files = chain(files, other_scheme_files)
607
608    # Get the defined entry points
609    distribution = get_wheel_distribution(wheel_path, canonicalize_name(name))
610    console, gui = get_entrypoints(distribution)
611
612    def is_entrypoint_wrapper(file):
613        # type: (File) -> bool
614        # EP, EP.exe and EP-script.py are scripts generated for
615        # entry point EP by setuptools
616        path = file.dest_path
617        name = os.path.basename(path)
618        if name.lower().endswith('.exe'):
619            matchname = name[:-4]
620        elif name.lower().endswith('-script.py'):
621            matchname = name[:-10]
622        elif name.lower().endswith(".pya"):
623            matchname = name[:-4]
624        else:
625            matchname = name
626        # Ignore setuptools-generated scripts
627        return (matchname in console or matchname in gui)
628
629    script_scheme_files = map(make_data_scheme_file, script_scheme_paths)
630    script_scheme_files = filterfalse(
631        is_entrypoint_wrapper, script_scheme_files
632    )
633    script_scheme_files = map(ScriptFile, script_scheme_files)
634    files = chain(files, script_scheme_files)
635
636    for file in files:
637        file.save()
638        record_installed(file.src_record_path, file.dest_path, file.changed)
639
640    def pyc_source_file_paths():
641        # type: () -> Iterator[str]
642        # We de-duplicate installation paths, since there can be overlap (e.g.
643        # file in .data maps to same location as file in wheel root).
644        # Sorting installation paths makes it easier to reproduce and debug
645        # issues related to permissions on existing files.
646        for installed_path in sorted(set(installed.values())):
647            full_installed_path = os.path.join(lib_dir, installed_path)
648            if not os.path.isfile(full_installed_path):
649                continue
650            if not full_installed_path.endswith('.py'):
651                continue
652            yield full_installed_path
653
654    def pyc_output_path(path):
655        # type: (str) -> str
656        """Return the path the pyc file would have been written to.
657        """
658        return importlib.util.cache_from_source(path)
659
660    # Compile all of the pyc files for the installed files
661    if pycompile:
662        with captured_stdout() as stdout:
663            with warnings.catch_warnings():
664                warnings.filterwarnings('ignore')
665                for path in pyc_source_file_paths():
666                    # Python 2's `compileall.compile_file` requires a str in
667                    # error cases, so we must convert to the native type.
668                    path_arg = ensure_str(
669                        path, encoding=sys.getfilesystemencoding()
670                    )
671                    success = compileall.compile_file(
672                        path_arg, force=True, quiet=True
673                    )
674                    if success:
675                        pyc_path = pyc_output_path(path)
676                        assert os.path.exists(pyc_path)
677                        pyc_record_path = cast(
678                            "RecordPath", pyc_path.replace(os.path.sep, "/")
679                        )
680                        record_installed(pyc_record_path, pyc_path)
681        logger.debug(stdout.getvalue())
682
683    maker = PipScriptMaker(None, scheme.scripts)
684
685    # Ensure old scripts are overwritten.
686    # See https://github.com/pypa/pip/issues/1800
687    maker.clobber = True
688
689    # Ensure we don't generate any variants for scripts because this is almost
690    # never what somebody wants.
691    # See https://bitbucket.org/pypa/distlib/issue/35/
692    maker.variants = {''}
693
694    # This is required because otherwise distlib creates scripts that are not
695    # executable.
696    # See https://bitbucket.org/pypa/distlib/issue/32/
697    maker.set_mode = True
698
699    # Generate the console and GUI entry points specified in the wheel
700    scripts_to_generate = get_console_script_specs(console)
701
702    gui_scripts_to_generate = list(starmap('{} = {}'.format, gui.items()))
703
704    generated_console_scripts = maker.make_multiple(scripts_to_generate)
705    generated.extend(generated_console_scripts)
706
707    generated.extend(
708        maker.make_multiple(gui_scripts_to_generate, {'gui': True})
709    )
710
711    if warn_script_location:
712        msg = message_about_scripts_not_on_PATH(generated_console_scripts)
713        if msg is not None:
714            logger.warning(msg)
715
716    generated_file_mode = 0o666 & ~current_umask()
717
718    @contextlib.contextmanager
719    def _generate_file(path, **kwargs):
720        # type: (str, **Any) -> Iterator[BinaryIO]
721        with adjacent_tmp_file(path, **kwargs) as f:
722            yield f
723        os.chmod(f.name, generated_file_mode)
724        replace(f.name, path)
725
726    dest_info_dir = os.path.join(lib_dir, info_dir)
727
728    # Record pip as the installer
729    installer_path = os.path.join(dest_info_dir, 'INSTALLER')
730    with _generate_file(installer_path) as installer_file:
731        installer_file.write(b'pip\n')
732    generated.append(installer_path)
733
734    # Record the PEP 610 direct URL reference
735    if direct_url is not None:
736        direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME)
737        with _generate_file(direct_url_path) as direct_url_file:
738            direct_url_file.write(direct_url.to_json().encode("utf-8"))
739        generated.append(direct_url_path)
740
741    # Record the REQUESTED file
742    if requested:
743        requested_path = os.path.join(dest_info_dir, 'REQUESTED')
744        with open(requested_path, "wb"):
745            pass
746        generated.append(requested_path)
747
748    record_text = distribution.read_text('RECORD')
749    record_rows = list(csv.reader(record_text.splitlines()))
750
751    rows = get_csv_rows_for_installed(
752        record_rows,
753        installed=installed,
754        changed=changed,
755        generated=generated,
756        lib_dir=lib_dir)
757
758    # Record details of all files installed
759    record_path = os.path.join(dest_info_dir, 'RECORD')
760
761    with _generate_file(record_path, **csv_io_kwargs('w')) as record_file:
762        # The type mypy infers for record_file is different for Python 3
763        # (typing.IO[Any]) and Python 2 (typing.BinaryIO). We explicitly
764        # cast to typing.IO[str] as a workaround.
765        writer = csv.writer(cast('IO[str]', record_file))
766        writer.writerows(_normalized_outrows(rows))
767
768
769@contextlib.contextmanager
770def req_error_context(req_description):
771    # type: (str) -> Iterator[None]
772    try:
773        yield
774    except InstallationError as e:
775        message = "For req: {}. {}".format(req_description, e.args[0])
776        reraise(
777            InstallationError, InstallationError(message), sys.exc_info()[2]
778        )
779
780
781def install_wheel(
782    name,  # type: str
783    wheel_path,  # type: str
784    scheme,  # type: Scheme
785    req_description,  # type: str
786    pycompile=True,  # type: bool
787    warn_script_location=True,  # type: bool
788    direct_url=None,  # type: Optional[DirectUrl]
789    requested=False,  # type: bool
790):
791    # type: (...) -> None
792    with ZipFile(wheel_path, allowZip64=True) as z:
793        with req_error_context(req_description):
794            _install_wheel(
795                name=name,
796                wheel_zip=z,
797                wheel_path=wheel_path,
798                scheme=scheme,
799                pycompile=pycompile,
800                warn_script_location=warn_script_location,
801                direct_url=direct_url,
802                requested=requested,
803            )
804