We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
AttributeError on tab completion of `pip install -U ...`
**Environment**

* pip version: 18.0
* Python version: 3.7.0
* OS: macOS High Sierra

Using iTerm2 3.1.7 or Terminal.app.

<!-- Feel free to add more information about your environment here -->

**Description**
<!-- A clear and concise description of what the bug is. -->

Attempt `pip install -U projectname` with tab completion.


**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->

Tab completion works, or at least no error.

**How to Reproduce**
<!-- Describe the steps to reproduce this bug. -->

1. Type `pip install -U` or `pip install --upgrade` then a few letters of a project name (eg. just `p` below), then press the tab key.
3. An error occurs:

**Output**

```console
$ pip install --upgrade pTraceback (most recent call last):
  File "/usr/local/bin/pip3", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.7/site-packages/pip/_internal/__init__.py", line 293, in main
    autocomplete()
  File "/usr/local/lib/python3.7/site-packages/pip/_internal/__init__.py", line 121, in autocomplete
    cwords, cword, subcommand.parser.option_list_all,
  File "/usr/local/lib/python3.7/site-packages/pip/_internal/__init__.py", line 170, in get_path_completion_type
    for x in opt.metavar.split('/')):
AttributeError: 'NoneType' object has no attribute 'split'
```

**Notes**

* When omitting `-U` or `--upgrade`, pressing tab doesn't complete anything but more importantly there's no error.

* No error with pip 18.0 on Python 2.7.15. Pressing tab suggests files/directories in current dir (with and without `-U`).

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/pip/_internal/cli/autocompletion.py`
Content:
```
1 """Logic that powers autocompletion installed by ``pip completion``.
2 """
3 
4 import optparse
5 import os
6 import sys
7 
8 from pip._internal.cli.main_parser import create_main_parser
9 from pip._internal.commands import commands_dict, get_summaries
10 from pip._internal.utils.misc import get_installed_distributions
11 
12 
13 def autocomplete():
14     """Entry Point for completion of main and subcommand options.
15     """
16     # Don't complete if user hasn't sourced bash_completion file.
17     if 'PIP_AUTO_COMPLETE' not in os.environ:
18         return
19     cwords = os.environ['COMP_WORDS'].split()[1:]
20     cword = int(os.environ['COMP_CWORD'])
21     try:
22         current = cwords[cword - 1]
23     except IndexError:
24         current = ''
25 
26     subcommands = [cmd for cmd, summary in get_summaries()]
27     options = []
28     # subcommand
29     try:
30         subcommand_name = [w for w in cwords if w in subcommands][0]
31     except IndexError:
32         subcommand_name = None
33 
34     parser = create_main_parser()
35     # subcommand options
36     if subcommand_name:
37         # special case: 'help' subcommand has no options
38         if subcommand_name == 'help':
39             sys.exit(1)
40         # special case: list locally installed dists for show and uninstall
41         should_list_installed = (
42             subcommand_name in ['show', 'uninstall'] and
43             not current.startswith('-')
44         )
45         if should_list_installed:
46             installed = []
47             lc = current.lower()
48             for dist in get_installed_distributions(local_only=True):
49                 if dist.key.startswith(lc) and dist.key not in cwords[1:]:
50                     installed.append(dist.key)
51             # if there are no dists installed, fall back to option completion
52             if installed:
53                 for dist in installed:
54                     print(dist)
55                 sys.exit(1)
56 
57         subcommand = commands_dict[subcommand_name]()
58 
59         for opt in subcommand.parser.option_list_all:
60             if opt.help != optparse.SUPPRESS_HELP:
61                 for opt_str in opt._long_opts + opt._short_opts:
62                     options.append((opt_str, opt.nargs))
63 
64         # filter out previously specified options from available options
65         prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
66         options = [(x, v) for (x, v) in options if x not in prev_opts]
67         # filter options by current input
68         options = [(k, v) for k, v in options if k.startswith(current)]
69         # get completion type given cwords and available subcommand options
70         completion_type = get_path_completion_type(
71             cwords, cword, subcommand.parser.option_list_all,
72         )
73         # get completion files and directories if ``completion_type`` is
74         # ``<file>``, ``<dir>`` or ``<path>``
75         if completion_type:
76             options = auto_complete_paths(current, completion_type)
77             options = ((opt, 0) for opt in options)
78         for option in options:
79             opt_label = option[0]
80             # append '=' to options which require args
81             if option[1] and option[0][:2] == "--":
82                 opt_label += '='
83             print(opt_label)
84     else:
85         # show main parser options only when necessary
86 
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         if current.startswith('-'):
91             for opt in opts:
92                 if opt.help != optparse.SUPPRESS_HELP:
93                     subcommands += opt._long_opts + opt._short_opts
94         else:
95             # get completion type given cwords and all available options
96             completion_type = get_path_completion_type(cwords, cword, opts)
97             if completion_type:
98                 subcommands = auto_complete_paths(current, completion_type)
99 
100         print(' '.join([x for x in subcommands if x.startswith(current)]))
101     sys.exit(1)
102 
103 
104 def get_path_completion_type(cwords, cword, opts):
105     """Get the type of path completion (``file``, ``dir``, ``path`` or None)
106 
107     :param cwords: same as the environmental variable ``COMP_WORDS``
108     :param cword: same as the environmental variable ``COMP_CWORD``
109     :param opts: The available options to check
110     :return: path completion type (``file``, ``dir``, ``path`` or None)
111     """
112     if cword < 2 or not cwords[cword - 2].startswith('-'):
113         return
114     for opt in opts:
115         if opt.help == optparse.SUPPRESS_HELP:
116             continue
117         for o in str(opt).split('/'):
118             if cwords[cword - 2].split('=')[0] == o:
119                 if any(x in ('path', 'file', 'dir')
120                         for x in opt.metavar.split('/')):
121                     return opt.metavar
122 
123 
124 def auto_complete_paths(current, completion_type):
125     """If ``completion_type`` is ``file`` or ``path``, list all regular files
126     and directories starting with ``current``; otherwise only list directories
127     starting with ``current``.
128 
129     :param current: The word to be completed
130     :param completion_type: path completion type(`file`, `path` or `dir`)i
131     :return: A generator of regular files and/or directories
132     """
133     directory, filename = os.path.split(current)
134     current_path = os.path.abspath(directory)
135     # Don't complete paths if they can't be accessed
136     if not os.access(current_path, os.R_OK):
137         return
138     filename = os.path.normcase(filename)
139     # list all files that start with ``filename``
140     file_list = (x for x in os.listdir(current_path)
141                  if os.path.normcase(x).startswith(filename))
142     for f in file_list:
143         opt = os.path.join(current_path, f)
144         comp_file = os.path.normcase(os.path.join(directory, f))
145         # complete regular files when there is not ``<dir>`` after option
146         # complete directories when there is ``<file>``, ``<path>`` or
147         # ``<dir>``after option
148         if completion_type != 'dir' and os.path.isfile(opt):
149             yield comp_file
150         elif os.path.isdir(opt):
151             yield os.path.join(comp_file, '')
152
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/pip/_internal/cli/autocompletion.py b/src/pip/_internal/cli/autocompletion.py
--- a/src/pip/_internal/cli/autocompletion.py
+++ b/src/pip/_internal/cli/autocompletion.py
@@ -116,7 +116,8 @@
             continue
         for o in str(opt).split('/'):
             if cwords[cword - 2].split('=')[0] == o:
