Coverage for pyTooling / CLIAbstraction / KeyValueFlag.py: 88%
78 statements
« prev ^ index » next coverage.py v7.12.0, created at 2025-11-21 22:22 +0000
« prev ^ index » next coverage.py v7.12.0, created at 2025-11-21 22:22 +0000
1# ==================================================================================================================== #
2# _____ _ _ ____ _ ___ _ _ _ _ _ #
3# _ __ _ |_ _|__ ___ | (_)_ __ __ _ / ___| | |_ _| / \ | |__ ___| |_ _ __ __ _ ___| |_(_) ___ _ __ #
4# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` || | | | | | / _ \ | '_ \/ __| __| '__/ _` |/ __| __| |/ _ \| '_ \ #
5# | |_) | |_| || | (_) | (_) | | | | | | (_| || |___| |___ | | / ___ \| |_) \__ \ |_| | | (_| | (__| |_| | (_) | | | | #
6# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____|_____|___/_/ \_\_.__/|___/\__|_| \__,_|\___|\__|_|\___/|_| |_| #
7# |_| |___/ |___/ #
8# ==================================================================================================================== #
9# Authors: #
10# Patrick Lehmann #
11# #
12# License: #
13# ==================================================================================================================== #
14# Copyright 2017-2025 Patrick Lehmann - Bötzingen, Germany #
15# Copyright 2014-2016 Technische Universität Dresden - Germany, Chair of VLSI-Design, Diagnostics and Architecture #
16# #
17# Licensed under the Apache License, Version 2.0 (the "License"); #
18# you may not use this file except in compliance with the License. #
19# You may obtain a copy of the License at #
20# #
21# http://www.apache.org/licenses/LICENSE-2.0 #
22# #
23# Unless required by applicable law or agreed to in writing, software #
24# distributed under the License is distributed on an "AS IS" BASIS, #
25# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
26# See the License for the specific language governing permissions and #
27# limitations under the License. #
28# #
29# SPDX-License-Identifier: Apache-2.0 #
30# ==================================================================================================================== #
31#
32"""
33Flag arguments represent simple boolean values by being present or absent.
35.. seealso::
37 * For flags with different pattern based on the boolean value itself. |br|
38 |rarr| :mod:`~pyTooling.CLIAbstraction.BooleanFlag`
39 * For flags with a value. |br|
40 |rarr| :mod:`~pyTooling.CLIAbstraction.ValuedFlag`
41 * For flags that have an optional value. |br|
42 |rarr| :mod:`~pyTooling.CLIAbstraction.NamedOptionalValuedFlag`
43"""
44from typing import Union, Iterable, Dict, cast, Any, Optional as Nullable
46try:
47 from pyTooling.Decorators import export
48 from pyTooling.Common import getFullyQualifiedName
49 from pyTooling.CLIAbstraction.Argument import NamedAndValuedArgument
50except (ImportError, ModuleNotFoundError): # pragma: no cover
51 print("[pyTooling.Versioning] Could not import from 'pyTooling.*'!")
53 try:
54 from Decorators import export
55 from Common import getFullyQualifiedName
56 from CLIAbstraction.Argument import NamedAndValuedArgument
57 except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover
58 print("[pyTooling.Versioning] Could not import directly!")
59 raise ex
62@export
63class NamedKeyValuePairsArgument(NamedAndValuedArgument, pattern="{0}{1}={2}"):
64 """
65 Class and base-class for all KeyValueFlag classes, which represents a flag argument with key and value
66 (key-value-pairs).
68 An optional valued flag is a flag name followed by a value. The default delimiter sign is equal (``=``). Name and
69 value are passed as one argument to the executable even if the delimiter sign is a whitespace character. If the value
70 is None, no delimiter sign and value is passed.
72 **Example:**
74 * ``-gWidth=100``
75 """
77 def __init_subclass__(cls, *args: Any, name: Nullable[str] = None, pattern: str = "{0}{1}={2}", **kwargs: Any):
78 kwargs["name"] = name
79 kwargs["pattern"] = pattern
80 super().__init_subclass__(*args, **kwargs)
82 def __new__(cls, *args: Any, **kwargs: Any):
83 if cls is NamedKeyValuePairsArgument:
84 raise TypeError(f"Class '{cls.__name__}' is abstract.")
85 return super().__new__(cls, *args, **kwargs)
87 def __init__(self, keyValuePairs: Dict[str, str]) -> None:
88 super().__init__({})
90 for key, value in keyValuePairs.items():
91 if not isinstance(key, str): 91 ↛ 92line 91 didn't jump to line 92 because the condition on line 91 was never true
92 ex = TypeError(f"Parameter 'keyValuePairs' contains a pair, where the key is not of type 'str'.")
93 ex.add_note(f"Got type '{getFullyQualifiedName(key)}'.")
94 raise ex
95 elif not isinstance(value, str): 95 ↛ 96line 95 didn't jump to line 96 because the condition on line 95 was never true
96 ex = TypeError(f"Parameter 'keyValuePairs' contains a pair, where the value is not of type 'str'.")
97 ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
98 raise ex
100 self._value[key] = value
102 @property
103 def Value(self) -> Dict[str, str]:
104 """
105 Get the internal value.
107 :return: Internal value.
108 """
109 return self._value
111 @Value.setter
112 def Value(self, keyValuePairs: Dict[str, str]) -> None:
113 """
114 Set the internal value.
116 :param keyValuePairs: Value to set.
117 :raises ValueError: If value to set is None.
118 """
119 innerDict = cast(Dict[str, str], self._value)
120 innerDict.clear()
121 for key, value in keyValuePairs.items():
122 if not isinstance(key, str):
123 ex = TypeError(f"Parameter 'keyValuePairs' contains a pair, where the key is not of type 'str'.")
124 ex.add_note(f"Got type '{getFullyQualifiedName(key)}'.")
125 raise ex
126 elif not isinstance(value, str):
127 ex = TypeError(f"Parameter 'keyValuePairs' contains a pair, where the value is not of type 'str'.")
128 ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
129 raise ex
131 innerDict[key] = value
133 def AsArgument(self) -> Union[str, Iterable[str]]:
134 """
135 Convert this argument instance to a string representation with proper escaping using the matching pattern based on
136 the internal name.
138 :return: Formatted argument.
139 :raises ValueError: If internal name is None.
140 """
141 if self._name is None: 141 ↛ 142line 141 didn't jump to line 142 because the condition on line 141 was never true
142 raise ValueError(f"Internal value '_name' is None.")
144 return [self._pattern.format(self._name, key, value) for key, value in self._value.items()]
147@export
148class ShortKeyValueFlag(NamedKeyValuePairsArgument, pattern="-{0}{1}={2}"):
149 """
150 Represents a :py:class:`NamedKeyValueFlagArgument` with a single dash in front of the switch name.
152 **Example:**
154 * ``-DDEBUG=TRUE``
155 """
157 def __init_subclass__(cls, *args: Any, name: Nullable[str] = None, pattern: str = "-{0}{1}={2}", **kwargs: Any):
158 kwargs["name"] = name
159 kwargs["pattern"] = pattern
160 super().__init_subclass__(*args, **kwargs)
162 def __new__(cls, *args: Any, **kwargs: Any):
163 if cls is ShortKeyValueFlag:
164 raise TypeError(f"Class '{cls.__name__}' is abstract.")
165 return super().__new__(cls, *args, **kwargs)
168@export
169class LongKeyValueFlag(NamedKeyValuePairsArgument, pattern="--{0}{1}={2}"):
170 """
171 Represents a :py:class:`NamedKeyValueFlagArgument` with a double dash in front of the switch name.
173 **Example:**
175 * ``--DDEBUG=TRUE``
176 """
178 def __init_subclass__(cls, *args: Any, name: Nullable[str] = None, pattern: str = "--{0}{1}={2}", **kwargs: Any):
179 kwargs["name"] = name
180 kwargs["pattern"] = pattern
181 super().__init_subclass__(*args, **kwargs)
183 def __new__(cls, *args: Any, **kwargs: Any):
184 if cls is LongKeyValueFlag:
185 raise TypeError(f"Class '{cls.__name__}' is abstract.")
186 return super().__new__(cls, *args, **kwargs)
189@export
190class WindowsKeyValueFlag(NamedKeyValuePairsArgument, pattern="/{0}:{1}={2}"):
191 """
192 Represents a :py:class:`NamedKeyValueFlagArgument` with a double dash in front of the switch name.
194 **Example:**
196 * ``--DDEBUG=TRUE``
197 """
199 def __init_subclass__(cls, *args: Any, name: Nullable[str] = None, pattern: str = "/{0}:{1}={2}", **kwargs: Any):
200 kwargs["name"] = name
201 kwargs["pattern"] = pattern
202 super().__init_subclass__(*args, **kwargs)
204 def __new__(cls, *args: Any, **kwargs: Any):
205 if cls is LongKeyValueFlag: 205 ↛ 206line 205 didn't jump to line 206 because the condition on line 205 was never true
206 raise TypeError(f"Class '{cls.__name__}' is abstract.")
207 return super().__new__(cls, *args, **kwargs)