We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
pip --no-cache-dir still warns about a cache folder
If I use the `--no-cache-dir` option, I expect it to not even try to figure out any cache, but you can see that it still does, and suggest to use `sudo -H`

```
$ sudo pip --no-cache-dir --disable-pip-version-check search glop
The directory '/home/ubuntu/.cache/pip/log' or its parent directory is not owned by the current user and the debug log has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
glopen     - Open-like interface to globus remotes
glopy      - Python library wrapping Globus Toolkit credential library
```

Verbose:

```
$ sudo pip --verbose --no-cache-dir --disable-pip-version-check search glop
The directory '/home/ubuntu/.cache/pip/log' or its parent directory is not owned by the current user and the debug log has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Starting new HTTPS connection (1): pypi.python.org
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
"POST /pypi HTTP/1.1" 200 None
glopen     - Open-like interface to globus remotes
glopy      - Python library wrapping Globus Toolkit credential library
```

Version:

```
$ pip --version
pip 6.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
```


--- 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/basecommand.py`
Content:
```
1 """Base Command class, and related routines"""
2 from __future__ import absolute_import
3 
4 import logging
5 import os
6 import sys
7 import traceback
8 import optparse
9 import warnings
10 
11 from pip._vendor.six import StringIO
12 
13 from pip import cmdoptions
14 from pip.locations import running_under_virtualenv
15 from pip.download import PipSession
16 from pip.exceptions import (BadCommand, InstallationError, UninstallationError,
17                             CommandError, PreviousBuildDirError)
18 from pip.compat import logging_dictConfig
19 from pip.baseparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
20 from pip.req import InstallRequirement, parse_requirements
21 from pip.status_codes import (
22     SUCCESS, ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND,
23     PREVIOUS_BUILD_DIR_ERROR,
24 )
25 from pip.utils import appdirs, get_prog, normalize_path
26 from pip.utils.deprecation import RemovedInPip8Warning
27 from pip.utils.filesystem import check_path_owner
28 from pip.utils.logging import IndentingFormatter
29 from pip.utils.outdated import pip_version_check
30 
31 
32 __all__ = ['Command']
33 
34 
35 logger = logging.getLogger(__name__)
36 
37 
38 class Command(object):
39     name = None
40     usage = None
41     hidden = False
42     log_streams = ("ext://sys.stdout", "ext://sys.stderr")
43 
44     def __init__(self, isolated=False):
45         parser_kw = {
46             'usage': self.usage,
47             'prog': '%s %s' % (get_prog(), self.name),
48             'formatter': UpdatingDefaultsHelpFormatter(),
49             'add_help_option': False,
50             'name': self.name,
51             'description': self.__doc__,
52             'isolated': isolated,
53         }
54 
55         self.parser = ConfigOptionParser(**parser_kw)
56 
57         # Commands should add options to this option group
58         optgroup_name = '%s Options' % self.name.capitalize()
59         self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
60 
61         # Add the general options
62         gen_opts = cmdoptions.make_option_group(
63             cmdoptions.general_group,
64             self.parser,
65         )
66         self.parser.add_option_group(gen_opts)
67 
68     def _build_session(self, options, retries=None, timeout=None):
69         session = PipSession(
70             cache=(
71                 normalize_path(os.path.join(options.cache_dir, "http"))
72                 if options.cache_dir else None
73             ),
74             retries=retries if retries is not None else options.retries,
75             insecure_hosts=options.trusted_hosts,
76         )
77 
78         # Handle custom ca-bundles from the user
79         if options.cert:
80             session.verify = options.cert
81 
82         # Handle SSL client certificate
83         if options.client_cert:
84             session.cert = options.client_cert
85 
86         # Handle timeouts
87         if options.timeout or timeout:
88             session.timeout = (
89                 timeout if timeout is not None else options.timeout
90             )
91 
92         # Handle configured proxies
93         if options.proxy:
94             session.proxies = {
95                 "http": options.proxy,
96                 "https": options.proxy,
97             }
98 
99         # Determine if we can prompt the user for authentication or not
100         session.auth.prompting = not options.no_input
101 
102         return session
103 
104     def parse_args(self, args):
105         # factored out for testability
106         return self.parser.parse_args(args)
107 
108     def main(self, args):
109         options, args = self.parse_args(args)
110 
111         if options.quiet:
112             if options.quiet == 1:
113                 level = "WARNING"
114             if options.quiet == 2:
115                 level = "ERROR"
116             else:
117                 level = "CRITICAL"
118         elif options.verbose:
119             level = "DEBUG"
120         else:
121             level = "INFO"
122 
123         # Compute the path for our debug log.
124         debug_log_path = os.path.join(appdirs.user_log_dir("pip"), "debug.log")
125 
126         # Ensure that the path for our debug log is owned by the current user
127         # and if it is not, disable the debug log.
128         write_debug_log = check_path_owner(debug_log_path)
129 
130         logging_dictConfig({
131             "version": 1,
132             "disable_existing_loggers": False,
133             "filters": {
134                 "exclude_warnings": {
135                     "()": "pip.utils.logging.MaxLevelFilter",
136                     "level": logging.WARNING,
137                 },
138             },
139             "formatters": {
140                 "indent": {
141                     "()": IndentingFormatter,
142                     "format": (
143                         "%(message)s"
144                         if not options.log_explicit_levels
145                         else "[%(levelname)s] %(message)s"
146                     ),
147                 },
148             },
149             "handlers": {
150                 "console": {
151                     "level": level,
152                     "class": "pip.utils.logging.ColorizedStreamHandler",
153                     "stream": self.log_streams[0],
154                     "filters": ["exclude_warnings"],
155                     "formatter": "indent",
156                 },
157                 "console_errors": {
158                     "level": "WARNING",
159                     "class": "pip.utils.logging.ColorizedStreamHandler",
160                     "stream": self.log_streams[1],
161                     "formatter": "indent",
162                 },
163                 "debug_log": {
164                     "level": "DEBUG",
165                     "class": "pip.utils.logging.BetterRotatingFileHandler",
166                     "filename": debug_log_path,
167                     "maxBytes": 10 * 1000 * 1000,  # 10 MB
168                     "backupCount": 1,
169                     "delay": True,
170                     "formatter": "indent",
171                 },
172                 "user_log": {
173                     "level": "DEBUG",
174                     "class": "pip.utils.logging.BetterRotatingFileHandler",
175                     "filename": options.log or "/dev/null",
176                     "delay": True,
177                     "formatter": "indent",
178                 },
179             },
180             "root": {
181                 "level": level,
182                 "handlers": list(filter(None, [
183                     "console",
184                     "console_errors",
185                     "debug_log" if write_debug_log else None,
186                     "user_log" if options.log else None,
187                 ])),
188             },
189             # Disable any logging besides WARNING unless we have DEBUG level
190             # logging enabled. These use both pip._vendor and the bare names
191             # for the case where someone unbundles our libraries.
192             "loggers": dict(
193                 (
194                     name,
195                     {
196                         "level": (
197                             "WARNING"
198                             if level in ["INFO", "ERROR"]
199                             else "DEBUG"
200                         ),
201                     },
202                 )
203                 for name in ["pip._vendor", "distlib", "requests", "urllib3"]
204             ),
205         })
206 
207         # We add this warning here instead of up above, because the logger
208         # hasn't been configured until just now.
209         if not write_debug_log:
210             logger.warning(
211                 "The directory '%s' or its parent directory is not owned by "
212                 "the current user and the debug log has been disabled. Please "
213                 "check the permissions and owner of that directory. If "
214                 "executing pip with sudo, you may want sudo's -H flag.",
215                 os.path.dirname(debug_log_path),
216             )
217 
218         if options.log_explicit_levels:
219             warnings.warn(
220                 "--log-explicit-levels has been deprecated and will be removed"
221                 " in a future version.",
222                 RemovedInPip8Warning,
223             )
224 
225         # TODO: try to get these passing down from the command?
226         #      without resorting to os.environ to hold these.
227 
228         if options.no_input:
229             os.environ['PIP_NO_INPUT'] = '1'
230 
231         if options.exists_action:
232             os.environ['PIP_EXISTS_ACTION'] = ' '.join(options.exists_action)
233 
234         if options.require_venv:
235             # If a venv is required check if it can really be found
236             if not running_under_virtualenv():
237                 logger.critical(
238                     'Could not find an activated virtualenv (required).'
239                 )
240                 sys.exit(VIRTUALENV_NOT_FOUND)
241 
242         # Check if we're using the latest version of pip available
243         if (not options.disable_pip_version_check and not
244                 getattr(options, "no_index", False)):
245             with self._build_session(
246                     options,
247                     retries=0,
248                     timeout=min(5, options.timeout)) as session:
249                 pip_version_check(session)
250 
251         try:
252             status = self.run(options, args)
253             # FIXME: all commands should return an exit status
254             # and when it is done, isinstance is not needed anymore
255             if isinstance(status, int):
256                 return status
257         except PreviousBuildDirError as exc:
258             logger.critical(str(exc))
259             logger.debug('Exception information:\n%s', format_exc())
260 
261             return PREVIOUS_BUILD_DIR_ERROR
262         except (InstallationError, UninstallationError, BadCommand) as exc:
263             logger.critical(str(exc))
264             logger.debug('Exception information:\n%s', format_exc())
265 
266             return ERROR
267         except CommandError as exc:
268             logger.critical('ERROR: %s', exc)
269             logger.debug('Exception information:\n%s', format_exc())
270 
271             return ERROR
272         except KeyboardInterrupt:
273             logger.critical('Operation cancelled by user')
274             logger.debug('Exception information:\n%s', format_exc())
275 
276             return ERROR
277         except:
278             logger.critical('Exception:\n%s', format_exc())
279 
280             return UNKNOWN_ERROR
281 
282         return SUCCESS
283 
284 
285 class RequirementCommand(Command):
286 
287     @staticmethod
288     def populate_requirement_set(requirement_set, args, options, finder,
289                                  session, name, wheel_cache):
290         """
291         Marshal cmd line args into a requirement set.
292         """
293         for req in args:
294             requirement_set.add_requirement(
295                 InstallRequirement.from_line(
296                     req, None, isolated=options.isolated_mode,
297                     wheel_cache=wheel_cache
298                 )
299             )
300 
301         for req in options.editables:
302             requirement_set.add_requirement(
303                 InstallRequirement.from_editable(
304                     req,
305                     default_vcs=options.default_vcs,
306                     isolated=options.isolated_mode,
307                     wheel_cache=wheel_cache
308                 )
309             )
310 
311         found_req_in_file = False
312         for filename in options.requirements:
313             for req in parse_requirements(
314                     filename,
315                     finder=finder, options=options, session=session,
316                     wheel_cache=wheel_cache):
317                 found_req_in_file = True
318                 requirement_set.add_requirement(req)
319 
320         if not (args or options.editables or found_req_in_file):
321             opts = {'name': name}
322             if options.find_links:
323                 msg = ('You must give at least one requirement to '
324                        '%(name)s (maybe you meant "pip %(name)s '
325                        '%(links)s"?)' %
326                        dict(opts, links=' '.join(options.find_links)))
327             else:
328                 msg = ('You must give at least one requirement '
329                        'to %(name)s (see "pip help %(name)s")' % opts)
330             logger.warning(msg)
331 
332 
333 def format_exc(exc_info=None):
334     if exc_info is None:
335         exc_info = sys.exc_info()
336     out = StringIO()
337     traceback.print_exception(*exc_info, **dict(file=out))
338     return out.getvalue()
339
```
--- 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/basecommand.py b/pip/basecommand.py
--- a/pip/basecommand.py
+++ b/pip/basecommand.py
@@ -22,9 +22,8 @@
     SUCCESS, ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND,
     PREVIOUS_BUILD_DIR_ERROR,
 )
-from pip.utils import appdirs, get_prog, normalize_path
+from pip.utils import get_prog, normalize_path
 from pip.utils.deprecation import RemovedInPip8Warning
-from pip.utils.filesystem import check_path_owner
 from pip.utils.logging import IndentingFormatter
 from pip.utils.outdated import pip_version_check
 
@@ -120,13 +119,6 @@
         else:
             level = "INFO"
 
-        # Compute the path for our debug log.
-        debug_log_path = os.path.join(appdirs.user_log_dir("pip"), "debug.log")
-
-        # Ensure that the path for our debug log is owned by the current user
-        # and if it is not, disable the debug log.
-        write_debug_log = check_path_owner(debug_log_path)
-
         logging_dictConfig({
             "version": 1,
             "disable_existing_loggers": False,
@@ -160,15 +152,6 @@
                     "stream": self.log_streams[1],
                     "formatter": "indent",
                 },
-                "debug_log": {
-                    "level": "DEBUG",
-                    "class": "pip.utils.logging.BetterRotatingFileHandler",
-                    "filename": debug_log_path,
-                    "maxBytes": 10 * 1000 * 1000,  # 10 MB
-                    "backupCount": 1,
-                    "delay": True,
-                    "formatter": "indent",
-                },
                 "user_log": {
                     "level": "DEBUG",
                     "class": "pip.utils.logging.BetterRotatingFileHandler",
@@ -182,7 +165,6 @@
                 "handlers": list(filter(None, [
                     "console",
                     "console_errors",
-                    "debug_log" if write_debug_log else None,
                     "user_log" if options.log else None,
                 ])),
             },
@@ -204,17 +186,6 @@
             ),
         })
 
-        # We add this warning here instead of up above, because the logger
-        # hasn't been configured until just now.
-        if not write_debug_log:
-            logger.warning(
-                "The directory '%s' or its parent directory is not owned by "
-                "the current user and the debug log has been disabled. Please "
-                "check the permissions and owner of that directory. If "
-                "executing pip with sudo, you may want sudo's -H flag.",
-                os.path.dirname(debug_log_path),
-            )
-
         if options.log_explicit_levels:
             warnings.warn(
                 "--log-explicit-levels has been deprecated and will be removed"

{"golden_diff": "diff --git a/pip/basecommand.py b/pip/basecommand.py\n--- a/pip/basecommand.py\n+++ b/pip/basecommand.py\n@@ -22,9 +22,8 @@\n     SUCCESS, ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND,\n     PREVIOUS_BUILD_DIR_ERROR,\n )\n-from pip.utils import appdirs, get_prog, normalize_path\n+from pip.utils import get_prog, normalize_path\n from pip.utils.deprecation import RemovedInPip8Warning\n-from pip.utils.filesystem import check_path_owner\n from pip.utils.logging import IndentingFormatter\n from pip.utils.outdated import pip_version_check\n \n@@ -120,13 +119,6 @@\n         else:\n             level = \"INFO\"\n \n-        # Compute the path for our debug log.\n-        debug_log_path = os.path.join(appdirs.user_log_dir(\"pip\"), \"debug.log\")\n-\n-        # Ensure that the path for our debug log is owned by the current user\n-        # and if it is not, disable the debug log.\n-        write_debug_log = check_path_owner(debug_log_path)\n-\n         logging_dictConfig({\n             \"version\": 1,\n             \"disable_existing_loggers\": False,\n@@ -160,15 +152,6 @@\n                     \"stream\": self.log_streams[1],\n                     \"formatter\": \"indent\",\n                 },\n-                \"debug_log\": {\n-                    \"level\": \"DEBUG\",\n-                    \"class\": \"pip.utils.logging.BetterRotatingFileHandler\",\n-                    \"filename\": debug_log_path,\n-                    \"maxBytes\": 10 * 1000 * 1000,  # 10 MB\n-                    \"backupCount\": 1,\n-                    \"delay\": True,\n-                    \"formatter\": \"indent\",\n-                },\n                 \"user_log\": {\n                     \"level\": \"DEBUG\",\n                     \"class\": \"pip.utils.logging.BetterRotatingFileHandler\",\n@@ -182,7 +165,6 @@\n                 \"handlers\": list(filter(None, [\n                     \"console\",\n                     \"console_errors\",\n-                    \"debug_log\" if write_debug_log else None,\n                     \"user_log\" if options.log else None,\n                 ])),\n             },\n@@ -204,17 +186,6 @@\n             ),\n         })\n \n-        # We add this warning here instead of up above, because the logger\n-        # hasn't been configured until just now.\n-        if not write_debug_log:\n-            logger.warning(\n-                \"The directory '%s' or its parent directory is not owned by \"\n-                \"the current user and the debug log has been disabled. Please \"\n-                \"check the permissions and owner of that directory. If \"\n-                \"executing pip with sudo, you may want sudo's -H flag.\",\n-                os.path.dirname(debug_log_path),\n-            )\n-\n         if options.log_explicit_levels:\n             warnings.warn(\n                 \"--log-explicit-levels has been deprecated and will be removed\"\n", "issue": "pip --no-cache-dir still warns about a cache folder\nIf I use the `--no-cache-dir` option, I expect it to not even try to figure out any cache, but you can see that it still does, and suggest to use `sudo -H`\n\n```\n$ sudo pip --no-cache-dir --disable-pip-version-check search glop\nThe directory '/home/ubuntu/.cache/pip/log' or its parent directory is not owned by the current user and the debug log has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.\n/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.\n  InsecurePlatformWarning\nglopen     - Open-like interface to globus remotes\nglopy      - Python library wrapping Globus Toolkit credential library\n```\n\nVerbose:\n\n```\n$ sudo pip --verbose --no-cache-dir --disable-pip-version-check search glop\nThe directory '/home/ubuntu/.cache/pip/log' or its parent directory is not owned by the current user and the debug log has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.\nStarting new HTTPS connection (1): pypi.python.org\n/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.\n  InsecurePlatformWarning\n\"POST /pypi HTTP/1.1\" 200 None\nglopen     - Open-like interface to globus remotes\nglopy      - Python library wrapping Globus Toolkit credential library\n```\n\nVersion:\n\n```\n$ pip --version\npip 6.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)\n```\n\n", "before_files": [{"content": "\"\"\"Base Command class, and related routines\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nimport os\nimport sys\nimport traceback\nimport optparse\nimport warnings\n\nfrom pip._vendor.six import StringIO\n\nfrom pip import cmdoptions\nfrom pip.locations import running_under_virtualenv\nfrom pip.download import PipSession\nfrom pip.exceptions import (BadCommand, InstallationError, UninstallationError,\n                            CommandError, PreviousBuildDirError)\nfrom pip.compat import logging_dictConfig\nfrom pip.baseparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter\nfrom pip.req import InstallRequirement, parse_requirements\nfrom pip.status_codes import (\n    SUCCESS, ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND,\n    PREVIOUS_BUILD_DIR_ERROR,\n)\nfrom pip.utils import appdirs, get_prog, normalize_path\nfrom pip.utils.deprecation import RemovedInPip8Warning\nfrom pip.utils.filesystem import check_path_owner\nfrom pip.utils.logging import IndentingFormatter\nfrom pip.utils.outdated import pip_version_check\n\n\n__all__ = ['Command']\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(object):\n    name = None\n    usage = None\n    hidden = False\n    log_streams = (\"ext://sys.stdout\", \"ext://sys.stderr\")\n\n    def __init__(self, isolated=False):\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 _build_session(self, options, retries=None, timeout=None):\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        # factored out for testability\n        return self.parser.parse_args(args)\n\n    def main(self, args):\n        options, args = self.parse_args(args)\n\n        if options.quiet:\n            if options.quiet == 1:\n                level = \"WARNING\"\n            if options.quiet == 2:\n                level = \"ERROR\"\n            else:\n                level = \"CRITICAL\"\n        elif options.verbose:\n            level = \"DEBUG\"\n        else:\n            level = \"INFO\"\n\n        # Compute the path for our debug log.\n        debug_log_path = os.path.join(appdirs.user_log_dir(\"pip\"), \"debug.log\")\n\n        # Ensure that the path for our debug log is owned by the current user\n        # and if it is not, disable the debug log.\n        write_debug_log = check_path_owner(debug_log_path)\n\n        logging_dictConfig({\n            \"version\": 1,\n            \"disable_existing_loggers\": False,\n            \"filters\": {\n                \"exclude_warnings\": {\n                    \"()\": \"pip.utils.logging.MaxLevelFilter\",\n                    \"level\": logging.WARNING,\n                },\n            },\n            \"formatters\": {\n                \"indent\": {\n                    \"()\": IndentingFormatter,\n                    \"format\": (\n                        \"%(message)s\"\n                        if not options.log_explicit_levels\n                        else \"[%(levelname)s] %(message)s\"\n                    ),\n                },\n            },\n            \"handlers\": {\n                \"console\": {\n                    \"level\": level,\n                    \"class\": \"pip.utils.logging.ColorizedStreamHandler\",\n                    \"stream\": self.log_streams[0],\n                    \"filters\": [\"exclude_warnings\"],\n                    \"formatter\": \"indent\",\n                },\n                \"console_errors\": {\n                    \"level\": \"WARNING\",\n                    \"class\": \"pip.utils.logging.ColorizedStreamHandler\",\n                    \"stream\": self.log_streams[1],\n                    \"formatter\": \"indent\",\n                },\n                \"debug_log\": {\n                    \"level\": \"DEBUG\",\n                    \"class\": \"pip.utils.logging.BetterRotatingFileHandler\",\n                    \"filename\": debug_log_path,\n                    \"maxBytes\": 10 * 1000 * 1000,  # 10 MB\n                    \"backupCount\": 1,\n                    \"delay\": True,\n                    \"formatter\": \"indent\",\n                },\n                \"user_log\": {\n                    \"level\": \"DEBUG\",\n                    \"class\": \"pip.utils.logging.BetterRotatingFileHandler\",\n                    \"filename\": options.log or \"/dev/null\",\n                    \"delay\": True,\n                    \"formatter\": \"indent\",\n                },\n            },\n            \"root\": {\n                \"level\": level,\n                \"handlers\": list(filter(None, [\n                    \"console\",\n                    \"console_errors\",\n                    \"debug_log\" if write_debug_log else None,\n                    \"user_log\" if options.log else None,\n                ])),\n            },\n            # Disable any logging besides WARNING unless we have DEBUG level\n            # logging enabled. These use both pip._vendor and the bare names\n            # for the case where someone unbundles our libraries.\n            \"loggers\": dict(\n                (\n                    name,\n                    {\n                        \"level\": (\n                            \"WARNING\"\n                            if level in [\"INFO\", \"ERROR\"]\n                            else \"DEBUG\"\n                        ),\n                    },\n                )\n                for name in [\"pip._vendor\", \"distlib\", \"requests\", \"urllib3\"]\n            ),\n        })\n\n        # We add this warning here instead of up above, because the logger\n        # hasn't been configured until just now.\n        if not write_debug_log:\n            logger.warning(\n                \"The directory '%s' or its parent directory is not owned by \"\n                \"the current user and the debug log has been disabled. Please \"\n                \"check the permissions and owner of that directory. If \"\n                \"executing pip with sudo, you may want sudo's -H flag.\",\n                os.path.dirname(debug_log_path),\n            )\n\n        if options.log_explicit_levels:\n            warnings.warn(\n                \"--log-explicit-levels has been deprecated and will be removed\"\n                \" in a future version.\",\n                RemovedInPip8Warning,\n            )\n\n        # TODO: try to get these passing down from the command?\n        #      without resorting to os.environ to hold these.\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:\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        # Check if we're using the latest version of pip available\n        if (not options.disable_pip_version_check and not\n                getattr(options, \"no_index\", False)):\n            with self._build_session(\n                    options,\n                    retries=0,\n                    timeout=min(5, options.timeout)) as session:\n                pip_version_check(session)\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:\\n%s', format_exc())\n\n            return PREVIOUS_BUILD_DIR_ERROR\n        except (InstallationError, UninstallationError, BadCommand) as exc:\n            logger.critical(str(exc))\n            logger.debug('Exception information:\\n%s', format_exc())\n\n            return ERROR\n        except CommandError as exc:\n            logger.critical('ERROR: %s', exc)\n            logger.debug('Exception information:\\n%s', format_exc())\n\n            return ERROR\n        except KeyboardInterrupt:\n            logger.critical('Operation cancelled by user')\n            logger.debug('Exception information:\\n%s', format_exc())\n\n            return ERROR\n        except:\n            logger.critical('Exception:\\n%s', format_exc())\n\n            return UNKNOWN_ERROR\n\n        return SUCCESS\n\n\nclass RequirementCommand(Command):\n\n    @staticmethod\n    def populate_requirement_set(requirement_set, args, options, finder,\n                                 session, name, wheel_cache):\n        \"\"\"\n        Marshal cmd line args into a requirement set.\n        \"\"\"\n        for req in args:\n            requirement_set.add_requirement(\n                InstallRequirement.from_line(\n                    req, None, isolated=options.isolated_mode,\n                    wheel_cache=wheel_cache\n                )\n            )\n\n        for req in options.editables:\n            requirement_set.add_requirement(\n                InstallRequirement.from_editable(\n                    req,\n                    default_vcs=options.default_vcs,\n                    isolated=options.isolated_mode,\n                    wheel_cache=wheel_cache\n                )\n            )\n\n        found_req_in_file = False\n        for filename in options.requirements:\n            for req in parse_requirements(\n                    filename,\n                    finder=finder, options=options, session=session,\n                    wheel_cache=wheel_cache):\n                found_req_in_file = True\n                requirement_set.add_requirement(req)\n\n        if not (args or options.editables or found_req_in_file):\n            opts = {'name': name}\n            if options.find_links:\n                msg = ('You must give at least one requirement to '\n                       '%(name)s (maybe you meant \"pip %(name)s '\n                       '%(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.warning(msg)\n\n\ndef format_exc(exc_info=None):\n    if exc_info is None:\n        exc_info = sys.exc_info()\n    out = StringIO()\n    traceback.print_exception(*exc_info, **dict(file=out))\n    return out.getvalue()\n", "path": "pip/basecommand.py"}], "after_files": [{"content": "\"\"\"Base Command class, and related routines\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nimport os\nimport sys\nimport traceback\nimport optparse\nimport warnings\n\nfrom pip._vendor.six import StringIO\n\nfrom pip import cmdoptions\nfrom pip.locations import running_under_virtualenv\nfrom pip.download import PipSession\nfrom pip.exceptions import (BadCommand, InstallationError, UninstallationError,\n                            CommandError, PreviousBuildDirError)\nfrom pip.compat import logging_dictConfig\nfrom pip.baseparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter\nfrom pip.req import InstallRequirement, parse_requirements\nfrom pip.status_codes import (\n    SUCCESS, ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND,\n    PREVIOUS_BUILD_DIR_ERROR,\n)\nfrom pip.utils import get_prog, normalize_path\nfrom pip.utils.deprecation import RemovedInPip8Warning\nfrom pip.utils.logging import IndentingFormatter\nfrom pip.utils.outdated import pip_version_check\n\n\n__all__ = ['Command']\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(object):\n    name = None\n    usage = None\n    hidden = False\n    log_streams = (\"ext://sys.stdout\", \"ext://sys.stderr\")\n\n    def __init__(self, isolated=False):\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 _build_session(self, options, retries=None, timeout=None):\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        # factored out for testability\n        return self.parser.parse_args(args)\n\n    def main(self, args):\n        options, args = self.parse_args(args)\n\n        if options.quiet:\n            if options.quiet == 1:\n                level = \"WARNING\"\n            if options.quiet == 2:\n                level = \"ERROR\"\n            else:\n                level = \"CRITICAL\"\n        elif options.verbose:\n            level = \"DEBUG\"\n        else:\n            level = \"INFO\"\n\n        logging_dictConfig({\n            \"version\": 1,\n            \"disable_existing_loggers\": False,\n            \"filters\": {\n                \"exclude_warnings\": {\n                    \"()\": \"pip.utils.logging.MaxLevelFilter\",\n                    \"level\": logging.WARNING,\n                },\n            },\n            \"formatters\": {\n                \"indent\": {\n                    \"()\": IndentingFormatter,\n                    \"format\": (\n                        \"%(message)s\"\n                        if not options.log_explicit_levels\n                        else \"[%(levelname)s] %(message)s\"\n                    ),\n                },\n            },\n            \"handlers\": {\n                \"console\": {\n                    \"level\": level,\n                    \"class\": \"pip.utils.logging.ColorizedStreamHandler\",\n                    \"stream\": self.log_streams[0],\n                    \"filters\": [\"exclude_warnings\"],\n                    \"formatter\": \"indent\",\n                },\n                \"console_errors\": {\n                    \"level\": \"WARNING\",\n                    \"class\": \"pip.utils.logging.ColorizedStreamHandler\",\n                    \"stream\": self.log_streams[1],\n                    \"formatter\": \"indent\",\n                },\n                \"user_log\": {\n                    \"level\": \"DEBUG\",\n                    \"class\": \"pip.utils.logging.BetterRotatingFileHandler\",\n                    \"filename\": options.log or \"/dev/null\",\n                    \"delay\": True,\n                    \"formatter\": \"indent\",\n                },\n            },\n            \"root\": {\n                \"level\": level,\n                \"handlers\": list(filter(None, [\n                    \"console\",\n                    \"console_errors\",\n                    \"user_log\" if options.log else None,\n                ])),\n            },\n            # Disable any logging besides WARNING unless we have DEBUG level\n            # logging enabled. These use both pip._vendor and the bare names\n            # for the case where someone unbundles our libraries.\n            \"loggers\": dict(\n                (\n                    name,\n                    {\n                        \"level\": (\n                            \"WARNING\"\n                            if level in [\"INFO\", \"ERROR\"]\n                            else \"DEBUG\"\n                        ),\n                    },\n                )\n                for name in [\"pip._vendor\", \"distlib\", \"requests\", \"urllib3\"]\n            ),\n        })\n\n        if options.log_explicit_levels:\n            warnings.warn(\n                \"--log-explicit-levels has been deprecated and will be removed\"\n                \" in a future version.\",\n                RemovedInPip8Warning,\n            )\n\n        # TODO: try to get these passing down from the command?\n        #      without resorting to os.environ to hold these.\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:\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        # Check if we're using the latest version of pip available\n        if (not options.disable_pip_version_check and not\n                getattr(options, \"no_index\", False)):\n            with self._build_session(\n                    options,\n                    retries=0,\n                    timeout=min(5, options.timeout)) as session:\n                pip_version_check(session)\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:\\n%s', format_exc())\n\n            return PREVIOUS_BUILD_DIR_ERROR\n        except (InstallationError, UninstallationError, BadCommand) as exc:\n            logger.critical(str(exc))\n            logger.debug('Exception information:\\n%s', format_exc())\n\n            return ERROR\n        except CommandError as exc:\n            logger.critical('ERROR: %s', exc)\n            logger.debug('Exception information:\\n%s', format_exc())\n\n            return ERROR\n        except KeyboardInterrupt:\n            logger.critical('Operation cancelled by user')\n            logger.debug('Exception information:\\n%s', format_exc())\n\n            return ERROR\n        except:\n            logger.critical('Exception:\\n%s', format_exc())\n\n            return UNKNOWN_ERROR\n\n        return SUCCESS\n\n\nclass RequirementCommand(Command):\n\n    @staticmethod\n    def populate_requirement_set(requirement_set, args, options, finder,\n                                 session, name, wheel_cache):\n        \"\"\"\n        Marshal cmd line args into a requirement set.\n        \"\"\"\n        for req in args:\n            requirement_set.add_requirement(\n                InstallRequirement.from_line(\n                    req, None, isolated=options.isolated_mode,\n                    wheel_cache=wheel_cache\n                )\n            )\n\n        for req in options.editables:\n            requirement_set.add_requirement(\n                InstallRequirement.from_editable(\n                    req,\n                    default_vcs=options.default_vcs,\n                    isolated=options.isolated_mode,\n                    wheel_cache=wheel_cache\n                )\n            )\n\n        found_req_in_file = False\n        for filename in options.requirements:\n            for req in parse_requirements(\n                    filename,\n                    finder=finder, options=options, session=session,\n                    wheel_cache=wheel_cache):\n                found_req_in_file = True\n                requirement_set.add_requirement(req)\n\n        if not (args or options.editables or found_req_in_file):\n            opts = {'name': name}\n            if options.find_links:\n                msg = ('You must give at least one requirement to '\n                       '%(name)s (maybe you meant \"pip %(name)s '\n                       '%(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.warning(msg)\n\n\ndef format_exc(exc_info=None):\n    if exc_info is None:\n        exc_info = sys.exc_info()\n    out = StringIO()\n    traceback.print_exception(*exc_info, **dict(file=out))\n    return out.getvalue()\n", "path": "pip/basecommand.py"}]}