Coverage for pyTooling / CLIAbstraction / OptionalValuedFlag.py: 97%
60 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-13 22:36 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-13 22:36 +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
39from pyTooling.Decorators import export
40from pyTooling.CLIAbstraction.Argument import NamedAndValuedArgument
43@export
44class OptionalValuedFlag(NamedAndValuedArgument, pattern="{0"):
45 """
46 Class and base-class for all OptionalValuedFlag classes, which represents a flag argument with data.
48 An optional valued flag is a flag name followed by a value. The default delimiter sign is equal (``=``). Name and
49 value are passed as one argument to the executable even if the delimiter sign is a whitespace character. If the value
50 is None, no delimiter sign and value is passed.
52 Example: ``width=100``
53 """
54 _patternWithValue: ClassVar[str]
56 def __init_subclass__(cls, *args: Any, pattern: str = "{0}", patternWithValue: str = "{0}={1}", **kwargs: Any) -> None:
57 """
58 This method is called when a class is derived.
60 :param args: Any positional arguments.
61 :param pattern: This pattern is used to format an argument without a value. |br|
62 Default: ``"{0}"``.
63 :param patternWithValue: This pattern is used to format an argument with a value. |br|
64 Default: ``"{0}={1}"``.
65 :param kwargs: Any keyword argument.
66 """
67 kwargs["pattern"] = pattern
68 super().__init_subclass__(*args, **kwargs)
69 cls._patternWithValue = patternWithValue
71 # TODO: the whole class should be marked as abstract
72 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code
73 def __new__(cls, *args: Any, **kwargs: Any) -> Self:
74 """
75 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error.
77 :param args: Any positional arguments.
78 :param kwargs: Any keyword arguments.
79 :raises TypeError: When this class gets directly instantiated without being derived to a subclass.
80 """
81 if cls is OptionalValuedFlag:
82 raise TypeError(f"Class '{cls.__name__}' is abstract.")
83 return super().__new__(cls, *args, **kwargs)
85 def __init__(self, value: Nullable[str] = None) -> None:
86 self._value = value
88 @property
89 def Value(self) -> Nullable[str]:
90 """
91 Get the internal value.
93 :return: Internal value.
94 """
95 return self._value
97 @Value.setter
98 def Value(self, value: Nullable[str]) -> None:
99 """
100 Set the internal value.
102 :param value: Value to set.
103 """
104 self._value = value
106 def AsArgument(self) -> Union[str, Iterable[str]]:
107 """
108 Convert this argument instance to a string representation with proper escaping using the matching pattern based on
109 the internal name and optional value.
111 :return: Formatted argument.
112 :raises ValueError: If internal name is None.
113 """
114 if self._name is None: 114 ↛ 115line 114 didn't jump to line 115 because the condition on line 114 was never true
115 raise ValueError(f"Internal value '_name' is None.")
117 pattern = self._pattern if self._value is None else self._patternWithValue
118 return pattern.format(self._name, self._value)
120 def __str__(self) -> str:
121 return f"\"{self.AsArgument()}\""
123 __repr__ = __str__
126@export
127class ShortOptionalValuedFlag(OptionalValuedFlag, pattern="-{0}", patternWithValue="-{0}={1}"):
128 """
129 Represents a :py:class:`OptionalValuedFlag` with a single dash.
131 Example: ``-optimizer=on``
132 """
133 def __init_subclass__(cls, *args: Any, pattern: str = "-{0}", patternWithValue: str = "-{0}={1}", **kwargs: Any) -> None:
134 """
135 This method is called when a class is derived.
137 :param args: Any positional arguments.
138 :param pattern: This pattern is used to format an argument without a value. |br|
139 Default: ``"-{0}"``.
140 :param patternWithValue: This pattern is used to format an argument with a value. |br|
141 Default: ``"-{0}={1}"``.
142 :param kwargs: Any keyword argument.
143 """
144 kwargs["pattern"] = pattern
145 kwargs["patternWithValue"] = patternWithValue
146 super().__init_subclass__(*args, **kwargs)
148 # TODO: the whole class should be marked as abstract
149 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code
150 def __new__(cls, *args: Any, **kwargs: Any) -> Self:
151 """
152 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error.
154 :param args: Any positional arguments.
155 :param kwargs: Any keyword arguments.
156 :raises TypeError: When this class gets directly instantiated without being derived to a subclass.
157 """
158 if cls is ShortOptionalValuedFlag:
159 raise TypeError(f"Class '{cls.__name__}' is abstract.")
160 return super().__new__(cls, *args, **kwargs)
163@export
164class LongOptionalValuedFlag(OptionalValuedFlag, pattern="--{0}", patternWithValue="--{0}={1}"):
165 """
166 Represents a :py:class:`OptionalValuedFlag` with a double dash.
168 Example: ``--optimizer=on``
169 """
170 def __init_subclass__(cls, *args: Any, pattern: str = "--{0}", patternWithValue: str = "--{0}={1}", **kwargs: Any) -> None:
171 """
172 This method is called when a class is derived.
174 :param args: Any positional arguments.
175 :param pattern: This pattern is used to format an argument without a value. |br|
176 Default: ``"--{0}"``.
177 :param patternWithValue: This pattern is used to format an argument with a value. |br|
178 Default: ``"--{0}={1}"``.
179 :param kwargs: Any keyword argument.
180 """
181 kwargs["pattern"] = pattern
182 kwargs["patternWithValue"] = patternWithValue
183 super().__init_subclass__(*args, **kwargs)
185 # TODO: the whole class should be marked as abstract
186 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code
187 def __new__(cls, *args: Any, **kwargs: Any) -> Self:
188 """
189 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error.
191 :param args: Any positional arguments.
192 :param kwargs: Any keyword arguments.
193 :raises TypeError: When this class gets directly instantiated without being derived to a subclass.
194 """
195 if cls is LongOptionalValuedFlag:
196 raise TypeError(f"Class '{cls.__name__}' is abstract.")
197 return super().__new__(cls, *args, **kwargs)
200@export
201class WindowsOptionalValuedFlag(OptionalValuedFlag, pattern="/{0}", patternWithValue="/{0}:{1}"):
202 """
203 Represents a :py:class:`OptionalValuedFlag` with a single slash.
205 Example: ``/optimizer:on``
206 """
207 def __init_subclass__(cls, *args: Any, pattern: str = "/{0}", patternWithValue: str = "/{0}:{1}", **kwargs: Any) -> None:
208 """
209 This method is called when a class is derived.
211 :param args: Any positional arguments.
212 :param pattern: This pattern is used to format an argument without a value. |br|
213 Default: ``"/{0}"``.
214 :param patternWithValue: This pattern is used to format an argument with a value. |br|
215 Default: ``"/{0}:{1}"``.
216 :param kwargs: Any keyword argument.
217 """
218 kwargs["pattern"] = pattern
219 kwargs["patternWithValue"] = patternWithValue
220 super().__init_subclass__(*args, **kwargs)
222 # TODO: the whole class should be marked as abstract
223 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code
224 def __new__(cls, *args: Any, **kwargs: Any) -> Self:
225 """
226 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error.
228 :param args: Any positional arguments.
229 :param kwargs: Any keyword arguments.
230 :raises TypeError: When this class gets directly instantiated without being derived to a subclass.
231 """
232 if cls is WindowsOptionalValuedFlag:
233 raise TypeError(f"Class '{cls.__name__}' is abstract.")
234 return super().__new__(cls, *args, **kwargs)