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

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