We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
pipenv install/graph fail with 2018.10.9: ImportError: No module named weakref
### Issue description

With pipenv 2018.10.9, all the pipenv commands fail (including `pipenv --support`): 

```pytb
Traceback (most recent call last):
  File "c:\python27\lib\runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "c:\python27\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "C:\Python27\Scripts\pipenv.exe\__main__.py", line 5, in <module>
  File "c:\python27\lib\site-packages\pipenv\__init__.py", line 23, in <module>
    from .cli import cli
  File "c:\python27\lib\site-packages\pipenv\cli\__init__.py", line 3, in <module>
    from .command import cli
  File "c:\python27\lib\site-packages\pipenv\cli\command.py", line 18, in <module>
    from .. import environments
  File "c:\python27\lib\site-packages\pipenv\environments.py", line 4, in <module>
    from .vendor.vistir.misc import fs_str
  File "c:\python27\lib\site-packages\pipenv\vendor\vistir\__init__.py", line 4, in <module>
    from .compat import NamedTemporaryFile, TemporaryDirectory, partialmethod
  File "c:\python27\lib\site-packages\pipenv\vendor\vistir\compat.py", line 34, in <module>
    from .backports.tempfile import NamedTemporaryFile
  File "c:\python27\lib\site-packages\pipenv\vendor\vistir\backports\__init__.py", line 5, in <module>
    from .tempfile import NamedTemporaryFile
  File "c:\python27\lib\site-packages\pipenv\vendor\vistir\backports\tempfile.py", line 16, in <module>
    from backports.weakref import finalize
ImportError: No module named weakref
```

### Enviroment

* pip version: 10.0.1 and 18.1
* Python version: 2.7
* OS: Windows


