Coverage for pyTooling / CLIAbstraction / ValuedFlagList.py: 97%
64 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"""
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 typing import List, Union, Iterable, cast, Any
49try:
50 from pyTooling.Decorators import export
51 from pyTooling.Common import getFullyQualifiedName
52 from pyTooling.CLIAbstraction.Argument import ValueT, NamedAndValuedArgument
53except (ImportError, ModuleNotFoundError): # pragma: no cover
54 print("[pyTooling.Versioning] Could not import from 'pyTooling.*'!")
56 try:
57 from Decorators import export
58 from Common import getFullyQualifiedName
59 from CLIAbstraction.Argument import ValueT, NamedAndValuedArgument
60 except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover
61 print("[pyTooling.Versioning] Could not import directly!")
62 raise ex
65@export
66class ValuedFlagList(NamedAndValuedArgument, pattern="{0}={1}"):
67 """
68 Class and base-class for all ValuedFlagList classes, which represents a list of valued flags.
70 Each list element gets translated to a valued flag using the pattern for formatting.
71 See :mod:`~pyTooling.CLIAbstraction.ValuedFlag` for more details on valued flags.
73 **Example:**
75 * ``file=file1.log file=file2.log``
76 """
78 def __init_subclass__(cls, *args: Any, pattern: str = "{0}={1}", **kwargs: Any):
79 """
80 This method is called when a class is derived.
82 :param args: Any positional arguments.
83 :param pattern: This pattern is used to format an argument.
84 :param kwargs: Any keyword argument.
85 """
86 kwargs["pattern"] = pattern
87 super().__init_subclass__(*args, **kwargs)
89 def __new__(cls, *args: Any, **kwargs: Any):
90 if cls is ValuedFlagList:
91 raise TypeError(f"Class '{cls.__name__}' is abstract.")
92 return super().__new__(cls, *args, **kwargs)
94 def __init__(self, value: List[ValueT]) -> None:
95 super().__init__(list(value))
97 @property
98 def Value(self) -> List[str]:
99 """
100 Get the internal value.
102 :return: Internal value.
103 """
104 return self._value
106 @Value.setter
107 def Value(self, values: Iterable[str]) -> None:
108 """
109 Set the internal value.
111 :param values: List of values to set.
112 :raises ValueError: If a list element is not o type :class:`str`.
113 """
114 innerList = cast(list, self._value)
115 innerList.clear()
116 for value in values:
117 if not isinstance(value, str):
118 ex = TypeError(f"Value contains elements which are not of type 'str'.")
119 ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
120 raise ex
121 innerList.append(value)
123 def AsArgument(self) -> Union[str, Iterable[str]]:
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"") # XXX: add message
127 return [self._pattern.format(self._name, value) for value in self._value]
129 def __str__(self) -> str:
130 """
131 Return a string representation of this argument instance.
133 :return: Space separated sequence of arguments formatted and each enclosed in double quotes.
134 """
135 return " ".join([f"\"{value}\"" for value in self.AsArgument()])
137 def __repr__(self) -> str:
138 """
139 Return a string representation of this argument instance.
141 :return: Comma separated sequence of arguments formatted and each enclosed in double quotes.
142 """
143 return ", ".join([f"\"{value}\"" for value in self.AsArgument()])
146@export
147class ShortValuedFlagList(ValuedFlagList, pattern="-{0}={1}"):
148 """
149 Represents a :py:class:`ValuedFlagArgument` with a single dash.
151 **Example:**
153 * ``-file=file1.log -file=file2.log``
154 """
156 def __init_subclass__(cls, *args: Any, pattern: str = "-{0}={1}", **kwargs: Any):
157 """
158 This method is called when a class is derived.
160 :param args: Any positional arguments.
161 :param pattern: This pattern is used to format an argument.
162 :param kwargs: Any keyword argument.
163 """
164 kwargs["pattern"] = pattern
165 super().__init_subclass__(*args, **kwargs)
167 def __new__(cls, *args: Any, **kwargs: Any):
168 if cls is ShortValuedFlagList:
169 raise TypeError(f"Class '{cls.__name__}' is abstract.")
170 return super().__new__(cls, *args, **kwargs)
173@export
174class LongValuedFlagList(ValuedFlagList, pattern="--{0}={1}"):
175 """
176 Represents a :py:class:`ValuedFlagArgument` with a double dash.
178 **Example:**
180 * ``--file=file1.log --file=file2.log``
181 """
183 def __init_subclass__(cls, *args: Any, pattern: str = "--{0}={1}", **kwargs: Any):
184 """
185 This method is called when a class is derived.
187 :param args: Any positional arguments.
188 :param pattern: This pattern is used to format an argument.
189 :param kwargs: Any keyword argument.
190 """
191 kwargs["pattern"] = pattern
192 super().__init_subclass__(*args, **kwargs)
194 def __new__(cls, *args: Any, **kwargs: Any):
195 if cls is LongValuedFlagList:
196 raise TypeError(f"Class '{cls.__name__}' is abstract.")
197 return super().__new__(cls, *args, **kwargs)
200@export
201class WindowsValuedFlagList(ValuedFlagList, pattern="/{0}:{1}"):
202 """
203 Represents a :py:class:`ValuedFlagArgument` with a single slash.
205 **Example:**
207 * ``/file:file1.log /file:file2.log``
208 """
210 # TODO: Is it possible to copy the doc-string from super?
211 def __init_subclass__(cls, *args: Any, pattern: str = "/{0}:{1}", **kwargs: Any):
212 """
213 This method is called when a class is derived.
215 :param args: Any positional arguments.
216 :param pattern: This pattern is used to format an argument.
217 :param kwargs: Any keyword argument.
218 """
219 kwargs["pattern"] = pattern
220 super().__init_subclass__(*args, **kwargs)
222 def __new__(cls, *args: Any, **kwargs: Any):
223 if cls is WindowsValuedFlagList:
224 raise TypeError(f"Class '{cls.__name__}' is abstract.")
225 return super().__new__(cls, *args, **kwargs)