Blame SOURCES/00198-add-rewheel-module.patch

1fe57a
diff --git a/Lib/ensurepip/__init__.py b/Lib/ensurepip/__init__.py
1fe57a
index 5021ebf..63c763a 100644
1fe57a
--- a/Lib/ensurepip/__init__.py
1fe57a
+++ b/Lib/ensurepip/__init__.py
1fe57a
@@ -7,6 +7,7 @@ import pkgutil
1fe57a
 import shutil
1fe57a
 import sys
1fe57a
 import tempfile
1fe57a
+from ensurepip import rewheel
1fe57a
 
1fe57a
 
1fe57a
 __all__ = ["version", "bootstrap"]
1fe57a
@@ -29,6 +30,8 @@ def _run_pip(args, additional_paths=None):
1fe57a
 
1fe57a
     # Install the bundled software
1fe57a
     import pip._internal
1fe57a
+    if args[0] in ["install", "list", "wheel"]:
1fe57a
+        args.append('--pre')
1fe57a
     return pip._internal.main(args)
1fe57a
 
1fe57a
 
1fe57a
@@ -93,21 +96,40 @@ def _bootstrap(root=None, upgrade=False, user=False,
1fe57a
         # omit pip and easy_install
1fe57a
         os.environ["ENSUREPIP_OPTIONS"] = "install"
1fe57a
 
1fe57a
+    whls = []
1fe57a
+    rewheel_dir = None
1fe57a
+    # try to see if we have system-wide versions of _PROJECTS
1fe57a
+    dep_records = rewheel.find_system_records([p[0] for p in _PROJECTS])
1fe57a
+    # TODO: check if system-wide versions are the newest ones
1fe57a
+    # if --upgrade is used?
1fe57a
+    if all(dep_records):
1fe57a
+        # if we have all _PROJECTS installed system-wide, we'll recreate
1fe57a
+        # wheels from them and install those
1fe57a
+        rewheel_dir = tempfile.mkdtemp()
1fe57a
+        for dr in dep_records:
1fe57a
+            new_whl = rewheel.rewheel_from_record(dr, rewheel_dir)
1fe57a
+            whls.append(os.path.join(rewheel_dir, new_whl))
1fe57a
+    else:
1fe57a
+        # if we don't have all the _PROJECTS installed system-wide,
1fe57a
+        # let's just fall back to bundled wheels
1fe57a
+        for project, version in _PROJECTS:
1fe57a
+            whl = os.path.join(
1fe57a
+                os.path.dirname(__file__),
1fe57a
+                "_bundled",
1fe57a
+                "{}-{}-py2.py3-none-any.whl".format(project, version)
1fe57a
+            )
1fe57a
+            whls.append(whl)
1fe57a
+
1fe57a
     tmpdir = tempfile.mkdtemp()
1fe57a
     try:
1fe57a
         # Put our bundled wheels into a temporary directory and construct the
1fe57a
         # additional paths that need added to sys.path
1fe57a
         additional_paths = []
1fe57a
-        for project, version in _PROJECTS:
1fe57a
-            wheel_name = "{}-{}-py2.py3-none-any.whl".format(project, version)
1fe57a
-            whl = pkgutil.get_data(
1fe57a
-                "ensurepip",
1fe57a
-                "_bundled/{}".format(wheel_name),
1fe57a
-            )
1fe57a
-            with open(os.path.join(tmpdir, wheel_name), "wb") as fp:
1fe57a
-                fp.write(whl)
1fe57a
-
1fe57a
-            additional_paths.append(os.path.join(tmpdir, wheel_name))
1fe57a
+        for whl in whls:
1fe57a
+            shutil.copy(whl, tmpdir)
1fe57a
+            additional_paths.append(os.path.join(tmpdir, os.path.basename(whl)))
1fe57a
+        if rewheel_dir:
1fe57a
+            shutil.rmtree(rewheel_dir)
1fe57a
 
1fe57a
         # Construct the arguments to be passed to the pip command
1fe57a
         args = ["install", "--no-index", "--find-links", tmpdir]
1fe57a
diff --git a/Lib/ensurepip/rewheel/__init__.py b/Lib/ensurepip/rewheel/__init__.py
1fe57a
new file mode 100644
1fe57a
index 0000000..75c2094
1fe57a
--- /dev/null
1fe57a
+++ b/Lib/ensurepip/rewheel/__init__.py
1fe57a
@@ -0,0 +1,158 @@
1fe57a
+import argparse
1fe57a
+import codecs
1fe57a
+import csv
1fe57a
+import email.parser
1fe57a
+import os
1fe57a
+import io
1fe57a
+import re
1fe57a
+import site
1fe57a
+import subprocess
1fe57a
+import sys
1fe57a
+import zipfile
1fe57a
+
1fe57a
+def run():
1fe57a
+    parser = argparse.ArgumentParser(description='Recreate wheel of package with given RECORD.')
1fe57a
+    parser.add_argument('record_path',
1fe57a
+                        help='Path to RECORD file')
1fe57a
+    parser.add_argument('-o', '--output-dir',
1fe57a
+                        help='Dir where to place the wheel, defaults to current working dir.',
1fe57a
+                        dest='outdir',
1fe57a
+                        default=os.path.curdir)
1fe57a
+
1fe57a
+    ns = parser.parse_args()
1fe57a
+    retcode = 0
1fe57a
+    try:
1fe57a
+        print(rewheel_from_record(**vars(ns)))
1fe57a
+    except BaseException as e:
1fe57a
+        print('Failed: {}'.format(e))
1fe57a
+        retcode = 1
1fe57a
+    sys.exit(1)
1fe57a
+
1fe57a
+def find_system_records(projects):
1fe57a
+    """Return list of paths to RECORD files for system-installed projects.
1fe57a
+
1fe57a
+    If a project is not installed, the resulting list contains None instead
1fe57a
+    of a path to its RECORD
1fe57a
+    """
1fe57a
+    records = []
1fe57a
+    # get system site-packages dirs
1fe57a
+    if hasattr(sys, 'real_prefix'):
1fe57a
+        #we are in python2 virtualenv and sys.real_prefix is the original sys.prefix
1fe57a
+        _orig_prefixes = site.PREFIXES
1fe57a
+        setattr(site, 'PREFIXES', [sys.real_prefix]*2)
1fe57a
+        sys_sitepack = site.getsitepackages()
1fe57a
+        setattr(site, 'PREFIXES', _orig_prefixes)
1fe57a
+    elif hasattr(sys, 'base_prefix'): # python3 venv doesn't inject real_prefix to sys
1fe57a
+        # we are on python3 and base(_exec)_prefix is unchanged in venv
1fe57a
+        sys_sitepack = site.getsitepackages([sys.base_prefix, sys.base_exec_prefix])
1fe57a
+    else:
1fe57a
+        # we are in python2 without virtualenv
1fe57a
+        sys_sitepack = site.getsitepackages()
1fe57a
+
1fe57a
+    sys_sitepack = [sp for sp in sys_sitepack if os.path.exists(sp)]
1fe57a
+    # try to find all projects in all system site-packages
1fe57a
+    for project in projects:
1fe57a
+        path = None
1fe57a
+        for sp in sys_sitepack:
1fe57a
+            dist_info_re = os.path.join(sp, project) + '-[^\{0}]+\.dist-info'.format(os.sep)
1fe57a
+            candidates = [os.path.join(sp, p) for p in os.listdir(sp)]
1fe57a
+            # filter out candidate dirs based on the above regexp
1fe57a
+            filtered = [c for c in candidates if re.match(dist_info_re, c)]
1fe57a
+            # if we have 0 or 2 or more dirs, something is wrong...
1fe57a
+            if len(filtered) == 1:
1fe57a
+                path = filtered[0]
1fe57a
+        if path is not None:
1fe57a
+            records.append(os.path.join(path, 'RECORD'))
1fe57a
+        else:
1fe57a
+            records.append(None)
1fe57a
+    return records
1fe57a
+
1fe57a
+def rewheel_from_record(record_path, outdir):
1fe57a
+    """Recreates a whee of package with given record_path and returns path
1fe57a
+    to the newly created wheel."""
1fe57a
+    site_dir = os.path.dirname(os.path.dirname(record_path))
1fe57a
+    record_relpath = record_path[len(site_dir):].strip(os.path.sep)
1fe57a
+    to_write, to_omit = get_records_to_pack(site_dir, record_relpath)
1fe57a
+    new_wheel_name = get_wheel_name(record_path)
1fe57a
+    new_wheel_path = os.path.join(outdir, new_wheel_name + '.whl')
1fe57a
+
1fe57a
+    new_wheel = zipfile.ZipFile(new_wheel_path, mode='w', compression=zipfile.ZIP_DEFLATED)
1fe57a
+    # we need to write a new record with just the files that we will write,
1fe57a
+    # e.g. not binaries and *.pyc/*.pyo files
1fe57a
+    if sys.version_info[0] < 3:
1fe57a
+        new_record = io.BytesIO()
1fe57a
+    else:
1fe57a
+        new_record = io.StringIO()
1fe57a
+    writer = csv.writer(new_record)
1fe57a
+
1fe57a
+    # handle files that we can write straight away
1fe57a
+    for f, sha_hash, size in to_write:
1fe57a
+        new_wheel.write(os.path.join(site_dir, f), arcname=f)
1fe57a
+        writer.writerow([f, sha_hash,size])
1fe57a
+
1fe57a
+    # rewrite the old wheel file with a new computed one
1fe57a
+    writer.writerow([record_relpath, '', ''])
1fe57a
+    new_wheel.writestr(record_relpath, new_record.getvalue())
1fe57a
+
1fe57a
+    new_wheel.close()
1fe57a
+
1fe57a
+    return new_wheel.filename
1fe57a
+
1fe57a
+def get_wheel_name(record_path):
1fe57a
+    """Return proper name of the wheel, without .whl."""
1fe57a
+
1fe57a
+    wheel_info_path = os.path.join(os.path.dirname(record_path), 'WHEEL')
1fe57a
+    with codecs.open(wheel_info_path, encoding='utf-8') as wheel_info_file:
1fe57a
+        wheel_info = email.parser.Parser().parsestr(wheel_info_file.read().encode('utf-8'))
1fe57a
+
1fe57a
+    metadata_path = os.path.join(os.path.dirname(record_path), 'METADATA')
1fe57a
+    with codecs.open(metadata_path, encoding='utf-8') as metadata_file:
1fe57a
+        metadata = email.parser.Parser().parsestr(metadata_file.read().encode('utf-8'))
1fe57a
+
1fe57a
+    # construct name parts according to wheel spec
1fe57a
+    distribution = metadata.get('Name')
1fe57a
+    version = metadata.get('Version')
1fe57a
+    build_tag = '' # nothing for now
1fe57a
+    lang_tag = []
1fe57a
+    for t in wheel_info.get_all('Tag'):
1fe57a
+        lang_tag.append(t.split('-')[0])
1fe57a
+    lang_tag = '.'.join(lang_tag)
1fe57a
+    abi_tag, plat_tag = wheel_info.get('Tag').split('-')[1:3]
1fe57a
+    # leave out build tag, if it is empty
1fe57a
+    to_join = filter(None, [distribution, version, build_tag, lang_tag, abi_tag, plat_tag])
1fe57a
+    return '-'.join(list(to_join))
1fe57a
+
1fe57a
+def get_records_to_pack(site_dir, record_relpath):
1fe57a
+    """Accepts path of sitedir and path of RECORD file relative to it.
1fe57a
+    Returns two lists:
1fe57a
+    - list of files that can be written to new RECORD straight away
1fe57a
+    - list of files that shouldn't be written or need some processing
1fe57a
+      (pyc and pyo files, scripts)
1fe57a
+    """
1fe57a
+    record_file_path = os.path.join(site_dir, record_relpath)
1fe57a
+    with codecs.open(record_file_path, encoding='utf-8') as record_file:
1fe57a
+        record_contents = record_file.read()
1fe57a
+    # temporary fix for https://github.com/pypa/pip/issues/1376
1fe57a
+    # we need to ignore files under ".data" directory
1fe57a
+    data_dir = os.path.dirname(record_relpath).strip(os.path.sep)
1fe57a
+    data_dir = data_dir[:-len('dist-info')] + 'data'
1fe57a
+
1fe57a
+    to_write = []
1fe57a
+    to_omit = []
1fe57a
+    for l in record_contents.splitlines():
1fe57a
+        spl = l.split(',')
1fe57a
+        if len(spl) == 3:
1fe57a
+            # new record will omit (or write differently):
1fe57a
+            # - abs paths, paths with ".." (entry points),
1fe57a
+            # - pyc+pyo files
1fe57a
+            # - the old RECORD file
1fe57a
+            # TODO: is there any better way to recognize an entry point?
1fe57a
+            if os.path.isabs(spl[0]) or spl[0].startswith('..') or \
1fe57a
+               spl[0].endswith('.pyc') or spl[0].endswith('.pyo') or \
1fe57a
+               spl[0] == record_relpath or spl[0].startswith(data_dir):
1fe57a
+                to_omit.append(spl)
1fe57a
+            else:
1fe57a
+                to_write.append(spl)
1fe57a
+        else:
1fe57a
+            pass # bad RECORD or empty line
1fe57a
+    return to_write, to_omit
1fe57a
diff --git a/Makefile.pre.in b/Makefile.pre.in
1fe57a
index 877698c..2c43611 100644
1fe57a
--- a/Makefile.pre.in
1fe57a
+++ b/Makefile.pre.in
1fe57a
@@ -1065,7 +1065,7 @@ LIBSUBDIRS=	lib-tk lib-tk/test lib-tk/test/test_tkinter \
1fe57a
 		test/tracedmodules \
1fe57a
 		encodings compiler hotshot \
1fe57a
 		email email/mime email/test email/test/data \
1fe57a
-		ensurepip ensurepip/_bundled \
1fe57a
+		ensurepip ensurepip/_bundled ensurepip/rewheel\
1fe57a
 		json json/tests \
1fe57a
 		sqlite3 sqlite3/test \
1fe57a
 		logging bsddb bsddb/test csv importlib wsgiref \