Fix import error on Python 2.7
Continue #2962 
Close #2961 #2950 

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pipenv/vendor/vistir/backports/tempfile.py`
Content:
```
1 # -*- coding=utf-8 -*-
2 from __future__ import absolute_import, unicode_literals
3 
4 import functools
5 import io
6 import os
7 import sys
8 
9 from tempfile import _bin_openflags, _mkstemp_inner, gettempdir
10 
11 import six
12 
13 try:
14     from weakref import finalize
15 except ImportError:
16     from backports.weakref import finalize
17 
18 
19 __all__ = ["finalize", "NamedTemporaryFile"]
20 
21 
22 try:
23     from tempfile import _infer_return_type
24 except ImportError:
25 
26     def _infer_return_type(*args):
27         _types = set()
28         for arg in args:
29             if isinstance(type(arg), six.string_types):
30                 _types.add(str)
31             elif isinstance(type(arg), bytes):
32                 _types.add(bytes)
33             elif arg:
34                 _types.add(type(arg))
35         return _types.pop()
36 
37 
38 def _sanitize_params(prefix, suffix, dir):
39     """Common parameter processing for most APIs in this module."""
40     output_type = _infer_return_type(prefix, suffix, dir)
41     if suffix is None:
42         suffix = output_type()
43     if prefix is None:
44         if output_type is str:
45             prefix = "tmp"
46         else:
47             prefix = os.fsencode("tmp")
48     if dir is None:
49         if output_type is str:
50             dir = gettempdir()
51         else:
52             dir = os.fsencode(gettempdir())
53     return prefix, suffix, dir, output_type
54 
55 
56 class _TemporaryFileCloser:
57     """A separate object allowing proper closing of a temporary file's
58     underlying file object, without adding a __del__ method to the
59     temporary file."""
60 
61     file = None  # Set here since __del__ checks it
62     close_called = False
63 
64     def __init__(self, file, name, delete=True):
65         self.file = file
66         self.name = name
67         self.delete = delete
68 
69     # NT provides delete-on-close as a primitive, so we don't need
70     # the wrapper to do anything special.  We still use it so that
71     # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
72     if os.name != "nt":
73 
74         # Cache the unlinker so we don't get spurious errors at
75         # shutdown when the module-level "os" is None'd out.  Note
76         # that this must be referenced as self.unlink, because the
77         # name TemporaryFileWrapper may also get None'd out before
78         # __del__ is called.
79 
80         def close(self, unlink=os.unlink):
81             if not self.close_called and self.file is not None:
82                 self.close_called = True
83                 try:
84                     self.file.close()
85                 finally:
86                     if self.delete:
87                         unlink(self.name)
88 
89         # Need to ensure the file is deleted on __del__
90 
91         def __del__(self):
92             self.close()
93 
94     else:
95 
96         def close(self):
97             if not self.close_called:
98                 self.close_called = True
99                 self.file.close()
100 
101 
102 class _TemporaryFileWrapper:
103     """Temporary file wrapper
104     This class provides a wrapper around files opened for
105     temporary use.  In particular, it seeks to automatically
106     remove the file when it is no longer needed.
107     """
108 
109     def __init__(self, file, name, delete=True):
110         self.file = file
111         self.name = name
112         self.delete = delete
113         self._closer = _TemporaryFileCloser(file, name, delete)
114 
115     def __getattr__(self, name):
116         # Attribute lookups are delegated to the underlying file
117         # and cached for non-numeric results
118         # (i.e. methods are cached, closed and friends are not)
119         file = self.__dict__["file"]
120         a = getattr(file, name)
121         if hasattr(a, "__call__"):
122             func = a
123 
124             @functools.wraps(func)
125             def func_wrapper(*args, **kwargs):
126                 return func(*args, **kwargs)
127 
128             # Avoid closing the file as long as the wrapper is alive,
129             # see issue #18879.
130             func_wrapper._closer = self._closer
131             a = func_wrapper
132         if not isinstance(a, int):
133             setattr(self, name, a)
134         return a
135 
136     # The underlying __enter__ method returns the wrong object
137     # (self.file) so override it to return the wrapper
138 
139     def __enter__(self):
140         self.file.__enter__()
141         return self
142 
143     # Need to trap __exit__ as well to ensure the file gets
144     # deleted when used in a with statement
145 
146     def __exit__(self, exc, value, tb):
147         result = self.file.__exit__(exc, value, tb)
148         self.close()
149         return result
150 
151     def close(self):
152         """
153         Close the temporary file, possibly deleting it.
154         """
155         self._closer.close()
156 
157     # iter() doesn't use __getattr__ to find the __iter__ method
158 
159     def __iter__(self):
160         # Don't return iter(self.file), but yield from it to avoid closing
161         # file as long as it's being used as iterator (see issue #23700).  We
162         # can't use 'yield from' here because iter(file) returns the file
163         # object itself, which has a close method, and thus the file would get
164         # closed when the generator is finalized, due to PEP380 semantics.
165         for line in self.file:
166             yield line
167 
168 
169 def NamedTemporaryFile(
170     mode="w+b",
171     buffering=-1,
172     encoding=None,
173     newline=None,
174     suffix=None,
175     prefix=None,
176     dir=None,
177     delete=True,
178 ):
179     """Create and return a temporary file.
180     Arguments:
181     'prefix', 'suffix', 'dir' -- as for mkstemp.
182     'mode' -- the mode argument to io.open (default "w+b").
183     'buffering' -- the buffer size argument to io.open (default -1).
184     'encoding' -- the encoding argument to io.open (default None)
185     'newline' -- the newline argument to io.open (default None)
186     'delete' -- whether the file is deleted on close (default True).
187     The file is created as mkstemp() would do it.
188     Returns an object with a file-like interface; the name of the file
189     is accessible as its 'name' attribute.  The file will be automatically
190     deleted when it is closed unless the 'delete' argument is set to False.
191     """
192     prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
193     flags = _bin_openflags
194     # Setting O_TEMPORARY in the flags causes the OS to delete
195     # the file when it is closed.  This is only supported by Windows.
196     if os.name == "nt" and delete:
197         flags |= os.O_TEMPORARY
198     if sys.version_info < (3, 5):
199         (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
200     else:
201         (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
202     try:
203         file = io.open(
204             fd, mode, buffering=buffering, newline=newline, encoding=encoding
205         )
206         return _TemporaryFileWrapper(file, name, delete)
207 
208     except BaseException:
209         os.unlink(name)
210         os.close(fd)
211         raise
212
```

Path: `pipenv/vendor/vistir/compat.py`
Content:
```
1 # -*- coding=utf-8 -*-
2 from __future__ import absolute_import, unicode_literals
3 
4 import os
5 import sys
6 import warnings
7 
8 from tempfile import mkdtemp
9 
10 import six
11 
12 
13 __all__ = [
14     "Path",
15     "get_terminal_size",
16     "finalize",
17     "partialmethod",
18     "JSONDecodeError",
19     "ResourceWarning",
20     "FileNotFoundError",
21     "fs_str",
22     "TemporaryDirectory",
23     "NamedTemporaryFile",
24 ]
25 
26 if sys.version_info >= (3, 5):
27     from pathlib import Path
28 
29 else:
30     from pathlib2 import Path
31 
32 if sys.version_info < (3, 3):
33     from backports.shutil_get_terminal_size import get_terminal_size
34     from .backports.tempfile import NamedTemporaryFile
35 else:
36     from tempfile import NamedTemporaryFile
37     from shutil import get_terminal_size
38 
39 try:
40     from weakref import finalize
41 except ImportError:
42     from backports.weakref import finalize
43 
44 try:
45     from functools import partialmethod
46 except Exception:
47     from .backports.functools import partialmethod
48 
49 try:
50     from json import JSONDecodeError
51 except ImportError:  # Old Pythons.
52     JSONDecodeError = ValueError
53 
54 if six.PY2:
55 
56     class ResourceWarning(Warning):
57         pass
58 
59     class FileNotFoundError(IOError):
60         pass
61 
62 else:
63     from builtins import ResourceWarning, FileNotFoundError
64 
65     class ResourceWarning(ResourceWarning):
66         pass
67 
68     class FileNotFoundError(FileNotFoundError):
69         pass
70 
71 
72 class TemporaryDirectory(object):
73     """Create and return a temporary directory.  This has the same
74     behavior as mkdtemp but can be used as a context manager.  For
75     example:
76 
77         with TemporaryDirectory() as tmpdir:
78             ...
79 
80     Upon exiting the context, the directory and everything contained
81     in it are removed.
82     """
83 
84     def __init__(self, suffix="", prefix=None, dir=None):
85         if "RAM_DISK" in os.environ:
86             import uuid
87 
88             name = uuid.uuid4().hex
89             dir_name = os.path.join(os.environ["RAM_DISK"].strip(), name)
90             os.mkdir(dir_name)
91             self.name = dir_name
92         else:
93             suffix = suffix if suffix else ""
94             if not prefix:
95                 self.name = mkdtemp(suffix=suffix, dir=dir)
96             else:
97                 self.name = mkdtemp(suffix, prefix, dir)
98         self._finalizer = finalize(
99             self,
100             self._cleanup,
101             self.name,
102             warn_message="Implicitly cleaning up {!r}".format(self),
103         )
104 
105     @classmethod
106     def _cleanup(cls, name, warn_message):
107         from .path import rmtree
108         rmtree(name)
109         warnings.warn(warn_message, ResourceWarning)
110 
111     def __repr__(self):
112         return "<{} {!r}>".format(self.__class__.__name__, self.name)
113 
114     def __enter__(self):
115         return self
116 
117     def __exit__(self, exc, value, tb):
118         self.cleanup()
119 
120     def cleanup(self):
121         from .path import rmtree
122         if self._finalizer.detach():
123             rmtree(self.name)
124 
125 
126 def fs_str(string):
127     """Encodes a string into the proper filesystem encoding
128 
129     Borrowed from pip-tools
130     """
131     if isinstance(string, str):
132         return string
133     assert not isinstance(string, bytes)
134     return string.encode(_fs_encoding)
135 
136 
137 _fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
138
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pipenv/vendor/vistir/backports/tempfile.py b/pipenv/vendor/vistir/backports/tempfile.py
--- a/pipenv/vendor/vistir/backports/tempfile.py
+++ b/pipenv/vendor/vistir/backports/tempfile.py
@@ -13,7 +13,7 @@
 try:
     from weakref import finalize
 except ImportError:
-    from backports.weakref import finalize
+    from pipenv.vendor.backports.weakref import finalize
 
 
 __all__ = ["finalize", "NamedTemporaryFile"]
diff --git a/pipenv/vendor/vistir/compat.py b/pipenv/vendor/vistir/compat.py
--- a/pipenv/vendor/vistir/compat.py
+++ b/pipenv/vendor/vistir/compat.py
@@ -30,7 +30,7 @@
     from pathlib2 import Path
 
 if sys.version_info < (3, 3):
-    from backports.shutil_get_terminal_size import get_terminal_size
+    from pipenv.vendor.backports.shutil_get_terminal_size import get_terminal_size
     from .backports.tempfile import NamedTemporaryFile
 else:
     from tempfile import NamedTemporaryFile
@@ -39,7 +39,7 @@
 try:
     from weakref import finalize
 except ImportError:
-    from backports.weakref import finalize
+    from pipenv.vendor.backports.weakref import finalize
 
 try:
     from functools import partialmethod

{"golden_diff": "diff --git a/pipenv/vendor/vistir/backports/tempfile.py b/pipenv/vendor/vistir/backports/tempfile.py\n--- a/pipenv/vendor/vistir/backports/tempfile.py\n+++ b/pipenv/vendor/vistir/backports/tempfile.py\n@@ -13,7 +13,7 @@\n try:\n     from weakref import finalize\n except ImportError:\n-    from backports.weakref import finalize\n+    from pipenv.vendor.backports.weakref import finalize\n \n \n __all__ = [\"finalize\", \"NamedTemporaryFile\"]\ndiff --git a/pipenv/vendor/vistir/compat.py b/pipenv/vendor/vistir/compat.py\n--- a/pipenv/vendor/vistir/compat.py\n+++ b/pipenv/vendor/vistir/compat.py\n@@ -30,7 +30,7 @@\n     from pathlib2 import Path\n \n if sys.version_info < (3, 3):\n-    from backports.shutil_get_terminal_size import get_terminal_size\n+    from pipenv.vendor.backports.shutil_get_terminal_size import get_terminal_size\n     from .backports.tempfile import NamedTemporaryFile\n else:\n     from tempfile import NamedTemporaryFile\n@@ -39,7 +39,7 @@\n try:\n     from weakref import finalize\n except ImportError:\n-    from backports.weakref import finalize\n+    from pipenv.vendor.backports.weakref import finalize\n \n try:\n     from functools import partialmethod\n", "issue": "pipenv install/graph fail with 2018.10.9: ImportError: No module named weakref\n### Issue description\r\n\r\nWith pipenv 2018.10.9, all the pipenv commands fail (including `pipenv --support`): \r\n\r\n```pytb\r\nTraceback (most recent call last):\r\n  File \"c:\\python27\\lib\\runpy.py\", line 174, in _run_module_as_main\r\n    \"__main__\", fname, loader, pkg_name)\r\n  File \"c:\\python27\\lib\\runpy.py\", line 72, in _run_code\r\n    exec code in run_globals\r\n  File \"C:\\Python27\\Scripts\\pipenv.exe\\__main__.py\", line 5, in <module>\r\n  File \"c:\\python27\\lib\\site-packages\\pipenv\\__init__.py\", line 23, in <module>\r\n    from .cli import cli\r\n  File \"c:\\python27\\lib\\site-packages\\pipenv\\cli\\__init__.py\", line 3, in <module>\r\n    from .command import cli\r\n  File \"c:\\python27\\lib\\site-packages\\pipenv\\cli\\command.py\", line 18, in <module>\r\n    from .. import environments\r\n  File \"c:\\python27\\lib\\site-packages\\pipenv\\environments.py\", line 4, in <module>\r\n    from .vendor.vistir.misc import fs_str\r\n  File \"c:\\python27\\lib\\site-packages\\pipenv\\vendor\\vistir\\__init__.py\", line 4, in <module>\r\n    from .compat import NamedTemporaryFile, TemporaryDirectory, partialmethod\r\n  File \"c:\\python27\\lib\\site-packages\\pipenv\\vendor\\vistir\\compat.py\", line 34, in <module>\r\n    from .backports.tempfile import NamedTemporaryFile\r\n  File \"c:\\python27\\lib\\site-packages\\pipenv\\vendor\\vistir\\backports\\__init__.py\", line 5, in <module>\r\n    from .tempfile import NamedTemporaryFile\r\n  File \"c:\\python27\\lib\\site-packages\\pipenv\\vendor\\vistir\\backports\\tempfile.py\", line 16, in <module>\r\n    from backports.weakref import finalize\r\nImportError: No module named weakref\r\n```\r\n\r\n### Enviroment\r\n\r\n* pip version: 10.0.1 and 18.1\r\n* Python version: 2.7\r\n* OS: Windows\r\n\r\n\nFix import error on Python 2.7\nContinue #2962 \r\nClose #2961 #2950 \n", "before_files": [{"content": "# -*- coding=utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\n\nimport functools\nimport io\nimport os\nimport sys\n\nfrom tempfile import _bin_openflags, _mkstemp_inner, gettempdir\n\nimport six\n\ntry:\n    from weakref import finalize\nexcept ImportError:\n    from backports.weakref import finalize\n\n\n__all__ = [\"finalize\", \"NamedTemporaryFile\"]\n\n\ntry:\n    from tempfile import _infer_return_type\nexcept ImportError:\n\n    def _infer_return_type(*args):\n        _types = set()\n        for arg in args:\n            if isinstance(type(arg), six.string_types):\n                _types.add(str)\n            elif isinstance(type(arg), bytes):\n                _types.add(bytes)\n            elif arg:\n                _types.add(type(arg))\n        return _types.pop()\n\n\ndef _sanitize_params(prefix, suffix, dir):\n    \"\"\"Common parameter processing for most APIs in this module.\"\"\"\n    output_type = _infer_return_type(prefix, suffix, dir)\n    if suffix is None:\n        suffix = output_type()\n    if prefix is None:\n        if output_type is str:\n            prefix = \"tmp\"\n        else:\n            prefix = os.fsencode(\"tmp\")\n    if dir is None:\n        if output_type is str:\n            dir = gettempdir()\n        else:\n            dir = os.fsencode(gettempdir())\n    return prefix, suffix, dir, output_type\n\n\nclass _TemporaryFileCloser:\n    \"\"\"A separate object allowing proper closing of a temporary file's\n    underlying file object, without adding a __del__ method to the\n    temporary file.\"\"\"\n\n    file = None  # Set here since __del__ checks it\n    close_called = False\n\n    def __init__(self, file, name, delete=True):\n        self.file = file\n        self.name = name\n        self.delete = delete\n\n    # NT provides delete-on-close as a primitive, so we don't need\n    # the wrapper to do anything special.  We still use it so that\n    # file.name is useful (i.e. not \"(fdopen)\") with NamedTemporaryFile.\n    if os.name != \"nt\":\n\n        # Cache the unlinker so we don't get spurious errors at\n        # shutdown when the module-level \"os\" is None'd out.  Note\n        # that this must be referenced as self.unlink, because the\n        # name TemporaryFileWrapper may also get None'd out before\n        # __del__ is called.\n\n        def close(self, unlink=os.unlink):\n            if not self.close_called and self.file is not None:\n                self.close_called = True\n                try:\n                    self.file.close()\n                finally:\n                    if self.delete:\n                        unlink(self.name)\n\n        # Need to ensure the file is deleted on __del__\n\n        def __del__(self):\n            self.close()\n\n    else:\n\n        def close(self):\n            if not self.close_called:\n                self.close_called = True\n                self.file.close()\n\n\nclass _TemporaryFileWrapper:\n    \"\"\"Temporary file wrapper\n    This class provides a wrapper around files opened for\n    temporary use.  In particular, it seeks to automatically\n    remove the file when it is no longer needed.\n    \"\"\"\n\n    def __init__(self, file, name, delete=True):\n        self.file = file\n        self.name = name\n        self.delete = delete\n        self._closer = _TemporaryFileCloser(file, name, delete)\n\n    def __getattr__(self, name):\n        # Attribute lookups are delegated to the underlying file\n        # and cached for non-numeric results\n        # (i.e. methods are cached, closed and friends are not)\n        file = self.__dict__[\"file\"]\n        a = getattr(file, name)\n        if hasattr(a, \"__call__\"):\n            func = a\n\n            @functools.wraps(func)\n            def func_wrapper(*args, **kwargs):\n                return func(*args, **kwargs)\n\n            # Avoid closing the file as long as the wrapper is alive,\n            # see issue #18879.\n            func_wrapper._closer = self._closer\n            a = func_wrapper\n        if not isinstance(a, int):\n            setattr(self, name, a)\n        return a\n\n    # The underlying __enter__ method returns the wrong object\n    # (self.file) so override it to return the wrapper\n\n    def __enter__(self):\n        self.file.__enter__()\n        return self\n\n    # Need to trap __exit__ as well to ensure the file gets\n    # deleted when used in a with statement\n\n    def __exit__(self, exc, value, tb):\n        result = self.file.__exit__(exc, value, tb)\n        self.close()\n        return result\n\n    def close(self):\n        \"\"\"\n        Close the temporary file, possibly deleting it.\n        \"\"\"\n        self._closer.close()\n\n    # iter() doesn't use __getattr__ to find the __iter__ method\n\n    def __iter__(self):\n        # Don't return iter(self.file), but yield from it to avoid closing\n        # file as long as it's being used as iterator (see issue #23700).  We\n        # can't use 'yield from' here because iter(file) returns the file\n        # object itself, which has a close method, and thus the file would get\n        # closed when the generator is finalized, due to PEP380 semantics.\n        for line in self.file:\n            yield line\n\n\ndef NamedTemporaryFile(\n    mode=\"w+b\",\n    buffering=-1,\n    encoding=None,\n    newline=None,\n    suffix=None,\n    prefix=None,\n    dir=None,\n    delete=True,\n):\n    \"\"\"Create and return a temporary file.\n    Arguments:\n    'prefix', 'suffix', 'dir' -- as for mkstemp.\n    'mode' -- the mode argument to io.open (default \"w+b\").\n    'buffering' -- the buffer size argument to io.open (default -1).\n    'encoding' -- the encoding argument to io.open (default None)\n    'newline' -- the newline argument to io.open (default None)\n    'delete' -- whether the file is deleted on close (default True).\n    The file is created as mkstemp() would do it.\n    Returns an object with a file-like interface; the name of the file\n    is accessible as its 'name' attribute.  The file will be automatically\n    deleted when it is closed unless the 'delete' argument is set to False.\n    \"\"\"\n    prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)\n    flags = _bin_openflags\n    # Setting O_TEMPORARY in the flags causes the OS to delete\n    # the file when it is closed.  This is only supported by Windows.\n    if os.name == \"nt\" and delete:\n        flags |= os.O_TEMPORARY\n    if sys.version_info < (3, 5):\n        (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)\n    else:\n        (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)\n    try:\n        file = io.open(\n            fd, mode, buffering=buffering, newline=newline, encoding=encoding\n        )\n        return _TemporaryFileWrapper(file, name, delete)\n\n    except BaseException:\n        os.unlink(name)\n        os.close(fd)\n        raise\n", "path": "pipenv/vendor/vistir/backports/tempfile.py"}, {"content": "# -*- coding=utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\n\nimport os\nimport sys\nimport warnings\n\nfrom tempfile import mkdtemp\n\nimport six\n\n\n__all__ = [\n    \"Path\",\n    \"get_terminal_size\",\n    \"finalize\",\n    \"partialmethod\",\n    \"JSONDecodeError\",\n    \"ResourceWarning\",\n    \"FileNotFoundError\",\n    \"fs_str\",\n    \"TemporaryDirectory\",\n    \"NamedTemporaryFile\",\n]\n\nif sys.version_info >= (3, 5):\n    from pathlib import Path\n\nelse:\n    from pathlib2 import Path\n\nif sys.version_info < (3, 3):\n    from backports.shutil_get_terminal_size import get_terminal_size\n    from .backports.tempfile import NamedTemporaryFile\nelse:\n    from tempfile import NamedTemporaryFile\n    from shutil import get_terminal_size\n\ntry:\n    from weakref import finalize\nexcept ImportError:\n    from backports.weakref import finalize\n\ntry:\n    from functools import partialmethod\nexcept Exception:\n    from .backports.functools import partialmethod\n\ntry:\n    from json import JSONDecodeError\nexcept ImportError:  # Old Pythons.\n    JSONDecodeError = ValueError\n\nif six.PY2:\n\n    class ResourceWarning(Warning):\n        pass\n\n    class FileNotFoundError(IOError):\n        pass\n\nelse:\n    from builtins import ResourceWarning, FileNotFoundError\n\n    class ResourceWarning(ResourceWarning):\n        pass\n\n    class FileNotFoundError(FileNotFoundError):\n        pass\n\n\nclass TemporaryDirectory(object):\n    \"\"\"Create and return a temporary directory.  This has the same\n    behavior as mkdtemp but can be used as a context manager.  For\n    example:\n\n        with TemporaryDirectory() as tmpdir:\n            ...\n\n    Upon exiting the context, the directory and everything contained\n    in it are removed.\n    \"\"\"\n\n    def __init__(self, suffix=\"\", prefix=None, dir=None):\n        if \"RAM_DISK\" in os.environ:\n            import uuid\n\n            name = uuid.uuid4().hex\n            dir_name = os.path.join(os.environ[\"RAM_DISK\"].strip(), name)\n            os.mkdir(dir_name)\n            self.name = dir_name\n        else:\n            suffix = suffix if suffix else \"\"\n            if not prefix:\n                self.name = mkdtemp(suffix=suffix, dir=dir)\n            else:\n                self.name = mkdtemp(suffix, prefix, dir)\n        self._finalizer = finalize(\n            self,\n            self._cleanup,\n            self.name,\n            warn_message=\"Implicitly cleaning up {!r}\".format(self),\n        )\n\n    @classmethod\n    def _cleanup(cls, name, warn_message):\n        from .path import rmtree\n        rmtree(name)\n        warnings.warn(warn_message, ResourceWarning)\n\n    def __repr__(self):\n        return \"<{} {!r}>\".format(self.__class__.__name__, self.name)\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc, value, tb):\n        self.cleanup()\n\n    def cleanup(self):\n        from .path import rmtree\n        if self._finalizer.detach():\n            rmtree(self.name)\n\n\ndef fs_str(string):\n    \"\"\"Encodes a string into the proper filesystem encoding\n\n    Borrowed from pip-tools\n    \"\"\"\n    if isinstance(string, str):\n        return string\n    assert not isinstance(string, bytes)\n    return string.encode(_fs_encoding)\n\n\n_fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()\n", "path": "pipenv/vendor/vistir/compat.py"}], "after_files": [{"content": "# -*- coding=utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\n\nimport functools\nimport io\nimport os\nimport sys\n\nfrom tempfile import _bin_openflags, _mkstemp_inner, gettempdir\n\nimport six\n\ntry:\n    from weakref import finalize\nexcept ImportError:\n    from pipenv.vendor.backports.weakref import finalize\n\n\n__all__ = [\"finalize\", \"NamedTemporaryFile\"]\n\n\ntry:\n    from tempfile import _infer_return_type\nexcept ImportError:\n\n    def _infer_return_type(*args):\n        _types = set()\n        for arg in args:\n            if isinstance(type(arg), six.string_types):\n                _types.add(str)\n            elif isinstance(type(arg), bytes):\n                _types.add(bytes)\n            elif arg:\n                _types.add(type(arg))\n        return _types.pop()\n\n\ndef _sanitize_params(prefix, suffix, dir):\n    \"\"\"Common parameter processing for most APIs in this module.\"\"\"\n    output_type = _infer_return_type(prefix, suffix, dir)\n    if suffix is None:\n        suffix = output_type()\n    if prefix is None:\n        if output_type is str:\n            prefix = \"tmp\"\n        else:\n            prefix = os.fsencode(\"tmp\")\n    if dir is None:\n        if output_type is str:\n            dir = gettempdir()\n        else:\n            dir = os.fsencode(gettempdir())\n    return prefix, suffix, dir, output_type\n\n\nclass _TemporaryFileCloser:\n    \"\"\"A separate object allowing proper closing of a temporary file's\n    underlying file object, without adding a __del__ method to the\n    temporary file.\"\"\"\n\n    file = None  # Set here since __del__ checks it\n    close_called = False\n\n    def __init__(self, file, name, delete=True):\n        self.file = file\n        self.name = name\n        self.delete = delete\n\n    # NT provides delete-on-close as a primitive, so we don't need\n    # the wrapper to do anything special.  We still use it so that\n    # file.name is useful (i.e. not \"(fdopen)\") with NamedTemporaryFile.\n    if os.name != \"nt\":\n\n        # Cache the unlinker so we don't get spurious errors at\n        # shutdown when the module-level \"os\" is None'd out.  Note\n        # that this must be referenced as self.unlink, because the\n        # name TemporaryFileWrapper may also get None'd out before\n        # __del__ is called.\n\n        def close(self, unlink=os.unlink):\n            if not self.close_called and self.file is not None:\n                self.close_called = True\n                try:\n                    self.file.close()\n                finally:\n                    if self.delete:\n                        unlink(self.name)\n\n        # Need to ensure the file is deleted on __del__\n\n        def __del__(self):\n            self.close()\n\n    else:\n\n        def close(self):\n            if not self.close_called:\n                self.close_called = True\n                self.file.close()\n\n\nclass _TemporaryFileWrapper:\n    \"\"\"Temporary file wrapper\n    This class provides a wrapper around files opened for\n    temporary use.  In particular, it seeks to automatically\n    remove the file when it is no longer needed.\n    \"\"\"\n\n    def __init__(self, file, name, delete=True):\n        self.file = file\n        self.name = name\n        self.delete = delete\n        self._closer = _TemporaryFileCloser(file, name, delete)\n\n    def __getattr__(self, name):\n        # Attribute lookups are delegated to the underlying file\n        # and cached for non-numeric results\n        # (i.e. methods are cached, closed and friends are not)\n        file = self.__dict__[\"file\"]\n        a = getattr(file, name)\n        if hasattr(a, \"__call__\"):\n            func = a\n\n            @functools.wraps(func)\n            def func_wrapper(*args, **kwargs):\n                return func(*args, **kwargs)\n\n            # Avoid closing the file as long as the wrapper is alive,\n            # see issue #18879.\n            func_wrapper._closer = self._closer\n            a = func_wrapper\n        if not isinstance(a, int):\n            setattr(self, name, a)\n        return a\n\n    # The underlying __enter__ method returns the wrong object\n    # (self.file) so override it to return the wrapper\n\n    def __enter__(self):\n        self.file.__enter__()\n        return self\n\n    # Need to trap __exit__ as well to ensure the file gets\n    # deleted when used in a with statement\n\n    def __exit__(self, exc, value, tb):\n        result = self.file.__exit__(exc, value, tb)\n        self.close()\n        return result\n\n    def close(self):\n        \"\"\"\n        Close the temporary file, possibly deleting it.\n        \"\"\"\n        self._closer.close()\n\n    # iter() doesn't use __getattr__ to find the __iter__ method\n\n    def __iter__(self):\n        # Don't return iter(self.file), but yield from it to avoid closing\n        # file as long as it's being used as iterator (see issue #23700).  We\n        # can't use 'yield from' here because iter(file) returns the file\n        # object itself, which has a close method, and thus the file would get\n        # closed when the generator is finalized, due to PEP380 semantics.\n        for line in self.file:\n            yield line\n\n\ndef NamedTemporaryFile(\n    mode=\"w+b\",\n    buffering=-1,\n    encoding=None,\n    newline=None,\n    suffix=None,\n    prefix=None,\n    dir=None,\n    delete=True,\n):\n    \"\"\"Create and return a temporary file.\n    Arguments:\n    'prefix', 'suffix', 'dir' -- as for mkstemp.\n    'mode' -- the mode argument to io.open (default \"w+b\").\n    'buffering' -- the buffer size argument to io.open (default -1).\n    'encoding' -- the encoding argument to io.open (default None)\n    'newline' -- the newline argument to io.open (default None)\n    'delete' -- whether the file is deleted on close (default True).\n    The file is created as mkstemp() would do it.\n    Returns an object with a file-like interface; the name of the file\n    is accessible as its 'name' attribute.  The file will be automatically\n    deleted when it is closed unless the 'delete' argument is set to False.\n    \"\"\"\n    prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)\n    flags = _bin_openflags\n    # Setting O_TEMPORARY in the flags causes the OS to delete\n    # the file when it is closed.  This is only supported by Windows.\n    if os.name == \"nt\" and delete:\n        flags |= os.O_TEMPORARY\n    if sys.version_info < (3, 5):\n        (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)\n    else:\n        (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)\n    try:\n        file = io.open(\n            fd, mode, buffering=buffering, newline=newline, encoding=encoding\n        )\n        return _TemporaryFileWrapper(file, name, delete)\n\n    except BaseException:\n        os.unlink(name)\n        os.close(fd)\n        raise\n", "path": "pipenv/vendor/vistir/backports/tempfile.py"}, {"content": "# -*- coding=utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\n\nimport os\nimport sys\nimport warnings\n\nfrom tempfile import mkdtemp\n\nimport six\n\n\n__all__ = [\n    \"Path\",\n    \"get_terminal_size\",\n    \"finalize\",\n    \"partialmethod\",\n    \"JSONDecodeError\",\n    \"ResourceWarning\",\n    \"FileNotFoundError\",\n    \"fs_str\",\n    \"TemporaryDirectory\",\n    \"NamedTemporaryFile\",\n]\n\nif sys.version_info >= (3, 5):\n    from pathlib import Path\n\nelse:\n    from pathlib2 import Path\n\nif sys.version_info < (3, 3):\n    from pipenv.vendor.backports.shutil_get_terminal_size import get_terminal_size\n    from .backports.tempfile import NamedTemporaryFile\nelse:\n    from tempfile import NamedTemporaryFile\n    from shutil import get_terminal_size\n\ntry:\n    from weakref import finalize\nexcept ImportError:\n    from pipenv.vendor.backports.weakref import finalize\n\ntry:\n    from functools import partialmethod\nexcept Exception:\n    from .backports.functools import partialmethod\n\ntry:\n    from json import JSONDecodeError\nexcept ImportError:  # Old Pythons.\n    JSONDecodeError = ValueError\n\nif six.PY2:\n\n    class ResourceWarning(Warning):\n        pass\n\n    class FileNotFoundError(IOError):\n        pass\n\nelse:\n    from builtins import ResourceWarning, FileNotFoundError\n\n    class ResourceWarning(ResourceWarning):\n        pass\n\n    class FileNotFoundError(FileNotFoundError):\n        pass\n\n\nclass TemporaryDirectory(object):\n    \"\"\"Create and return a temporary directory.  This has the same\n    behavior as mkdtemp but can be used as a context manager.  For\n    example:\n\n        with TemporaryDirectory() as tmpdir:\n            ...\n\n    Upon exiting the context, the directory and everything contained\n    in it are removed.\n    \"\"\"\n\n    def __init__(self, suffix=\"\", prefix=None, dir=None):\n        if \"RAM_DISK\" in os.environ:\n            import uuid\n\n            name = uuid.uuid4().hex\n            dir_name = os.path.join(os.environ[\"RAM_DISK\"].strip(), name)\n            os.mkdir(dir_name)\n            self.name = dir_name\n        else:\n            suffix = suffix if suffix else \"\"\n            if not prefix:\n                self.name = mkdtemp(suffix=suffix, dir=dir)\n            else:\n                self.name = mkdtemp(suffix, prefix, dir)\n        self._finalizer = finalize(\n            self,\n            self._cleanup,\n            self.name,\n            warn_message=\"Implicitly cleaning up {!r}\".format(self),\n        )\n\n    @classmethod\n    def _cleanup(cls, name, warn_message):\n        from .path import rmtree\n        rmtree(name)\n        warnings.warn(warn_message, ResourceWarning)\n\n    def __repr__(self):\n        return \"<{} {!r}>\".format(self.__class__.__name__, self.name)\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc, value, tb):\n        self.cleanup()\n\n    def cleanup(self):\n        from .path import rmtree\n        if self._finalizer.detach():\n            rmtree(self.name)\n\n\ndef fs_str(string):\n    \"\"\"Encodes a string into the proper filesystem encoding\n\n    Borrowed from pip-tools\n    \"\"\"\n    if isinstance(string, str):\n        return string\n    assert not isinstance(string, bytes)\n    return string.encode(_fs_encoding)\n\n\n_fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()\n", "path": "pipenv/vendor/vistir/compat.py"}]}