We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
--target option causes issues when upgrading or re-installing
If you install using the "--target" option:

```
pip install --target lib requests
```

And then repeat the command a second time, it doesn't say "requirement satisfied" it installs it again as a subdirectory of the existing installation (lib/requests/requests and lib/requests-2.2.0.dist-info/requests-2.2.0.dist-info

Repeat the command a third time and it appears the nesting stops but it chokes and still doesn't report "requirement satisfied":

```
Downloading/unpacking requests
  Downloading requests-2.2.0-py2.py3-none-any.whl (623kB): 623kB downloaded
Installing collected packages: requests
Successfully installed requests
Cleaning up...
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 307, in run
    os.path.join(options.target_dir, item)
  File "/usr/lib/python2.7/shutil.py", line 291, in move
    raise Error, "Destination path '%s' already exists" % real_dst
Error: Destination path '/tmp/piptest/lib/requests/requests' already exists

Storing debug log for failure in /tmp/tmpcBDoql
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pip/commands/install.py`
Content:
```
1 import os
2 import tempfile
3 import shutil
4 
5 from pip.req import InstallRequirement, RequirementSet, parse_requirements
6 from pip.log import logger
7 from pip.locations import (virtualenv_no_global, distutils_scheme,
8                            build_prefix)
9 from pip.basecommand import Command
10 from pip.index import PackageFinder
11 from pip.exceptions import (
12     InstallationError, CommandError, PreviousBuildDirError,
13 )
14 from pip import cmdoptions
15 
16 
17 class InstallCommand(Command):
18     """
19     Install packages from:
20 
21     - PyPI (and other indexes) using requirement specifiers.
22     - VCS project urls.
23     - Local project directories.
24     - Local or remote source archives.
25 
26     pip also supports installing from "requirements files", which provide
27     an easy way to specify a whole environment to be installed.
28     """
29     name = 'install'
30 
31     usage = """
32       %prog [options] <requirement specifier> [package-index-options] ...
33       %prog [options] -r <requirements file> [package-index-options] ...
34       %prog [options] [-e] <vcs project url> ...
35       %prog [options] [-e] <local project path> ...
36       %prog [options] <archive url/path> ..."""
37 
38     summary = 'Install packages.'
39 
40     def __init__(self, *args, **kw):
41         super(InstallCommand, self).__init__(*args, **kw)
42 
43         cmd_opts = self.cmd_opts
44 
45         cmd_opts.add_option(cmdoptions.editable.make())
46         cmd_opts.add_option(cmdoptions.requirements.make())
47         cmd_opts.add_option(cmdoptions.build_dir.make())
48 
49         cmd_opts.add_option(
50             '-t', '--target',
51             dest='target_dir',
52             metavar='dir',
53             default=None,
54             help='Install packages into <dir>.')
55 
56         cmd_opts.add_option(
57             '-d', '--download', '--download-dir', '--download-directory',
58             dest='download_dir',
59             metavar='dir',
60             default=None,
61             help=("Download packages into <dir> instead of installing them, "
62                   "regardless of what's already installed."),
63         )
64 
65         cmd_opts.add_option(cmdoptions.download_cache.make())
66         cmd_opts.add_option(cmdoptions.src.make())
67 
68         cmd_opts.add_option(
69             '-U', '--upgrade',
70             dest='upgrade',
71             action='store_true',
72             help='Upgrade all packages to the newest available version. '
73                  'This process is recursive regardless of whether a dependency'
74                  ' is already satisfied.'
75         )
76 
77         cmd_opts.add_option(
78             '--force-reinstall',
79             dest='force_reinstall',
80             action='store_true',
81             help='When upgrading, reinstall all packages even if they are '
82                  'already up-to-date.')
83 
84         cmd_opts.add_option(
85             '-I', '--ignore-installed',
86             dest='ignore_installed',
87             action='store_true',
88             help='Ignore the installed packages (reinstalling instead).')
89 
90         cmd_opts.add_option(cmdoptions.no_deps.make())
91 
92         cmd_opts.add_option(
93             '--no-install',
94             dest='no_install',
95             action='store_true',
96             help="DEPRECATED. Download and unpack all packages, but don't "
97                  "actually install them."
98         )
99 
100         cmd_opts.add_option(
101             '--no-download',
102             dest='no_download',
103             action="store_true",
104             help="DEPRECATED. Don't download any packages, just install the "
105                  "ones already downloaded (completes an install run with "
106                  "--no-install).")
107 
108         cmd_opts.add_option(cmdoptions.install_options.make())
109         cmd_opts.add_option(cmdoptions.global_options.make())
110 
111         cmd_opts.add_option(
112             '--user',
113             dest='use_user_site',
114             action='store_true',
115             help='Install using the user scheme.')
116 
117         cmd_opts.add_option(
118             '--egg',
119             dest='as_egg',
120             action='store_true',
121             help="Install packages as eggs, not 'flat', like pip normally "
122                  "does. This option is not about installing *from* eggs. "
123                  "(WARNING: Because this option overrides pip's normal install"
124                  " logic, requirements files may not behave as expected.)")
125 
126         cmd_opts.add_option(
127             '--root',
128             dest='root_path',
129             metavar='dir',
130             default=None,
131             help="Install everything relative to this alternate root "
132                  "directory.")
133 
134         cmd_opts.add_option(
135             "--compile",
136             action="store_true",
137             dest="compile",
138             default=True,
139             help="Compile py files to pyc",
140         )
141 
142         cmd_opts.add_option(
143             "--no-compile",
144             action="store_false",
145             dest="compile",
146             help="Do not compile py files to pyc",
147         )
148 
149         cmd_opts.add_option(cmdoptions.use_wheel.make())
150         cmd_opts.add_option(cmdoptions.no_use_wheel.make())
151 
152         cmd_opts.add_option(
153             '--pre',
154             action='store_true',
155             default=False,
156             help="Include pre-release and development versions. By default, "
157                  "pip only finds stable versions.")
158 
159         cmd_opts.add_option(cmdoptions.no_clean.make())
160 
161         index_opts = cmdoptions.make_option_group(
162             cmdoptions.index_group,
163             self.parser,
164         )
165 
166         self.parser.insert_option_group(0, index_opts)
167         self.parser.insert_option_group(0, cmd_opts)
168 
169     def _build_package_finder(self, options, index_urls, session):
170         """
171         Create a package finder appropriate to this install command.
172         This method is meant to be overridden by subclasses, not
173         called directly.
174         """
175         return PackageFinder(
176             find_links=options.find_links,
177             index_urls=index_urls,
178             use_wheel=options.use_wheel,
179             allow_external=options.allow_external,
180             allow_unverified=options.allow_unverified,
181             allow_all_external=options.allow_all_external,
182             allow_all_prereleases=options.pre,
183             process_dependency_links=options.process_dependency_links,
184             session=session,
185         )
186 
187     def run(self, options, args):
188 
189         if (
190             options.no_install or
191             options.no_download or
192             (options.build_dir != build_prefix) or
193             options.no_clean
194         ):
195             logger.deprecated(
196                 '1.7',
197                 'DEPRECATION: --no-install, --no-download, --build, '
198                 'and --no-clean are deprecated.  See '
199                 'https://github.com/pypa/pip/issues/906.',
200             )
201 
202         if options.download_dir:
203             options.no_install = True
204             options.ignore_installed = True
205         options.build_dir = os.path.abspath(options.build_dir)
206         options.src_dir = os.path.abspath(options.src_dir)
207         install_options = options.install_options or []
208         if options.use_user_site:
209             if virtualenv_no_global():
210                 raise InstallationError(
211                     "Can not perform a '--user' install. User site-packages "
212                     "are not visible in this virtualenv."
213                 )
214             install_options.append('--user')
215 
216         temp_target_dir = None
217         if options.target_dir:
218             options.ignore_installed = True
219             temp_target_dir = tempfile.mkdtemp()
220             options.target_dir = os.path.abspath(options.target_dir)
221             if (os.path.exists(options.target_dir)
222                     and not os.path.isdir(options.target_dir)):
223                 raise CommandError(
224                     "Target path exists but is not a directory, will not "
225                     "continue."
226                 )
227             install_options.append('--home=' + temp_target_dir)
228 
229         global_options = options.global_options or []
230         index_urls = [options.index_url] + options.extra_index_urls
231         if options.no_index:
232             logger.notify('Ignoring indexes: %s' % ','.join(index_urls))
233             index_urls = []
234 
235         if options.use_mirrors:
236             logger.deprecated(
237                 "1.7",
238                 "--use-mirrors has been deprecated and will be removed"
239                 " in the future. Explicit uses of --index-url and/or "
240                 "--extra-index-url is suggested."
241             )
242 
243         if options.mirrors:
244             logger.deprecated(
245                 "1.7",
246                 "--mirrors has been deprecated and will be removed in "
247                 " the future. Explicit uses of --index-url and/or "
248                 "--extra-index-url is suggested."
249             )
250             index_urls += options.mirrors
251 
252         if options.download_cache:
253             logger.deprecated(
254                 "1.8",
255                 "--download-cache has been deprecated and will be removed in "
256                 " the future. Pip now automatically uses and configures its "
257                 "cache."
258             )
259 
260         with self._build_session(options) as session:
261 
262             finder = self._build_package_finder(options, index_urls, session)
263 
264             requirement_set = RequirementSet(
265                 build_dir=options.build_dir,
266                 src_dir=options.src_dir,
267                 download_dir=options.download_dir,
268                 upgrade=options.upgrade,
269                 as_egg=options.as_egg,
270                 ignore_installed=options.ignore_installed,
271                 ignore_dependencies=options.ignore_dependencies,
272                 force_reinstall=options.force_reinstall,
273                 use_user_site=options.use_user_site,
274                 target_dir=temp_target_dir,
275                 session=session,
276                 pycompile=options.compile,
277             )
278             for name in args:
279                 requirement_set.add_requirement(
280                     InstallRequirement.from_line(name, None))
281             for name in options.editables:
282                 requirement_set.add_requirement(
283                     InstallRequirement.from_editable(
284                         name,
285                         default_vcs=options.default_vcs
286                     )
287                 )
288             for filename in options.requirements:
289                 for req in parse_requirements(
290                         filename,
291                         finder=finder, options=options, session=session):
292                     requirement_set.add_requirement(req)
293             if not requirement_set.has_requirements:
294                 opts = {'name': self.name}
295                 if options.find_links:
296                     msg = ('You must give at least one requirement to %(name)s'
297                            ' (maybe you meant "pip %(name)s %(links)s"?)' %
298                            dict(opts, links=' '.join(options.find_links)))
299                 else:
300                     msg = ('You must give at least one requirement '
301                            'to %(name)s (see "pip help %(name)s")' % opts)
302                 logger.warn(msg)
303                 return
304 
305             try:
306                 if not options.no_download:
307                     requirement_set.prepare_files(finder)
308                 else:
309                     requirement_set.locate_files()
310 
311                 if not options.no_install:
312                     requirement_set.install(
313                         install_options,
314                         global_options,
315                         root=options.root_path,
316                     )
317                     installed = ' '.join([
318                         req.name for req in
319                         requirement_set.successfully_installed
320                     ])
321                     if installed:
322                         logger.notify('Successfully installed %s' % installed)
323                 else:
324                     downloaded = ' '.join([
325                         req.name
326                         for req in requirement_set.successfully_downloaded
327                     ])
328                     if downloaded:
329                         logger.notify(
330                             'Successfully downloaded %s' % downloaded
331                         )
332             except PreviousBuildDirError:
333                 options.no_clean = True
334                 raise
335             finally:
336                 # Clean up
337                 if ((not options.no_clean)
338                         and ((not options.no_install)
339                              or options.download_dir)):
340                     requirement_set.cleanup_files()
341 
342             if options.target_dir:
343                 if not os.path.exists(options.target_dir):
344                     os.makedirs(options.target_dir)
345                 lib_dir = distutils_scheme('', home=temp_target_dir)['purelib']
346                 for item in os.listdir(lib_dir):
347                     shutil.move(
348                         os.path.join(lib_dir, item),
349                         os.path.join(options.target_dir, item),
350                     )
351                 shutil.rmtree(temp_target_dir)
352             return requirement_set
353
```
--- 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/pip/commands/install.py b/pip/commands/install.py
--- a/pip/commands/install.py
+++ b/pip/commands/install.py
@@ -51,7 +51,11 @@
             dest='target_dir',
             metavar='dir',
             default=None,
