comparison planemo/lib/python3.7/site-packages/pip/_internal/cli/autocompletion.py @ 1:56ad4e20f292 draft

"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
author guerler
date Fri, 31 Jul 2020 00:32:28 -0400
parents
children
comparison
equal deleted inserted replaced
0:d30785e31577 1:56ad4e20f292
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 not opt.metavar or any(
120 x in ('path', 'file', 'dir')
121 for x in opt.metavar.split('/')):
122 return opt.metavar
123
124
125 def auto_complete_paths(current, completion_type):
126 """If ``completion_type`` is ``file`` or ``path``, list all regular files
127 and directories starting with ``current``; otherwise only list directories
128 starting with ``current``.
129
130 :param current: The word to be completed
131 :param completion_type: path completion type(`file`, `path` or `dir`)i
132 :return: A generator of regular files and/or directories
133 """
134 directory, filename = os.path.split(current)
135 current_path = os.path.abspath(directory)
136 # Don't complete paths if they can't be accessed
137 if not os.access(current_path, os.R_OK):
138 return
139 filename = os.path.normcase(filename)
140 # list all files that start with ``filename``
141 file_list = (x for x in os.listdir(current_path)
142 if os.path.normcase(x).startswith(filename))
143 for f in file_list:
144 opt = os.path.join(current_path, f)
145 comp_file = os.path.normcase(os.path.join(directory, f))
146 # complete regular files when there is not ``<dir>`` after option
147 # complete directories when there is ``<file>``, ``<path>`` or
148 # ``<dir>``after option
149 if completion_type != 'dir' and os.path.isfile(opt):
150 yield comp_file
151 elif os.path.isdir(opt):
152 yield os.path.join(comp_file, '')