Coverage for pyTooling / CLIAbstraction / KeyValueFlag.py: 88%

77 statements  

« 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""" 

33Flag arguments represent simple boolean values by being present or absent. 

34 

35.. seealso:: 

36 

37 * For flags with different pattern based on the boolean value itself. |br| 

38 |rarr| :mod:`~pyTooling.CLIAbstraction.BooleanFlag` 

39 * For flags with a value. |br| 

40 |rarr| :mod:`~pyTooling.CLIAbstraction.ValuedFlag` 

41 * For flags that have an optional value. |br| 

42 |rarr| :mod:`~pyTooling.CLIAbstraction.NamedOptionalValuedFlag` 

43""" 

44from typing import Union, Iterable, Dict, cast, Any, Optional as Nullable, Self 

45 

46from pyTooling.Decorators import export 

47from pyTooling.Common import getFullyQualifiedName 

48from pyTooling.CLIAbstraction.Argument import NamedAndValuedArgument 

49 

50 

51@export 

52class NamedKeyValuePairsArgument(NamedAndValuedArgument, pattern="{0}{1}={2}"): 

53 """ 

54 Class and base-class for all KeyValueFlag classes, which represents a flag argument with key and value 

55 (key-value-pairs). 

56 

57 An optional valued flag is a flag name followed by a value. The default delimiter sign is equal (``=``). Name and 

58 value are passed as one argument to the executable even if the delimiter sign is a whitespace character. If the value 

59 is None, no delimiter sign and value is passed. 

60 

61 **Example:** 

62 

63 * ``-gWidth=100`` 

64 """ 

65 

66 def __init_subclass__(cls, *args: Any, name: Nullable[str] = None, pattern: str = "{0}{1}={2}", **kwargs: Any) -> None: 

67 """ 

68 This method is called when a class is derived. 

69 

70 :param args: Any positional arguments. 

71 :param name: Name of the CLI argument. 

72 :param pattern: This pattern is used to format an argument. |br| 

73 Default: ``"{0}{1}={2}"``. 

74 :param kwargs: Any keyword argument. 

75 """ 

76 kwargs["name"] = name 

77 kwargs["pattern"] = pattern 

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

79 

80 # TODO: the whole class should be marked as abstract 

81 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code 

82 def __new__(cls, *args: Any, **kwargs: Any) -> Self: 

83 """ 

84 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error. 

85 

86 :param args: Any positional arguments. 

87 :param kwargs: Any keyword arguments. 

88 :raises TypeError: When this class gets directly instantiated without being derived to a subclass. 

89 """ 

90 if cls is NamedKeyValuePairsArgument: 

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

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

93 

94 def __init__(self, keyValuePairs: Dict[str, str]) -> None: 

95 super().__init__({}) 

96 

97 for key, value in keyValuePairs.items(): 

98 if not isinstance(key, str): 98 ↛ 99line 98 didn't jump to line 99 because the condition on line 98 was never true

99 ex = TypeError(f"Parameter 'keyValuePairs' contains a pair, where the key is not of type 'str'.") 

100 ex.add_note(f"Got type '{getFullyQualifiedName(key)}'.") 

101 raise ex 

102 elif not isinstance(value, str): 102 ↛ 103line 102 didn't jump to line 103 because the condition on line 102 was never true

103 ex = TypeError(f"Parameter 'keyValuePairs' contains a pair, where the value is not of type 'str'.") 

104 ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.") 

105 raise ex 

106 

107 self._value[key] = value 

108 

109 @property 

110 def Value(self) -> Dict[str, str]: 

111 """ 

112 Get the internal value. 

113 

114 :return: Internal value. 

115 """ 

116 return self._value 

117 

118 @Value.setter 

119 def Value(self, keyValuePairs: Dict[str, str]) -> None: 

120 """ 

121 Set the internal value. 

122 

123 :param keyValuePairs: Value to set. 

124 :raises ValueError: If value to set is None. 

125 """ 

126 innerDict = cast(Dict[str, str], self._value) 

127 innerDict.clear() 

128 for key, value in keyValuePairs.items(): 

129 if not isinstance(key, str): 

130 ex = TypeError(f"Parameter 'keyValuePairs' contains a pair, where the key is not of type 'str'.") 

131 ex.add_note(f"Got type '{getFullyQualifiedName(key)}'.") 

132 raise ex 

133 elif not isinstance(value, str): 

134 ex = TypeError(f"Parameter 'keyValuePairs' contains a pair, where the value is not of type 'str'.") 

135 ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.") 

136 raise ex 

137 

138 innerDict[key] = value 

139 

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

141 """ 

142 Convert this argument instance to a string representation with proper escaping using the matching pattern based on 

143 the internal name. 

144 

145 :return: Formatted argument. 

146 :raises ValueError: If internal name is None. 

147 """ 

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