-            help='Install packages into <dir>.')
+            help='Install packages into <dir>. '
+                 'By default this will not replace existing files/folders in '
+                 '<dir>. Use --upgrade to replace existing packages in <dir> '
+                 'with new versions.'
+        )
 
         cmd_opts.add_option(
             '-d', '--download', '--download-dir', '--download-directory',
@@ -344,9 +348,32 @@
                     os.makedirs(options.target_dir)
                 lib_dir = distutils_scheme('', home=temp_target_dir)['purelib']
                 for item in os.listdir(lib_dir):
+                    target_item_dir = os.path.join(options.target_dir, item)
+                    if os.path.exists(target_item_dir):
+                        if not options.upgrade:
+                            logger.warn(
+                                'Target directory %s already exists. Specify '
+                                '--upgrade to force replacement.'
+                                % target_item_dir
+                            )
+                            continue
+                        if os.path.islink(target_item_dir):
+                            logger.warn(
+                                'Target directory %s already exists and is '
+                                'a link. Pip will not automatically replace '
+                                'links, please remove if replacement is '
+                                'desired.'
+                                % target_item_dir
+                            )
+                            continue
+                        if os.path.isdir(target_item_dir):
+                            shutil.rmtree(target_item_dir)
+                        else:
+                            os.remove(target_item_dir)
+
                     shutil.move(
                         os.path.join(lib_dir, item),
-                        os.path.join(options.target_dir, item),
+                        target_item_dir
                     )
                 shutil.rmtree(temp_target_dir)
             return requirement_set

{"golden_diff": "diff --git a/pip/commands/install.py b/pip/commands/install.py\n--- a/pip/commands/install.py\n+++ b/pip/commands/install.py\n@@ -51,7 +51,11 @@\n             dest='target_dir',\n             metavar='dir',\n             default=None,\n-            help='Install packages into <dir>.')\n+            help='Install packages into <dir>. '\n+                 'By default this will not replace existing files/folders in '\n+                 '<dir>. Use --upgrade to replace existing packages in <dir> '\n+                 'with new versions.'\n+        )\n \n         cmd_opts.add_option(\n             '-d', '--download', '--download-dir', '--download-directory',\n@@ -344,9 +348,32 @@\n                     os.makedirs(options.target_dir)\n                 lib_dir = distutils_scheme('', home=temp_target_dir)['purelib']\n                 for item in os.listdir(lib_dir):\n+                    target_item_dir = os.path.join(options.target_dir, item)\n+                    if os.path.exists(target_item_dir):\n+                        if not options.upgrade:\n+                            logger.warn(\n+                                'Target directory %s already exists. Specify '\n+                                '--upgrade to force replacement.'\n+                                % target_item_dir\n+                            )\n+                            continue\n+                        if os.path.islink(target_item_dir):\n+                            logger.warn(\n+                                'Target directory %s already exists and is '\n+                                'a link. Pip will not automatically replace '\n+                                'links, please remove if replacement is '\n+                                'desired.'\n+                                % target_item_dir\n+                            )\n+                            continue\n+                        if os.path.isdir(target_item_dir):\n+                            shutil.rmtree(target_item_dir)\n+                        else:\n+                            os.remove(target_item_dir)\n+\n                     shutil.move(\n                         os.path.join(lib_dir, item),\n-                        os.path.join(options.target_dir, item),\n+                        target_item_dir\n                     )\n                 shutil.rmtree(temp_target_dir)\n             return requirement_set\n", "issue": "--target option causes issues when upgrading or re-installing\nIf you install using the \"--target\" option:\n\n```\npip install --target lib requests\n```\n\nAnd then repeat the command a second time, it doesn't say \"requirement satisfied\" it installs it again as a subdirectory of the existing installation (lib/requests/requests and lib/requests-2.2.0.dist-info/requests-2.2.0.dist-info\n\nRepeat the command a third time and it appears the nesting stops but it chokes and still doesn't report \"requirement satisfied\":\n\n```\nDownloading/unpacking requests\n  Downloading requests-2.2.0-py2.py3-none-any.whl (623kB): 623kB downloaded\nInstalling collected packages: requests\nSuccessfully installed requests\nCleaning up...\nException:\nTraceback (most recent call last):\n  File \"/usr/local/lib/python2.7/dist-packages/pip/basecommand.py\", line 122, in main\n    status = self.run(options, args)\n  File \"/usr/local/lib/python2.7/dist-packages/pip/commands/install.py\", line 307, in run\n    os.path.join(options.target_dir, item)\n  File \"/usr/lib/python2.7/shutil.py\", line 291, in move\n    raise Error, \"Destination path '%s' already exists\" % real_dst\nError: Destination path '/tmp/piptest/lib/requests/requests' already exists\n\nStoring debug log for failure in /tmp/tmpcBDoql\n```\n\n", "before_files": [{"content": "import os\nimport tempfile\nimport shutil\n\nfrom pip.req import InstallRequirement, RequirementSet, parse_requirements\nfrom pip.log import logger\nfrom pip.locations import (virtualenv_no_global, distutils_scheme,\n                           build_prefix)\nfrom pip.basecommand import Command\nfrom pip.index import PackageFinder\nfrom pip.exceptions import (\n    InstallationError, CommandError, PreviousBuildDirError,\n)\nfrom pip import cmdoptions\n\n\nclass InstallCommand(Command):\n    \"\"\"\n    Install packages from:\n\n    - PyPI (and other indexes) using requirement specifiers.\n    - VCS project urls.\n    - Local project directories.\n    - Local or remote source archives.\n\n    pip also supports installing from \"requirements files\", which provide\n    an easy way to specify a whole environment to be installed.\n    \"\"\"\n    name = 'install'\n\n    usage = \"\"\"\n      %prog [options] <requirement specifier> [package-index-options] ...\n      %prog [options] -r <requirements file> [package-index-options] ...\n      %prog [options] [-e] <vcs project url> ...\n      %prog [options] [-e] <local project path> ...\n      %prog [options] <archive url/path> ...\"\"\"\n\n    summary = 'Install packages.'\n\n    def __init__(self, *args, **kw):\n        super(InstallCommand, self).__init__(*args, **kw)\n\n        cmd_opts = self.cmd_opts\n\n        cmd_opts.add_option(cmdoptions.editable.make())\n        cmd_opts.add_option(cmdoptions.requirements.make())\n        cmd_opts.add_option(cmdoptions.build_dir.make())\n\n        cmd_opts.add_option(\n            '-t', '--target',\n            dest='target_dir',\n            metavar='dir',\n            default=None,\n            help='Install packages into <dir>.')\n\n        cmd_opts.add_option(\n            '-d', '--download', '--download-dir', '--download-directory',\n            dest='download_dir',\n            metavar='dir',\n            default=None,\n            help=(\"Download packages into <dir> instead of installing them, \"\n                  \"regardless of what's already installed.\"),\n        )\n\n        cmd_opts.add_option(cmdoptions.download_cache.make())\n        cmd_opts.add_option(cmdoptions.src.make())\n\n        cmd_opts.add_option(\n            '-U', '--upgrade',\n            dest='upgrade',\n            action='store_true',\n            help='Upgrade all packages to the newest available version. '\n                 'This process is recursive regardless of whether a dependency'\n                 ' is already satisfied.'\n        )\n\n        cmd_opts.add_option(\n            '--force-reinstall',\n            dest='force_reinstall',\n            action='store_true',\n            help='When upgrading, reinstall all packages even if they are '\n                 'already up-to-date.')\n\n        cmd_opts.add_option(\n            '-I', '--ignore-installed',\n            dest='ignore_installed',\n            action='store_true',\n            help='Ignore the installed packages (reinstalling instead).')\n\n        cmd_opts.add_option(cmdoptions.no_deps.make())\n\n        cmd_opts.add_option(\n            '--no-install',\n            dest='no_install',\n            action='store_true',\n            help=\"DEPRECATED. Download and unpack all packages, but don't \"\n                 \"actually install them.\"\n        )\n\n        cmd_opts.add_option(\n            '--no-download',\n            dest='no_download',\n            action=\"store_true\",\n            help=\"DEPRECATED. Don't download any packages, just install the \"\n                 \"ones already downloaded (completes an install run with \"\n                 \"--no-install).\")\n\n        cmd_opts.add_option(cmdoptions.install_options.make())\n        cmd_opts.add_option(cmdoptions.global_options.make())\n\n        cmd_opts.add_option(\n            '--user',\n            dest='use_user_site',\n            action='store_true',\n            help='Install using the user scheme.')\n\n        cmd_opts.add_option(\n            '--egg',\n            dest='as_egg',\n            action='store_true',\n            help=\"Install packages as eggs, not 'flat', like pip normally \"\n                 \"does. This option is not about installing *from* eggs. \"\n                 \"(WARNING: Because this option overrides pip's normal install\"\n                 \" logic, requirements files may not behave as expected.)\")\n\n        cmd_opts.add_option(\n            '--root',\n            dest='root_path',\n            metavar='dir',\n            default=None,\n            help=\"Install everything relative to this alternate root \"\n                 \"directory.\")\n\n        cmd_opts.add_option(\n            \"--compile\",\n            action=\"store_true\",\n            dest=\"compile\",\n            default=True,\n            help=\"Compile py files to pyc\",\n        )\n\n        cmd_opts.add_option(\n            \"--no-compile\",\n            action=\"store_false\",\n            dest=\"compile\",\n            help=\"Do not compile py files to pyc\",\n        )\n\n        cmd_opts.add_option(cmdoptions.use_wheel.make())\n        cmd_opts.add_option(cmdoptions.no_use_wheel.make())\n\n        cmd_opts.add_option(\n            '--pre',\n            action='store_true',\n            default=False,\n            help=\"Include pre-release and development versions. By default, \"\n                 \"pip only finds stable versions.\")\n\n        cmd_opts.add_option(cmdoptions.no_clean.make())\n\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, cmd_opts)\n\n    def _build_package_finder(self, options, index_urls, session):\n        \"\"\"\n        Create a package finder appropriate to this install command.\n        This method is meant to be overridden by subclasses, not\n        called directly.\n        \"\"\"\n        return PackageFinder(\n            find_links=options.find_links,\n            index_urls=index_urls,\n            use_wheel=options.use_wheel,\n            allow_external=options.allow_external,\n            allow_unverified=options.allow_unverified,\n            allow_all_external=options.allow_all_external,\n            allow_all_prereleases=options.pre,\n            process_dependency_links=options.process_dependency_links,\n            session=session,\n        )\n\n    def run(self, options, args):\n\n        if (\n            options.no_install or\n            options.no_download or\n            (options.build_dir != build_prefix) or\n            options.no_clean\n        ):\n            logger.deprecated(\n                '1.7',\n                'DEPRECATION: --no-install, --no-download, --build, '\n                'and --no-clean are deprecated.  See '\n                'https://github.com/pypa/pip/issues/906.',\n            )\n\n        if options.download_dir:\n            options.no_install = True\n            options.ignore_installed = True\n        options.build_dir = os.path.abspath(options.build_dir)\n        options.src_dir = os.path.abspath(options.src_dir)\n        install_options = options.install_options or []\n        if options.use_user_site:\n            if virtualenv_no_global():\n                raise InstallationError(\n                    \"Can not perform a '--user' install. User site-packages \"\n                    \"are not visible in this virtualenv.\"\n                )\n            install_options.append('--user')\n\n        temp_target_dir = None\n        if options.target_dir:\n            options.ignore_installed = True\n            temp_target_dir = tempfile.mkdtemp()\n            options.target_dir = os.path.abspath(options.target_dir)\n            if (os.path.exists(options.target_dir)\n                    and not os.path.isdir(options.target_dir)):\n                raise CommandError(\n                    \"Target path exists but is not a directory, will not \"\n                    \"continue.\"\n                )\n            install_options.append('--home=' + temp_target_dir)\n\n        global_options = options.global_options or []\n        index_urls = [options.index_url] + options.extra_index_urls\n        if options.no_index:\n            logger.notify('Ignoring indexes: %s' % ','.join(index_urls))\n            index_urls = []\n\n        if options.use_mirrors:\n            logger.deprecated(\n                \"1.7\",\n                \"--use-mirrors has been deprecated and will be removed\"\n                \" in the future. Explicit uses of --index-url and/or \"\n                \"--extra-index-url is suggested.\"\n            )\n\n        if options.mirrors:\n            logger.deprecated(\n                \"1.7\",\n                \"--mirrors has been deprecated and will be removed in \"\n                \" the future. Explicit uses of --index-url and/or \"\n                \"--extra-index-url is suggested.\"\n            )\n            index_urls += options.mirrors\n\n        if options.download_cache:\n            logger.deprecated(\n                \"1.8\",\n                \"--download-cache has been deprecated and will be removed in \"\n                \" the future. Pip now automatically uses and configures its \"\n                \"cache.\"\n            )\n\n        with self._build_session(options) as session:\n\n            finder = self._build_package_finder(options, index_urls, session)\n\n            requirement_set = RequirementSet(\n                build_dir=options.build_dir,\n                src_dir=options.src_dir,\n                download_dir=options.download_dir,\n                upgrade=options.upgrade,\n                as_egg=options.as_egg,\n                ignore_installed=options.ignore_installed,\n                ignore_dependencies=options.ignore_dependencies,\n                force_reinstall=options.force_reinstall,\n                use_user_site=options.use_user_site,\n                target_dir=temp_target_dir,\n                session=session,\n                pycompile=options.compile,\n            )\n            for name in args:\n                requirement_set.add_requirement(\n                    InstallRequirement.from_line(name, None))\n            for name in options.editables:\n                requirement_set.add_requirement(\n                    InstallRequirement.from_editable(\n                        name,\n                        default_vcs=options.default_vcs\n                    )\n                )\n            for filename in options.requirements:\n                for req in parse_requirements(\n                        filename,\n                        finder=finder, options=options, session=session):\n                    requirement_set.add_requirement(req)\n            if not requirement_set.has_requirements:\n                opts = {'name': self.name}\n                if options.find_links:\n                    msg = ('You must give at least one requirement to %(name)s'\n                           ' (maybe you meant \"pip %(name)s %(links)s\"?)' %\n                           dict(opts, links=' '.join(options.find_links)))\n                else:\n                    msg = ('You must give at least one requirement '\n                           'to %(name)s (see \"pip help %(name)s\")' % opts)\n                logger.warn(msg)\n                return\n\n            try:\n                if not options.no_download:\n                    requirement_set.prepare_files(finder)\n                else:\n                    requirement_set.locate_files()\n\n                if not options.no_install:\n                    requirement_set.install(\n                        install_options,\n                        global_options,\n                        root=options.root_path,\n                    )\n                    installed = ' '.join([\n                        req.name for req in\n                        requirement_set.successfully_installed\n                    ])\n                    if installed:\n                        logger.notify('Successfully installed %s' % installed)\n                else:\n                    downloaded = ' '.join([\n                        req.name\n                        for req in requirement_set.successfully_downloaded\n                    ])\n                    if downloaded:\n                        logger.notify(\n                            'Successfully downloaded %s' % downloaded\n                        )\n            except PreviousBuildDirError:\n                options.no_clean = True\n                raise\n            finally:\n                # Clean up\n                if ((not options.no_clean)\n                        and ((not options.no_install)\n                             or options.download_dir)):\n                    requirement_set.cleanup_files()\n\n            if options.target_dir:\n                if not os.path.exists(options.target_dir):\n                    os.makedirs(options.target_dir)\n                lib_dir = distutils_scheme('', home=temp_target_dir)['purelib']\n                for item in os.listdir(lib_dir):\n                    shutil.move(\n                        os.path.join(lib_dir, item),\n                        os.path.join(options.target_dir, item),\n                    )\n                shutil.rmtree(temp_target_dir)\n            return requirement_set\n", "path": "pip/commands/install.py"}], "after_files": [{"content": "import os\nimport tempfile\nimport shutil\n\nfrom pip.req import InstallRequirement, RequirementSet, parse_requirements\nfrom pip.log import logger\nfrom pip.locations import (virtualenv_no_global, distutils_scheme,\n                           build_prefix)\nfrom pip.basecommand import Command\nfrom pip.index import PackageFinder\nfrom pip.exceptions import (\n    InstallationError, CommandError, PreviousBuildDirError,\n)\nfrom pip import cmdoptions\n\n\nclass InstallCommand(Command):\n    \"\"\"\n    Install packages from:\n\n    - PyPI (and other indexes) using requirement specifiers.\n    - VCS project urls.\n    - Local project directories.\n    - Local or remote source archives.\n\n    pip also supports installing from \"requirements files\", which provide\n    an easy way to specify a whole environment to be installed.\n    \"\"\"\n    name = 'install'\n\n    usage = \"\"\"\n      %prog [options] <requirement specifier> [package-index-options] ...\n      %prog [options] -r <requirements file> [package-index-options] ...\n      %prog [options] [-e] <vcs project url> ...\n      %prog [options] [-e] <local project path> ...\n      %prog [options] <archive url/path> ...\"\"\"\n\n    summary = 'Install packages.'\n\n    def __init__(self, *args, **kw):\n        super(InstallCommand, self).__init__(*args, **kw)\n\n        cmd_opts = self.cmd_opts\n\n        cmd_opts.add_option(cmdoptions.editable.make())\n        cmd_opts.add_option(cmdoptions.requirements.make())\n        cmd_opts.add_option(cmdoptions.build_dir.make())\n\n        cmd_opts.add_option(\n            '-t', '--target',\n            dest='target_dir',\n            metavar='dir',\n            default=None,\n            help='Install packages into <dir>. '\n                 'By default this will not replace existing files/folders in '\n                 '<dir>. Use --upgrade to replace existing packages in <dir> '\n                 'with new versions.'\n        )\n\n        cmd_opts.add_option(\n            '-d', '--download', '--download-dir', '--download-directory',\n            dest='download_dir',\n            metavar='dir',\n            default=None,\n            help=(\"Download packages into <dir> instead of installing them, \"\n                  \"regardless of what's already installed.\"),\n        )\n\n        cmd_opts.add_option(cmdoptions.download_cache.make())\n        cmd_opts.add_option(cmdoptions.src.make())\n\n        cmd_opts.add_option(\n            '-U', '--upgrade',\n            dest='upgrade',\n            action='store_true',\n            help='Upgrade all packages to the newest available version. '\n                 'This process is recursive regardless of whether a dependency'\n                 ' is already satisfied.'\n        )\n\n        cmd_opts.add_option(\n            '--force-reinstall',\n            dest='force_reinstall',\n            action='store_true',\n            help='When upgrading, reinstall all packages even if they are '\n                 'already up-to-date.')\n\n        cmd_opts.add_option(\n            '-I', '--ignore-installed',\n            dest='ignore_installed',\n            action='store_true',\n            help='Ignore the installed packages (reinstalling instead).')\n\n        cmd_opts.add_option(cmdoptions.no_deps.make())\n\n        cmd_opts.add_option(\n            '--no-install',\n            dest='no_install',\n            action='store_true',\n            help=\"DEPRECATED. Download and unpack all packages, but don't \"\n                 \"actually install them.\"\n        )\n\n        cmd_opts.add_option(\n            '--no-download',\n            dest='no_download',\n            action=\"store_true\",\n            help=\"DEPRECATED. Don't download any packages, just install the \"\n                 \"ones already downloaded (completes an install run with \"\n                 \"--no-install).\")\n\n        cmd_opts.add_option(cmdoptions.install_options.make())\n        cmd_opts.add_option(cmdoptions.global_options.make())\n\n        cmd_opts.add_option(\n            '--user',\n            dest='use_user_site',\n            action='store_true',\n            help='Install using the user scheme.')\n\n        cmd_opts.add_option(\n            '--egg',\n            dest='as_egg',\n            action='store_true',\n            help=\"Install packages as eggs, not 'flat', like pip normally \"\n                 \"does. This option is not about installing *from* eggs. \"\n                 \"(WARNING: Because this option overrides pip's normal install\"\n                 \" logic, requirements files may not behave as expected.)\")\n\n        cmd_opts.add_option(\n            '--root',\n            dest='root_path',\n            metavar='dir',\n            default=None,\n            help=\"Install everything relative to this alternate root \"\n                 \"directory.\")\n\n        cmd_opts.add_option(\n            \"--compile\",\n            action=\"store_true\",\n            dest=\"compile\",\n            default=True,\n            help=\"Compile py files to pyc\",\n        )\n\n        cmd_opts.add_option(\n            \"--no-compile\",\n            action=\"store_false\",\n            dest=\"compile\",\n            help=\"Do not compile py files to pyc\",\n        )\n\n        cmd_opts.add_option(cmdoptions.use_wheel.make())\n        cmd_opts.add_option(cmdoptions.no_use_wheel.make())\n\n        cmd_opts.add_option(\n            '--pre',\n            action='store_true',\n            default=False,\n            help=\"Include pre-release and development versions. By default, \"\n                 \"pip only finds stable versions.\")\n\n        cmd_opts.add_option(cmdoptions.no_clean.make())\n\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, cmd_opts)\n\n    def _build_package_finder(self, options, index_urls, session):\n        \"\"\"\n        Create a package finder appropriate to this install command.\n        This method is meant to be overridden by subclasses, not\n        called directly.\n        \"\"\"\n        return PackageFinder(\n            find_links=options.find_links,\n            index_urls=index_urls,\n            use_wheel=options.use_wheel,\n            allow_external=options.allow_external,\n            allow_unverified=options.allow_unverified,\n            allow_all_external=options.allow_all_external,\n            allow_all_prereleases=options.pre,\n            process_dependency_links=options.process_dependency_links,\n            session=session,\n        )\n\n    def run(self, options, args):\n\n        if (\n            options.no_install or\n            options.no_download or\n            (options.build_dir != build_prefix) or\n            options.no_clean\n        ):\n            logger.deprecated(\n                '1.7',\n                'DEPRECATION: --no-install, --no-download, --build, '\n                'and --no-clean are deprecated.  See '\n                'https://github.com/pypa/pip/issues/906.',\n            )\n\n        if options.download_dir:\n            options.no_install = True\n            options.ignore_installed = True\n        options.build_dir = os.path.abspath(options.build_dir)\n        options.src_dir = os.path.abspath(options.src_dir)\n        install_options = options.install_options or []\n        if options.use_user_site:\n            if virtualenv_no_global():\n                raise InstallationError(\n                    \"Can not perform a '--user' install. User site-packages \"\n                    \"are not visible in this virtualenv.\"\n                )\n            install_options.append('--user')\n\n        temp_target_dir = None\n        if options.target_dir:\n            options.ignore_installed = True\n            temp_target_dir = tempfile.mkdtemp()\n            options.target_dir = os.path.abspath(options.target_dir)\n            if (os.path.exists(options.target_dir)\n                    and not os.path.isdir(options.target_dir)):\n                raise CommandError(\n                    \"Target path exists but is not a directory, will not \"\n                    \"continue.\"\n                )\n            install_options.append('--home=' + temp_target_dir)\n\n        global_options = options.global_options or []\n        index_urls = [options.index_url] + options.extra_index_urls\n        if options.no_index:\n            logger.notify('Ignoring indexes: %s' % ','.join(index_urls))\n            index_urls = []\n\n        if options.use_mirrors:\n            logger.deprecated(\n                \"1.7\",\n                \"--use-mirrors has been deprecated and will be removed\"\n                \" in the future. Explicit uses of --index-url and/or \"\n                \"--extra-index-url is suggested.\"\n            )\n\n        if options.mirrors:\n            logger.deprecated(\n                \"1.7\",\n                \"--mirrors has been deprecated and will be removed in \"\n                \" the future. Explicit uses of --index-url and/or \"\n                \"--extra-index-url is suggested.\"\n            )\n            index_urls += options.mirrors\n\n        if options.download_cache:\n            logger.deprecated(\n                \"1.8\",\n                \"--download-cache has been deprecated and will be removed in \"\n                \" the future. Pip now automatically uses and configures its \"\n                \"cache.\"\n            )\n\n        with self._build_session(options) as session:\n\n            finder = self._build_package_finder(options, index_urls, session)\n\n            requirement_set = RequirementSet(\n                build_dir=options.build_dir,\n                src_dir=options.src_dir,\n                download_dir=options.download_dir,\n                upgrade=options.upgrade,\n                as_egg=options.as_egg,\n                ignore_installed=options.ignore_installed,\n                ignore_dependencies=options.ignore_dependencies,\n                force_reinstall=options.force_reinstall,\n                use_user_site=options.use_user_site,\n                target_dir=temp_target_dir,\n                session=session,\n                pycompile=options.compile,\n            )\n            for name in args:\n                requirement_set.add_requirement(\n                    InstallRequirement.from_line(name, None))\n            for name in options.editables:\n                requirement_set.add_requirement(\n                    InstallRequirement.from_editable(\n                        name,\n                        default_vcs=options.default_vcs\n                    )\n                )\n            for filename in options.requirements:\n                for req in parse_requirements(\n                        filename,\n                        finder=finder, options=options, session=session):\n                    requirement_set.add_requirement(req)\n            if not requirement_set.has_requirements:\n                opts = {'name': self.name}\n                if options.find_links:\n                    msg = ('You must give at least one requirement to %(name)s'\n                           ' (maybe you meant \"pip %(name)s %(links)s\"?)' %\n                           dict(opts, links=' '.join(options.find_links)))\n                else:\n                    msg = ('You must give at least one requirement '\n                           'to %(name)s (see \"pip help %(name)s\")' % opts)\n                logger.warn(msg)\n                return\n\n            try:\n                if not options.no_download:\n                    requirement_set.prepare_files(finder)\n                else:\n                    requirement_set.locate_files()\n\n                if not options.no_install:\n                    requirement_set.install(\n                        install_options,\n                        global_options,\n                        root=options.root_path,\n                    )\n                    installed = ' '.join([\n                        req.name for req in\n                        requirement_set.successfully_installed\n                    ])\n                    if installed:\n                        logger.notify('Successfully installed %s' % installed)\n                else:\n                    downloaded = ' '.join([\n                        req.name\n                        for req in requirement_set.successfully_downloaded\n                    ])\n                    if downloaded:\n                        logger.notify(\n                            'Successfully downloaded %s' % downloaded\n                        )\n            except PreviousBuildDirError:\n                options.no_clean = True\n                raise\n            finally:\n                # Clean up\n                if ((not options.no_clean)\n                        and ((not options.no_install)\n                             or options.download_dir)):\n                    requirement_set.cleanup_files()\n\n            if options.target_dir:\n                if not os.path.exists(options.target_dir):\n                    os.makedirs(options.target_dir)\n                lib_dir = distutils_scheme('', home=temp_target_dir)['purelib']\n                for item in os.listdir(lib_dir):\n                    target_item_dir = os.path.join(options.target_dir, item)\n                    if os.path.exists(target_item_dir):\n                        if not options.upgrade:\n                            logger.warn(\n                                'Target directory %s already exists. Specify '\n                                '--upgrade to force replacement.'\n                                % target_item_dir\n                            )\n                            continue\n                        if os.path.islink(target_item_dir):\n                            logger.warn(\n                                'Target directory %s already exists and is '\n                                'a link. Pip will not automatically replace '\n                                'links, please remove if replacement is '\n                                'desired.'\n                                % target_item_dir\n                            )\n                            continue\n                        if os.path.isdir(target_item_dir):\n                            shutil.rmtree(target_item_dir)\n                        else:\n                            os.remove(target_item_dir)\n\n                    shutil.move(\n                        os.path.join(lib_dir, item),\n                        target_item_dir\n                    )\n                shutil.rmtree(temp_target_dir)\n            return requirement_set\n", "path": "pip/commands/install.py"}]}