Coverage for pyTooling/CLIAbstraction/ValuedFlagList.py: 97%
64 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-25 22:22 +0000
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-25 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"""
33List of valued flags are argument lists where each item is a valued flag (See
34:mod:`~pyTooling.CLIAbstraction.ValuedFlag.ValuedFlag`).
36Each list item gets translated into a ``***ValuedFlag``, with the same flag name, but differing values.
38.. seealso::
40 * For single valued flags. |br|
41 |rarr| :mod:`~pyTooling.CLIAbstraction.ValuedFlag`
42 * For list of strings. |br|
43 |rarr| :mod:`~pyTooling.CLIAbstraction.Argument.StringListArgument`
44 * For list of paths. |br|
45 |rarr| :mod:`~pyTooling.CLIAbstraction.Argument.PathListArgument`
46"""
47from sys import version_info # needed for versions before Python 3.11
48from typing import List, Union, Iterable, cast, Any
50try:
51 from pyTooling.Decorators import export
52 from pyTooling.Common import getFullyQualifiedName
53 from pyTooling.CLIAbstraction.Argument import ValueT, NamedAndValuedArgument
54except (ImportError, ModuleNotFoundError): # pragma: no cover
55 print("[pyTooling.Versioning] Could not import from 'pyTooling.*'!")
57 try:
58 from Decorators import export
59 from Common import getFullyQualifiedName
60 from CLIAbstraction.Argument import ValueT, NamedAndValuedArgument
61 except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover
62 print("[pyTooling.Versioning] Could not import directly!")
63 raise ex
66@export
67class ValuedFlagList(NamedAndValuedArgument, pattern="{0}={1}"):
68 """
69 Class and base-class for all ValuedFlagList classes, which represents a list of valued flags.
71 Each list element gets translated to a valued flag using the pattern for formatting.
72 See :mod:`~pyTooling.CLIAbstraction.ValuedFlag` for more details on valued flags.
74 **Example:**
76 * ``file=file1.log file=file2.log``
77 """
79 def __init_subclass__(cls, *args: Any, pattern: str = "{0}={1}", **kwargs: Any):
80 """
81 This method is called when a class is derived.
83 :param args: Any positional arguments.
84 :param pattern: This pattern is used to format an argument.
85 :param kwargs: Any keyword argument.
86 """
87 kwargs["pattern"] = pattern
88 super().__init_subclass__(*args, **kwargs)
90 def __new__(cls, *args: Any, **kwargs: Any):
91 if cls is ValuedFlagList:
92 raise TypeError(f"Class '{cls.__name__}' is abstract.")
93 return super().__new__(cls, *args, **kwargs)
95 def __init__(self, value: List[ValueT]) -> None:
96 super().__init__(list(value))
98 @property
99 def Value(self) -> List[str]:
100 """
101 Get the internal value.
103 :return: Internal value.
104 """
105 return self._value
107 @Value.setter
108 def Value(self, values: Iterable[str]) -> None:
109 """
110 Set the internal value.
112 :param values: List of values to set.
113 :raises ValueError: If a list element is not o type :class:`str`.
114 """
115 innerList = cast(list, self._value)
116 innerList.clear()
117 for value in values:
118 if not isinstance(value, str):
119 ex = TypeError(f"Value contains elements which are not of type 'str'.")
120 if version_info >= (3, 11): # pragma: no cover
121 ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
122 raise ex
123 innerList.append(value)
125 def AsArgument(self) -> Union[str, Iterable[str]]:
126 if self._name is None: 126 ↛ 127line 126 didn't jump to line 127 because the condition on line 126 was never true
127 raise ValueError(f"") # XXX: add message
129 return [self._pattern.format(self._name, value) for value in self._value]
131 def __str__(self) -> str:
132 """
133 Return a string representation of this argument instance.
135 :return: Space separated sequence of arguments formatted and each enclosed in double quotes.
136 """
137 return " ".join([f"\"{value}\"" for value in self.AsArgument()])
139 def __repr__(self) -> str:
140 """
141 Return a string representation of this argument instance.
143 :return: Comma separated sequence of arguments formatted and each enclosed in double quotes.
144 """
145 return ", ".join([f"\"{value}\"" for value in self.AsArgument()])
148@export
149class ShortValuedFlagList(ValuedFlagList, pattern="-{0}={1}"):
150 """
151 Represents a :py:class:`ValuedFlagArgument` with a single dash.
153 **Example:**
155 * ``-file=file1.log -file=file2.log``
156 """
158 def __init_subclass__(cls, *args: Any, pattern: str = "-{0}={1}", **kwargs: Any):
159 """
160 This method is called when a class is derived.
162 :param args: Any positional arguments.
163 :param pattern: This pattern is used to format an argument.
164 :param kwargs: Any keyword argument.
165 """
166 kwargs["pattern"] = pattern
167 super().__init_subclass__(*args, **kwargs)
169 def __new__(cls, *args: Any, **kwargs: Any):
170 if cls is ShortValuedFlagList:
171 raise TypeError(f"Class '{cls.__name__}' is abstract.")
172 return super().__new__(cls, *args, **kwargs)
175@export
176class LongValuedFlagList(ValuedFlagList, pattern="--{0}={1}"):
177 """
178 Represents a :py:class:`ValuedFlagArgument` with a double dash.
180 **Example:**
182 * ``--file=file1.log --file=file2.log``
183 """
185 def __init_subclass__(cls, *args: Any, pattern: str = "--{0}={1}", **kwargs: Any):
186 """
187 This method is called when a class is derived.
189 :param args: Any positional arguments.
190 :param pattern: This pattern is used to format an argument.
191 :param kwargs: Any keyword argument.
192 """
193 kwargs["pattern"] = pattern
194 super().__init_subclass__(*args, **kwargs)
196 def __new__(cls, *args: Any, **kwargs: Any):
197 if cls is LongValuedFlagList:
198 raise TypeError(f"Class '{cls.__name__}' is abstract.")
199 return super().__new__(cls, *args, **kwargs)
202@export
203class WindowsValuedFlagList(ValuedFlagList, pattern="/{0}:{1}"):
204 """
205 Represents a :py:class:`ValuedFlagArgument` with a single slash.
207 **Example:**
209 * ``/file:file1.log /file:file2.log``
210 """
212 # TODO: Is it possible to copy the doc-string from super?
213 def __init_subclass__(cls, *args: Any, pattern: str = "/{0}:{1}", **kwargs: Any):
214 """
215 This method is called when a class is derived.
217 :param args: Any positional arguments.
218 :param pattern: This pattern is used to format an argument.
219 :param kwargs: Any keyword argument.
220 """
221 kwargs["pattern"] = pattern
222 super().__init_subclass__(*args, **kwargs)
224 def __new__(cls, *args: Any, **kwargs: Any):
225 if cls is WindowsValuedFlagList:
226 raise TypeError(f"Class '{cls.__name__}' is abstract.")
227 return super().__new__(cls, *args, **kwargs)