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

75 statements  

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

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 sys import version_info # needed for versions before Python 3.11 

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

46 

47try: 

48 from pyTooling.Decorators import export 

49 from pyTooling.Common import getFullyQualifiedName 

50 from pyTooling.CLIAbstraction.Argument import NamedAndValuedArgument 

51except (ImportError, ModuleNotFoundError): # pragma: no cover 

52 print("[pyTooling.Versioning] Could not import from 'pyTooling.*'!") 

53 

54 try: 

55 from Decorators import export 

56 from Common import getFullyQualifiedName 

57 from CLIAbstraction.Argument import NamedAndValuedArgument 

58 except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover 

59 print("[pyTooling.Versioning] Could not import directly!") 

60 raise ex 

61 

62 

63@export 

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

65 """ 

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

67 (key-value-pairs). 

68 

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

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

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

72 

73 **Example:** 

74 

75 * ``-gWidth=100`` 

76 """ 

77 

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

79 kwargs["name"] = name 

80 kwargs["pattern"] = pattern 

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

82 

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

84 if cls is NamedKeyValuePairsArgument: 

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

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

87 

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

89 super().__init__({}) 

90 

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

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

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

94 if version_info >= (3, 11): # pragma: no cover 

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

96 raise ex 

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

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

99 if version_info >= (3, 11): # pragma: no cover 

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

101 raise ex 

102 

103 self._value[key] = value 

104 

105 @property 

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

107 """ 

108 Get the internal value. 

109 

110 :return: Internal value. 

111 """ 

112 return self._value 

113 

114 @Value.setter 

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

116 """ 

117 Set the internal value. 

118 

119 :param keyValuePairs: Value to set. 

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

121 """ 

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

123 innerDict.clear() 

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

125 if not isinstance(key, str): 

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

127 if version_info >= (3, 11): # pragma: no cover 

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

129 raise ex 

130 elif not isinstance(value, str): 

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

132 if version_info >= (3, 11): # pragma: no cover 

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

134 raise ex 

135 

136 innerDict[key] = value 

137 

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

139 """ 

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

141 the internal name. 

142 

143 :return: Formatted argument. 

144 :raises ValueError: If internal name is None. 

145 """ 

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

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

148 

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

150 

151 

152@export 

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

154 """ 

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

156 

157 **Example:** 

158 

159 * ``-DDEBUG=TRUE`` 

160 """ 

161 

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

163 kwargs["name"] = name 

164 kwargs["pattern"] = pattern 

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

166 

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

168 if cls is ShortKeyValueFlag: 

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

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

171 

172 

173@export 

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

175 """ 

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

177 

178 **Example:** 

179 

180 * ``--DDEBUG=TRUE`` 

181 """ 

182 

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

184 kwargs["name"] = name 

185 kwargs["pattern"] = pattern 

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

187 

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

189 if cls is LongKeyValueFlag: 

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

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

192 

193 

194@export 

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

196 """ 

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

198 

199 **Example:** 

200 

201 * ``--DDEBUG=TRUE`` 

202 """ 

203 

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

205 kwargs["name"] = name 

206 kwargs["pattern"] = pattern 

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

208 

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

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

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

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