-                if any(x in ('path', 'file', 'dir')
+                if not opt.metavar or any(
+                        x in ('path', 'file', 'dir')
                         for x in opt.metavar.split('/')):
                     return opt.metavar

{"golden_diff": "diff --git a/src/pip/_internal/cli/autocompletion.py b/src/pip/_internal/cli/autocompletion.py\n--- a/src/pip/_internal/cli/autocompletion.py\n+++ b/src/pip/_internal/cli/autocompletion.py\n@@ -116,7 +116,8 @@\n             continue\n         for o in str(opt).split('/'):\n             if cwords[cword - 2].split('=')[0] == o:\n-                if any(x in ('path', 'file', 'dir')\n+                if not opt.metavar or any(\n+                        x in ('path', 'file', 'dir')\n                         for x in opt.metavar.split('/')):\n                     return opt.metavar\n", "issue": "AttributeError on tab completion of `pip install -U ...`\n**Environment**\r\n\r\n* pip version: 18.0\r\n* Python version: 3.7.0\r\n* OS: macOS High Sierra\r\n\r\nUsing iTerm2 3.1.7 or Terminal.app.\r\n\r\n<!-- Feel free to add more information about your environment here -->\r\n\r\n**Description**\r\n<!-- A clear and concise description of what the bug is. -->\r\n\r\nAttempt `pip install -U projectname` with tab completion.\r\n\r\n\r\n**Expected behavior**\r\n<!-- A clear and concise description of what you expected to happen. -->\r\n\r\nTab completion works, or at least no error.\r\n\r\n**How to Reproduce**\r\n<!-- Describe the steps to reproduce this bug. -->\r\n\r\n1. Type `pip install -U` or `pip install --upgrade` then a few letters of a project name (eg. just `p` below), then press the tab key.\r\n3. An error occurs:\r\n\r\n**Output**\r\n\r\n```console\r\n$ pip install --upgrade pTraceback (most recent call last):\r\n  File \"/usr/local/bin/pip3\", line 11, in <module>\r\n    sys.exit(main())\r\n  File \"/usr/local/lib/python3.7/site-packages/pip/_internal/__init__.py\", line 293, in main\r\n    autocomplete()\r\n  File \"/usr/local/lib/python3.7/site-packages/pip/_internal/__init__.py\", line 121, in autocomplete\r\n    cwords, cword, subcommand.parser.option_list_all,\r\n  File \"/usr/local/lib/python3.7/site-packages/pip/_internal/__init__.py\", line 170, in get_path_completion_type\r\n    for x in opt.metavar.split('/')):\r\nAttributeError: 'NoneType' object has no attribute 'split'\r\n```\r\n\r\n**Notes**\r\n\r\n* When omitting `-U` or `--upgrade`, pressing tab doesn't complete anything but more importantly there's no error.\r\n\r\n* No error with pip 18.0 on Python 2.7.15. Pressing tab suggests files/directories in current dir (with and without `-U`).\n", "before_files": [{"content": "\"\"\"Logic that powers autocompletion installed by ``pip completion``.\n\"\"\"\n\nimport optparse\nimport os\nimport sys\n\nfrom pip._internal.cli.main_parser import create_main_parser\nfrom pip._internal.commands import commands_dict, get_summaries\nfrom pip._internal.utils.misc import get_installed_distributions\n\n\ndef autocomplete():\n    \"\"\"Entry Point for completion of main and subcommand options.\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 show and uninstall\n        should_list_installed = (\n            subcommand_name in ['show', 'uninstall'] and\n            not current.startswith('-')\n        )\n        if should_list_installed:\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_dict[subcommand_name]()\n\n        for opt in subcommand.parser.option_list_all:\n            if opt.help != optparse.SUPPRESS_HELP:\n                for opt_str in opt._long_opts + opt._short_opts:\n                    options.append((opt_str, opt.nargs))\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        # get completion type given cwords and available subcommand options\n        completion_type = get_path_completion_type(\n            cwords, cword, subcommand.parser.option_list_all,\n        )\n        # get completion files and directories if ``completion_type`` is\n        # ``<file>``, ``<dir>`` or ``<path>``\n        if completion_type:\n            options = auto_complete_paths(current, completion_type)\n            options = ((opt, 0) for opt in options)\n        for option in options:\n            opt_label = option[0]\n            # append '=' to options which require args\n            if option[1] and option[0][:2] == \"--\":\n                opt_label += '='\n            print(opt_label)\n    else:\n        # show main parser options only when necessary\n\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        if current.startswith('-'):\n            for opt in opts:\n                if opt.help != optparse.SUPPRESS_HELP:\n                    subcommands += opt._long_opts + opt._short_opts\n        else:\n            # get completion type given cwords and all available options\n            completion_type = get_path_completion_type(cwords, cword, opts)\n            if completion_type:\n                subcommands = auto_complete_paths(current, completion_type)\n\n        print(' '.join([x for x in subcommands if x.startswith(current)]))\n    sys.exit(1)\n\n\ndef get_path_completion_type(cwords, cword, opts):\n    \"\"\"Get the type of path completion (``file``, ``dir``, ``path`` or None)\n\n    :param cwords: same as the environmental variable ``COMP_WORDS``\n    :param cword: same as the environmental variable ``COMP_CWORD``\n    :param opts: The available options to check\n    :return: path completion type (``file``, ``dir``, ``path`` or None)\n    \"\"\"\n    if cword < 2 or not cwords[cword - 2].startswith('-'):\n        return\n    for opt in opts:\n        if opt.help == optparse.SUPPRESS_HELP:\n            continue\n        for o in str(opt).split('/'):\n            if cwords[cword - 2].split('=')[0] == o:\n                if any(x in ('path', 'file', 'dir')\n                        for x in opt.metavar.split('/')):\n                    return opt.metavar\n\n\ndef auto_complete_paths(current, completion_type):\n    \"\"\"If ``completion_type`` is ``file`` or ``path``, list all regular files\n    and directories starting with ``current``; otherwise only list directories\n    starting with ``current``.\n\n    :param current: The word to be completed\n    :param completion_type: path completion type(`file`, `path` or `dir`)i\n    :return: A generator of regular files and/or directories\n    \"\"\"\n    directory, filename = os.path.split(current)\n    current_path = os.path.abspath(directory)\n    # Don't complete paths if they can't be accessed\n    if not os.access(current_path, os.R_OK):\n        return\n    filename = os.path.normcase(filename)\n    # list all files that start with ``filename``\n    file_list = (x for x in os.listdir(current_path)\n                 if os.path.normcase(x).startswith(filename))\n    for f in file_list:\n        opt = os.path.join(current_path, f)\n        comp_file = os.path.normcase(os.path.join(directory, f))\n        # complete regular files when there is not ``<dir>`` after option\n        # complete directories when there is ``<file>``, ``<path>`` or\n        # ``<dir>``after option\n        if completion_type != 'dir' and os.path.isfile(opt):\n            yield comp_file\n        elif os.path.isdir(opt):\n            yield os.path.join(comp_file, '')\n", "path": "src/pip/_internal/cli/autocompletion.py"}], "after_files": [{"content": "\"\"\"Logic that powers autocompletion installed by ``pip completion``.\n\"\"\"\n\nimport optparse\nimport os\nimport sys\n\nfrom pip._internal.cli.main_parser import create_main_parser\nfrom pip._internal.commands import commands_dict, get_summaries\nfrom pip._internal.utils.misc import get_installed_distributions\n\n\ndef autocomplete():\n    \"\"\"Entry Point for completion of main and subcommand options.\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 show and uninstall\n        should_list_installed = (\n            subcommand_name in ['show', 'uninstall'] and\n            not current.startswith('-')\n        )\n        if should_list_installed:\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_dict[subcommand_name]()\n\n        for opt in subcommand.parser.option_list_all:\n            if opt.help != optparse.SUPPRESS_HELP:\n                for opt_str in opt._long_opts + opt._short_opts:\n                    options.append((opt_str, opt.nargs))\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        # get completion type given cwords and available subcommand options\n        completion_type = get_path_completion_type(\n            cwords, cword, subcommand.parser.option_list_all,\n        )\n        # get completion files and directories if ``completion_type`` is\n        # ``<file>``, ``<dir>`` or ``<path>``\n        if completion_type:\n            options = auto_complete_paths(current, completion_type)\n            options = ((opt, 0) for opt in options)\n        for option in options:\n            opt_label = option[0]\n            # append '=' to options which require args\n            if option[1] and option[0][:2] == \"--\":\n                opt_label += '='\n            print(opt_label)\n    else:\n        # show main parser options only when necessary\n\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        if current.startswith('-'):\n            for opt in opts:\n                if opt.help != optparse.SUPPRESS_HELP:\n                    subcommands += opt._long_opts + opt._short_opts\n        else:\n            # get completion type given cwords and all available options\n            completion_type = get_path_completion_type(cwords, cword, opts)\n            if completion_type:\n                subcommands = auto_complete_paths(current, completion_type)\n\n        print(' '.join([x for x in subcommands if x.startswith(current)]))\n    sys.exit(1)\n\n\ndef get_path_completion_type(cwords, cword, opts):\n    \"\"\"Get the type of path completion (``file``, ``dir``, ``path`` or None)\n\n    :param cwords: same as the environmental variable ``COMP_WORDS``\n    :param cword: same as the environmental variable ``COMP_CWORD``\n    :param opts: The available options to check\n    :return: path completion type (``file``, ``dir``, ``path`` or None)\n    \"\"\"\n    if cword < 2 or not cwords[cword - 2].startswith('-'):\n        return\n    for opt in opts:\n        if opt.help == optparse.SUPPRESS_HELP:\n            continue\n        for o in str(opt).split('/'):\n            if cwords[cword - 2].split('=')[0] == o:\n                if not opt.metavar or any(\n                        x in ('path', 'file', 'dir')\n                        for x in opt.metavar.split('/')):\n                    return opt.metavar\n\n\ndef auto_complete_paths(current, completion_type):\n    \"\"\"If ``completion_type`` is ``file`` or ``path``, list all regular files\n    and directories starting with ``current``; otherwise only list directories\n    starting with ``current``.\n\n    :param current: The word to be completed\n    :param completion_type: path completion type(`file`, `path` or `dir`)i\n    :return: A generator of regular files and/or directories\n    \"\"\"\n    directory, filename = os.path.split(current)\n    current_path = os.path.abspath(directory)\n    # Don't complete paths if they can't be accessed\n    if not os.access(current_path, os.R_OK):\n        return\n    filename = os.path.normcase(filename)\n    # list all files that start with ``filename``\n    file_list = (x for x in os.listdir(current_path)\n                 if os.path.normcase(x).startswith(filename))\n    for f in file_list:\n        opt = os.path.join(current_path, f)\n        comp_file = os.path.normcase(os.path.join(directory, f))\n        # complete regular files when there is not ``<dir>`` after option\n        # complete directories when there is ``<file>``, ``<path>`` or\n        # ``<dir>``after option\n        if completion_type != 'dir' and os.path.isfile(opt):\n            yield comp_file\n        elif os.path.isdir(opt):\n            yield os.path.join(comp_file, '')\n", "path": "src/pip/_internal/cli/autocompletion.py"}]}