Debian Codegraph @

crazy_complete/bash_parser_v2.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 '''Code for parsing a command line in Bash, version 2'''
5
6 from collections import namedtuple
7
8 from . import utils
9 from . import shell
10 from . import bash_patterns
11 from .str_utils import indent
12 from .bash_parser_subcommand_code import (
13 make_subcommand_switch_code, get_subcommand_path
14 )
15 from .preprocessor import preprocess
16
17 _PARSER_CODE = '''\
18 #ifdef positionals
19 POSITIONALS=()
20 #endif
21 END_OF_OPTIONS=0
22
23 local cmd="root" argi arg i char trailing_chars VAR ARGS
24
25 %FIND_OPTION_CODE%
26
27 __append_to_array() {
28 local -n arr=$1
29 arr+=("$2")
30 }
31
32 for ((argi=1; argi < cword; ++argi)); do
33 arg="${words_dequoted[argi]}"
34
35 case "$arg" in
36 --)
37 END_OF_OPTIONS=1
38 #ifdef positionals
39 POSITIONALS+=("${words_dequoted[@]:$((++argi))}")
40 #endif
41 return;;
42 #ifdef long_options
43 --*=*)
44 if __find_option "$cmd" "${arg%%=*}"
45 then __append_to_array "$VAR" "${arg#*=}"
46 fi;;
47 --*)
48 if __find_option "$cmd" "$arg"; then
49 if [[ "$ARGS" == 1 ]]
50 then __append_to_array "$VAR" "${words_dequoted[++argi]}"
51 else __append_to_array "$VAR" "_OPT_ISSET_"
52 fi
53 fi;;
54 #else
55 --*);;
56 #endif
57 -?*) # ignore '-'
58 #ifdef old_options
59 if [[ "$arg" == -*=* ]]; then
60 if __find_option "$cmd" "${arg%%=*}"; then
61 __append_to_array "$VAR" "${arg#*=}"
62 continue
63 fi
64 fi
65
66 if __find_option "$cmd" "$arg"; then
67 if [[ "$ARGS" == 1 ]]
68 then __append_to_array "$VAR" "${words_dequoted[++argi]}"
69 else __append_to_array "$VAR" "_OPT_ISSET_"
70 fi
71
72 continue
73 fi
74 #endif
75
76 #ifdef short_options
77 for ((i=1; i < ${#arg}; ++i)); do
78 char="${arg:$i:1}"
79 trailing_chars="${arg:$((i + 1))}"
80
81 if __find_option "$cmd" "-$char"; then
82 if [[ "$ARGS" == 1 ]]; then
83 if [[ -n "$trailing_chars" ]]
84 then __append_to_array "$VAR" "$trailing_chars"
85 else __append_to_array "$VAR" "${words_dequoted[++argi]}"
86 fi
87 break;
88 #ifdef short_optionals
89 elif [[ "$ARGS" == '?' ]]; then
90 if [[ -n "$trailing_chars" ]]
91 then __append_to_array "$VAR" "$trailing_chars"
92 else __append_to_array "$VAR" _OPT_ISSET_
93 fi
94 break;
95 #endif
96 else
97 __append_to_array "$VAR" "_OPT_ISSET_"
98 fi
99 fi
100 done
101 #endif
102 ;;
103 #ifdef positionals
104 *)
105 POSITIONALS+=("$arg")
106 %SUBCOMMAND_SWITCH_CODE%
107 ;;
108 #endif
109 esac
110 done
111 #ifdef positionals
112
113 for ((; argi <= cword; ++argi)); do
114 case "${words_dequoted[argi]}" in
115 -?*);;
116 *) POSITIONALS+=("${words_dequoted[argi]}");;
117 esac
118 done
119 #endif'''
120
121 _OPT_ISSET = '_OPT_ISSET_'
122
123
124 def _make_find_option_code(commandline, variable_manager):
125 cmdlines = list(reversed(commandline.get_all_commandlines()))
126 code = []
127
128 if len(cmdlines) == 1:
129 code += [_make_cmd_plus_option_switch_code(cmdlines[0], variable_manager, True)]
130 else:
131 for cmdline in cmdlines:
132 code += [_make_cmd_plus_option_switch_code(cmdline, variable_manager)]
133
134 r = '__find_option() {\n'
135 r += '%s\n' % indent('\n'.join(filter(None, code)), 2)
136 r += ' return 1\n'
137 r += '}'
138 return r
139
140
141 def _make_cmd_plus_option_switch_code(commandline, variable_manager, omit_cmd_check=False):
142 option_cases = _generate_option_cases(commandline, variable_manager)
143 if not option_cases:
144 return None
145
146 if omit_cmd_check:
147 return _make_option_switch_code(option_cases)
148
149 command = get_subcommand_path(commandline)
150 command = shell.quote(command)
151 if commandline.inherit_options:
152 command += '*'
153
154 r = f'case "$1" in {command})\n'
155 r += '%s\n' % indent(_make_option_switch_code(option_cases), 2)
156 r += 'esac'
157 return r
158
159
160 def _make_option_switch_code(option_cases):
161 r = 'case "$2" in\n'
162
163 for case in option_cases:
164 pattern = bash_patterns.make_pattern(case.option_strings)
165 r += f' {pattern}) VAR={case.variable}; ARGS={case.args}; return;;\n'
166
167 r += 'esac'
168 return r
169
170
171 def generate(commandline, variable_manager):
172 '''Generate code for parsing the command line.'''
173
174 find_option_code = _make_find_option_code(commandline, variable_manager)
175 subcommand_switch_code = make_subcommand_switch_code(commandline)
176
177 defines = []
178 types = utils.get_defined_option_types(commandline)
179 if types.short:
180 defines.append('short_options')
181 if types.long:
182 defines.append('long_options')
183 if types.old:
184 defines.append('old_options')
185 if types.short_optional:
186 defines.append('short_optionals')
187 if types.positionals:
188 defines.append('positionals')
189
190 s = preprocess(_PARSER_CODE, defines)
191
192 if subcommand_switch_code:
193 s = s.replace('%SUBCOMMAND_SWITCH_CODE%',
194 indent(subcommand_switch_code, 6))
195 else:
196 s = s.replace('%SUBCOMMAND_SWITCH_CODE%\n', '')
197
198 if find_option_code:
199 s = s.replace('%FIND_OPTION_CODE%', find_option_code)
200 else:
201 s = s.replace('%FIND_OPTION_CODE%\n', '')
202
203 return s
204
205
206 def _generate_option_cases(commandline, variable_manager):
207 OptionCase = namedtuple('OptionCase', ['option_strings', 'variable', 'args'])
208 options = commandline.get_options()
209 abbreviations = utils.get_option_abbreviator(commandline)
210 option_cases = []
211
212 for option in options:
213 option_strings = option.get_short_option_strings()
214
215 option_strings += abbreviations.get_many_abbreviations(
216 option.get_long_option_strings())
217
218 option_strings += abbreviations.get_many_abbreviations(
219 option.get_old_option_strings())
220
221 value_variable = variable_manager.capture_variable(option)
222
223 if option.has_optional_arg():
224 args = "'?'"
225 elif option.has_required_arg():
226 args = '1'
227 else:
228 args = '0'
229
230 option_cases.append(OptionCase(option_strings, value_variable, args))
231
232 return option_cases