We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Emit a warning when pip is used on Python 2.6
Python 2.6 is unmaintained by the Python core team, we should encourage users to upgrade.

<!-- Reviewable:start -->

[<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/pypa/pip/3329)

<!-- Reviewable:end -->


--- 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/utils/deprecation.py`
Content:
```
1 """
2 A module that implments tooling to enable easy warnings about deprecations.
3 """
4 from __future__ import absolute_import
5 
6 import logging
7 import warnings
8 
9 
10 class PipDeprecationWarning(Warning):
11     pass
12 
13 
14 class RemovedInPip9Warning(PipDeprecationWarning, DeprecationWarning):
15     pass
16 
17 
18 class RemovedInPip10Warning(PipDeprecationWarning, PendingDeprecationWarning):
19     pass
20 
21 
22 DEPRECATIONS = [RemovedInPip9Warning, RemovedInPip10Warning]
23 
24 
25 # Warnings <-> Logging Integration
26 
27 
28 _warnings_showwarning = None
29 
30 
31 def _showwarning(message, category, filename, lineno, file=None, line=None):
32     if file is not None:
33         if _warnings_showwarning is not None:
34             _warnings_showwarning(
35                 message, category, filename, lineno, file, line,
36             )
37     else:
38         if issubclass(category, PipDeprecationWarning):
39             # We use a specially named logger which will handle all of the
40             # deprecation messages for pip.
41             logger = logging.getLogger("pip.deprecations")
42 
43             # This is purposely using the % formatter here instead of letting
44             # the logging module handle the interpolation. This is because we
45             # want it to appear as if someone typed this entire message out.
46             log_message = "DEPRECATION: %s" % message
47 
48             # Things that are DeprecationWarnings will be removed in the very
49             # next version of pip. We want these to be more obvious so we
50             # use the ERROR logging level while the PendingDeprecationWarnings
51             # are still have at least 2 versions to go until they are removed
52             # so they can just be warnings.
53             if issubclass(category, DeprecationWarning):
54                 logger.error(log_message)
55             else:
56                 logger.warning(log_message)
57         else:
58             _warnings_showwarning(
59                 message, category, filename, lineno, file, line,
60             )
61 
62 
63 def install_warning_logger():
64     global _warnings_showwarning
65 
66     if _warnings_showwarning is None:
67         _warnings_showwarning = warnings.showwarning
68         warnings.showwarning = _showwarning
69
```

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

{"golden_diff": "diff --git a/pip/basecommand.py b/pip/basecommand.py\n--- a/pip/basecommand.py\n+++ b/pip/basecommand.py\n@@ -5,6 +5,7 @@\n import os\n import sys\n import optparse\n+import warnings\n \n from pip import cmdoptions\n from pip.index import PackageFinder\n@@ -20,7 +21,7 @@\n     SUCCESS, ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND,\n     PREVIOUS_BUILD_DIR_ERROR,\n )\n-from pip.utils import get_prog, normalize_path\n+from pip.utils import deprecation, get_prog, normalize_path\n from pip.utils.logging import IndentingFormatter\n from pip.utils.outdated import pip_version_check\n \n@@ -179,6 +180,14 @@\n             ),\n         })\n \n+        if sys.version_info[:2] == (2, 6):\n+            warnings.warn(\n+                \"Python 2.6 is no longer supported by the Python core team, \"\n+                \"please upgrade your Python. A future version of pip will \"\n+                \"drop support for Python 2.6\",\n+                deprecation.Python26DeprecationWarning\n+            )\n+\n         # TODO: try to get these passing down from the command?\n         #      without resorting to os.environ to hold these.\n \ndiff --git a/pip/utils/deprecation.py b/pip/utils/deprecation.py\n--- a/pip/utils/deprecation.py\n+++ b/pip/utils/deprecation.py\n@@ -19,7 +19,15 @@\n     pass\n \n \n-DEPRECATIONS = [RemovedInPip9Warning, RemovedInPip10Warning]\n+class Python26DeprecationWarning(\n+    PipDeprecationWarning, PendingDeprecationWarning\n+):\n+    pass\n+\n+\n+DEPRECATIONS = [\n+    RemovedInPip9Warning, RemovedInPip10Warning, Python26DeprecationWarning\n+]\n \n \n # Warnings <-> Logging Integration\n", "issue": "Emit a warning when pip is used on Python 2.6\nPython 2.6 is unmaintained by the Python core team, we should encourage users to upgrade.\n\n<!-- Reviewable:start -->\n\n[<img src=\"https://reviewable.io/review_button.png\" height=40 alt=\"Review on Reviewable\"/>](https://reviewable.io/reviews/pypa/pip/3329)\n\n<!-- Reviewable:end -->\n\n", "before_files": [{"content": "\"\"\"\nA module that implments tooling to enable easy warnings about deprecations.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nimport warnings\n\n\nclass PipDeprecationWarning(Warning):\n    pass\n\n\nclass RemovedInPip9Warning(PipDeprecationWarning, DeprecationWarning):\n    pass\n\n\nclass RemovedInPip10Warning(PipDeprecationWarning, PendingDeprecationWarning):\n    pass\n\n\nDEPRECATIONS = [RemovedInPip9Warning, RemovedInPip10Warning]\n\n\n# Warnings <-> Logging Integration\n\n\n_warnings_showwarning = None\n\n\ndef _showwarning(message, category, filename, lineno, file=None, line=None):\n    if file is not None:\n        if _warnings_showwarning is not None:\n            _warnings_showwarning(\n                message, category, filename, lineno, file, line,\n            )\n    else:\n        if issubclass(category, PipDeprecationWarning):\n            # We use a specially named logger which will handle all of the\n            # deprecation messages for pip.\n            logger = logging.getLogger(\"pip.deprecations\")\n\n            # This is purposely using the % formatter here instead of letting\n            # the logging module handle the interpolation. This is because we\n            # want it to appear as if someone typed this entire message out.\n            log_message = \"DEPRECATION: %s\" % message\n\n            # Things that are DeprecationWarnings will be removed in the very\n            # next version of pip. We want these to be more obvious so we\n            # use the ERROR logging level while the PendingDeprecationWarnings\n            # are still have at least 2 versions to go until they are removed\n            # so they can just be warnings.\n            if issubclass(category, DeprecationWarning):\n                logger.error(log_message)\n            else:\n                logger.warning(log_message)\n        else:\n            _warnings_showwarning(\n                message, category, filename, lineno, file, line,\n            )\n\n\ndef install_warning_logger():\n    global _warnings_showwarning\n\n    if _warnings_showwarning is None:\n        _warnings_showwarning = warnings.showwarning\n        warnings.showwarning = _showwarning\n", "path": "pip/utils/deprecation.py"}, {"content": "\"\"\"Base Command class, and related routines\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nimport os\nimport sys\nimport optparse\n\nfrom pip import cmdoptions\nfrom pip.index import PackageFinder\nfrom pip.locations import running_under_virtualenv\nfrom pip.download import PipSession\nfrom pip.exceptions import (BadCommand, InstallationError, UninstallationError,\n                            CommandError, PreviousBuildDirError)\n\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.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\": \"%(message)s\",\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        # 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        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:\n            logger.critical('Exception:', exc_info=True)\n\n            return UNKNOWN_ERROR\n        finally:\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        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 filename in options.constraints:\n            for req in parse_requirements(\n                    filename,\n                    constraint=True, finder=finder, options=options,\n                    session=session, wheel_cache=wheel_cache):\n                requirement_set.add_requirement(req)\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        # 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 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    def _build_package_finder(self, options, session):\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.info('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            process_dependency_links=options.process_dependency_links,\n            session=session,\n        )\n", "path": "pip/basecommand.py"}], "after_files": [{"content": "\"\"\"\nA module that implments tooling to enable easy warnings about deprecations.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nimport warnings\n\n\nclass PipDeprecationWarning(Warning):\n    pass\n\n\nclass RemovedInPip9Warning(PipDeprecationWarning, DeprecationWarning):\n    pass\n\n\nclass RemovedInPip10Warning(PipDeprecationWarning, PendingDeprecationWarning):\n    pass\n\n\nclass Python26DeprecationWarning(\n    PipDeprecationWarning, PendingDeprecationWarning\n):\n    pass\n\n\nDEPRECATIONS = [\n    RemovedInPip9Warning, RemovedInPip10Warning, Python26DeprecationWarning\n]\n\n\n# Warnings <-> Logging Integration\n\n\n_warnings_showwarning = None\n\n\ndef _showwarning(message, category, filename, lineno, file=None, line=None):\n    if file is not None:\n        if _warnings_showwarning is not None:\n            _warnings_showwarning(\n                message, category, filename, lineno, file, line,\n            )\n    else:\n        if issubclass(category, PipDeprecationWarning):\n            # We use a specially named logger which will handle all of the\n            # deprecation messages for pip.\n            logger = logging.getLogger(\"pip.deprecations\")\n\n            # This is purposely using the % formatter here instead of letting\n            # the logging module handle the interpolation. This is because we\n            # want it to appear as if someone typed this entire message out.\n            log_message = \"DEPRECATION: %s\" % message\n\n            # Things that are DeprecationWarnings will be removed in the very\n            # next version of pip. We want these to be more obvious so we\n            # use the ERROR logging level while the PendingDeprecationWarnings\n            # are still have at least 2 versions to go until they are removed\n            # so they can just be warnings.\n            if issubclass(category, DeprecationWarning):\n                logger.error(log_message)\n            else:\n                logger.warning(log_message)\n        else:\n            _warnings_showwarning(\n                message, category, filename, lineno, file, line,\n            )\n\n\ndef install_warning_logger():\n    global _warnings_showwarning\n\n    if _warnings_showwarning is None:\n        _warnings_showwarning = warnings.showwarning\n        warnings.showwarning = _showwarning\n", "path": "pip/utils/deprecation.py"}, {"content": "\"\"\"Base Command class, and related routines\"\"\"\nfrom __future__ import absolute_import\n\nimport logging\nimport os\nimport sys\nimport optparse\nimport warnings\n\nfrom pip import cmdoptions\nfrom pip.index import PackageFinder\nfrom pip.locations import running_under_virtualenv\nfrom pip.download import PipSession\nfrom pip.exceptions import (BadCommand, InstallationError, UninstallationError,\n                            CommandError, PreviousBuildDirError)\n\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 deprecation, get_prog, normalize_path\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\": \"%(message)s\",\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 sys.version_info[:2] == (2, 6):\n            warnings.warn(\n                \"Python 2.6 is no longer supported by the Python core team, \"\n                \"please upgrade your Python. A future version of pip will \"\n                \"drop support for Python 2.6\",\n                deprecation.Python26DeprecationWarning\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        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:\n            logger.critical('Exception:', exc_info=True)\n\n            return UNKNOWN_ERROR\n        finally:\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        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 filename in options.constraints:\n            for req in parse_requirements(\n                    filename,\n                    constraint=True, finder=finder, options=options,\n                    session=session, wheel_cache=wheel_cache):\n                requirement_set.add_requirement(req)\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        # 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 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    def _build_package_finder(self, options, session):\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.info('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            process_dependency_links=options.process_dependency_links,\n            session=session,\n        )\n", "path": "pip/basecommand.py"}]}