Debian Codegraph @

crazy_complete/fish_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 Fish.'''
5
6 from . import shell
7 from . import utils
8 from .pattern import bash_glob_to_regex
9 from .type_utils import is_dict_type
10 from .str_utils import indent, join_with_wrap
11
12
13 CHOICES_INLINE_THRESHOLD = 80
14 # The `choices` command can in Fish be expressed inline in a complete command
15 # like this:
16 # complete -c program -a 'foo bar baz'
17 # or:
18 # complete -c program -a 'foo\t"Foo value" bar\t"Bar value" baz\t"Baz value"'
19 #
20 # This variable defines how big this string can get before a function
21 # is used instead.
22
23
24 class FishCompletionBase:
25 '''Base class for Fish completions.'''
26
27 def __init__(self, ctxt):
28 self.ctxt = ctxt
29
30 def get_args(self):
31 '''Return a list of arguments to be appended to the `complete`
32 command in Fish.
33
34 The returned arguments should be in raw form, without any escaping.
35 Escaping will be handled at a later stage.
36 '''
37 raise NotImplementedError
38
39 def get_code(self):
40 '''Return the code that can be used for completing an argument.'''
41 raise NotImplementedError
42
43 def get_function(self):
44 '''Return a function that runs the code.'''
45 func = self.ctxt.helpers.add_dynamic_func(self.ctxt, self.get_code())
46 return func
47
48
49 class FishCompleteNone(FishCompletionBase):
50 '''Class for completing an argument without a completer.'''
51
52 def get_args(self):
53 return ['-f']
54
55 def get_code(self):
56 return ''
57
58 def get_function(self):
59 return 'true'
60
61
62 class FishCompletionCommand(FishCompletionBase):
63 '''Class for executing a command.'''
64
65 def __init__(self, ctxt, args):
66 super().__init__(ctxt)
67 self.args = args
68
69 def get_code(self):
70 return shell.join_quoted(self.args)
71
72 def get_args(self):
73 command = shell.join_quoted(self.args)
74 return ['-f', '-a', '(%s)' % command]
75
76 def get_function(self):
77 if len(self.args) == 1:
78 return self.args[0]
79
80 func = self.ctxt.helpers.add_dynamic_func(self.ctxt, self.get_code())
81 return func
82
83
84 class FishCompletionRawCommand(FishCompletionBase):
85 '''Class for executing a command (without any escaping)'''
86
87 def __init__(self, ctxt, command):
88 super().__init__(ctxt)
89 self.command = command
90
91 def get_code(self):
92 return self.command
93
94 def get_args(self):
95 return ['-f', '-a', '(%s)' % self.command]
96
97
98 class FishCompleteChoices(FishCompletionBase):
99 '''Class for completing choices.'''
100
101 def __init__(self, ctxt, choices):
102 super().__init__(ctxt)
103 self.choices = choices
104
105 def _get_inline_for_list(self):
106 return ' '.join(shell.quote(str(c)) for c in self.choices)
107
108 def _get_inline_for_dict(self):
109 def str0(s):
110 return str(s) if s is not None else ''
111
112 stringified = {str(item): str0(desc) for item, desc in self.choices.items()}
113 q = shell.quote
114 r = ['%s\\t%s' % (q(item), q(desc)) for item, desc in stringified.items()]
115 return ' '.join(r)
116
117 def _get_code_for_list(self):
118 code = "printf '%s\\n' \\\n"
119 quoted = [shell.quote(str(item)) for item in self.choices]
120 line_length = self.ctxt.config.line_length - 2
121 code += indent(join_with_wrap(' ', ' \\\n', line_length, quoted), 2)
122 return code.rstrip(' \\\n')
123
124 def _get_code_for_dict(self):
125 code = "printf '%s\\t%s\\n' \\\n"
126 for item, desc in self.choices.items():
127 if desc is None:
128 desc = ''
129 code += ' %s %s \\\n' % (shell.quote(str(item)), shell.quote(str(desc)))
130 return code.rstrip(' \\\n')
131
132 def get_args(self):
133 if is_dict_type(self.choices):
134 arg = self._get_inline_for_dict()
135 else:
136 arg = self._get_inline_for_list()
137
138 if len(arg) <= CHOICES_INLINE_THRESHOLD:
139 return ['-f', '-a', arg]
140
141 func = self.get_function()
142 return ['-f', '-a', '(%s)' % func]
143
144 def get_code(self):
145 if is_dict_type(self.choices):
146 return self._get_code_for_dict()
147 return self._get_code_for_list()
148
149
150 def _get_extension_regex(extensions, fuzzy):
151 patterns = []
152
153 for extension in extensions:
154 pattern = ''
155 for c in extension:
156 if c.isalpha():
157 pattern += '[%s%s]' % (c.lower(), c.upper())
158 elif c in ('.', '+'):
159 pattern += f'\\{c}'
160 else:
161 pattern += c
162
163 if fuzzy:
164 pattern += '.*'
165
166 patterns.append(pattern)
167
168 return '|'.join(f'(.*\\.{pattern})' for pattern in patterns)
169
170
171 class FishCompleteFile(FishCompletionBase):
172 '''Class for completing files.'''
173
174 def __init__(self, ctxt, opts):
175 super().__init__(ctxt)
176
177 fuzzy = False
178 directory = None
179 extensions = None
180 ignore_globs = None
181 self.args = []
182
183 if opts:
184 fuzzy = opts.get('fuzzy', False)
185 directory = opts.get('directory', None)
186 extensions = opts.get('extensions', None)
187 ignore_globs = opts.get('ignore_globs', None)
188
189 if directory:
190 self.args.extend(['-C', directory])
191
192 if extensions:
193 ctxt.helpers.use_function('filedir', 'regex')
194 self.args.extend(['-r', _get_extension_regex(extensions, fuzzy)])
195
196 if ignore_globs:
197 ctxt.helpers.use_function('filedir', 'regex_ignore')
198 patterns = map(bash_glob_to_regex, ignore_globs)
199 patterns = [f'({p})' for p in patterns]
200 self.args.extend(['-i', '|'.join(patterns)])
201
202 def get_args(self):
203 if len(self.args) == 0:
204 return ['-F']
205
206 func = self.ctxt.helpers.use_function('filedir')
207 return FishCompletionCommand(self.ctxt, [func] + self.args).get_args()
208
209 def get_code(self):
210 func = self.ctxt.helpers.use_function('filedir')
211 return FishCompletionCommand(self.ctxt, [func] + self.args).get_code()
212
213 def get_function(self):
214 func = self.ctxt.helpers.use_function('filedir')
215 return FishCompletionCommand(self.ctxt, [func] + self.args).get_function()
216
217
218 class FishCompleteDirectory(FishCompletionCommand):
219 '''Class for completing directories.'''
220
221 def __init__(self, ctxt, trace, opts):
222 directory = None if opts is None else opts.get('directory', None)
223
224 # __fish_complete_directories does not respect __fish_stripprefix
225 # which is used inside list/key_value_list/key_value_pair/prefix
226 use_filedir = (
227 'list' in trace or
228 'key_value_list' in trace or
229 'key_value_pair' in trace or
230 'prefix' in trace
231 )
232
233 if directory is not None:
234 func = ctxt.helpers.use_function('filedir')
235 super().__init__(ctxt, [func, '-D', '-C', directory])
236 elif use_filedir:
237 func = ctxt.helpers.use_function('filedir')
238 super().__init__(ctxt, [func, '-D'])
239 else:
240 super().__init__(ctxt, ['__fish_complete_directories'])
241
242
243 class FishCompleteValueList(FishCompletionCommand):
244 '''Class for completing a list of values.'''
245
246 def __init__(self, ctxt, opts):
247 separator = opts.get('separator', ',')
248 duplicates = opts.get('duplicates', False)
249 values = opts['values']
250
251 if is_dict_type(values):
252 code = "printf '%s\\t%s\\n' \\\n"
253 for item, desc in values.items():
254 code += ' %s %s \\\n' % (shell.quote(item), shell.quote(desc))
255 code = code.rstrip(' \\\n')
256 else:
257 code = "printf '%s\\n' \\\n"
258 for value in values:
259 code += ' %s \\\n' % shell.quote(value)
260 code = code.rstrip(' \\\n')
261
262 func = ctxt.helpers.add_dynamic_func(ctxt, code)
263
264 if duplicates:
265 super().__init__(ctxt, ['__fish_complete_list', separator, func])
266 else:
267 complete_list_func = ctxt.helpers.use_function('list')
268 super().__init__(ctxt, [complete_list_func, separator, func])
269
270
271 class FishCompleteKeyValueList(FishCompletionCommand):
272 '''Used for completing a list of key-value pairs.'''
273
274 # pylint: disable=too-many-arguments
275 # pylint: disable=too-many-positional-arguments
276
277 def __init__(self, ctxt, trace, completer, pair_separator, value_separator,
278 values, condition_func):
279 trace.append('key_value_list')
280
281 args = []
282
283 for definition in utils.get_key_value_list_definitions(values):
284 if not definition.completer:
285 func = 'false'
286 elif definition.completer[0] == 'none':
287 func = 'true'
288 else:
289 obj = completer.complete_from_def(ctxt, trace, definition.completer)
290 func = obj.get_function()
291
292 excludes = []
293 if not definition.repeatable:
294 excludes.append(definition.key)
295 excludes.extend(definition.excludes)
296
297 condition = ''
298 if condition_func is not None:
299 condition = '$c %s && ' % (shell.quote(definition.key))
300
301 args.append('%sset -a a %s %s %s %s' % (
302 condition,
303 shell.quote(definition.key),
304 shell.quote(definition.description or ''),
305 shell.quote(func),
306 shell.quote(' '.join(excludes))))
307
308 code = 'set -l a\n'
309 if condition_func is not None:
310 code += 'set -l c %s\n' % shell.quote(condition_func)
311 code += '%s\n' % '\n'.join(args)
312 code += '%s %s %s $a' % (
313 ctxt.helpers.use_function('key_value_list'),
314 shell.quote(pair_separator),
315 shell.quote(value_separator),
316 )
317
318 func = ctxt.helpers.add_dynamic_func(ctxt, code)
319
320 super().__init__(ctxt, [func])
321
322
323 class FishCompleteKeyValuePair(FishCompletionCommand):
324 '''Used for completing a single key-value pair.'''
325
326 # pylint: disable=too-many-arguments
327 # pylint: disable=too-many-positional-arguments
328
329 def __init__(self, ctxt, trace, completer, value_separator, values,
330 condition_func):
331 trace.append('key_value_pair')
332
333 args = []
334
335 for key, desc, complete in values:
336 if not complete:
337 func = 'false'
338 elif complete[0] == 'none':
339 func = 'true'
340 else:
341 obj = completer.complete_from_def(ctxt, trace, complete)
342 func = obj.get_function()
343
344 condition = ''
345 if condition_func is not None:
346 condition = '$c %s && ' % shell.quote(condition_func)
347
348 args.append('%sset -a a %s %s %s' % (
349 condition,
350 shell.quote(key),
351 shell.quote(desc or ''),
352 shell.quote(func)))
353
354 code = 'set -l a\n'
355 if condition_func is not None:
356 code += 'set -l c %s\n' % shell.quote(condition_func)
357 code += '%s\n' % '\n'.join(args)
358 code += '%s %s $a' % (
359 ctxt.helpers.use_function('key_value_pair'),
360 shell.quote(value_separator),
361 )
362
363 func = ctxt.helpers.add_dynamic_func(ctxt, code)
364
365 super().__init__(ctxt, [func])
366
367
368 class FishCompleteCommand(FishCompletionBase):
369 '''Complete a command from $PATH.'''
370
371 def __init__(self, ctxt, opts):
372 super().__init__(ctxt)
373
374 code = None
375 path = None
376 append = None
377 prepend = None
378
379 if opts:
380 path = opts.get('path', None)
381 append = opts.get('path_append', None)
382 prepend = opts.get('path_prepend', None)
383
384 def mkpath(path):
385 return shell.join_quoted(path.split(':'))
386
387 if path:
388 code = 'set -lx PATH %s' % mkpath(path)
389 elif append and prepend:
390 code = 'set -lx PATH %s $PATH %s' % (mkpath(prepend), mkpath(append))
391 elif append:
392 code = 'set -lx -a PATH %s' % mkpath(append)
393 elif prepend:
394 code = 'set -lx PATH %s $PATH' % mkpath(prepend)
395
396 if not code:
397 self.code = "__fish_complete_command"
398 else:
399 self.code = f'{code}\n__fish_complete_command'
400
401 def get_args(self):
402 if '\n' in self.code:
403 func = self.ctxt.helpers.add_dynamic_func(self.ctxt, self.code)
404 return ['-f', '-a', '(%s)' % func]
405
406 return ['-f', '-a', '(%s)' % self.code]
407
408 def get_code(self):
409 return self.code
410
411
412 class FishCompleteCombine(FishCompletionBase):
413 '''Used for combining multiple complete commands.'''
414
415 def __init__(self, ctxt, trace, completer, commands):
416 super().__init__(ctxt)
417
418 self.code = []
419 trace.append('combine')
420
421 for command in commands:
422 obj = completer.complete_from_def(ctxt, trace, command)
423 self.code.append(obj.get_code())
424
425 def get_code(self):
426 return '\n'.join(self.code)
427
428 def get_args(self):
429 code_is_singleline = not any('\n' in code for code in self.code)
430
431 if code_is_singleline:
432 return ['-f', '-a', '(%s)' % '; '.join(self.code)]
433
434 code = '\n'.join(self.code)
435 func = self.ctxt.helpers.add_dynamic_func(self.ctxt, code)
436 return ['-f', '-a', '(%s)' % func]
437
438
439 class FishCompleteCommandArg(FishCompletionBase):
440 '''Complete an argument of a command'''
441
442 def __init__(self, ctxt):
443 super().__init__(ctxt)
444
445 ctxt.helpers.use_function('query_init', 'positional_position')
446 pos_pos_func = ctxt.helpers.use_function('positional_position')
447 command_pos = ctxt.option.get_positional_num() - 1
448
449 r = 'set -l pos (%s %d)\n' % (pos_pos_func, command_pos)
450 r += 'set -l cmdline (commandline -poc | string escape) (commandline -ct)\n'
451 r += 'complete -C -- "$cmdline[$pos..]"'
452
453 self.code = r
454
455 def get_code(self):
456 return self.code
457
458 def get_args(self):
459 func = self.ctxt.helpers.add_dynamic_func(self.ctxt, self.code)
460 return ['-f', '-a', '(%s)' % func]
461
462 def get_function(self):
463 func = self.ctxt.helpers.add_dynamic_func(self.ctxt, self.code)
464 return func
465
466
467 class FishCompleter(shell.ShellCompleter):
468 '''Code generator for completing arguments in Fish.'''
469
470 # pylint: disable=missing-function-docstring
471 # pylint: disable=too-many-public-methods
472 # pylint: disable=too-many-arguments
473 # pylint: disable=too-many-positional-arguments
474
475 def none(self, ctxt, _trace, *_):
476 return FishCompleteNone(ctxt)
477
478 def integer(self, ctxt, _trace, options=None):
479 suffixes = []
480
481 if options:
482 if 'suffixes' in options:
483 for suffix, description in options['suffixes'].items():
484 suffixes.append(f'{suffix}:{description}')
485
486 if not suffixes:
487 return FishCompleteNone(ctxt)
488
489 func = ctxt.helpers.use_function('number')
490 return FishCompletionCommand(ctxt, [func, *suffixes])
491
492 def float(self, ctxt, trace, options=None):
493 return self.integer(ctxt, trace, options)
494
495 def choices(self, ctxt, _trace, choices):
496 return FishCompleteChoices(ctxt, choices)
497
498 def command(self, ctxt, _trace, opts=None):
499 return FishCompleteCommand(ctxt, opts)
500
501 def directory(self, ctxt, trace, opts=None):
502 return FishCompleteDirectory(ctxt, trace, opts)
503
504 def file(self, ctxt, _trace, opts=None):
505 return FishCompleteFile(ctxt, opts)
506
507 def mime_file(self, ctxt, _trace, pattern):
508 func = ctxt.helpers.use_function('mime_file')
509 return FishCompletionCommand(ctxt, [func, pattern])
510
511 def group(self, ctxt, _trace):
512 return FishCompletionCommand(ctxt, ["__fish_complete_groups"])
513
514 def hostname(self, ctxt, _trace):
515 return FishCompletionCommand(ctxt, ["__fish_print_hostnames"])
516
517 def pid(self, ctxt, _trace):
518 return FishCompletionCommand(ctxt, ["__fish_complete_pids"])
519
520 def process(self, ctxt, _trace):
521 return FishCompletionCommand(ctxt, ["__fish_complete_proc"])
522
523 def range(self, ctxt, _trace, start, stop, step=1):
524 if step == 1:
525 return FishCompletionCommand(ctxt, ['seq', str(start), str(stop)])
526
527 return FishCompletionCommand(ctxt, ['seq', str(start), str(step), str(stop)])
528
529 def service(self, ctxt, _trace):
530 return FishCompletionCommand(ctxt, ["__fish_systemctl_services"])
531
532 def user(self, ctxt, _trace):
533 return FishCompletionCommand(ctxt, ["__fish_complete_users"])
534
535 def variable(self, ctxt, _trace):
536 return FishCompletionCommand(ctxt, ["set", "-n"])
537
538 def environment(self, ctxt, _trace):
539 return FishCompletionCommand(ctxt, ["set", "-n", "-x"])
540
541 def exec(self, ctxt, _trace, command):
542 return FishCompletionRawCommand(ctxt, command)
543
544 def exec_fast(self, ctxt, _trace, command):
545 return FishCompletionRawCommand(ctxt, command)
546
547 def exec_internal(self, ctxt, _trace, command):
548 return FishCompletionRawCommand(ctxt, command)
549
550 def value_list(self, ctxt, _trace, opts):
551 return FishCompleteValueList(ctxt, opts)
552
553 def key_value_list(self, ctxt, trace, pair_separator, value_separator, values, condition_func=None):
554 return FishCompleteKeyValueList(ctxt, trace, self, pair_separator, value_separator, values, condition_func)
555
556 def key_value_pair(self, ctxt, trace, value_separator, values, condition_func=None):
557 return FishCompleteKeyValuePair(ctxt, trace, self, value_separator, values, condition_func)
558
559 def key_value_list_exec(self, ctxt, _trace, pair_separator, value_separator, command):
560 func = ctxt.helpers.use_function('key_value_list_exec')
561 return FishCompletionCommand(ctxt, [func, pair_separator, value_separator, command])
562
563 def key_value_pair_exec(self, ctxt, _trace, value_separator, command):
564 func = ctxt.helpers.use_function('key_value_pair_exec')
565 return FishCompletionCommand(ctxt, [func, value_separator, command])
566
567 def combine(self, ctxt, trace, commands):
568 return FishCompleteCombine(ctxt, trace, self, commands)
569
570 def list(self, ctxt, trace, command, opts=None):
571 separator = opts.get('separator', ',') if opts else ','
572 duplicates = opts.get('duplicates', False) if opts else False
573 trace.append('list')
574
575 obj = self.complete_from_def(ctxt, trace, command)
576 func = obj.get_function()
577
578 list_func = ctxt.helpers.use_function('list')
579 if not duplicates:
580 return FishCompletionCommand(ctxt, [list_func, separator, func])
581
582 return FishCompletionCommand(ctxt, [list_func, '-d', separator, func])
583
584 def history(self, ctxt, _trace, pattern):
585 func = ctxt.helpers.use_function('history')
586 return FishCompletionCommand(ctxt, [func, pattern])
587
588 def commandline_string(self, ctxt, _trace):
589 func = ctxt.helpers.use_function('commandline_string')
590 return FishCompletionCommand(ctxt, [func])
591
592 def command_arg(self, ctxt, _trace):
593 return FishCompleteCommandArg(ctxt)
594
595 def date(self, ctxt, _trace, _format):
596 return FishCompleteNone(ctxt)
597
598 def date_format(self, ctxt, _trace):
599 func = ctxt.helpers.use_function('date_format')
600 return FishCompletionCommand(ctxt, [func])
601
602 def uid(self, ctxt, _trace):
603 return FishCompletionCommand(ctxt, ['__fish_complete_user_ids'])
604
605 def gid(self, ctxt, _trace):
606 return FishCompletionCommand(ctxt, ['__fish_complete_group_ids'])
607
608 def filesystem_type(self, ctxt, _trace):
609 return FishCompletionCommand(ctxt, ['__fish_print_filesystems'])
610
611 def prefix(self, ctxt, trace, prefix, command):
612 obj = self.complete_from_def(ctxt, trace, command)
613 func = obj.get_function()
614
615 prefix_func = ctxt.helpers.use_function('prefix')
616 return FishCompletionCommand(ctxt, [prefix_func, prefix, func])
617
618 def ip_address(self, ctxt, _trace, type_='all'):
619 func = '__fish_print_addresses'
620
621 if type_ == 'ipv4':
622 cmd = f"{func} | string match -e '.'"
623 return FishCompletionRawCommand(ctxt, cmd)
624
625 if type_ == 'ipv6':
626 cmd = f"{func} | string match -e ':'"
627 return FishCompletionRawCommand(ctxt, cmd)
628
629 if type_ == 'ipv4+':
630 cmd = f"{func} --all | string match -e '.'"
631 return FishCompletionRawCommand(ctxt, cmd)
632
633 if type_ == 'ipv6+':
634 cmd = f"{func} --all | string match -e ':'"
635 return FishCompletionRawCommand(ctxt, cmd)
636
637 if type_ == 'all+':
638 return FishCompletionCommand(ctxt, [func, '--all'])
639
640 return FishCompletionCommand(ctxt, [func])
641
642 # =========================================================================
643 # Bonus
644 # =========================================================================
645
646 def net_interface(self, ctxt, _trace):
647 return FishCompletionCommand(ctxt, ['__fish_print_interfaces'])
648
649 def mountpoint(self, ctxt, _trace):
650 return FishCompletionCommand(ctxt, ['__fish_print_mounted'])
651
652 def timezone(self, ctxt, _trace):
653 func = ctxt.helpers.use_function('timezone_list')
654 return FishCompletionCommand(ctxt, [func])
655
656 def alsa_card(self, ctxt, _trace):
657 func = ctxt.helpers.use_function('alsa_list_cards')
658 return FishCompletionCommand(ctxt, [func])
659
660 def alsa_device(self, ctxt, _trace):
661 func = ctxt.helpers.use_function('alsa_list_devices')
662 return FishCompletionCommand(ctxt, [func])