Debian Codegraph @

crazy_complete/bash_complete.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 '''This module contains code for completing arguments in Bash.'''
5
6 from . import shell
7 from . import utils
8 from . import bash_versions
9 from .str_utils import indent
10 from .type_utils import is_dict_type
11 from .bash_utils import make_file_extension_pattern
12
13
14 class BashCompletionBase:
15 '''Base class for Bash completions.'''
16
17 def get_code(self, append=False):
18 '''Returns the code used for completing an argument.
19
20 If `append` is `True`, then the results will be appended to $COMPREPLY,
21 otherwise $COMPREPLY will be truncated.
22
23 Args:
24 append (bool): If True, the results will be appended to $COMPREPLY.
25
26 Returns:
27 str: The command for Bash completion.
28 '''
29 raise NotImplementedError
30
31 def get_function(self):
32 '''Returns a function.'''
33 raise NotImplementedError
34
35
36 class BashCompletionCode(BashCompletionBase):
37 '''Used for completion code that internally modify $COMPREPLY.'''
38
39 def __init__(self, ctxt, code):
40 self.ctxt = ctxt
41 self.code = code
42
43 def get_code(self, append=False):
44 if not self.code:
45 return ''
46
47 r = []
48
49 if append:
50 r.append('local COMPREPLY_OLD=("${COMPREPLY[@]}")')
51
52 r.append(self.code)
53
54 if append:
55 r.append('COMPREPLY=("${COMPREPLY_OLD[@]}" "${COMPREPLY[@]}")')
56
57 return '\n'.join(r)
58
59 def get_function(self):
60 if not self.code:
61 return 'true'
62
63 return self.ctxt.helpers.add_dynamic_func(self.ctxt, self.get_code())
64
65
66 class BashCompletionFunc(BashCompletionBase):
67 '''Used for completion functions that internally modify $COMPREPLY.'''
68
69 def __init__(self, ctxt, args):
70 self.ctxt = ctxt
71 self.args = args
72
73 def get_code(self, append=False):
74 r = []
75
76 if append:
77 r.append('local COMPREPLY_OLD=("${COMPREPLY[@]}")')
78
79 r.append(shell.join_quoted(self.args))
80
81 if append:
82 r.append('COMPREPLY=("${COMPREPLY_OLD[@]}" "${COMPREPLY[@]}")')
83
84 return '\n'.join(r)
85
86 def get_function(self):
87 if len(self.args) == 1:
88 return self.args[0]
89
90 return self.ctxt.helpers.add_dynamic_func(self.ctxt, self.get_code())
91
92
93 class CompgenW(BashCompletionBase):
94 '''Used for completing a list of words.'''
95
96 def __init__(self, ctxt, values):
97 self.ctxt = ctxt
98 self.values = [str(value) for value in values]
99
100 def get_code(self, append=False):
101 needs_quote = any(filter(shell.needs_quote, self.values))
102
103 if not needs_quote:
104 return 'COMPREPLY%s=($(compgen -W %s -- "$cur"))' % (
105 ('+' if append else ''),
106 shell.quote(' '.join(self.values)))
107
108 return ('%s %s-- %s' % (
109 self.ctxt.helpers.use_function('values'),
110 ('-a ' if append else ''),
111 shell.join_quoted(self.values)))
112
113 def get_function(self):
114 return self.ctxt.helpers.add_dynamic_func(self.ctxt, self.get_code())
115
116
117 class BashCompletionCompgen(BashCompletionBase):
118 '''Used for completion that uses Bash's `compgen` command.'''
119
120 def __init__(self, ctxt, compgen_args, code=None):
121 self.ctxt = ctxt
122 self.compgen_args = compgen_args
123 self.code = code
124
125 def get_code(self, append=False):
126 compgen_cmd = 'COMPREPLY%s=($(compgen %s -- "$cur"))' % (
127 ('+' if append else ''), self.compgen_args)
128
129 if not self.code:
130 return compgen_cmd
131
132 return f'{self.code}\n{compgen_cmd}'
133
134 def get_function(self):
135 return self.ctxt.helpers.add_dynamic_func(self.ctxt, self.get_code())
136
137
138 class BashCompleteCombine(BashCompletionBase):
139 '''Used for combining multiple completion commands.'''
140
141 def __init__(self, ctxt, trace, completer, commands):
142 self.ctxt = ctxt
143 self.completion_objects = []
144
145 for command_args in commands:
146 obj = completer.complete_from_def(ctxt, trace, command_args)
147 self.completion_objects.append(obj)
148
149 def get_code(self, append=False):
150 code = [self.completion_objects[0].get_code(append=append)]
151 for obj in self.completion_objects[1:]:
152 code.append(obj.get_code(append=True))
153 return '\n'.join(code)
154
155 def get_function(self):
156 return self.ctxt.helpers.add_dynamic_func(self.ctxt, self.get_code())
157
158
159 class BashCompleteKeyValueList(BashCompletionCode):
160 '''Used for completing a list of key-value pairs.'''
161
162 # pylint: disable=too-many-arguments
163 # pylint: disable=too-many-positional-arguments
164
165 def __init__(self, ctxt, trace, completer, pair_separator, value_separator,
166 values, condition_func):
167 args = []
168
169 for definition in utils.get_key_value_list_definitions(values):
170 if not definition.completer:
171 func = 'false'
172 elif definition.completer[0] == 'none':
173 func = 'true'
174 else:
175 obj = completer.complete_from_def(ctxt, trace, definition.completer)
176 func = obj.get_function()
177
178 excludes = []
179 if not definition.repeatable:
180 excludes.append(definition.key)
181 excludes.extend(definition.excludes)
182
183 condition = ''
184 if condition_func is not None:
185 condition = '$c %s && ' % shell.quote(definition.key)
186
187 args.append('%sa+=(%s %s %s)' % (
188 condition,
189 shell.quote(definition.key),
190 shell.quote(func),
191 shell.quote(' '.join(excludes))))
192
193 code = 'local -a a=()\n'
194 if condition_func is not None:
195 code += 'local c=%s\n' % shell.quote(condition_func)
196 code += '%s\n' % '\n'.join(args)
197 code += '%s %s %s "${a[@]}"' % (
198 ctxt.helpers.use_function('key_value_list'),
199 shell.quote(pair_separator),
200 shell.quote(value_separator)
201 )
202
203 super().__init__(ctxt, code)
204
205
206 class BashCompleteKeyValuePair(BashCompletionCode):
207 '''Used for completing a single of key-value pair.'''
208
209 # pylint: disable=too-many-arguments
210 # pylint: disable=too-many-positional-arguments
211
212 def __init__(self, ctxt, trace, completer, value_separator, values,
213 condition_func):
214 args = []
215
216 for key, _desc, complete in values:
217 if not complete:
218 func = 'false'
219 elif complete[0] == 'none':
220 func = 'true'
221 else:
222 obj = completer.complete_from_def(ctxt, trace, complete)
223 func = obj.get_function()
224
225 condition = ''
226 if condition_func is not None:
227 condition = '$c %s && ' % shell.quote(key)
228
229 args.append('%sa+=(%s %s)' % (
230 condition,
231 shell.quote(key),
232 shell.quote(func)))
233
234 code = 'local -a a=()\n'
235 if condition_func is not None:
236 code += 'local c=%s\n' % shell.quote(condition_func)
237 code += '%s\n' % '\n'.join(args)
238 code += '%s %s "${a[@]}"' % (
239 ctxt.helpers.use_function('key_value_pair'),
240 shell.quote(value_separator),
241 )
242
243 super().__init__(ctxt, code)
244
245
246 class BashCompleter(shell.ShellCompleter):
247 '''Code generator for completing arguments in Bash.'''
248
249 # pylint: disable=missing-function-docstring
250 # pylint: disable=too-many-public-methods
251 # pylint: disable=too-many-arguments
252 # pylint: disable=too-many-positional-arguments
253
254 def none(self, ctxt, _trace, *_):
255 return BashCompletionCode(ctxt, '')
256
257 def integer(self, ctxt, _trace, options=None):
258 suffixes = []
259
260 if options:
261 if 'suffixes' in options:
262 for suffix, description in options['suffixes'].items():
263 suffixes.append(f'{suffix}:{description}')
264
265 if not suffixes:
266 return BashCompletionCode(ctxt, '')
267
268 func = ctxt.helpers.use_function('number')
269 return BashCompletionFunc(ctxt, [func, *suffixes])
270
271 def float(self, ctxt, trace, options=None):
272 return self.integer(ctxt, trace, options)
273
274 def choices(self, ctxt, _trace, choices):
275 return CompgenW(ctxt, choices)
276
277 def command(self, ctxt, _trace, opts=None):
278 code = None
279 path = None
280 append = None
281 prepend = None
282
283 if opts:
284 path = opts.get('path', None)
285 append = opts.get('path_append', None)
286 prepend = opts.get('path_prepend', None)
287
288 if path:
289 code = 'local -x PATH=%s' % shell.quote(path)
290 elif append and prepend:
291 append = shell.quote(append)
292 prepend = shell.quote(prepend)
293 code = 'local -x PATH=%s:"$PATH":%s' % (prepend, append)
294 elif append:
295 code = 'local -x PATH="$PATH":%s' % shell.quote(append)
296 elif prepend:
297 code = 'local -x PATH=%s:"$PATH"' % shell.quote(prepend)
298
299 return BashCompletionCompgen(ctxt, '-A command', code=code)
300
301 def directory(self, ctxt, _trace, opts=None):
302 directory = None if opts is None else opts.get('directory', None)
303 filedir = bash_versions.filedir(ctxt)
304
305 if directory:
306 r = 'builtin pushd %s &>/dev/null && {\n' % shell.quote(directory)
307 r += ' %s -d\n' % filedir
308 r += ' builtin popd >/dev/null\n'
309 r += '}'
310 return BashCompletionCode(ctxt, r)
311
312 return BashCompletionFunc(ctxt, [filedir, '-d'])
313
314 def file(self, ctxt, _trace, opts=None):
315 fuzzy = False
316 directory = None
317 extensions = None
318 ignore_globs = None
319
320 if opts:
321 fuzzy = opts.get('fuzzy', False)
322 directory = opts.get('directory', None)
323 extensions = opts.get('extensions', None)
324 ignore_globs = opts.get('ignore_globs', None)
325
326 args = [bash_versions.filedir(ctxt)]
327
328 if extensions:
329 args.append(make_file_extension_pattern(extensions, fuzzy))
330
331 if not directory and not ignore_globs:
332 return BashCompletionFunc(ctxt, args)
333
334 if directory:
335 r = 'builtin pushd %s &>/dev/null && {\n' % shell.quote(directory)
336 r += ' %s\n' % shell.join_quoted(args)
337 r += ' builtin popd >/dev/null\n'
338 r += '}'
339 else:
340 r = shell.join_quoted(args)
341
342 if ignore_globs:
343 func = ctxt.helpers.use_function('file_filter')
344 r += '\n%s %s' % (func, shell.join_quoted(ignore_globs))
345
346 return BashCompletionCode(ctxt, r)
347
348 def mime_file(self, ctxt, _trace, pattern):
349 func = ctxt.helpers.use_function('mime_file')
350 return BashCompletionFunc(ctxt, [func, pattern])
351
352 def group(self, ctxt, _trace):
353 return BashCompletionCompgen(ctxt, '-A group')
354
355 def hostname(self, ctxt, _trace):
356 return BashCompletionCompgen(ctxt, '-A hostname')
357
358 def pid(self, ctxt, _trace):
359 return BashCompletionFunc(ctxt, [bash_versions.pids(ctxt)])
360
361 def process(self, ctxt, _trace):
362 return BashCompletionFunc(ctxt, [bash_versions.pnames(ctxt)])
363
364 def range(self, ctxt, _trace, start, stop, step=1):
365 if step == 1:
366 return BashCompletionCompgen(ctxt, f"-W '{{{start}..{stop}}}'")
367
368 return BashCompletionCompgen(ctxt, f"-W '{{{start}..{stop}..{step}}}'")
369
370 def service(self, ctxt, _trace):
371 return BashCompletionCompgen(ctxt, '-A service')
372
373 def user(self, ctxt, _trace):
374 return BashCompletionCompgen(ctxt, '-A user')
375
376 def variable(self, ctxt, _trace):
377 return BashCompletionCompgen(ctxt, '-A variable')
378
379 def environment(self, ctxt, _trace):
380 return BashCompletionCompgen(ctxt, '-A export')
381
382 def exec(self, ctxt, _trace, command):
383 func = ctxt.helpers.use_function('exec')
384 return BashCompletionFunc(ctxt, [func, command])
385
386 def exec_fast(self, ctxt, _trace, command):
387 func = ctxt.helpers.use_function('exec_fast')
388 return BashCompletionFunc(ctxt, [func, command])
389
390 def exec_internal(self, ctxt, _trace, command):
391 return BashCompletionCode(ctxt, command)
392
393 def value_list(self, ctxt, _trace, opts):
394 separator = opts.get('separator', ',')
395 duplicates = opts.get('duplicates', False)
396 values = opts['values']
397
398 if is_dict_type(values):
399 values = list(values.keys())
400
401 args = [ctxt.helpers.use_function('value_list')]
402 if duplicates:
403 ctxt.helpers.use_function('value_list', 'duplicates')
404 args.append('-d')
405 args.append(separator)
406
407 return BashCompletionFunc(ctxt, args + values)
408
409 def key_value_list(self, ctxt, trace, pair_separator, value_separator, values, condition_func=None):
410 return BashCompleteKeyValueList(ctxt, trace, self, pair_separator, value_separator, values, condition_func)
411
412 def key_value_pair(self, ctxt, trace, value_separator, values, condition_func=None):
413 return BashCompleteKeyValuePair(ctxt, trace, self, value_separator, values, condition_func)
414
415 def key_value_list_exec(self, ctxt, _trace, pair_separator, value_separator, command):
416 func = ctxt.helpers.use_function('key_value_list_exec')
417 return BashCompletionFunc(ctxt, [func, pair_separator, value_separator, command])
418
419 def key_value_pair_exec(self, ctxt, _trace, value_separator, command):
420 func = ctxt.helpers.use_function('key_value_pair_exec')
421 return BashCompletionFunc(ctxt, [func, value_separator, command])
422
423 def combine(self, ctxt, trace, commands):
424 return BashCompleteCombine(ctxt, trace, self, commands)
425
426 def list(self, ctxt, trace, command, opts=None):
427 separator = opts.get('separator', ',') if opts else ','
428 duplicates = opts.get('duplicates', False) if opts else False
429
430 obj = self.complete_from_def(ctxt, trace, command)
431 code = obj.get_code()
432
433 func = ctxt.helpers.use_function('value_list')
434
435 dup_arg = ''
436 if duplicates:
437 ctxt.helpers.use_function('value_list', 'duplicates')
438 dup_arg = ' -d'
439
440 r = 'local cur_old="$cur"\n'
441 r += 'cur="${cur##*%s}"\n' % shell.quote(separator)
442 r += '%s\n' % code
443 r += 'cur="$cur_old"\n'
444 r += '%s%s %s "${COMPREPLY[@]}"' % (func, dup_arg, shell.quote(separator))
445 return BashCompletionCode(ctxt, r)
446
447 def history(self, ctxt, _trace, pattern):
448 func = ctxt.helpers.use_function('history')
449 return BashCompletionFunc(ctxt, [func, pattern])
450
451 def commandline_string(self, ctxt, _trace):
452 func = ctxt.helpers.use_function('commandline_string')
453 return BashCompletionFunc(ctxt, [func])
454
455 def command_arg(self, ctxt, _trace):
456 return BashCompletionCode(ctxt, '')
457
458 def date(self, ctxt, _trace, _format):
459 return BashCompletionCode(ctxt, '')
460
461 def date_format(self, ctxt, _trace):
462 return BashCompletionCode(ctxt, '')
463
464 def uid(self, ctxt, _trace):
465 return BashCompletionFunc(ctxt, [bash_versions.uids(ctxt)])
466
467 def gid(self, ctxt, _trace):
468 return BashCompletionFunc(ctxt, [bash_versions.gids(ctxt)])
469
470 def signal(self, ctxt, _trace):
471 return BashCompletionFunc(ctxt, [bash_versions.signals(ctxt)])
472
473 def filesystem_type(self, ctxt, _trace):
474 return BashCompletionFunc(ctxt, [bash_versions.fstypes(ctxt)])
475
476 def prefix(self, ctxt, trace, prefix, command):
477 obj = self.complete_from_def(ctxt, trace, command)
478 func = obj.get_function()
479 prefix_func = ctxt.helpers.use_function('prefix')
480 return BashCompletionFunc(ctxt, [prefix_func, prefix, func])
481
482 def ip_address(self, ctxt, _trace, type_='all'):
483 func = bash_versions.ip_addresses(ctxt)
484
485 if type_ == 'ipv4':
486 return BashCompletionFunc(ctxt, [func])
487
488 if type_ == 'ipv6':
489 return BashCompletionFunc(ctxt, [func, '-6'])
490
491 if type_ == 'ipv4+':
492 code = f'{func}\n'
493 code += 'COMPREPLY+=($(compgen -W 0.0.0.0 -- "$cur"))'
494 return BashCompletionCode(ctxt, code)
495
496 if type_ == 'ipv6+':
497 code = f'{func} -6\n'
498 code += 'COMPREPLY+=($(compgen -W :: -- "$cur"))'
499 return BashCompletionCode(ctxt, code)
500
501 if type_ == 'all+':
502 code = f'{func} -a\n'
503 code += 'COMPREPLY+=($(compgen -W "0.0.0.0 ::" -- "$cur"))'
504 return BashCompletionCode(ctxt, code)
505
506 return BashCompletionFunc(ctxt, [func, '-a'])
507
508 # =========================================================================
509 # Bonus
510 # =========================================================================
511
512 def mountpoint(self, ctxt, _trace):
513 func = ctxt.helpers.use_function('mountpoint')
514 return BashCompletionFunc(ctxt, [func])
515
516 def locale(self, ctxt, trace):
517 func = ctxt.helpers.use_function('locales')
518 return BashCompletionFunc(ctxt, [func])
519
520 def charset(self, ctxt, trace):
521 func = ctxt.helpers.use_function('charsets')
522 return BashCompletionFunc(ctxt, [func])
523
524 def login_shell(self, ctxt, _trace):
525 return BashCompletionFunc(ctxt, [bash_versions.shells(ctxt)])
526
527 def net_interface(self, ctxt, _trace):
528 func = bash_versions.available_interfaces(ctxt)
529 return BashCompletionFunc(ctxt, [func])
530
531 def timezone(self, ctxt, _trace):
532 exec_func = ctxt.helpers.use_function('exec')
533 list_func = ctxt.helpers.use_function('timezone_list')
534 return BashCompletionFunc(ctxt, [exec_func, list_func])
535
536 def alsa_card(self, ctxt, _trace):
537 func = ctxt.helpers.use_function('alsa_list_cards')
538 return BashCompletionFunc(ctxt, [func])
539
540 def alsa_device(self, ctxt, _trace):
541 func = ctxt.helpers.use_function('alsa_list_devices')
542 return BashCompletionFunc(ctxt, [func])