17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194 | class ParseFromTerminal:
"""Parse configuration values from terminal arguments.
This class generates an argument parser based on configuration metadata and
converts parsed command-line values to their target types. The parser is
built from configuration entries that provide terminal option names, help
text, and default values.
Attributes:
config (list): List of configuration dictionaries describing each parameter.
description (str | None): Optional parser description used in the CLI help text.
value_from_type (ValuesFromType): Converter for terminal string values to typed values.
values (dict): Parsed and converted terminal values keyed by configuration name.
Example:
>>> config = [
... {
... "name": "verbose",
... "type": "bool",
... "default": False,
... "terminal_name": "verbose",
... "terminal_name_short": "v",
... "terminal_help": "Enable verbose mode"
... }
... ]
>>> parser = ParseFromTerminal(config=config)
>>> values = parser.get_values()
>>> print(values)
{'verbose': False}
"""
def __init__(self, config: list, description: str = None) -> None:
"""Initialize the ParseFromTerminal instance and parse terminal arguments.
Args:
config (list): List of configuration dictionaries. Each item can include:
- name: The internal configuration key.
- type: The target type for the argument ('string', 'bool', 'int', etc.).
- default: The default value when the terminal argument is not provided.
- terminal_name: The long-form command-line option name.
- terminal_name_short: Optional short-form command-line option name.
- terminal_help: Help text for the argument.
description (str, optional): Description text for the generated CLI parser.
Raises:
ValueError: If parsed values fail validation.
Example:
>>> parser = ParseFromTerminal(config=config, description="Application config")
"""
self.config = config
self.description = description
self.value_from_type = ValuesFromType(source_name="terminal")
self.__set_values()
self.__check_values()
def __set_value_bool(self, parser: argparse.ArgumentParser, entry: dict) -> None:
"""Register a boolean terminal argument with argparse.
Boolean terminal arguments are added as flags using the `store_true`
action. If a short name is provided, the option is registered with both
short and long forms.
Args:
parser (argparse.ArgumentParser): The argument parser instance.
entry (dict): Configuration dictionary for the boolean argument.
Returns:
None
"""
if entry.get("terminal_name_short") == '' or entry.get("terminal_name_short") is None:
parser.add_argument(
f'--{entry.get("terminal_name")}',
help=entry.get("terminal_help"),
default=entry.get("default"),
action='store_true'
)
else:
parser.add_argument(
f'-{entry.get("terminal_name_short")}',
f'--{entry.get("terminal_name")}',
help=entry.get("terminal_help"),
default=entry.get("default"),
action='store_true'
)
def __set_value_non_bool(self, parser: argparse.ArgumentParser, entry: dict) -> None:
"""Register a non-boolean terminal argument with argparse.
Non-boolean arguments are accepted as strings and converted later to the
configured type by `ValuesFromType`.
Args:
parser (argparse.ArgumentParser): The argument parser instance.
entry (dict): Configuration dictionary for the argument.
Returns:
None
"""
if entry.get("terminal_name_short") == '' or entry.get("terminal_name_short") is None:
parser.add_argument(
f'--{entry.get("terminal_name")}',
help=entry.get("terminal_help"),
default=entry.get("default"),
type=str
)
else:
parser.add_argument(
f'-{entry.get("terminal_name_short")}',
f'--{entry.get("terminal_name")}',
help=entry.get("terminal_help"),
default=entry.get("default"),
type=str
)
def __set_values(self) -> None:
"""Build the argument parser and convert terminal values to typed values.
The method creates an `argparse.ArgumentParser` using the provided
description or a default description. It registers arguments for all
configuration items that include `terminal_name` and `terminal_help`.
After parsing the current process command line, the method converts
argument values from strings to the configured types using
`ValuesFromType`.
Returns:
None
"""
if self.description is not None:
description = self.description
else:
description = DEFAULT_APP_DESCRIPTION
parser = argparse.ArgumentParser(description=description)
for item in self.config:
# Only if set
if item.get("terminal_name") is not None and item.get("terminal_help") is not None:
if str(item["type"]).lower() in ["bool", "boolean"]:
self.__set_value_bool(parser=parser, entry=item)
else:
self.__set_value_non_bool(parser=parser, entry=item)
# Check Parsed Values and Convert Types
ret_dict = {}
from_terminal_dict = parser.parse_args().__dict__
if from_terminal_dict is not None:
for item in self.config:
if item["name"] in from_terminal_dict.keys():
ret_dict[item["name"]] = self.value_from_type.get_value(
value_type=item["type"],
value_found=from_terminal_dict.get(item.get("name"))
)
self.values = ret_dict
def __check_values(self) -> None:
"""Validate parsed terminal values against configuration.
The method delegates validation to the `ValuesCheck` class.
Raises:
ValueError: If any parsed values do not match the configured types.
Returns:
None
"""
ValuesCheck(config=self.config, values_found=self.values, info_string="terminal values")
def get_values(self) -> dict:
"""Return the parsed terminal values.
Returns:
dict: Dictionary mapping configuration names to their parsed values.
"""
return self.values
|