Coverage for pyTooling/CLIAbstraction/ValuedFlagList.py: 97%

65 statements  

« prev     ^ index     » next       coverage.py v7.11.1, created at 2025-11-07 22:21 +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`). 

35 

36Each list item gets translated into a ``***ValuedFlag``, with the same flag name, but differing values. 

37 

38.. seealso:: 

39 

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 

49 

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.*'!") 

56 

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 

64 

65 

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. 

70 

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. 

73 

74 **Example:** 

75 

76 * ``file=file1.log file=file2.log`` 

77 """ 

78 

79 def __init_subclass__(cls, *args: Any, pattern: str = "{0}={1}", **kwargs: Any): 

80 """ 

81 This method is called when a class is derived. 

82 

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) 

89 

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) 

94 

95 def __init__(self, value: List[ValueT]) -> None: 

96 super().__init__(list(value)) 

97 

98 @property 

99 def Value(self) -> List[str]: 

100 """ 

101 Get the internal value. 

102 

103 :return: Internal value. 

104 """ 

105 return self._value 

106 

107 @Value.setter 

108 def Value(self, values: Iterable[str]) -> None: 

109 """ 

110 Set the internal value. 

111 

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 ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.") 

121 raise ex 

122 innerList.append(value) 

123 

124 def AsArgument(self) -> Union[str, Iterable[str]]: 

125 if self._name is None: 125 ↛ 126line 125 didn't jump to line 126 because the condition on line 125 was never true

126 raise ValueError(f"") # XXX: add message 

127 

128 return [self._pattern.format(self._name, value) for value in self._value] 

129 

130 def __str__(self) -> str: 

131 """ 

132 Return a string representation of this argument instance. 

133 

134 :return: Space separated sequence of arguments formatted and each enclosed in double quotes. 

135 """ 

136 return " ".join([f"\"{value}\"" for value in self.AsArgument()]) 

137 

138 def __repr__(self) -> str: 

139 """ 

140 Return a string representation of this argument instance. 

141 

142 :return: Comma separated sequence of arguments formatted and each enclosed in double quotes. 

143 """ 

144 return ", ".join([f"\"{value}\"" for value in self.AsArgument()]) 

145 

146 

147@export 

148class ShortValuedFlagList(ValuedFlagList, pattern="-{0}={1}"): 

149 """ 

150 Represents a :py:class:`ValuedFlagArgument` with a single dash. 

151 

152 **Example:** 

153 

154 * ``-file=file1.log -file=file2.log`` 

155 """ 

156 

157 def __init_subclass__(cls, *args: Any, pattern: str = "-{0}={1}", **kwargs: Any): 

158 """ 

159 This method is called when a class is derived. 

160 

161 :param args: Any positional arguments. 

162 :param pattern: This pattern is used to format an argument. 

163 :param kwargs: Any keyword argument. 

164 """ 

165 kwargs["pattern"] = pattern 

166 super().__init_subclass__(*args, **kwargs) 

167 

168 def __new__(cls, *args: Any, **kwargs: Any): 

169 if cls is ShortValuedFlagList: 

170 raise TypeError(f"Class '{cls.__name__}' is abstract.") 

171 return super().__new__(cls, *args, **kwargs) 

172 

173 

174@export 

175class LongValuedFlagList(ValuedFlagList, pattern="--{0}={1}"): 

176 """ 

177 Represents a :py:class:`ValuedFlagArgument` with a double dash. 

178 

179 **Example:** 

180 

181 * ``--file=file1.log --file=file2.log`` 

182 """ 

183 

184 def __init_subclass__(cls, *args: Any, pattern: str = "--{0}={1}", **kwargs: Any): 

185 """ 

186 This method is called when a class is derived. 

187 

188 :param args: Any positional arguments. 

189 :param pattern: This pattern is used to format an argument. 

190 :param kwargs: Any keyword argument. 

191 """ 

192 kwargs["pattern"] = pattern 

193 super().__init_subclass__(*args, **kwargs) 

194 

195 def __new__(cls, *args: Any, **kwargs: Any): 

196 if cls is LongValuedFlagList: 

197 raise TypeError(f"Class '{cls.__name__}' is abstract.") 

198 return super().__new__(cls, *args, **kwargs) 

199 

200 

201@export 

202class WindowsValuedFlagList(ValuedFlagList, pattern="/{0}:{1}"): 

203 """ 

204 Represents a :py:class:`ValuedFlagArgument` with a single slash. 

205 

206 **Example:** 

207 

208 * ``/file:file1.log /file:file2.log`` 

209 """ 

210 

211 # TODO: Is it possible to copy the doc-string from super? 

212 def __init_subclass__(cls, *args: Any, pattern: str = "/{0}:{1}", **kwargs: Any): 

213 """ 

214 This method is called when a class is derived. 

215 

216 :param args: Any positional arguments. 

217 :param pattern: This pattern is used to format an argument. 

218 :param kwargs: Any keyword argument. 

219 """ 

220 kwargs["pattern"] = pattern 

221 super().__init_subclass__(*args, **kwargs) 

222 

223 def __new__(cls, *args: Any, **kwargs: Any): 

224 if cls is WindowsValuedFlagList: 

225 raise TypeError(f"Class '{cls.__name__}' is abstract.") 

226 return super().__new__(cls, *args, **kwargs)