Debian Codegraph @

crazy_complete/bash_parser_subcommand_code.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 '''Code for creating the subcommand switch code in Bash'''
5
6 from collections import OrderedDict
7
8 from . import utils
9 from . import shell
10 from . import bash_patterns
11 from .str_utils import indent
12
13
14 def get_subcommand_path(commandline):
15 '''Return the path for `commandline`.'''
16 commandlines = commandline.get_parents(include_self=True)[1:]
17 prognames = ['root'] + [c.prog for c in commandlines]
18 return ':'.join(prognames)
19
20
21 def make_subcommand_switch_code(commandline):
22 '''
23 Generate Bash code that tracks and updates the current subcommand path.
24
25 This function walks through all known command lines (starting from the
26 given top-level `commandline`) and generates conditional Bash code that
27 appends the currently matched subcommand to the `cmd` variable. This
28 allows the generated completion script to keep track of the full
29 subcommand hierarchy as the user types.
30
31 While tracking, all variations of a subcommand are considered, including
32 defined aliases and any supported abbreviations. This ensures that the
33 resulting `cmd` variable always contains the canonical subcommand name,
34 regardless of how the user typed it.
35 '''
36
37 assert commandline.parent is None, \
38 "This function should only be used on top-level command lines"
39
40 cases = []
41
42 for cmdline in commandline.get_all_commandlines():
43 if not cmdline.get_subcommands():
44 continue
45
46 positional_num = cmdline.get_subcommands().get_positional_num()
47 command_path = get_subcommand_path(cmdline)
48 switch_code = _make_switch_case(cmdline)
49
50 cases.append(('%s|%d' % (command_path, positional_num), switch_code))
51
52 if not cases:
53 return None
54
55 r = 'case "$cmd|${#POSITIONALS[@]}" in\n'
56 for case in cases:
57 if '\n' not in case[1]:
58 r += ' %s) %s;;\n' % (shell.quote(case[0]), case[1])
59 else:
60 r += ' %s)\n%s;;\n' % (shell.quote(case[0]), indent(case[1], 4))
61 r += 'esac'
62
63 return r
64
65
66 def _make_switch_case(cmdline):
67 subcommand_aliases = OrderedDict()
68
69 for subcommand in cmdline.get_subcommands().subcommands:
70 aliases = utils.get_all_command_variations(subcommand)
71 aliases.remove(subcommand.prog)
72
73 if aliases:
74 subcommand_aliases[subcommand.prog] = aliases
75
76 # We have no aliases or abbreviations, just add $arg to $cmd
77 if not subcommand_aliases:
78 return 'cmd+=":$arg"'
79
80 r = 'case "$arg" in\n'
81 for command, aliases in subcommand_aliases.items():
82 r += ' %s) cmd+=":%s";;\n' % (bash_patterns.make_pattern(aliases), command)
83 r += ' *) cmd+=":$arg";;\n'
84 r += 'esac'
85 return r