Debian Codegraph @

crazy_complete/application.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 '''Class for main command line application.'''
5
6 import os
7 import sys
8 import shlex
9 import argparse
10
11 from .errors import CrazyError
12 from . import bash, fish, zsh
13 from . import argparse_source, json_source, yaml_source
14 from . import argparse_mod # .complete()
15 from . import help_converter
16 from . import utils
17 from . import config
18 from . import paths
19
20
21 # The import of `argparse_mod` only modifies the classes provided by the
22 # argparse module. We use the dummy function to silence warnings about the
23 # unused import.
24 argparse_mod.dummy()
25
26
27 def boolean(string):
28 '''Convert string to bool, else raise ValueError.'''
29
30 try:
31 return {'true': True, 'false': False}[string.lower()]
32 except KeyError as e:
33 raise ValueError(f"Not a bool: {string}") from e
34
35
36 def version(string):
37 '''Parse a version.'''
38
39 return tuple(map(int, string.split('.')))
40
41
42 def feature_list(string):
43 '''Convert a comma separated string of features to list.'''
44
45 features = string.split(',')
46
47 for feature in features:
48 if feature not in ('hidden', 'final', 'groups', 'repeatable', 'when'):
49 raise ValueError(f"Invalid feature: {feature}")
50
51 return features
52
53 _URL = "https://github.com/crazy-complete/crazy-complete"
54 _EPILOG = f"For complete documentation, see {_URL}"
55
56 p = argparse.ArgumentParser(
57 'crazy-complete',
58 description='Generate shell auto completion files for all major shells',
59 epilog=_EPILOG,
60 exit_on_error=False)
61
62 p.add_argument(
63 'shell', choices=('bash', 'fish', 'zsh', 'json', 'yaml'),
64 help='Specify the shell type for the completion script')
65
66 p.add_argument(
67 'definition_file',
68 help='The file containing the command line definitions'
69 ).complete('file')
70
71 p.add_argument(
72 '--version', action='version', version='%(prog)s 0.3.9',
73 help='Show program version')
74
75 p.add_argument(
76 '--manual', metavar='TOPIC', nargs='?',
77 help='Show manual for topic')
78
79 p.add_argument(
80 '--parser-variable', default=None,
81 help='Specify the variable name of the ArgumentParser object (for --input-type=python)')
82
83 p.add_argument(
84 '--input-type', choices=('yaml', 'json', 'python', 'help', 'auto'), default='auto',
85 help='Specify input file type')
86
87 p.add_argument(
88 '--abbreviate-commands', metavar='BOOL', default=False, type=boolean,
89 help='Sets whether commands can be abbreviated'
90 ).complete('choices', ('True', 'False'))
91
92 p.add_argument(
93 '--abbreviate-options', metavar='BOOL', default=False, type=boolean,
94 help='Sets whether options can be abbreviated'
95 ).complete('choices', ('True', 'False'))
96
97 p.add_argument(
98 '--repeatable-options', metavar='BOOL', default=False, type=boolean,
99 help='Sets whether options are suggested multiple times during completion'
100 ).complete('choices', ('True', 'False'))
101
102 p.add_argument(
103 '--inherit-options', metavar='BOOL', default=False, type=boolean,
104 help='Sets whether parent options are visible to subcommands'
105 ).complete('choices', ('True', 'False'))
106
107 p.add_argument(
108 '--option-stacking', metavar='BOOL', default=True, type=boolean,
109 help='Sets whether short option stacking is allowed'
110 ).complete('choices', ('True', 'False'))
111
112 p.add_argument(
113 '--long-option-argument-separator', default='both',
114 choices=('space', 'equals', 'both'),
115 dest='long_opt_arg_sep',
116 help='Sets which separators are used for delimiting a long option from its argument'
117 ).complete('choices', ('space', 'equals', 'both'))
118
119 p.add_argument(
120 '--disable', metavar='FEATURES', default=[], type=feature_list,
121 help='Disable features (hidden,final,groups,repeatable,when)'
122 ).complete('value_list', {'values': {
123 'hidden': 'Disable hidden options',
124 'final': 'Disable final options',
125 'groups': 'Disable option groups',
126 'repeatable': 'Disable check for repeatable options',
127 'when': 'Disable conditional options and positionals',
128 }})
129
130 p.add_argument(
131 '--vim-modeline', metavar='BOOL', default=True, type=boolean,
132 help='Sets whether a vim modeline comment shall be appended to the generated code'
133 ).complete('choices', ('True', 'False'))
134
135 p.add_argument(
136 '--bash-completions-version', metavar='VERSION', default=(2,), type=version,
137 help='Generate code for a specific bash-completions version'
138 )
139
140 p.add_argument(
141 '--zsh-compdef', metavar='BOOL', default=True, type=boolean,
142 help='Sets whether #compdef is used in zsh scripts'
143 ).complete('choices', ('True', 'False'))
144
145 p.add_argument(
146 '--fish-inline-conditions', metavar='BOOL', default=False, type=boolean,
147 help="Don't store conditions in a variable"
148 ).complete('choices', ('True', 'False'))
149
150 p.add_argument(
151 '--include-file', metavar='FILE', action='append',
152 help='Include file in output'
153 ).complete('file')
154
155 p.add_argument(
156 '--comment', metavar='COMMENT', action='append',
157 help='Add a comment to output'
158 )
159
160 p.add_argument(
161 '--debug', action='store_true', default=False,
162 help='Enable debug mode')
163
164 p.add_argument(
165 '--keep-comments', action='store_true', default=False,
166 help='Keep comments in generated output')
167
168 p.add_argument(
169 '--max-line-length', default=80, type=int,
170 help='Set the maximum line length of the generated output'
171 )
172
173 p.add_argument(
174 '--function-prefix', metavar='PREFIX', default='_$PROG',
175 help='Set the prefix used for generated functions')
176
177 grp = p.add_mutually_exclusive_group()
178
179 grp.add_argument(
180 '-o', '--output', metavar='FILE', default=None, dest='output_file',
181 help='Write output to destination file [default: stdout]'
182 ).complete('file')
183
184 grp.add_argument(
185 '-i', '--install-system-wide', default=False, action='store_true',
186 help='Write output to the system-wide completions dir of shell')
187
188 grp.add_argument(
189 '-u', '--uninstall-system-wide', default=False, action='store_true',
190 help='Uninstall the system-wide completion file for program')
191
192 # We use a unique object name for avoiding name clashes when
193 # importing/executing the foreign python script
194 _crazy_complete_argument_parser = p
195 del p
196
197
198 def write_string_to_file(string, file):
199 '''Writes string to file if file is given.'''
200
201 if file is not None:
202 with open(file, 'w', encoding='utf-8') as fh:
203 fh.write(string)
204 else:
205 print(string)
206
207
208 def load_definition_file(opts):
209 '''Load a definition file as specified in `opts`.'''
210
211 if opts.input_type == 'auto':
212 basename = os.path.basename(opts.definition_file)
213 extension = os.path.splitext(basename)[1].lower().strip('.')
214
215 if extension == 'json':
216 return json_source.load_from_file(opts.definition_file)
217
218 if extension in ('yaml', 'yml'):
219 return yaml_source.load_from_file(opts.definition_file)
220
221 if extension == 'py':
222 msg = 'Reading Python files must be enabled by --input-type=python'
223 raise CrazyError(msg)
224
225 if extension == '':
226 msg = ('File has no extension. '
227 'Please supply --input-type=json|yaml|help|python')
228 raise CrazyError(msg)
229
230 msg = (f'Unknown file extension `{extension}`. '
231 'Please supply --input-type=json|yaml|help|python')
232 raise CrazyError(msg)
233
234 if opts.input_type == 'json':
235 return json_source.load_from_file(opts.definition_file)
236
237 if opts.input_type == 'yaml':
238 return yaml_source.load_from_file(opts.definition_file)
239
240 if opts.input_type == 'python':
241 return argparse_source.load_from_file(
242 opts.definition_file,
243 opts.parser_variable,
244 parser_blacklist=[_crazy_complete_argument_parser])
245
246 raise AssertionError("Should not be reached")
247
248
249 def _get_config_from_options(opts):
250 conf = config.Config()
251 conf.set_debug(opts.debug)
252 conf.set_function_prefix(opts.function_prefix)
253 conf.set_abbreviate_commands(opts.abbreviate_commands)
254 conf.set_abbreviate_options(opts.abbreviate_options)
255 conf.set_repeatable_options(opts.repeatable_options)
256 conf.set_inherit_options(opts.inherit_options)
257 conf.set_option_stacking(opts.option_stacking)
258 conf.set_long_option_argument_separator(opts.long_opt_arg_sep)
259 conf.set_vim_modeline(opts.vim_modeline)
260 conf.set_bash_completions_version(opts.bash_completions_version)
261 conf.set_zsh_compdef(opts.zsh_compdef)
262 conf.set_fish_inline_conditions(opts.fish_inline_conditions)
263 conf.include_many_files(opts.include_file or [])
264 conf.set_keep_comments(opts.keep_comments)
265 conf.add_comments(opts.comment or [])
266 conf.set_line_length(opts.max_line_length)
267
268 for feature in opts.disable:
269 if feature == 'hidden':
270 conf.disable_hidden(True)
271 elif feature == 'final':
272 conf.disable_final(True)
273 elif feature == 'groups':
274 conf.disable_groups(True)
275 elif feature == 'repeatable':
276 conf.disable_repeatable(True)
277 elif feature == 'when':
278 conf.disable_when(True)
279
280 return conf
281
282
283 def try_print_manual(args):
284 '''Print manual.'''
285
286 parser = argparse.ArgumentParser(add_help=False)
287 parser.add_argument('--manual', nargs='?', const='all')
288 opts, _ = parser.parse_known_args(args)
289
290 if not opts.manual:
291 return
292
293 from . import manual
294 manual.print_help_topic(opts.manual, os.isatty(sys.stdout.fileno()))
295 sys.exit(0)
296
297
298 def try_batch(args):
299 '''Do batch processing.'''
300
301 parser = argparse.ArgumentParser(add_help=False)
302 parser.add_argument('--batch')
303 opts, _ = parser.parse_known_args(args)
304
305 if not opts.batch:
306 return
307
308 with open(opts.batch, 'r', encoding='utf-8') as fh:
309 content = fh.read()
310
311 for line in content.split('\n'):
312 line = line.strip()
313
314 if not line or line.startswith('#'):
315 continue
316
317 utils.print_err('Running:', sys.argv[0], line)
318
319 app = Application()
320 app.parse_args(shlex.split(line))
321 app.run()
322
323 sys.exit(0)
324
325
326 def generate(opts):
327 '''Generate output file as specified in `opts`.'''
328
329 if opts.input_type == 'help':
330 if opts.shell != 'yaml':
331 raise CrazyError('The `help` input-type currently only supports YAML generation')
332 output = help_converter.from_file_to_yaml(opts.definition_file)
333 write_string_to_file(output, opts.output_file)
334 return
335
336 cmdline = load_definition_file(opts)
337
338 if opts.shell == 'json':
339 output = json_source.commandline_to_json(cmdline)
340 write_string_to_file(output, opts.output_file)
341 return
342
343 if opts.shell == 'yaml':
344 output = yaml_source.commandline_to_yaml(cmdline)
345 write_string_to_file(output, opts.output_file)
346 return
347
348 conf = _get_config_from_options(opts)
349
350 if opts.shell == 'bash':
351 output = bash.generate_completion(cmdline, conf)
352 elif opts.shell == 'fish':
353 output = fish.generate_completion(cmdline, conf)
354 elif opts.shell == 'zsh':
355 output = zsh.generate_completion(cmdline, conf)
356
357 if opts.install_system_wide or opts.uninstall_system_wide:
358 file = {
359 'bash': paths.get_bash_completion_file,
360 'fish': paths.get_fish_completion_file,
361 'zsh': paths.get_zsh_completion_file,
362 }[opts.shell](cmdline.prog)
363
364 if opts.install_system_wide:
365 utils.print_err(f'Installing to {file}')
366 write_string_to_file(output, file)
367 else:
368 utils.print_err(f'Removing {file}')
369 os.remove(file)
370 else:
371 write_string_to_file(output, opts.output_file)
372
373
374 class Application:
375 '''Class for main command line application.'''
376
377 def __init__(self):
378 self.options = None
379
380 def parse_args(self, args):
381 '''Parse command line arguments.
382
383 Raises:
384 - argparse.ArgumentError
385 '''
386 try_print_manual(args)
387 try_batch(args)
388 self.options = _crazy_complete_argument_parser.parse_args(args)
389
390 def run(self):
391 '''Run the crazy-complete program.
392
393 Raises:
394 - CrazyError
395 - FileNotFoundError
396 - yaml.scanner.ScannerError
397 - yaml.parser.ParserError
398 - json.decoder.JSONDecodeError
399 '''
400 generate(self.options)