Debian Codegraph @

crazy_complete/yaml_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 YAML
6 and vice versa.
7 """
8
9 import json
10 import yaml
11
12 from . import dictionary_source
13 from . import scheme_validator
14 from .str_utils import indent
15 from .extended_yaml_parser import ExtendedYAMLParser
16 from .cli import INHERIT
17
18
19 # pylint: disable=redefined-builtin
20
21
22 def option_to_yaml(dictionary):
23 '''Convert an option dictionary to YAML.'''
24
25 option_strings = dictionary['option_strings']
26
27 fields = [
28 # name, default, include-if
29 ('metavar', None, lambda v: v is not None),
30 ('help', None, lambda v: v is not None),
31 ('optional_arg', False, lambda v: v is True),
32 ('groups', None, lambda v: v is not None),
33 ('repeatable', INHERIT, lambda v: v != INHERIT),
34 ('final', False, lambda v: v is True),
35 ('hidden', False, lambda v: v is True),
36 ('complete', None, lambda v: v is not None),
37 ('nosort', None, lambda v: v is True),
38 ('when', None, lambda v: v is not None),
39 ('capture', None, lambda v: v is not None),
40 ('long_opt_arg_sep', INHERIT, lambda v: v != INHERIT),
41 ]
42
43 r = [f'- option_strings: {json.dumps(option_strings)}']
44
45 for name, default, include_if in fields:
46 value = dictionary.get(name, default)
47
48 if include_if(value):
49 r.append(f' {name}: {json.dumps(value)}')
50
51 return '\n'.join(r)
52
53
54 def positional_to_yaml(dictionary):
55 '''Convert a positional dictionary to YAML.'''
56
57 number = dictionary['number']
58
59 fields = [
60 # name, default, include-if
61 ('metavar', None, lambda v: v is not None),
62 ('help', None, lambda v: v is not None),
63 ('repeatable', False, lambda v: v is True),
64 ('complete', None, lambda v: v is not None),
65 ('nosort', None, lambda v: v is True),
66 ('when', None, lambda v: v is not None),
67 ('capture', None, lambda v: v is not None),
68 ]
69
70 r = [f'- number: {number}']
71
72 for name, default, include_if in fields:
73 value = dictionary.get(name, default)
74
75 if include_if(value):
76 r.append(f' {name}: {json.dumps(value)}')
77
78 return '\n'.join(r)
79
80
81 def to_yaml(dictionary):
82 '''Convert a single dictionary to YAML.'''
83
84 prog = dictionary['prog']
85 aliases = dictionary.get('aliases', None)
86 help = dictionary.get('help', None)
87 wraps = dictionary.get('wraps', None)
88 abbreviate_commands = dictionary.get('abbreviate_commands', INHERIT)
89 abbreviate_options = dictionary.get('abbreviate_options', INHERIT)
90 inherit_options = dictionary.get('inherit_options', INHERIT)
91 options = dictionary.get('options', None)
92 positionals = dictionary.get('positionals', None)
93
94 r = 'prog: %s\n' % json.dumps(prog)
95
96 if aliases is not None:
97 r += 'aliases: %s\n' % json.dumps(aliases)
98
99 if help is not None:
100 r += 'help: %s\n' % json.dumps(help)
101
102 if wraps is not None:
103 r += 'wraps: %s\n' % json.dumps(wraps)
104
105 if abbreviate_commands != INHERIT:
106 r += 'abbreviate_commands: %s\n' % json.dumps(abbreviate_commands)
107
108 if abbreviate_options != INHERIT:
109 r += 'abbreviate_options: %s\n' % json.dumps(abbreviate_options)
110
111 if inherit_options != INHERIT:
112 r += 'inherit_options: %s\n' % json.dumps(inherit_options)
113
114 if options:
115 r += 'options:\n'
116 for option in options:
117 r += indent(option_to_yaml(option), 2)
118 r += '\n\n'
119
120 if positionals:
121 r += 'positionals:\n'
122 for positional in positionals:
123 r += indent(positional_to_yaml(positional), 2)
124 r += '\n\n'
125
126 return r.rstrip()
127
128
129 def commandline_to_yaml(commandline):
130 '''Convert a cli.CommandLine object to YAML.'''
131
132 dictionaries = dictionary_source.commandline_to_dictionaries(commandline)
133 r = []
134
135 for dictionary in dictionaries:
136 r.append(to_yaml(dictionary))
137
138 return '\n---\n'.join(r)
139
140
141 def replace_defines_in_documents(documents):
142 '''Replaces defines in a list of documents.
143
144 Example:
145 prog: '%defines%'
146 my_completer: ['choices', ['foo', 'bar']]
147 ---
148 prog: 'example'
149 options:
150 - option_strings: ['-o']
151 complete: 'my_completer'
152 '''
153
154 defines = None
155
156 for document in documents:
157 if not isinstance(document.value, dict):
158 continue
159
160 if 'prog' in document.value and document.value['prog'].value == '%defines%':
161 defines = document
162 break
163
164 if defines is None:
165 return documents
166
167 documents.remove(defines)
168 defines.value.pop('prog')
169
170 def replace_defines(obj):
171 if isinstance(obj.value, str):
172 return defines.value.get(obj.value, obj)
173 if isinstance(obj.value, list):
174 obj.value = [replace_defines(sub) for sub in obj.value]
175 return obj
176 if isinstance(obj.value, dict):
177 obj.value = {key: replace_defines(val) for key, val in obj.value.items()}
178 return obj
179 return obj
180
181 new = []
182 for document in documents:
183 new.append(replace_defines(document))
184 return new
185
186
187 def load_from_file(file):
188 '''Load a YAML file and turn it into a cli.CommandLine object.'''
189
190 # First, load using normal yaml loader. It gives better error messages
191 # in case of syntax errors.
192 with open(file, 'r', encoding='utf-8') as fh:
193 dictionaries = list(yaml.safe_load_all(fh))
194
195 # Then load using extended yaml loader...
196 with open(file, 'r', encoding='utf-8') as fh:
197 content = fh.read()
198
199 # Validate YAML...
200 parser = ExtendedYAMLParser()
201 parsed = parser.parse(content)
202 parsed = replace_defines_in_documents(parsed)
203 scheme_validator.validate(parsed)
204
205 # Finally convert the config structure to CommandLine objects
206 return dictionary_source.dictionaries_to_commandline(dictionaries)