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

78 statements  

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

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 

45 

46try: 

47 from pyTooling.Decorators import export 

48 from pyTooling.Common import getFullyQualifiedName 

49 from pyTooling.CLIAbstraction.Argument import NamedAndValuedArgument 

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

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

52 

53 try: 

54 from Decorators import export 

55 from Common import getFullyQualifiedName 

56 from CLIAbstraction.Argument import NamedAndValuedArgument 

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

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

59 raise ex 

60 

61 

62@export 

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

64 """ 

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

66 (key-value-pairs). 

67 

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

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

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

71 

72 **Example:** 

73 

74 * ``-gWidth=100`` 

75 """ 

76 

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

78 kwargs["name"] = name 

79 kwargs["pattern"] = pattern 

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

81 

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

83 if cls is NamedKeyValuePairsArgument: 

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

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

86 

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

88 super().__init__({}) 

89 

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

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

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

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

94 raise ex 

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

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

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

98 raise ex 

99 

100 self._value[key] = value 

101 

102 @property 

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

104 """ 

105 Get the internal value. 

106 

107 :return: Internal value. 

108 """ 

109 return self._value 

110 

111 @Value.setter 

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

113 """ 

114 Set the internal value. 

115 

116 :param keyValuePairs: Value to set. 

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

118 """ 

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

120 innerDict.clear() 

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

122 if not isinstance(key, str): 

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

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

125 raise ex 

126 elif not isinstance(value, str): 

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

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

129 raise ex 

130 

131 innerDict[key] = value 

132 

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

134 """ 

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

136 the internal name. 

137 

138 :return: Formatted argument. 

139 :raises ValueError: If internal name is None. 

140 """ 

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

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

143 

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

145 

146 

147@export 

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

149 """ 

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

151 

152 **Example:** 

153 

154 * ``-DDEBUG=TRUE`` 

155 """ 

156 

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

158 kwargs["name"] = name 

159 kwargs["pattern"] = pattern 

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

161 

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

163 if cls is ShortKeyValueFlag: 

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

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

166 

167 

168@export 

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

170 """ 

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

172 

173 **Example:** 

174 

175 * ``--DDEBUG=TRUE`` 

176 """ 

177 

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

179 kwargs["name"] = name 

180 kwargs["pattern"] = pattern 

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

182 

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

184 if cls is LongKeyValueFlag: 

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

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

187 

188 

189@export 

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

191 """ 

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

193 

194 **Example:** 

195 

196 * ``--DDEBUG=TRUE`` 

197 """ 

198 

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

200 kwargs["name"] = name 

201 kwargs["pattern"] = pattern 

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

203 

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

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

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

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