Coverage for pyTooling / CLIAbstraction / OptionalValuedFlag.py: 97%
61 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-23 22:21 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-23 22:21 +0000
1# ==================================================================================================================== #
2# _____ _ _ ____ _ ___ _ _ _ _ _ #
3# _ __ _ |_ _|__ ___ | (_)_ __ __ _ / ___| | |_ _| / \ | |__ ___| |_ _ __ __ _ ___| |_(_) ___ _ __ #
4# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` || | | | | | / _ \ | '_ \/ __| __| '__/ _` |/ __| __| |/ _ \| '_ \ #
5# | |_) | |_| || | (_) | (_) | | | | | | (_| || |___| |___ | | / ___ \| |_) \__ \ |_| | | (_| | (__| |_| | (_) | | | | #
6# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____|_____|___/_/ \_\_.__/|___/\__|_| \__,_|\___|\__|_|\___/|_| |_| #
7# |_| |___/ |___/ #
8# ==================================================================================================================== #
9# Authors: #
10# Patrick Lehmann #
11# #
12# License: #
13# ==================================================================================================================== #
14# Copyright 2017-2026 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"""
34.. TODO:: Write module documentation.
36"""
37from typing import ClassVar, Union, Iterable, Any, Optional as Nullable, Self
39try:
40 from pyTooling.Decorators import export
41 from pyTooling.CLIAbstraction.Argument import NamedAndValuedArgument
42except (ImportError, ModuleNotFoundError): # pragma: no cover
43 print("[pyTooling.Versioning] Could not import from 'pyTooling.*'!")
45 try:
46 from Decorators import export
47 from CLIAbstraction.Argument import NamedAndValuedArgument
48 except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover
49 print("[pyTooling.Versioning] Could not import directly!")
50 raise ex
53@export
54class OptionalValuedFlag(NamedAndValuedArgument, pattern="{0"):
55 """
56 Class and base-class for all OptionalValuedFlag classes, which represents a flag argument with data.
58 An optional valued flag is a flag name followed by a value. The default delimiter sign is equal (``=``). Name and
59 value are passed as one argument to the executable even if the delimiter sign is a whitespace character. If the value
60 is None, no delimiter sign and value is passed.
62 Example: ``width=100``
63 """
64 _patternWithValue: ClassVar[str]
66 def __init_subclass__(cls, *args: Any, pattern: str = "{0}", patternWithValue: str = "{0}={1}", **kwargs: Any) -> None:
67 """
68 This method is called when a class is derived.
70 :param args: Any positional arguments.
71 :param pattern: This pattern is used to format an argument without a value. |br|
72 Default: ``"{0}"``.
73 :param patternWithValue: This pattern is used to format an argument with a value. |br|
74 Default: ``"{0}={1}"``.
75 :param kwargs: Any keyword argument.
76 """
77 kwargs["pattern"] = pattern
78 super().__init_subclass__(*args, **kwargs)
79 cls._patternWithValue = patternWithValue
81 # TODO: the whole class should be marked as abstract
82 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code
83 def __new__(cls, *args: Any, **kwargs: Any) -> Self:
84 """
85 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error.
87 :param args: Any positional arguments.
88 :param kwargs: Any keyword arguments.
89 :raises TypeError: When this class gets directly instantiated without being derived to a subclass.
90 """
91 if cls is OptionalValuedFlag:
92 raise TypeError(f"Class '{cls.__name__}' is abstract.")
93 return super().__new__(cls, *args, **kwargs)
95 def __init__(self, value: Nullable[str] = None) -> None:
96 self._value = value
98 @property
99 def Value(self) -> Nullable[str]:
100 """
101 Get the internal value.
103 :return: Internal value.
104 """
105 return self._value
107 @Value.setter
108 def Value(self, value: Nullable[str]) -> None:
109 """
110 Set the internal value.
112 :param value: Value to set.
113 """
114 self._value = value
116 def AsArgument(self) -> Union[str, Iterable[str]]:
117 """
118 Convert this argument instance to a string representation with proper escaping using the matching pattern based on
119 the internal name and optional value.
121 :return: Formatted argument.
122 :raises ValueError: If internal name is None.
123 """
124 if self._name is None: 124 ↛ 125line 124 didn't jump to line 125 because the condition on line 124 was never true
125 raise ValueError(f"Internal value '_name' is None.")
127 pattern = self._pattern if self._value is None else self._patternWithValue
128 return pattern.format(self._name, self._value)
130 def __str__(self) -> str:
131 return f"\"{self.AsArgument()}\""
133 __repr__ = __str__
136@export
137class ShortOptionalValuedFlag(OptionalValuedFlag, pattern="-{0}", patternWithValue="-{0}={1}"):
138 """
139 Represents a :py:class:`OptionalValuedFlag` with a single dash.
141 Example: ``-optimizer=on``
142 """
143 def __init_subclass__(cls, *args: Any, pattern: str = "-{0}", patternWithValue: str = "-{0}={1}", **kwargs: Any) -> None:
144 """
145 This method is called when a class is derived.
147 :param args: Any positional arguments.
148 :param pattern: This pattern is used to format an argument without a value. |br|
149 Default: ``"-{0}"``.
150 :param patternWithValue: This pattern is used to format an argument with a value. |br|
151 Default: ``"-{0}={1}"``.
152 :param kwargs: Any keyword argument.
153 """
154 kwargs["pattern"] = pattern
155 kwargs["patternWithValue"] = patternWithValue
156 super().__init_subclass__(*args, **kwargs)
158 # TODO: the whole class should be marked as abstract
159 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code
160 def __new__(cls, *args: Any, **kwargs: Any) -> Self:
161 """
162 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error.
164 :param args: Any positional arguments.
165 :param kwargs: Any keyword arguments.
166 :raises TypeError: When this class gets directly instantiated without being derived to a subclass.
167 """
168 if cls is ShortOptionalValuedFlag:
169 raise TypeError(f"Class '{cls.__name__}' is abstract.")
170 return super().__new__(cls, *args, **kwargs)
173@export
174class LongOptionalValuedFlag(OptionalValuedFlag, pattern="--{0}", patternWithValue="--{0}={1}"):
175 """
176 Represents a :py:class:`OptionalValuedFlag` with a double dash.
178 Example: ``--optimizer=on``
179 """
180 def __init_subclass__(cls, *args: Any, pattern: str = "--{0}", patternWithValue: str = "--{0}={1}", **kwargs: Any) -> None:
181 """
182 This method is called when a class is derived.
184 :param args: Any positional arguments.
185 :param pattern: This pattern is used to format an argument without a value. |br|
186 Default: ``"--{0}"``.
187 :param patternWithValue: This pattern is used to format an argument with a value. |br|
188 Default: ``"--{0}={1}"``.
189 :param kwargs: Any keyword argument.
190 """
191 kwargs["pattern"] = pattern
192 kwargs["patternWithValue"] = patternWithValue
193 super().__init_subclass__(*args, **kwargs)
195 # TODO: the whole class should be marked as abstract
196 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code
197 def __new__(cls, *args: Any, **kwargs: Any) -> Self:
198 """
199 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error.
201 :param args: Any positional arguments.
202 :param kwargs: Any keyword arguments.
203 :raises TypeError: When this class gets directly instantiated without being derived to a subclass.
204 """
205 if cls is LongOptionalValuedFlag:
206 raise TypeError(f"Class '{cls.__name__}' is abstract.")
207 return super().__new__(cls, *args, **kwargs)
210@export
211class WindowsOptionalValuedFlag(OptionalValuedFlag, pattern="/{0}", patternWithValue="/{0}:{1}"):
212 """
213 Represents a :py:class:`OptionalValuedFlag` with a single slash.
215 Example: ``/optimizer:on``
216 """
217 def __init_subclass__(cls, *args: Any, pattern: str = "/{0}", patternWithValue: str = "/{0}:{1}", **kwargs: Any) -> None:
218 """
219 This method is called when a class is derived.
221 :param args: Any positional arguments.
222 :param pattern: This pattern is used to format an argument without a value. |br|
223 Default: ``"/{0}"``.
224 :param patternWithValue: This pattern is used to format an argument with a value. |br|
225 Default: ``"/{0}:{1}"``.
226 :param kwargs: Any keyword argument.
227 """
228 kwargs["pattern"] = pattern
229 kwargs["patternWithValue"] = patternWithValue
230 super().__init_subclass__(*args, **kwargs)
232 # TODO: the whole class should be marked as abstract
233 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code
234 def __new__(cls, *args: Any, **kwargs: Any) -> Self:
235 """
236 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error.
238 :param args: Any positional arguments.
239 :param kwargs: Any keyword arguments.
240 :raises TypeError: When this class gets directly instantiated without being derived to a subclass.
241 """
242 if cls is WindowsOptionalValuedFlag:
243 raise TypeError(f"Class '{cls.__name__}' is abstract.")
244 return super().__new__(cls, *args, **kwargs)