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

79 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-10-19 06:41 +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 ex.add_note(f"Got type '{getFullyQualifiedName(key)}'.") 

95 raise ex 

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

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

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

99 raise ex 

100 

101 self._value[key] = value 

102 

103 @property 

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

105 """ 

106 Get the internal value. 

107 

108 :return: Internal value. 

109 """ 

110 return self._value 

111 

112 @Value.setter 

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

114 """ 

115 Set the internal value. 

116 

117 :param keyValuePairs: Value to set. 

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

119 """ 

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

121 innerDict.clear() 

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

123 if not isinstance(key, str): 

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

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

126 raise ex 

127 elif not isinstance(value, str): 

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

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

130 raise ex 

131 

132 innerDict[key] = value 

133 

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

135 """ 

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

137 the internal name. 

138 

139 :return: Formatted argument. 

140 :raises ValueError: If internal name is None. 

141 """ 

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

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

144 

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

146 

147 

148@export 

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

150 """ 

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

152 

153 **Example:** 

154 

155 * ``-DDEBUG=TRUE`` 

156 """ 

157 

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

159 kwargs["name"] = name 

160 kwargs["pattern"] = pattern 

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

162 

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

164 if cls is ShortKeyValueFlag: 

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

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

167 

168 

169@export 

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

171 """ 

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

173 

174 **Example:** 

175 

176 * ``--DDEBUG=TRUE`` 

177 """ 

178 

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

180 kwargs["name"] = name 

181 kwargs["pattern"] = pattern 

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

183 

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

185 if cls is LongKeyValueFlag: 

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

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

188 

189 

190@export 

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

192 """ 

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

194 

195 **Example:** 

196 

197 * ``--DDEBUG=TRUE`` 

198 """ 

199 

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

201 kwargs["name"] = name 

202 kwargs["pattern"] = pattern 

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

204 

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

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

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

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