149 raise ValueError(f"Internal value '_name' is None.") 

150 

151 return [self._pattern.format(self._name, key, value) for key, value in self._value.items()] 

152 

153 

154@export 

155class ShortKeyValueFlag(NamedKeyValuePairsArgument, pattern="-{0}{1}={2}"): 

156 """ 

157 Represents a :py:class:`NamedKeyValueFlagArgument` with a single dash in front of the switch name. 

158 

159 **Example:** 

160 

161 * ``-DDEBUG=TRUE`` 

162 """ 

163 

164 def __init_subclass__(cls, *args: Any, name: Nullable[str] = None, pattern: str = "-{0}{1}={2}", **kwargs: Any) -> None: 

165 """ 

166 This method is called when a class is derived. 

167 

168 :param args: Any positional arguments. 

169 :param name: Name of the CLI argument. 

170 :param pattern: This pattern is used to format an argument. |br| 

171 Default: ``"-{0}{1}={2}"``. 

172 :param kwargs: Any keyword argument. 

173 """ 

174 kwargs["name"] = name 

175 kwargs["pattern"] = pattern 

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

177 

178 # TODO: the whole class should be marked as abstract 

179 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code 

180 def __new__(cls, *args: Any, **kwargs: Any) -> Self: 

181 """ 

182 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error. 

183 

184 :param args: Any positional arguments. 

185 :param kwargs: Any keyword arguments. 

186 :raises TypeError: When this class gets directly instantiated without being derived to a subclass. 

187 """ 

188 if cls is ShortKeyValueFlag: 

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

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

191 

192 

193@export 

194class LongKeyValueFlag(NamedKeyValuePairsArgument, pattern="--{0}{1}={2}"): 

195 """ 

196 Represents a :py:class:`NamedKeyValueFlagArgument` with a double dash in front of the switch name. 

197 

198 **Example:** 

199 

200 * ``--DDEBUG=TRUE`` 

201 """ 

202 

203 def __init_subclass__(cls, *args: Any, name: Nullable[str] = None, pattern: str = "--{0}{1}={2}", **kwargs: Any) -> None: 

204 """ 

205 This method is called when a class is derived. 

206 

207 :param args: Any positional arguments. 

208 :param name: Name of the CLI argument. 

209 :param pattern: This pattern is used to format an argument. |br| 

210 Default: ``"--{0}{1}={2}"``. 

211 :param kwargs: Any keyword argument. 

212 """ 

213 kwargs["name"] = name 

214 kwargs["pattern"] = pattern 

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

216 

217 # TODO: the whole class should be marked as abstract 

218 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code 

219 def __new__(cls, *args: Any, **kwargs: Any) -> Self: 

220 """ 

221 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error. 

222 

223 :param args: Any positional arguments. 

224 :param kwargs: Any keyword arguments. 

225 :raises TypeError: When this class gets directly instantiated without being derived to a subclass. 

226 """ 

227 if cls is LongKeyValueFlag: 

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

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

230 

231 

232@export 

233class WindowsKeyValueFlag(NamedKeyValuePairsArgument, pattern="/{0}:{1}={2}"): 

234 """ 

235 Represents a :py:class:`NamedKeyValueFlagArgument` with a double dash in front of the switch name. 

236 

237 **Example:** 

238 

239 * ``--DDEBUG=TRUE`` 

240 """ 

241 

242 def __init_subclass__(cls, *args: Any, name: Nullable[str] = None, pattern: str = "/{0}:{1}={2}", **kwargs: Any) -> None: 

243 """ 

244 This method is called when a class is derived. 

245 

246 :param args: Any positional arguments. 

247 :param name: Name of the CLI argument. 

248 :param pattern: This pattern is used to format an argument. |br| 

249 Default: ``"/{0}:{1}={2}"``. 

250 :param kwargs: Any keyword argument. 

251 """ 

252 kwargs["name"] = name 

253 kwargs["pattern"] = pattern 

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

255 

256 # TODO: the whole class should be marked as abstract 

257 # TODO: a decorator should solve the issue and overwrite the __new__ method with that code 

258 def __new__(cls, *args: Any, **kwargs: Any) -> Self: 

259 """ 

260 Check if this class was directly instantiated without being derived to a subclass. If so, raise an error. 

261 

262 :param args: Any positional arguments. 

263 :param kwargs: Any keyword arguments. 

264 :raises TypeError: When this class gets directly instantiated without being derived to a subclass. 

265 """ 

266 if cls is LongKeyValueFlag: 266 ↛ 267line 266 didn't jump to line 267 because the condition on line 266 was never true

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

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