We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Indexes with password are not redacted when using --no-index --verbose

```
$ pip -V
pip 18.1 from /home/xfernandez/.virtualenvs/tmp-13c0d8450eb8175/lib/python3.7/site-packages/pip (python 3.7)
$ pip install mccabe --no-index -v
Ignoring indexes: https://user:supers3cret@pypi.example.com/root/ci/+simple/
Created temporary directory: /tmp/pip-ephem-wheel-cache-lcf7j0sa
Created temporary directory: /tmp/pip-req-tracker-mqzoa99d
Created requirements tracker '/tmp/pip-req-tracker-mqzoa99d'
Created temporary directory: /tmp/pip-install-_ecz3ykx
Requirement already satisfied: mccabe in ./lib/python3.7/site-packages (0.6.1)
Cleaning up...
Removed build tracker '/tmp/pip-req-tracker-mqzoa99d'
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/pip/_internal/cli/base_command.py`
Content:
```
1 """Base Command class, and related routines"""
2 from __future__ import absolute_import
3 
4 import logging
5 import logging.config
6 import optparse
7 import os
8 import sys
9 
10 from pip._internal.cli import cmdoptions
11 from pip._internal.cli.parser import (
12     ConfigOptionParser, UpdatingDefaultsHelpFormatter,
13 )
14 from pip._internal.cli.status_codes import (
15     ERROR, PREVIOUS_BUILD_DIR_ERROR, SUCCESS, UNKNOWN_ERROR,
16     VIRTUALENV_NOT_FOUND,
17 )
18 from pip._internal.download import PipSession
19 from pip._internal.exceptions import (
20     BadCommand, CommandError, InstallationError, PreviousBuildDirError,
21     UninstallationError,
22 )
23 from pip._internal.index import PackageFinder
24 from pip._internal.locations import running_under_virtualenv
25 from pip._internal.req.constructors import (
26     install_req_from_editable, install_req_from_line,
27 )
28 from pip._internal.req.req_file import parse_requirements
29 from pip._internal.utils.logging import setup_logging
30 from pip._internal.utils.misc import get_prog, normalize_path
31 from pip._internal.utils.outdated import pip_version_check
32 from pip._internal.utils.typing import MYPY_CHECK_RUNNING
33 
34 if MYPY_CHECK_RUNNING:
35     from typing import Optional, List, Tuple, Any  # noqa: F401
36     from optparse import Values  # noqa: F401
37     from pip._internal.cache import WheelCache  # noqa: F401
38     from pip._internal.req.req_set import RequirementSet  # noqa: F401
39 
40 __all__ = ['Command']
41 
42 logger = logging.getLogger(__name__)
43 
44 
45 class Command(object):
46     name = None  # type: Optional[str]
47     usage = None  # type: Optional[str]
48     hidden = False  # type: bool
49     ignore_require_venv = False  # type: bool
50 
51     def __init__(self, isolated=False):
52         # type: (bool) -> None
53         parser_kw = {
54             'usage': self.usage,
55             'prog': '%s %s' % (get_prog(), self.name),
56             'formatter': UpdatingDefaultsHelpFormatter(),
57             'add_help_option': False,
58             'name': self.name,
59             'description': self.__doc__,
60             'isolated': isolated,
61         }
62 
63         self.parser = ConfigOptionParser(**parser_kw)
64 
65         # Commands should add options to this option group
66         optgroup_name = '%s Options' % self.name.capitalize()
67         self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
68 
69         # Add the general options
70         gen_opts = cmdoptions.make_option_group(
71             cmdoptions.general_group,
72             self.parser,
73         )
74         self.parser.add_option_group(gen_opts)
75 
76     def run(self, options, args):
77         # type: (Values, List[Any]) -> Any
78         raise NotImplementedError
79 
80     def _build_session(self, options, retries=None, timeout=None):
81         # type: (Values, Optional[int], Optional[int]) -> PipSession
82         session = PipSession(
83             cache=(
84                 normalize_path(os.path.join(options.cache_dir, "http"))
85                 if options.cache_dir else None
86             ),
87             retries=retries if retries is not None else options.retries,
88             insecure_hosts=options.trusted_hosts,
89         )
90 
91         # Handle custom ca-bundles from the user
92         if options.cert:
93             session.verify = options.cert
94 
95         # Handle SSL client certificate
96         if options.client_cert:
97             session.cert = options.client_cert
98 
99         # Handle timeouts
100         if options.timeout or timeout:
101             session.timeout = (
102                 timeout if timeout is not None else options.timeout
103             )
104 
105         # Handle configured proxies
106         if options.proxy:
107             session.proxies = {
108                 "http": options.proxy,
109                 "https": options.proxy,
110             }
111 
112         # Determine if we can prompt the user for authentication or not
113         session.auth.prompting = not options.no_input
114 
115         return session
116 
117     def parse_args(self, args):
118         # type: (List[str]) -> Tuple
119         # factored out for testability
120         return self.parser.parse_args(args)
121 
122     def main(self, args):
123         # type: (List[str]) -> int
124         options, args = self.parse_args(args)
125 
126         # Set verbosity so that it can be used elsewhere.
127         self.verbosity = options.verbose - options.quiet
128 
129         setup_logging(
130             verbosity=self.verbosity,
131             no_color=options.no_color,
132             user_log_file=options.log,
133         )
134 
135         # TODO: Try to get these passing down from the command?
136         #       without resorting to os.environ to hold these.
137         #       This also affects isolated builds and it should.
138 
139         if options.no_input:
140             os.environ['PIP_NO_INPUT'] = '1'
141 
142         if options.exists_action:
143             os.environ['PIP_EXISTS_ACTION'] = ' '.join(options.exists_action)
144 
145         if options.require_venv and not self.ignore_require_venv:
146             # If a venv is required check if it can really be found
147             if not running_under_virtualenv():
148                 logger.critical(
149                     'Could not find an activated virtualenv (required).'
150                 )
151                 sys.exit(VIRTUALENV_NOT_FOUND)
152 
153         try:
154             status = self.run(options, args)
155             # FIXME: all commands should return an exit status
156             # and when it is done, isinstance is not needed anymore
157             if isinstance(status, int):
158                 return status
159         except PreviousBuildDirError as exc:
160             logger.critical(str(exc))
161             logger.debug('Exception information:', exc_info=True)
162 
163             return PREVIOUS_BUILD_DIR_ERROR
164         except (InstallationError, UninstallationError, BadCommand) as exc:
165             logger.critical(str(exc))
166             logger.debug('Exception information:', exc_info=True)
167 
168             return ERROR
169         except CommandError as exc:
170             logger.critical('ERROR: %s', exc)
171             logger.debug('Exception information:', exc_info=True)
172 
173             return ERROR
174         except KeyboardInterrupt:
175             logger.critical('Operation cancelled by user')
176             logger.debug('Exception information:', exc_info=True)
177 
178             return ERROR
179         except BaseException:
180             logger.critical('Exception:', exc_info=True)
181 
182             return UNKNOWN_ERROR
183         finally:
184             allow_version_check = (
185                 # Does this command have the index_group options?
186                 hasattr(options, "no_index") and
187                 # Is this command allowed to perform this check?
188                 not (options.disable_pip_version_check or options.no_index)
189             )
190             # Check if we're using the latest version of pip available
191             if allow_version_check:
192                 session = self._build_session(
193                     options,
194                     retries=0,
195                     timeout=min(5, options.timeout)
196                 )
197                 with session:
198                     pip_version_check(session, options)
199 
200             # Shutdown the logging module
201             logging.shutdown()
202 
203         return SUCCESS
204 
205 
206 class RequirementCommand(Command):
207 
208     @staticmethod
209     def populate_requirement_set(requirement_set,  # type: RequirementSet
210                                  args,             # type: List[str]
211                                  options,          # type: Values
212                                  finder,           # type: PackageFinder
213                                  session,          # type: PipSession
214                                  name,             # type: str
215                                  wheel_cache       # type: Optional[WheelCache]
216                                  ):
217         # type: (...) -> None
218         """
219         Marshal cmd line args into a requirement set.
220         """
221         # NOTE: As a side-effect, options.require_hashes and
222         #       requirement_set.require_hashes may be updated
223 
224         for filename in options.constraints:
225             for req_to_add in parse_requirements(
226                     filename,
227                     constraint=True, finder=finder, options=options,
228                     session=session, wheel_cache=wheel_cache):
229                 req_to_add.is_direct = True
230                 requirement_set.add_requirement(req_to_add)
231 
232         for req in args:
233             req_to_add = install_req_from_line(
234                 req, None, isolated=options.isolated_mode,
235                 use_pep517=options.use_pep517,
236                 wheel_cache=wheel_cache
237             )
238             req_to_add.is_direct = True
239             requirement_set.add_requirement(req_to_add)
240 
241         for req in options.editables:
242             req_to_add = install_req_from_editable(
243                 req,
244                 isolated=options.isolated_mode,
245                 use_pep517=options.use_pep517,
246                 wheel_cache=wheel_cache
247             )
248             req_to_add.is_direct = True
249             requirement_set.add_requirement(req_to_add)
250 
251         for filename in options.requirements:
252             for req_to_add in parse_requirements(
253                     filename,
254                     finder=finder, options=options, session=session,
255                     wheel_cache=wheel_cache,
256                     use_pep517=options.use_pep517):
257                 req_to_add.is_direct = True
258                 requirement_set.add_requirement(req_to_add)
259         # If --require-hashes was a line in a requirements file, tell
260         # RequirementSet about it:
261         requirement_set.require_hashes = options.require_hashes
262 
263         if not (args or options.editables or options.requirements):
264             opts = {'name': name}
265             if options.find_links:
266                 raise CommandError(
267                     'You must give at least one requirement to %(name)s '
268                     '(maybe you meant "pip %(name)s %(links)s"?)' %
269                     dict(opts, links=' '.join(options.find_links)))
270             else:
271                 raise CommandError(
272                     'You must give at least one requirement to %(name)s '
273                     '(see "pip help %(name)s")' % opts)
274 
275     def _build_package_finder(
276         self,
277         options,               # type: Values
278         session,               # type: PipSession
279         platform=None,         # type: Optional[str]
280         python_versions=None,  # type: Optional[List[str]]
281         abi=None,              # type: Optional[str]
282         implementation=None    # type: Optional[str]
283     ):
284         # type: (...) -> PackageFinder
285         """
286         Create a package finder appropriate to this requirement command.
287         """
288         index_urls = [options.index_url] + options.extra_index_urls
289         if options.no_index:
290             logger.debug('Ignoring indexes: %s', ','.join(index_urls))
291             index_urls = []
292 
293         return PackageFinder(
294             find_links=options.find_links,
295             format_control=options.format_control,
296             index_urls=index_urls,
297             trusted_hosts=options.trusted_hosts,
298             allow_all_prereleases=options.pre,
299             session=session,
300             platform=platform,
301             versions=python_versions,
302             abi=abi,
303             implementation=implementation,
304             prefer_binary=options.prefer_binary,
305         )
306
```
--- 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/src/pip/_internal/cli/base_command.py b/src/pip/_internal/cli/base_command.py
--- a/src/pip/_internal/cli/base_command.py
+++ b/src/pip/_internal/cli/base_command.py
@@ -27,7 +27,9 @@
 )
 from pip._internal.req.req_file import parse_requirements
 from pip._internal.utils.logging import setup_logging
