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

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