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

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