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

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