-from pip._internal.utils.misc import get_prog, normalize_path
+from pip._internal.utils.misc import (
+    get_prog, normalize_path, redact_password_from_url,
+)
 from pip._internal.utils.outdated import pip_version_check
 from pip._internal.utils.typing import MYPY_CHECK_RUNNING
 
@@ -287,7 +289,10 @@
         """
         index_urls = [options.index_url] + options.extra_index_urls
         if options.no_index:
-            logger.debug('Ignoring indexes: %s', ','.join(index_urls))
+            logger.debug(
+                'Ignoring indexes: %s',
+                ','.join(redact_password_from_url(url) for url in index_urls),
+            )
             index_urls = []
 
         return PackageFinder(

{"golden_diff": "diff --git a/src/pip/_internal/cli/base_command.py b/src/pip/_internal/cli/base_command.py\n--- a/src/pip/_internal/cli/base_command.py\n+++ b/src/pip/_internal/cli/base_command.py\n@@ -27,7 +27,9 @@\n )\n from pip._internal.req.req_file import parse_requirements\n from pip._internal.utils.logging import setup_logging\n-from pip._internal.utils.misc import get_prog, normalize_path\n+from pip._internal.utils.misc import (\n+    get_prog, normalize_path, redact_password_from_url,\n+)\n from pip._internal.utils.outdated import pip_version_check\n from pip._internal.utils.typing import MYPY_CHECK_RUNNING\n \n@@ -287,7 +289,10 @@\n         \"\"\"\n         index_urls = [options.index_url] + options.extra_index_urls\n         if options.no_index:\n-            logger.debug('Ignoring indexes: %s', ','.join(index_urls))\n+            logger.debug(\n+                'Ignoring indexes: %s',\n+                ','.join(redact_password_from_url(url) for url in index_urls),\n+            )\n             index_urls = []\n \n         return PackageFinder(\n", "issue": "Indexes with password are not redacted when using --no-index --verbose\n\r\n```\r\n$ pip -V\r\npip 18.1 from /home/xfernandez/.virtualenvs/tmp-13c0d8450eb8175/lib/python3.7/site-packages/pip (python 3.7)\r\n$ pip install mccabe --no-index -v\r\nIgnoring indexes: https://user:supers3cret@pypi.example.com/root/ci/+simple/\r\nCreated temporary directory: /tmp/pip-ephem-wheel-cache-lcf7j0sa\r\nCreated temporary directory: /tmp/pip-req-tracker-mqzoa99d\r\nCreated requirements tracker '/tmp/pip-req-tracker-mqzoa99d'\r\nCreated temporary directory: /tmp/pip-install-_ecz3ykx\r\nRequirement already satisfied: mccabe in ./lib/python3.7/site-packages (0.6.1)\r\nCleaning up...\r\nRemoved build tracker '/tmp/pip-req-tracker-mqzoa99d'\r\n```\r\n\n", "before_files": [{"content": "\"\"\"Base Command class, and related routines\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nimport logging.config\nimport optparse\nimport os\nimport sys\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.parser import (\n    ConfigOptionParser, UpdatingDefaultsHelpFormatter,\n)\nfrom pip._internal.cli.status_codes import (\n    ERROR, PREVIOUS_BUILD_DIR_ERROR, SUCCESS, UNKNOWN_ERROR,\n    VIRTUALENV_NOT_FOUND,\n)\nfrom pip._internal.download import PipSession\nfrom pip._internal.exceptions import (\n    BadCommand, CommandError, InstallationError, PreviousBuildDirError,\n    UninstallationError,\n)\nfrom pip._internal.index import PackageFinder\nfrom pip._internal.locations import running_under_virtualenv\nfrom pip._internal.req.constructors import (\n    install_req_from_editable, install_req_from_line,\n)\nfrom pip._internal.req.req_file import parse_requirements\nfrom pip._internal.utils.logging import setup_logging\nfrom pip._internal.utils.misc import get_prog, normalize_path\nfrom pip._internal.utils.outdated import pip_version_check\nfrom pip._internal.utils.typing import MYPY_CHECK_RUNNING\n\nif MYPY_CHECK_RUNNING:\n    from typing import Optional, List, Tuple, Any  # noqa: F401\n    from optparse import Values  # noqa: F401\n    from pip._internal.cache import WheelCache  # noqa: F401\n    from pip._internal.req.req_set import RequirementSet  # noqa: F401\n\n__all__ = ['Command']\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(object):\n    name = None  # type: Optional[str]\n    usage = None  # type: Optional[str]\n    hidden = False  # type: bool\n    ignore_require_venv = False  # type: bool\n\n    def __init__(self, isolated=False):\n        # type: (bool) -> None\n        parser_kw = {\n            'usage': self.usage,\n            'prog': '%s %s' % (get_prog(), self.name),\n            'formatter': UpdatingDefaultsHelpFormatter(),\n            'add_help_option': False,\n            'name': self.name,\n            'description': self.__doc__,\n            'isolated': isolated,\n        }\n\n        self.parser = ConfigOptionParser(**parser_kw)\n\n        # Commands should add options to this option group\n        optgroup_name = '%s Options' % self.name.capitalize()\n        self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)\n\n        # Add the general options\n        gen_opts = cmdoptions.make_option_group(\n            cmdoptions.general_group,\n            self.parser,\n        )\n        self.parser.add_option_group(gen_opts)\n\n    def run(self, options, args):\n        # type: (Values, List[Any]) -> Any\n        raise NotImplementedError\n\n    def _build_session(self, options, retries=None, timeout=None):\n        # type: (Values, Optional[int], Optional[int]) -> PipSession\n        session = PipSession(\n            cache=(\n                normalize_path(os.path.join(options.cache_dir, \"http\"))\n                if options.cache_dir else None\n            ),\n            retries=retries if retries is not None else options.retries,\n            insecure_hosts=options.trusted_hosts,\n        )\n\n        # Handle custom ca-bundles from the user\n        if options.cert:\n            session.verify = options.cert\n\n        # Handle SSL client certificate\n        if options.client_cert:\n            session.cert = options.client_cert\n\n        # Handle timeouts\n        if options.timeout or timeout:\n            session.timeout = (\n                timeout if timeout is not None else options.timeout\n            )\n\n        # Handle configured proxies\n        if options.proxy:\n            session.proxies = {\n                \"http\": options.proxy,\n                \"https\": options.proxy,\n            }\n\n        # Determine if we can prompt the user for authentication or not\n        session.auth.prompting = not options.no_input\n\n        return session\n\n    def parse_args(self, args):\n        # type: (List[str]) -> Tuple\n        # factored out for testability\n        return self.parser.parse_args(args)\n\n    def main(self, args):\n        # type: (List[str]) -> int\n        options, args = self.parse_args(args)\n\n        # Set verbosity so that it can be used elsewhere.\n        self.verbosity = options.verbose - options.quiet\n\n        setup_logging(\n            verbosity=self.verbosity,\n            no_color=options.no_color,\n            user_log_file=options.log,\n        )\n\n        # TODO: Try to get these passing down from the command?\n        #       without resorting to os.environ to hold these.\n        #       This also affects isolated builds and it should.\n\n        if options.no_input:\n            os.environ['PIP_NO_INPUT'] = '1'\n\n        if options.exists_action:\n            os.environ['PIP_EXISTS_ACTION'] = ' '.join(options.exists_action)\n\n        if options.require_venv and not self.ignore_require_venv:\n            # If a venv is required check if it can really be found\n            if not running_under_virtualenv():\n                logger.critical(\n                    'Could not find an activated virtualenv (required).'\n                )\n                sys.exit(VIRTUALENV_NOT_FOUND)\n\n        try:\n            status = self.run(options, args)\n            # FIXME: all commands should return an exit status\n            # and when it is done, isinstance is not needed anymore\n            if isinstance(status, int):\n                return status\n        except PreviousBuildDirError as exc:\n            logger.critical(str(exc))\n            logger.debug('Exception information:', exc_info=True)\n\n            return PREVIOUS_BUILD_DIR_ERROR\n        except (InstallationError, UninstallationError, BadCommand) as exc:\n            logger.critical(str(exc))\n            logger.debug('Exception information:', exc_info=True)\n\n            return ERROR\n        except CommandError as exc:\n            logger.critical('ERROR: %s', exc)\n            logger.debug('Exception information:', exc_info=True)\n\n            return ERROR\n        except KeyboardInterrupt:\n            logger.critical('Operation cancelled by user')\n            logger.debug('Exception information:', exc_info=True)\n\n            return ERROR\n        except BaseException:\n            logger.critical('Exception:', exc_info=True)\n\n            return UNKNOWN_ERROR\n        finally:\n            allow_version_check = (\n                # Does this command have the index_group options?\n                hasattr(options, \"no_index\") and\n                # Is this command allowed to perform this check?\n                not (options.disable_pip_version_check or options.no_index)\n            )\n            # Check if we're using the latest version of pip available\n            if allow_version_check:\n                session = self._build_session(\n                    options,\n                    retries=0,\n                    timeout=min(5, options.timeout)\n                )\n                with session:\n                    pip_version_check(session, options)\n\n            # Shutdown the logging module\n            logging.shutdown()\n\n        return SUCCESS\n\n\nclass RequirementCommand(Command):\n\n    @staticmethod\n    def populate_requirement_set(requirement_set,  # type: RequirementSet\n                                 args,             # type: List[str]\n                                 options,          # type: Values\n                                 finder,           # type: PackageFinder\n                                 session,          # type: PipSession\n                                 name,             # type: str\n                                 wheel_cache       # type: Optional[WheelCache]\n                                 ):\n        # type: (...) -> None\n        \"\"\"\n        Marshal cmd line args into a requirement set.\n        \"\"\"\n        # NOTE: As a side-effect, options.require_hashes and\n        #       requirement_set.require_hashes may be updated\n\n        for filename in options.constraints:\n            for req_to_add in parse_requirements(\n                    filename,\n                    constraint=True, finder=finder, options=options,\n                    session=session, wheel_cache=wheel_cache):\n                req_to_add.is_direct = True\n                requirement_set.add_requirement(req_to_add)\n\n        for req in args:\n            req_to_add = install_req_from_line(\n                req, None, isolated=options.isolated_mode,\n                use_pep517=options.use_pep517,\n                wheel_cache=wheel_cache\n            )\n            req_to_add.is_direct = True\n            requirement_set.add_requirement(req_to_add)\n\n        for req in options.editables:\n            req_to_add = install_req_from_editable(\n                req,\n                isolated=options.isolated_mode,\n                use_pep517=options.use_pep517,\n                wheel_cache=wheel_cache\n            )\n            req_to_add.is_direct = True\n            requirement_set.add_requirement(req_to_add)\n\n        for filename in options.requirements:\n            for req_to_add in parse_requirements(\n                    filename,\n                    finder=finder, options=options, session=session,\n                    wheel_cache=wheel_cache,\n                    use_pep517=options.use_pep517):\n                req_to_add.is_direct = True\n                requirement_set.add_requirement(req_to_add)\n        # If --require-hashes was a line in a requirements file, tell\n        # RequirementSet about it:\n        requirement_set.require_hashes = options.require_hashes\n\n        if not (args or options.editables or options.requirements):\n            opts = {'name': name}\n            if options.find_links:\n                raise CommandError(\n                    '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                raise CommandError(\n                    'You must give at least one requirement to %(name)s '\n                    '(see \"pip help %(name)s\")' % opts)\n\n    def _build_package_finder(\n        self,\n        options,               # type: Values\n        session,               # type: PipSession\n        platform=None,         # type: Optional[str]\n        python_versions=None,  # type: Optional[List[str]]\n        abi=None,              # type: Optional[str]\n        implementation=None    # type: Optional[str]\n    ):\n        # type: (...) -> PackageFinder\n        \"\"\"\n        Create a package finder appropriate to this requirement command.\n        \"\"\"\n        index_urls = [options.index_url] + options.extra_index_urls\n        if options.no_index:\n            logger.debug('Ignoring indexes: %s', ','.join(index_urls))\n            index_urls = []\n\n        return PackageFinder(\n            find_links=options.find_links,\n            format_control=options.format_control,\n            index_urls=index_urls,\n            trusted_hosts=options.trusted_hosts,\n            allow_all_prereleases=options.pre,\n            session=session,\n            platform=platform,\n            versions=python_versions,\n            abi=abi,\n            implementation=implementation,\n            prefer_binary=options.prefer_binary,\n        )\n", "path": "src/pip/_internal/cli/base_command.py"}], "after_files": [{"content": "\"\"\"Base Command class, and related routines\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nimport logging.config\nimport optparse\nimport os\nimport sys\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.parser import (\n    ConfigOptionParser, UpdatingDefaultsHelpFormatter,\n)\nfrom pip._internal.cli.status_codes import (\n    ERROR, PREVIOUS_BUILD_DIR_ERROR, SUCCESS, UNKNOWN_ERROR,\n    VIRTUALENV_NOT_FOUND,\n)\nfrom pip._internal.download import PipSession\nfrom pip._internal.exceptions import (\n    BadCommand, CommandError, InstallationError, PreviousBuildDirError,\n    UninstallationError,\n)\nfrom pip._internal.index import PackageFinder\nfrom pip._internal.locations import running_under_virtualenv\nfrom pip._internal.req.constructors import (\n    install_req_from_editable, install_req_from_line,\n)\nfrom pip._internal.req.req_file import parse_requirements\nfrom pip._internal.utils.logging import setup_logging\nfrom pip._internal.utils.misc import (\n    get_prog, normalize_path, redact_password_from_url,\n)\nfrom pip._internal.utils.outdated import pip_version_check\nfrom pip._internal.utils.typing import MYPY_CHECK_RUNNING\n\nif MYPY_CHECK_RUNNING:\n    from typing import Optional, List, Tuple, Any  # noqa: F401\n    from optparse import Values  # noqa: F401\n    from pip._internal.cache import WheelCache  # noqa: F401\n    from pip._internal.req.req_set import RequirementSet  # noqa: F401\n\n__all__ = ['Command']\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(object):\n    name = None  # type: Optional[str]\n    usage = None  # type: Optional[str]\n    hidden = False  # type: bool\n    ignore_require_venv = False  # type: bool\n\n    def __init__(self, isolated=False):\n        # type: (bool) -> None\n        parser_kw = {\n            'usage': self.usage,\n            'prog': '%s %s' % (get_prog(), self.name),\n            'formatter': UpdatingDefaultsHelpFormatter(),\n            'add_help_option': False,\n            'name': self.name,\n            'description': self.__doc__,\n            'isolated': isolated,\n        }\n\n        self.parser = ConfigOptionParser(**parser_kw)\n\n        # Commands should add options to this option group\n        optgroup_name = '%s Options' % self.name.capitalize()\n        self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)\n\n        # Add the general options\n        gen_opts = cmdoptions.make_option_group(\n            cmdoptions.general_group,\n            self.parser,\n        )\n        self.parser.add_option_group(gen_opts)\n\n    def run(self, options, args):\n        # type: (Values, List[Any]) -> Any\n        raise NotImplementedError\n\n    def _build_session(self, options, retries=None, timeout=None):\n        # type: (Values, Optional[int], Optional[int]) -> PipSession\n        session = PipSession(\n            cache=(\n                normalize_path(os.path.join(options.cache_dir, \"http\"))\n                if options.cache_dir else None\n            ),\n            retries=retries if retries is not None else options.retries,\n            insecure_hosts=options.trusted_hosts,\n        )\n\n        # Handle custom ca-bundles from the user\n        if options.cert:\n            session.verify = options.cert\n\n        # Handle SSL client certificate\n        if options.client_cert:\n            session.cert = options.client_cert\n\n        # Handle timeouts\n        if options.timeout or timeout:\n            session.timeout = (\n                timeout if timeout is not None else options.timeout\n            )\n\n        # Handle configured proxies\n        if options.proxy:\n            session.proxies = {\n                \"http\": options.proxy,\n                \"https\": options.proxy,\n            }\n\n        # Determine if we can prompt the user for authentication or not\n        session.auth.prompting = not options.no_input\n\n        return session\n\n    def parse_args(self, args):\n        # type: (List[str]) -> Tuple\n        # factored out for testability\n        return self.parser.parse_args(args)\n\n    def main(self, args):\n        # type: (List[str]) -> int\n        options, args = self.parse_args(args)\n\n        # Set verbosity so that it can be used elsewhere.\n        self.verbosity = options.verbose - options.quiet\n\n        setup_logging(\n            verbosity=self.verbosity,\n            no_color=options.no_color,\n            user_log_file=options.log,\n        )\n\n        # TODO: Try to get these passing down from the command?\n        #       without resorting to os.environ to hold these.\n        #       This also affects isolated builds and it should.\n\n        if options.no_input:\n            os.environ['PIP_NO_INPUT'] = '1'\n\n        if options.exists_action:\n            os.environ['PIP_EXISTS_ACTION'] = ' '.join(options.exists_action)\n\n        if options.require_venv and not self.ignore_require_venv:\n            # If a venv is required check if it can really be found\n            if not running_under_virtualenv():\n                logger.critical(\n                    'Could not find an activated virtualenv (required).'\n                )\n                sys.exit(VIRTUALENV_NOT_FOUND)\n\n        try:\n            status = self.run(options, args)\n            # FIXME: all commands should return an exit status\n            # and when it is done, isinstance is not needed anymore\n            if isinstance(status, int):\n                return status\n        except PreviousBuildDirError as exc:\n            logger.critical(str(exc))\n            logger.debug('Exception information:', exc_info=True)\n\n            return PREVIOUS_BUILD_DIR_ERROR\n        except (InstallationError, UninstallationError, BadCommand) as exc:\n            logger.critical(str(exc))\n            logger.debug('Exception information:', exc_info=True)\n\n            return ERROR\n        except CommandError as exc:\n            logger.critical('ERROR: %s', exc)\n            logger.debug('Exception information:', exc_info=True)\n\n            return ERROR\n        except KeyboardInterrupt:\n            logger.critical('Operation cancelled by user')\n            logger.debug('Exception information:', exc_info=True)\n\n            return ERROR\n        except BaseException:\n            logger.critical('Exception:', exc_info=True)\n\n            return UNKNOWN_ERROR\n        finally:\n            allow_version_check = (\n                # Does this command have the index_group options?\n                hasattr(options, \"no_index\") and\n                # Is this command allowed to perform this check?\n                not (options.disable_pip_version_check or options.no_index)\n            )\n            # Check if we're using the latest version of pip available\n            if allow_version_check:\n                session = self._build_session(\n                    options,\n                    retries=0,\n                    timeout=min(5, options.timeout)\n                )\n                with session:\n                    pip_version_check(session, options)\n\n            # Shutdown the logging module\n            logging.shutdown()\n\n        return SUCCESS\n\n\nclass RequirementCommand(Command):\n\n    @staticmethod\n    def populate_requirement_set(requirement_set,  # type: RequirementSet\n                                 args,             # type: List[str]\n                                 options,          # type: Values\n                                 finder,           # type: PackageFinder\n                                 session,          # type: PipSession\n                                 name,             # type: str\n                                 wheel_cache       # type: Optional[WheelCache]\n                                 ):\n        # type: (...) -> None\n        \"\"\"\n        Marshal cmd line args into a requirement set.\n        \"\"\"\n        # NOTE: As a side-effect, options.require_hashes and\n        #       requirement_set.require_hashes may be updated\n\n        for filename in options.constraints:\n            for req_to_add in parse_requirements(\n                    filename,\n                    constraint=True, finder=finder, options=options,\n                    session=session, wheel_cache=wheel_cache):\n                req_to_add.is_direct = True\n                requirement_set.add_requirement(req_to_add)\n\n        for req in args:\n            req_to_add = install_req_from_line(\n                req, None, isolated=options.isolated_mode,\n                use_pep517=options.use_pep517,\n                wheel_cache=wheel_cache\n            )\n            req_to_add.is_direct = True\n            requirement_set.add_requirement(req_to_add)\n\n        for req in options.editables:\n            req_to_add = install_req_from_editable(\n                req,\n                isolated=options.isolated_mode,\n                use_pep517=options.use_pep517,\n                wheel_cache=wheel_cache\n            )\n            req_to_add.is_direct = True\n            requirement_set.add_requirement(req_to_add)\n\n        for filename in options.requirements:\n            for req_to_add in parse_requirements(\n                    filename,\n                    finder=finder, options=options, session=session,\n                    wheel_cache=wheel_cache,\n                    use_pep517=options.use_pep517):\n                req_to_add.is_direct = True\n                requirement_set.add_requirement(req_to_add)\n        # If --require-hashes was a line in a requirements file, tell\n        # RequirementSet about it:\n        requirement_set.require_hashes = options.require_hashes\n\n        if not (args or options.editables or options.requirements):\n            opts = {'name': name}\n            if options.find_links:\n                raise CommandError(\n                    '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                raise CommandError(\n                    'You must give at least one requirement to %(name)s '\n                    '(see \"pip help %(name)s\")' % opts)\n\n    def _build_package_finder(\n        self,\n        options,               # type: Values\n        session,               # type: PipSession\n        platform=None,         # type: Optional[str]\n        python_versions=None,  # type: Optional[List[str]]\n        abi=None,              # type: Optional[str]\n        implementation=None    # type: Optional[str]\n    ):\n        # type: (...) -> PackageFinder\n        \"\"\"\n        Create a package finder appropriate to this requirement command.\n        \"\"\"\n        index_urls = [options.index_url] + options.extra_index_urls\n        if options.no_index:\n            logger.debug(\n                'Ignoring indexes: %s',\n                ','.join(redact_password_from_url(url) for url in index_urls),\n            )\n            index_urls = []\n\n        return PackageFinder(\n            find_links=options.find_links,\n            format_control=options.format_control,\n            index_urls=index_urls,\n            trusted_hosts=options.trusted_hosts,\n            allow_all_prereleases=options.pre,\n            session=session,\n            platform=platform,\n            versions=python_versions,\n            abi=abi,\n            implementation=implementation,\n            prefer_binary=options.prefer_binary,\n        )\n", "path": "src/pip/_internal/cli/base_command.py"}]}