Fix when packages are unvendored
authorIan Cordasco <graffatcolmingov@gmail.com>
Sun, 1 Mar 2015 05:04:22 +0000 (23:04 -0600)
committerIan Cordasco <graffatcolmingov@gmail.com>
Sun, 1 Mar 2015 05:04:24 +0000 (23:04 -0600)
When working these changes back upstream to pip, we realized that the
previous fix wasn't ideal since unvendoring the packages broke the
imports. For example, if urllib3 were unvendored, then the following
would fail:

    from requests.packages import urllib3

requests/packages/__init__.py

index 7b2a09138262b90423659d3ef849dce8aa4a3248..4dcf870f3ba7de37b6c3ac328ac5e06f83b781e8 100644 (file)
@@ -27,10 +27,13 @@ import sys
 
 class VendorAlias(object):
 
-    def __init__(self, package_name):
-        self._package_name = package_name
+    def __init__(self, package_names):
+        self._package_names = package_names
         self._vendor_name = __name__
-        self._vendor_pkg = self._vendor_name + "." + self._package_name
+        self._vendor_pkg = self._vendor_name + "."
+        self._vendor_pkgs = [
+            self._vendor_pkg + name for name in self._package_names
+        ]
 
     def find_module(self, fullname, path=None):
         if fullname.startswith(self._vendor_pkg):
@@ -45,6 +48,14 @@ class VendorAlias(object):
                 )
             )
 
+        if not (name == self._vendor_name or
+                any(name.startswith(pkg) for pkg in self._vendor_pkgs)):
+            raise ImportError(
+                "Cannot import %s, must be one of %s." % (
+                    name, self._vendor_pkgs
+                )
+            )
+
         # Check to see if we already have this item in sys.modules, if we do
         # then simply return that.
         if name in sys.modules:
@@ -93,4 +104,4 @@ class VendorAlias(object):
         return module
 
 
-sys.meta_path.extend([VendorAlias("urllib3"), VendorAlias("chardet")])
+sys.meta_path.append(VendorAlias(["urllib3", "chardet"]))