We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Traceback if any uppercase command entered.
c:\Python34\Scripts>pip3.exe -V
pip 1.5.2 from C:\Python34\lib\site-packages (python 3.4)
Windows 7.1

c:\Python34\Scripts>pip3.exe LIST
Traceback (most recent call last):
  File "C:\Python34\lib\runpy.py", line 171, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Python34\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "c:\Python34\Scripts\pip3.exe__main__.py", line 9, in <module>
  File "C:\Python34\lib\site-packages\pip__init__.py", line 177, in main
    cmd_name, cmd_args = parseopts(initial_args)
  File "C:\Python34\lib\site-packages\pip__init__.py", line 156, in parseopts
    cmd_args.remove(args_else[0].lower())
ValueError: list.remove(x): x not in list

This was confirmed in response to my query on the main python mailing list.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pip/commands/__init__.py`
Content:
```
1 """
2 Package containing all pip commands
3 """
4 
5 
6 from pip.commands.bundle import BundleCommand
7 from pip.commands.completion import CompletionCommand
8 from pip.commands.freeze import FreezeCommand
9 from pip.commands.help import HelpCommand
10 from pip.commands.list import ListCommand
11 from pip.commands.search import SearchCommand
12 from pip.commands.show import ShowCommand
13 from pip.commands.install import InstallCommand
14 from pip.commands.uninstall import UninstallCommand
15 from pip.commands.unzip import UnzipCommand
16 from pip.commands.zip import ZipCommand
17 from pip.commands.wheel import WheelCommand
18 
19 
20 commands = {
21     BundleCommand.name: BundleCommand,
22     CompletionCommand.name: CompletionCommand,
23     FreezeCommand.name: FreezeCommand,
24     HelpCommand.name: HelpCommand,
25     SearchCommand.name: SearchCommand,
26     ShowCommand.name: ShowCommand,
27     InstallCommand.name: InstallCommand,
28     UninstallCommand.name: UninstallCommand,
29     UnzipCommand.name: UnzipCommand,
30     ZipCommand.name: ZipCommand,
31     ListCommand.name: ListCommand,
32     WheelCommand.name: WheelCommand,
33 }
34 
35 
36 commands_order = [
37     InstallCommand,
38     UninstallCommand,
39     FreezeCommand,
40     ListCommand,
41     ShowCommand,
42     SearchCommand,
43     WheelCommand,
44     ZipCommand,
45     UnzipCommand,
46     BundleCommand,
47     HelpCommand,
48 ]
49 
50 
51 def get_summaries(ignore_hidden=True, ordered=True):
52     """Yields sorted (command name, command summary) tuples."""
53 
54     if ordered:
55         cmditems = _sort_commands(commands, commands_order)
56     else:
57         cmditems = commands.items()
58 
59     for name, command_class in cmditems:
60         if ignore_hidden and command_class.hidden:
61             continue
62 
63         yield (name, command_class.summary)
64 
65 
66 def get_similar_commands(name):
67     """Command name auto-correct."""
68     from difflib import get_close_matches
69 
70     close_commands = get_close_matches(name, commands.keys())
71 
72     if close_commands:
73         guess = close_commands[0]
74     else:
75         guess = False
76 
77     return guess
78 
79 
80 def _sort_commands(cmddict, order):
81     def keyfn(key):
82         try:
83             return order.index(key[1])
84         except ValueError:
85             # unordered items should come last
86             return 0xff
87 
88     return sorted(cmddict.items(), key=keyfn)
89
```

Path: `pip/__init__.py`
Content:
```
1 #!/usr/bin/env python
2 import os
3 import optparse
4 
5 import sys
6 import re
7 
8 from pip.exceptions import InstallationError, CommandError, PipError
9 from pip.log import logger
10 from pip.util import get_installed_distributions, get_prog
11 from pip.vcs import git, mercurial, subversion, bazaar  # noqa
12 from pip.baseparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
13 from pip.commands import commands, get_summaries, get_similar_commands
14 
15 # This fixes a peculiarity when importing via __import__ - as we are
16 # initialising the pip module, "from pip import cmdoptions" is recursive
17 # and appears not to work properly in that situation.
18 import pip.cmdoptions
19 cmdoptions = pip.cmdoptions
20 
21 # The version as used in the setup.py and the docs conf.py
22 __version__ = "1.6.dev1"
23 
24 
25 def autocomplete():
26     """Command and option completion for the main option parser (and options)
27     and its subcommands (and options).
28 
29     Enable by sourcing one of the completion shell scripts (bash or zsh).
30     """
31     # Don't complete if user hasn't sourced bash_completion file.
32     if 'PIP_AUTO_COMPLETE' not in os.environ:
33         return
34     cwords = os.environ['COMP_WORDS'].split()[1:]
35     cword = int(os.environ['COMP_CWORD'])
36     try:
37         current = cwords[cword - 1]
38     except IndexError:
39         current = ''
40 
41     subcommands = [cmd for cmd, summary in get_summaries()]
42     options = []
43     # subcommand
44     try:
45         subcommand_name = [w for w in cwords if w in subcommands][0]
46     except IndexError:
47         subcommand_name = None
48 
49     parser = create_main_parser()
50     # subcommand options
51     if subcommand_name:
52         # special case: 'help' subcommand has no options
53         if subcommand_name == 'help':
54             sys.exit(1)
55         # special case: list locally installed dists for uninstall command
56         if subcommand_name == 'uninstall' and not current.startswith('-'):
57             installed = []
58             lc = current.lower()
59             for dist in get_installed_distributions(local_only=True):
60                 if dist.key.startswith(lc) and dist.key not in cwords[1:]:
61                     installed.append(dist.key)
62             # if there are no dists installed, fall back to option completion
63             if installed:
64                 for dist in installed:
65                     print(dist)
66                 sys.exit(1)
67 
68         subcommand = commands[subcommand_name]()
69         options += [(opt.get_opt_string(), opt.nargs)
70                     for opt in subcommand.parser.option_list_all
71                     if opt.help != optparse.SUPPRESS_HELP]
72 
73         # filter out previously specified options from available options
74         prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
75         options = [(x, v) for (x, v) in options if x not in prev_opts]
76         # filter options by current input
77         options = [(k, v) for k, v in options if k.startswith(current)]
78         for option in options:
79             opt_label = option[0]
80             # append '=' to options which require args
81             if option[1]:
82                 opt_label += '='
83             print(opt_label)
84     else:
85         # show main parser options only when necessary
86         if current.startswith('-') or current.startswith('--'):
87             opts = [i.option_list for i in parser.option_groups]
88             opts.append(parser.option_list)
89             opts = (o for it in opts for o in it)
90 
91             subcommands += [i.get_opt_string() for i in opts
92                             if i.help != optparse.SUPPRESS_HELP]
93 
94         print(' '.join([x for x in subcommands if x.startswith(current)]))
95     sys.exit(1)
96 
97 
98 def create_main_parser():
99     parser_kw = {
100         'usage': '\n%prog <command> [options]',
101         'add_help_option': False,
102         'formatter': UpdatingDefaultsHelpFormatter(),
103         'name': 'global',
104         'prog': get_prog(),
105     }
106 
107     parser = ConfigOptionParser(**parser_kw)
108     parser.disable_interspersed_args()
109 
110     pip_pkg_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
111     parser.version = 'pip %s from %s (python %s)' % (
112         __version__, pip_pkg_dir, sys.version[:3])
113 
114     # add the general options
115     gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
116     parser.add_option_group(gen_opts)
117 
118     parser.main = True  # so the help formatter knows
119 
120     # create command listing for description
121     command_summaries = get_summaries()
122     description = [''] + ['%-27s %s' % (i, j) for i, j in command_summaries]
123     parser.description = '\n'.join(description)
124 
125     return parser
126 
127 
128 def parseopts(args):
129     parser = create_main_parser()
130 
131     # Note: parser calls disable_interspersed_args(), so the result of this
132     # call is to split the initial args into the general options before the
133     # subcommand and everything else.
134     # For example:
135     #  args: ['--timeout=5', 'install', '--user', 'INITools']
136     #  general_options: ['--timeout==5']
137     #  args_else: ['install', '--user', 'INITools']
138     general_options, args_else = parser.parse_args(args)
139 
140     # --version
141     if general_options.version:
142         sys.stdout.write(parser.version)
143         sys.stdout.write(os.linesep)
144         sys.exit()
145 
146     # pip || pip help -> print_help()
147     if not args_else or (args_else[0] == 'help' and len(args_else) == 1):
148         parser.print_help()
149         sys.exit()
150 
151     # the subcommand name
152     cmd_name = args_else[0].lower()
153 
154     # all the args without the subcommand
155     cmd_args = args[:]
156     cmd_args.remove(args_else[0].lower())
157 
158     if cmd_name not in commands:
159         guess = get_similar_commands(cmd_name)
160 
161         msg = ['unknown command "%s"' % cmd_name]
162         if guess:
163             msg.append('maybe you meant "%s"' % guess)
164 
165         raise CommandError(' - '.join(msg))
166 
167     return cmd_name, cmd_args
168 
169 
170 def main(args=None):
171     if args is None:
172         args = sys.argv[1:]
173 
174     autocomplete()
175 
176     try:
177         cmd_name, cmd_args = parseopts(args)
178     except PipError as exc:
179         sys.stderr.write("ERROR: %s" % exc)
180         sys.stderr.write(os.linesep)
181         sys.exit(1)
182 
183     command = commands[cmd_name]()
184     return command.main(cmd_args)
185 
186 
187 # ###########################################################
188 # # Writing freeze files
189 
190 class FrozenRequirement(object):
191 
192     def __init__(self, name, req, editable, comments=()):
193         self.name = name
194         self.req = req
195         self.editable = editable
196         self.comments = comments
197 
198     _rev_re = re.compile(r'-r(\d+)$')
199     _date_re = re.compile(r'-(20\d\d\d\d\d\d)$')
200 
201     @classmethod
202     def from_dist(cls, dist, find_tags=False):
203         location = os.path.normcase(os.path.abspath(dist.location))
204         comments = []
205         from pip.vcs import vcs, get_src_requirement
206         if vcs.get_backend_name(location):
207             editable = True
208             try:
209                 req = get_src_requirement(dist, location, find_tags)
210             except InstallationError as exc:
211                 logger.warn(
212                     "Error when trying to get requirement for VCS system %s, "
213                     "falling back to uneditable format" % exc
214                 )
215                 req = None
216             if req is None:
217                 logger.warn(
218                     'Could not determine repository location of %s' % location
219                 )
220                 comments.append(
221                     '## !! Could not determine repository location'
222                 )
223                 req = dist.as_requirement()
224                 editable = False
225         else:
226             editable = False
227             req = dist.as_requirement()
228             specs = req.specs
229             assert len(specs) == 1 and specs[0][0] == '=='
230 
231         return cls(dist.project_name, req, editable, comments)
232 
233     @staticmethod
234     def egg_name(dist):
235         name = dist.egg_name()
236         match = re.search(r'-py\d\.\d$', name)
237         if match:
238             name = name[:match.start()]
239         return name
240 
241     def __str__(self):
242         req = self.req
243         if self.editable:
244             req = '-e %s' % req
245         return '\n'.join(list(self.comments) + [str(req)]) + '\n'
246 
247 
248 if __name__ == '__main__':
249     sys.exit(main())
250
```
--- 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/__init__.py b/pip/__init__.py
--- a/pip/__init__.py
+++ b/pip/__init__.py
@@ -149,11 +149,11 @@
         sys.exit()
 
     # the subcommand name
-    cmd_name = args_else[0].lower()
+    cmd_name = args_else[0]
 
     # all the args without the subcommand
     cmd_args = args[:]
-    cmd_args.remove(args_else[0].lower())
+    cmd_args.remove(args_else[0])
 
     if cmd_name not in commands:
         guess = get_similar_commands(cmd_name)
diff --git a/pip/commands/__init__.py b/pip/commands/__init__.py
--- a/pip/commands/__init__.py
+++ b/pip/commands/__init__.py
@@ -67,14 +67,14 @@
     """Command name auto-correct."""
     from difflib import get_close_matches
 
+    name = name.lower()
+
     close_commands = get_close_matches(name, commands.keys())
 
     if close_commands:
-        guess = close_commands[0]
+        return close_commands[0]
     else:
-        guess = False
-
-    return guess
+        return False
 
 
 def _sort_commands(cmddict, order):

{"golden_diff": "diff --git a/pip/__init__.py b/pip/__init__.py\n--- a/pip/__init__.py\n+++ b/pip/__init__.py\n@@ -149,11 +149,11 @@\n         sys.exit()\n \n     # the subcommand name\n-    cmd_name = args_else[0].lower()\n+    cmd_name = args_else[0]\n \n     # all the args without the subcommand\n     cmd_args = args[:]\n-    cmd_args.remove(args_else[0].lower())\n+    cmd_args.remove(args_else[0])\n \n     if cmd_name not in commands:\n         guess = get_similar_commands(cmd_name)\ndiff --git a/pip/commands/__init__.py b/pip/commands/__init__.py\n--- a/pip/commands/__init__.py\n+++ b/pip/commands/__init__.py\n@@ -67,14 +67,14 @@\n     \"\"\"Command name auto-correct.\"\"\"\n     from difflib import get_close_matches\n \n+    name = name.lower()\n+\n     close_commands = get_close_matches(name, commands.keys())\n \n     if close_commands:\n-        guess = close_commands[0]\n+        return close_commands[0]\n     else:\n-        guess = False\n-\n-    return guess\n+        return False\n \n \n def _sort_commands(cmddict, order):\n", "issue": "Traceback if any uppercase command entered.\nc:\\Python34\\Scripts>pip3.exe -V\npip 1.5.2 from C:\\Python34\\lib\\site-packages (python 3.4)\nWindows 7.1\n\nc:\\Python34\\Scripts>pip3.exe LIST\nTraceback (most recent call last):\n  File \"C:\\Python34\\lib\\runpy.py\", line 171, in _run_module_as_main\n    \"__main__\", mod_spec)\n  File \"C:\\Python34\\lib\\runpy.py\", line 86, in _run_code\n    exec(code, run_globals)\n  File \"c:\\Python34\\Scripts\\pip3.exe__main__.py\", line 9, in <module>\n  File \"C:\\Python34\\lib\\site-packages\\pip__init__.py\", line 177, in main\n    cmd_name, cmd_args = parseopts(initial_args)\n  File \"C:\\Python34\\lib\\site-packages\\pip__init__.py\", line 156, in parseopts\n    cmd_args.remove(args_else[0].lower())\nValueError: list.remove(x): x not in list\n\nThis was confirmed in response to my query on the main python mailing list.\n\n", "before_files": [{"content": "\"\"\"\nPackage containing all pip commands\n\"\"\"\n\n\nfrom pip.commands.bundle import BundleCommand\nfrom pip.commands.completion import CompletionCommand\nfrom pip.commands.freeze import FreezeCommand\nfrom pip.commands.help import HelpCommand\nfrom pip.commands.list import ListCommand\nfrom pip.commands.search import SearchCommand\nfrom pip.commands.show import ShowCommand\nfrom pip.commands.install import InstallCommand\nfrom pip.commands.uninstall import UninstallCommand\nfrom pip.commands.unzip import UnzipCommand\nfrom pip.commands.zip import ZipCommand\nfrom pip.commands.wheel import WheelCommand\n\n\ncommands = {\n    BundleCommand.name: BundleCommand,\n    CompletionCommand.name: CompletionCommand,\n    FreezeCommand.name: FreezeCommand,\n    HelpCommand.name: HelpCommand,\n    SearchCommand.name: SearchCommand,\n    ShowCommand.name: ShowCommand,\n    InstallCommand.name: InstallCommand,\n    UninstallCommand.name: UninstallCommand,\n    UnzipCommand.name: UnzipCommand,\n    ZipCommand.name: ZipCommand,\n    ListCommand.name: ListCommand,\n    WheelCommand.name: WheelCommand,\n}\n\n\ncommands_order = [\n    InstallCommand,\n    UninstallCommand,\n    FreezeCommand,\n    ListCommand,\n    ShowCommand,\n    SearchCommand,\n    WheelCommand,\n    ZipCommand,\n    UnzipCommand,\n    BundleCommand,\n    HelpCommand,\n]\n\n\ndef get_summaries(ignore_hidden=True, ordered=True):\n    \"\"\"Yields sorted (command name, command summary) tuples.\"\"\"\n\n    if ordered:\n        cmditems = _sort_commands(commands, commands_order)\n    else:\n        cmditems = commands.items()\n\n    for name, command_class in cmditems:\n        if ignore_hidden and command_class.hidden:\n            continue\n\n        yield (name, command_class.summary)\n\n\ndef get_similar_commands(name):\n    \"\"\"Command name auto-correct.\"\"\"\n    from difflib import get_close_matches\n\n    close_commands = get_close_matches(name, commands.keys())\n\n    if close_commands:\n        guess = close_commands[0]\n    else:\n        guess = False\n\n    return guess\n\n\ndef _sort_commands(cmddict, order):\n    def keyfn(key):\n        try:\n            return order.index(key[1])\n        except ValueError:\n            # unordered items should come last\n            return 0xff\n\n    return sorted(cmddict.items(), key=keyfn)\n", "path": "pip/commands/__init__.py"}, {"content": "#!/usr/bin/env python\nimport os\nimport optparse\n\nimport sys\nimport re\n\nfrom pip.exceptions import InstallationError, CommandError, PipError\nfrom pip.log import logger\nfrom pip.util import get_installed_distributions, get_prog\nfrom pip.vcs import git, mercurial, subversion, bazaar  # noqa\nfrom pip.baseparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter\nfrom pip.commands import commands, get_summaries, get_similar_commands\n\n# This fixes a peculiarity when importing via __import__ - as we are\n# initialising the pip module, \"from pip import cmdoptions\" is recursive\n# and appears not to work properly in that situation.\nimport pip.cmdoptions\ncmdoptions = pip.cmdoptions\n\n# The version as used in the setup.py and the docs conf.py\n__version__ = \"1.6.dev1\"\n\n\ndef autocomplete():\n    \"\"\"Command and option completion for the main option parser (and options)\n    and its subcommands (and options).\n\n    Enable by sourcing one of the completion shell scripts (bash or zsh).\n    \"\"\"\n    # Don't complete if user hasn't sourced bash_completion file.\n    if 'PIP_AUTO_COMPLETE' not in os.environ:\n        return\n    cwords = os.environ['COMP_WORDS'].split()[1:]\n    cword = int(os.environ['COMP_CWORD'])\n    try:\n        current = cwords[cword - 1]\n    except IndexError:\n        current = ''\n\n    subcommands = [cmd for cmd, summary in get_summaries()]\n    options = []\n    # subcommand\n    try:\n        subcommand_name = [w for w in cwords if w in subcommands][0]\n    except IndexError:\n        subcommand_name = None\n\n    parser = create_main_parser()\n    # subcommand options\n    if subcommand_name:\n        # special case: 'help' subcommand has no options\n        if subcommand_name == 'help':\n            sys.exit(1)\n        # special case: list locally installed dists for uninstall command\n        if subcommand_name == 'uninstall' and not current.startswith('-'):\n            installed = []\n            lc = current.lower()\n            for dist in get_installed_distributions(local_only=True):\n                if dist.key.startswith(lc) and dist.key not in cwords[1:]:\n                    installed.append(dist.key)\n            # if there are no dists installed, fall back to option completion\n            if installed:\n                for dist in installed:\n                    print(dist)\n                sys.exit(1)\n\n        subcommand = commands[subcommand_name]()\n        options += [(opt.get_opt_string(), opt.nargs)\n                    for opt in subcommand.parser.option_list_all\n                    if opt.help != optparse.SUPPRESS_HELP]\n\n        # filter out previously specified options from available options\n        prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]\n        options = [(x, v) for (x, v) in options if x not in prev_opts]\n        # filter options by current input\n        options = [(k, v) for k, v in options if k.startswith(current)]\n        for option in options:\n            opt_label = option[0]\n            # append '=' to options which require args\n            if option[1]:\n                opt_label += '='\n            print(opt_label)\n    else:\n        # show main parser options only when necessary\n        if current.startswith('-') or current.startswith('--'):\n            opts = [i.option_list for i in parser.option_groups]\n            opts.append(parser.option_list)\n            opts = (o for it in opts for o in it)\n\n            subcommands += [i.get_opt_string() for i in opts\n                            if i.help != optparse.SUPPRESS_HELP]\n\n        print(' '.join([x for x in subcommands if x.startswith(current)]))\n    sys.exit(1)\n\n\ndef create_main_parser():\n    parser_kw = {\n        'usage': '\\n%prog <command> [options]',\n        'add_help_option': False,\n        'formatter': UpdatingDefaultsHelpFormatter(),\n        'name': 'global',\n        'prog': get_prog(),\n    }\n\n    parser = ConfigOptionParser(**parser_kw)\n    parser.disable_interspersed_args()\n\n    pip_pkg_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n    parser.version = 'pip %s from %s (python %s)' % (\n        __version__, pip_pkg_dir, sys.version[:3])\n\n    # add the general options\n    gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)\n    parser.add_option_group(gen_opts)\n\n    parser.main = True  # so the help formatter knows\n\n    # create command listing for description\n    command_summaries = get_summaries()\n    description = [''] + ['%-27s %s' % (i, j) for i, j in command_summaries]\n    parser.description = '\\n'.join(description)\n\n    return parser\n\n\ndef parseopts(args):\n    parser = create_main_parser()\n\n    # Note: parser calls disable_interspersed_args(), so the result of this\n    # call is to split the initial args into the general options before the\n    # subcommand and everything else.\n    # For example:\n    #  args: ['--timeout=5', 'install', '--user', 'INITools']\n    #  general_options: ['--timeout==5']\n    #  args_else: ['install', '--user', 'INITools']\n    general_options, args_else = parser.parse_args(args)\n\n    # --version\n    if general_options.version:\n        sys.stdout.write(parser.version)\n        sys.stdout.write(os.linesep)\n        sys.exit()\n\n    # pip || pip help -> print_help()\n    if not args_else or (args_else[0] == 'help' and len(args_else) == 1):\n        parser.print_help()\n        sys.exit()\n\n    # the subcommand name\n    cmd_name = args_else[0].lower()\n\n    # all the args without the subcommand\n    cmd_args = args[:]\n    cmd_args.remove(args_else[0].lower())\n\n    if cmd_name not in commands:\n        guess = get_similar_commands(cmd_name)\n\n        msg = ['unknown command \"%s\"' % cmd_name]\n        if guess:\n            msg.append('maybe you meant \"%s\"' % guess)\n\n        raise CommandError(' - '.join(msg))\n\n    return cmd_name, cmd_args\n\n\ndef main(args=None):\n    if args is None:\n        args = sys.argv[1:]\n\n    autocomplete()\n\n    try:\n        cmd_name, cmd_args = parseopts(args)\n    except PipError as exc:\n        sys.stderr.write(\"ERROR: %s\" % exc)\n        sys.stderr.write(os.linesep)\n        sys.exit(1)\n\n    command = commands[cmd_name]()\n    return command.main(cmd_args)\n\n\n# ###########################################################\n# # Writing freeze files\n\nclass FrozenRequirement(object):\n\n    def __init__(self, name, req, editable, comments=()):\n        self.name = name\n        self.req = req\n        self.editable = editable\n        self.comments = comments\n\n    _rev_re = re.compile(r'-r(\\d+)$')\n    _date_re = re.compile(r'-(20\\d\\d\\d\\d\\d\\d)$')\n\n    @classmethod\n    def from_dist(cls, dist, find_tags=False):\n        location = os.path.normcase(os.path.abspath(dist.location))\n        comments = []\n        from pip.vcs import vcs, get_src_requirement\n        if vcs.get_backend_name(location):\n            editable = True\n            try:\n                req = get_src_requirement(dist, location, find_tags)\n            except InstallationError as exc:\n                logger.warn(\n                    \"Error when trying to get requirement for VCS system %s, \"\n                    \"falling back to uneditable format\" % exc\n                )\n                req = None\n            if req is None:\n                logger.warn(\n                    'Could not determine repository location of %s' % location\n                )\n                comments.append(\n                    '## !! Could not determine repository location'\n                )\n                req = dist.as_requirement()\n                editable = False\n        else:\n            editable = False\n            req = dist.as_requirement()\n            specs = req.specs\n            assert len(specs) == 1 and specs[0][0] == '=='\n\n        return cls(dist.project_name, req, editable, comments)\n\n    @staticmethod\n    def egg_name(dist):\n        name = dist.egg_name()\n        match = re.search(r'-py\\d\\.\\d$', name)\n        if match:\n            name = name[:match.start()]\n        return name\n\n    def __str__(self):\n        req = self.req\n        if self.editable:\n            req = '-e %s' % req\n        return '\\n'.join(list(self.comments) + [str(req)]) + '\\n'\n\n\nif __name__ == '__main__':\n    sys.exit(main())\n", "path": "pip/__init__.py"}], "after_files": [{"content": "\"\"\"\nPackage containing all pip commands\n\"\"\"\n\n\nfrom pip.commands.bundle import BundleCommand\nfrom pip.commands.completion import CompletionCommand\nfrom pip.commands.freeze import FreezeCommand\nfrom pip.commands.help import HelpCommand\nfrom pip.commands.list import ListCommand\nfrom pip.commands.search import SearchCommand\nfrom pip.commands.show import ShowCommand\nfrom pip.commands.install import InstallCommand\nfrom pip.commands.uninstall import UninstallCommand\nfrom pip.commands.unzip import UnzipCommand\nfrom pip.commands.zip import ZipCommand\nfrom pip.commands.wheel import WheelCommand\n\n\ncommands = {\n    BundleCommand.name: BundleCommand,\n    CompletionCommand.name: CompletionCommand,\n    FreezeCommand.name: FreezeCommand,\n    HelpCommand.name: HelpCommand,\n    SearchCommand.name: SearchCommand,\n    ShowCommand.name: ShowCommand,\n    InstallCommand.name: InstallCommand,\n    UninstallCommand.name: UninstallCommand,\n    UnzipCommand.name: UnzipCommand,\n    ZipCommand.name: ZipCommand,\n    ListCommand.name: ListCommand,\n    WheelCommand.name: WheelCommand,\n}\n\n\ncommands_order = [\n    InstallCommand,\n    UninstallCommand,\n    FreezeCommand,\n    ListCommand,\n    ShowCommand,\n    SearchCommand,\n    WheelCommand,\n    ZipCommand,\n    UnzipCommand,\n    BundleCommand,\n    HelpCommand,\n]\n\n\ndef get_summaries(ignore_hidden=True, ordered=True):\n    \"\"\"Yields sorted (command name, command summary) tuples.\"\"\"\n\n    if ordered:\n        cmditems = _sort_commands(commands, commands_order)\n    else:\n        cmditems = commands.items()\n\n    for name, command_class in cmditems:\n        if ignore_hidden and command_class.hidden:\n            continue\n\n        yield (name, command_class.summary)\n\n\ndef get_similar_commands(name):\n    \"\"\"Command name auto-correct.\"\"\"\n    from difflib import get_close_matches\n\n    name = name.lower()\n\n    close_commands = get_close_matches(name, commands.keys())\n\n    if close_commands:\n        return close_commands[0]\n    else:\n        return False\n\n\ndef _sort_commands(cmddict, order):\n    def keyfn(key):\n        try:\n            return order.index(key[1])\n        except ValueError:\n            # unordered items should come last\n            return 0xff\n\n    return sorted(cmddict.items(), key=keyfn)\n", "path": "pip/commands/__init__.py"}, {"content": "#!/usr/bin/env python\nimport os\nimport optparse\n\nimport sys\nimport re\n\nfrom pip.exceptions import InstallationError, CommandError, PipError\nfrom pip.log import logger\nfrom pip.util import get_installed_distributions, get_prog\nfrom pip.vcs import git, mercurial, subversion, bazaar  # noqa\nfrom pip.baseparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter\nfrom pip.commands import commands, get_summaries, get_similar_commands\n\n# This fixes a peculiarity when importing via __import__ - as we are\n# initialising the pip module, \"from pip import cmdoptions\" is recursive\n# and appears not to work properly in that situation.\nimport pip.cmdoptions\ncmdoptions = pip.cmdoptions\n\n# The version as used in the setup.py and the docs conf.py\n__version__ = \"1.6.dev1\"\n\n\ndef autocomplete():\n    \"\"\"Command and option completion for the main option parser (and options)\n    and its subcommands (and options).\n\n    Enable by sourcing one of the completion shell scripts (bash or zsh).\n    \"\"\"\n    # Don't complete if user hasn't sourced bash_completion file.\n    if 'PIP_AUTO_COMPLETE' not in os.environ:\n        return\n    cwords = os.environ['COMP_WORDS'].split()[1:]\n    cword = int(os.environ['COMP_CWORD'])\n    try:\n        current = cwords[cword - 1]\n    except IndexError:\n        current = ''\n\n    subcommands = [cmd for cmd, summary in get_summaries()]\n    options = []\n    # subcommand\n    try:\n        subcommand_name = [w for w in cwords if w in subcommands][0]\n    except IndexError:\n        subcommand_name = None\n\n    parser = create_main_parser()\n    # subcommand options\n    if subcommand_name:\n        # special case: 'help' subcommand has no options\n        if subcommand_name == 'help':\n            sys.exit(1)\n        # special case: list locally installed dists for uninstall command\n        if subcommand_name == 'uninstall' and not current.startswith('-'):\n            installed = []\n            lc = current.lower()\n            for dist in get_installed_distributions(local_only=True):\n                if dist.key.startswith(lc) and dist.key not in cwords[1:]:\n                    installed.append(dist.key)\n            # if there are no dists installed, fall back to option completion\n            if installed:\n                for dist in installed:\n                    print(dist)\n                sys.exit(1)\n\n        subcommand = commands[subcommand_name]()\n        options += [(opt.get_opt_string(), opt.nargs)\n                    for opt in subcommand.parser.option_list_all\n                    if opt.help != optparse.SUPPRESS_HELP]\n\n        # filter out previously specified options from available options\n        prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]\n        options = [(x, v) for (x, v) in options if x not in prev_opts]\n        # filter options by current input\n        options = [(k, v) for k, v in options if k.startswith(current)]\n        for option in options:\n            opt_label = option[0]\n            # append '=' to options which require args\n            if option[1]:\n                opt_label += '='\n            print(opt_label)\n    else:\n        # show main parser options only when necessary\n        if current.startswith('-') or current.startswith('--'):\n            opts = [i.option_list for i in parser.option_groups]\n            opts.append(parser.option_list)\n            opts = (o for it in opts for o in it)\n\n            subcommands += [i.get_opt_string() for i in opts\n                            if i.help != optparse.SUPPRESS_HELP]\n\n        print(' '.join([x for x in subcommands if x.startswith(current)]))\n    sys.exit(1)\n\n\ndef create_main_parser():\n    parser_kw = {\n        'usage': '\\n%prog <command> [options]',\n        'add_help_option': False,\n        'formatter': UpdatingDefaultsHelpFormatter(),\n        'name': 'global',\n        'prog': get_prog(),\n    }\n\n    parser = ConfigOptionParser(**parser_kw)\n    parser.disable_interspersed_args()\n\n    pip_pkg_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n    parser.version = 'pip %s from %s (python %s)' % (\n        __version__, pip_pkg_dir, sys.version[:3])\n\n    # add the general options\n    gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)\n    parser.add_option_group(gen_opts)\n\n    parser.main = True  # so the help formatter knows\n\n    # create command listing for description\n    command_summaries = get_summaries()\n    description = [''] + ['%-27s %s' % (i, j) for i, j in command_summaries]\n    parser.description = '\\n'.join(description)\n\n    return parser\n\n\ndef parseopts(args):\n    parser = create_main_parser()\n\n    # Note: parser calls disable_interspersed_args(), so the result of this\n    # call is to split the initial args into the general options before the\n    # subcommand and everything else.\n    # For example:\n    #  args: ['--timeout=5', 'install', '--user', 'INITools']\n    #  general_options: ['--timeout==5']\n    #  args_else: ['install', '--user', 'INITools']\n    general_options, args_else = parser.parse_args(args)\n\n    # --version\n    if general_options.version:\n        sys.stdout.write(parser.version)\n        sys.stdout.write(os.linesep)\n        sys.exit()\n\n    # pip || pip help -> print_help()\n    if not args_else or (args_else[0] == 'help' and len(args_else) == 1):\n        parser.print_help()\n        sys.exit()\n\n    # the subcommand name\n    cmd_name = args_else[0]\n\n    # all the args without the subcommand\n    cmd_args = args[:]\n    cmd_args.remove(args_else[0])\n\n    if cmd_name not in commands:\n        guess = get_similar_commands(cmd_name)\n\n        msg = ['unknown command \"%s\"' % cmd_name]\n        if guess:\n            msg.append('maybe you meant \"%s\"' % guess)\n\n        raise CommandError(' - '.join(msg))\n\n    return cmd_name, cmd_args\n\n\ndef main(args=None):\n    if args is None:\n        args = sys.argv[1:]\n\n    autocomplete()\n\n    try:\n        cmd_name, cmd_args = parseopts(args)\n    except PipError as exc:\n        sys.stderr.write(\"ERROR: %s\" % exc)\n        sys.stderr.write(os.linesep)\n        sys.exit(1)\n\n    command = commands[cmd_name]()\n    return command.main(cmd_args)\n\n\n# ###########################################################\n# # Writing freeze files\n\nclass FrozenRequirement(object):\n\n    def __init__(self, name, req, editable, comments=()):\n        self.name = name\n        self.req = req\n        self.editable = editable\n        self.comments = comments\n\n    _rev_re = re.compile(r'-r(\\d+)$')\n    _date_re = re.compile(r'-(20\\d\\d\\d\\d\\d\\d)$')\n\n    @classmethod\n    def from_dist(cls, dist, find_tags=False):\n        location = os.path.normcase(os.path.abspath(dist.location))\n        comments = []\n        from pip.vcs import vcs, get_src_requirement\n        if vcs.get_backend_name(location):\n            editable = True\n            try:\n                req = get_src_requirement(dist, location, find_tags)\n            except InstallationError as exc:\n                logger.warn(\n                    \"Error when trying to get requirement for VCS system %s, \"\n                    \"falling back to uneditable format\" % exc\n                )\n                req = None\n            if req is None:\n                logger.warn(\n                    'Could not determine repository location of %s' % location\n                )\n                comments.append(\n                    '## !! Could not determine repository location'\n                )\n                req = dist.as_requirement()\n                editable = False\n        else:\n            editable = False\n            req = dist.as_requirement()\n            specs = req.specs\n            assert len(specs) == 1 and specs[0][0] == '=='\n\n        return cls(dist.project_name, req, editable, comments)\n\n    @staticmethod\n    def egg_name(dist):\n        name = dist.egg_name()\n        match = re.search(r'-py\\d\\.\\d$', name)\n        if match:\n            name = name[:match.start()]\n        return name\n\n    def __str__(self):\n        req = self.req\n        if self.editable:\n            req = '-e %s' % req\n        return '\\n'.join(list(self.comments) + [str(req)]) + '\\n'\n\n\nif __name__ == '__main__':\n    sys.exit(main())\n", "path": "pip/__init__.py"}]}