Debian Codegraph @

crazy_complete/argparse_source.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 """
5 This module provides functions for creating CommandLine objects from
6 Python's argparse.ArgumentParser.
7 """
8
9 import argparse
10 from collections import OrderedDict
11
12 from . import file_loader
13 from . import utils
14 from .errors import CrazyError
15 from .cli import CommandLine, MutuallyExclusiveGroup
16
17 # We have to use implementation details of the argparse module...
18 # pylint: disable=protected-access
19 # pylint: disable=redefined-builtin
20
21
22 def range_to_complete(r):
23 '''Convert a Python range object to a range complete format.'''
24
25 start = r.start
26 step = r.step
27 end = r.stop - 1 if step > 0 else r.stop + 1
28
29 if step == 1:
30 return ('range', start, end)
31
32 return ('range', start, end, step)
33
34
35 def get_complete(action):
36 '''
37 Get the `complete` attribute of `action` if it is set.
38 Otherwise determine `complete` from action type.
39 '''
40
41 complete = action.get_complete()
42
43 if isinstance(action, (
44 argparse._HelpAction,
45 argparse._VersionAction,
46 argparse._StoreTrueAction,
47 argparse._StoreFalseAction,
48 argparse._StoreConstAction,
49 argparse._AppendConstAction,
50 argparse._CountAction)):
51
52 if complete:
53 utils.warn(f"Action has .complete() set but takes no arguments: {action}")
54
55 return None
56
57 if isinstance(action, (
58 argparse._StoreAction,
59 argparse._ExtendAction,
60 argparse._AppendAction)):
61
62 if complete:
63 if action.choices:
64 utils.warn(f"Action's choices overridden by .complete(): {action}")
65 return complete
66
67 if action.choices:
68 if isinstance(action.choices, range):
69 return range_to_complete(action.choices)
70 return ['choices', action.choices]
71
72 return ['none']
73
74 if isinstance(action, argparse.BooleanOptionalAction):
75 raise CrazyError("argparse.BooleanOptionalAction is not supported yet")
76
77 raise CrazyError(f'Unknown action type: {action}')
78
79
80 def get_final(action):
81 '''Return if an argparse action object is final.'''
82
83 if isinstance(action, (argparse._HelpAction, argparse._VersionAction)):
84 return True
85
86 return action.get_final()
87
88
89 def argumentparser_to_commandline(parser, prog=None, description=None):
90 '''Converts an ArgumentParser object to a CommandLine object.
91
92 Args:
93 parser (argparse.ArgumentParser):
94 The ArgumentParser object to convert.
95
96 prog (str, optional):
97 The name of the program.
98 Defaults to the program name of the parser.
99
100 description (str, optional):
101 The description of the program.
102 Defaults to the description of the parser.
103
104 Returns:
105 CommandLine: A CommandLine object representing the converted parser.
106 '''
107
108 # pylint: disable=too-many-locals
109 # pylint: disable=too-many-branches
110
111 if not description:
112 description = parser.description
113
114 if not prog:
115 prog = parser.prog
116
117 commandline = CommandLine(prog, help=description, aliases=parser.get_aliases())
118 positional_number = 0
119
120 for action in parser._actions:
121 if isinstance(action, argparse._SubParsersAction):
122 subparsers = OrderedDict()
123 for name, subparser in action.choices.items():
124 subparsers[name] = {'parser': subparser, 'help': None}
125
126 for subaction in action._get_subactions():
127 subparsers[subaction.dest]['help'] = subaction.help
128
129 subcommands = commandline.add_subcommands()
130 for name, data in subparsers.items():
131 subcmd = argumentparser_to_commandline(data['parser'], name, data['help'])
132 subcommands.add_commandline_object(subcmd)
133 elif not action.option_strings:
134 if action.nargs in ('+', '*'):
135 is_repeatable = True
136 elif action.nargs in (1, None, '?'):
137 is_repeatable = False
138 else:
139 is_repeatable = True
140 utils.warn(f'Truncating nargs={action.nargs} of {action}')
141
142 positional_number += 1
143 commandline.add_positional(
144 positional_number,
145 metavar = action.metavar or action.dest,
146 complete = get_complete(action),
147 help = action.help,
148 repeatable = is_repeatable,
149 when = action.get_when()
150 )
151 else:
152 complete = get_complete(action)
153 optional_arg = False
154 metavar = None
155 help = None
156
157 if action.nargs == '?':
158 optional_arg = True
159 elif action.nargs not in (None, 0, 1, True):
160 utils.warn(f'Truncating nargs={action.nargs} of {action}')
161
162 if complete:
163 metavar = action.metavar or action.dest
164
165 if action.help != argparse.SUPPRESS:
166 help = action.help
167
168 commandline.add_option(
169 action.option_strings,
170 metavar = metavar,
171 complete = complete,
172 help = help,
173 optional_arg = optional_arg,
174 repeatable = action.get_repeatable(),
175 final = get_final(action),
176 hidden = (action.help == argparse.SUPPRESS),
177 when = action.get_when()
178 )
179
180 group_counter = 0
181 for group in parser._mutually_exclusive_groups:
182 group_counter += 1
183 group_name = f'group{group_counter}'
184
185 exclusive_group = MutuallyExclusiveGroup(commandline, group_name)
186 for action in group._group_actions:
187 for option in commandline.get_options():
188 for option_string in action.option_strings:
189 if option_string in option.option_strings:
190 exclusive_group.add_option(option)
191 break
192
193 return commandline
194
195
196 def find_objects_by_type(module, types):
197 '''Search a module for objects of a specific type.'''
198
199 r = []
200
201 for obj_name in dir(module):
202 obj = getattr(module, obj_name)
203 if isinstance(obj, types):
204 r.append(obj)
205
206 return r
207
208
209 def find_root_argument_parsers(module):
210 '''Return a list of all ArgumentParser objects that have no parent.'''
211
212 parsers = find_objects_by_type(module, argparse.ArgumentParser)
213 actions = find_objects_by_type(module, argparse._SubParsersAction)
214
215 for action in actions:
216 for parser in action.choices.values():
217 try:
218 parsers.remove(parser)
219 except ValueError:
220 pass
221
222 return parsers
223
224
225 def load_from_file(file, parser_variable=None, parser_blacklist=()):
226 '''
227 Load a Python file, search for the ArgumentParser object and convert
228 it to a CommandLine object.
229 '''
230
231 # pylint: disable=broad-exception-caught
232
233 try:
234 module = file_loader.import_file(file)
235 except Exception as e:
236 utils.warn(e)
237 utils.warn(f"Failed to load `{file}` using importlib, falling back to exec")
238 module = file_loader.execute_file(file)
239
240 if parser_variable is not None:
241 try:
242 parser = getattr(module, parser_variable)
243 except AttributeError:
244 raise CrazyError(f"No variable named `{parser_variable}` found in `{file}`") from None
245 else:
246 parsers = find_root_argument_parsers(module)
247 for blacklisted in parser_blacklist:
248 try:
249 parsers.remove(blacklisted)
250 except ValueError:
251 pass
252 if len(parsers) == 0:
253 raise CrazyError(f"Could not find any ArgumentParser object in `{file}`")
254 if len(parsers) > 1:
255 raise CrazyError(f"Found too many ArgumentParser objects in `{file}`")
256 parser = parsers[0]
257
258 return argumentparser_to_commandline(parser)