From: Geoffrey Thomas <geofft@ldpreload.com>
Date: Wed, 3 Dec 2014 11:18:11 -0600
Subject: Prevent pip from removing system packages.

Adjust is_local() to consider OS-owned paths non-local.  Fix the error
message for is_local() in the non-virtualenv case.

This patch can probably be dropped now that we have PEP-668 support. But
we'll keep it for now until we see how things play out with PEP-668.

Author: Geoffrey Thomas <geofft@ldpreload.com>
Bug-Debian: http://bugs.debian.org/771794
Origin: https://github.com/geofft/pip.git
Forwarded: not-needed
Reviewed-By: Donald Stufft <donald@stufft.io>
Reviewed-By: Scott Kitterman <scott@kitterman.com>
Last-Update: 2014-12-04
---
 src/pip/_internal/utils/misc.py | 34 +++++++++++++++++++++++++++++-----
 1 file changed, 29 insertions(+), 5 deletions(-)

diff --git a/src/pip/_internal/utils/misc.py b/src/pip/_internal/utils/misc.py
index baa1ba7..cdf9b3a 100644
--- a/src/pip/_internal/utils/misc.py
+++ b/src/pip/_internal/utils/misc.py
@@ -321,16 +321,40 @@ def renames(old: str, new: str) -> None:
 
 def is_local(path: str) -> bool:
     """
-    Return True if path is within sys.prefix, if we're running in a virtualenv.
+    Return True if this is a path pip is allowed to modify.
 
-    If we're not in a virtualenv, all paths are considered "local."
+    If we're in a virtualenv, sys.prefix points to the virtualenv's
+    prefix; only sys.prefix is considered local.
+
+    If we're not in a virtualenv, in general we can modify anything.
+    However, if the OS vendor has configured distutils to install
+    somewhere other than sys.prefix (which could be a subdirectory of
+    sys.prefix, e.g. /usr/local), we consider sys.prefix itself nonlocal
+    and the domain of the OS vendor. (In other words, everything _other
+    than_ sys.prefix is considered local.)
 
     Caution: this function assumes the head of path has been normalized
     with normalize_path.
     """
-    if not running_under_virtualenv():
-        return True
-    return path.startswith(normalize_path(sys.prefix))
+
+    path = normalize_path(path)
+    # Hard-coded becouse PyPy uses a different sys.prefix on Debian
+    prefix = '/usr'
+
+    if running_under_virtualenv():
+        return path.startswith(normalize_path(sys.prefix))
+    else:
+        from pip._internal.locations import get_scheme
+        from pip._internal.models.scheme import SCHEME_KEYS
+        if path.startswith(prefix):
+            scheme = get_scheme("")
+            for key in SCHEME_KEYS:
+                local_path = getattr(scheme, key)
+                if path.startswith(normalize_path(local_path)):
+                    return True
+            return False
+        else:
+            return True
 
 
 def write_output(msg: Any, *args: Any) -> None:
