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

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

33 

34.. TODO:: Write module documentation. 

35 

36""" 

37from typing import ClassVar, Union, Iterable, Any, Optional as Nullable 

38 

39try: 

40 from pyTooling.Decorators import export 

41 from pyTooling.CLIAbstraction.Argument import NamedAndValuedArgument 

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

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

44 

45 try: 

46 from Decorators import export 

47 from CLIAbstraction.Argument import NamedAndValuedArgument 

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

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

50 raise ex 

51 

52 

53@export 

54class OptionalValuedFlag(NamedAndValuedArgument, pattern="{0"): 

55 """ 

56 Class and base-class for all OptionalValuedFlag classes, which represents a flag argument with data. 

57 

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

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

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

61 

62 Example: ``width=100`` 

63 """ 

64 _patternWithValue: ClassVar[str] 

65 

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

67 kwargs["pattern"] = pattern 

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

69 cls._patternWithValue = patternWithValue 

70 

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

72 if cls is OptionalValuedFlag: 

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

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

75 

76 def __init__(self, value: Nullable[str] = None) -> None: 

77 self._value = value 

78 

79 @property 

80 def Value(self) -> Nullable[str]: 

81 """ 

82 Get the internal value. 

83 

84 :return: Internal value. 

85 """ 

86 return self._value 

87 

88 @Value.setter 

89 def Value(self, value: Nullable[str]) -> None: 

90 """ 

91 Set the internal value. 

92 

93 :param value: Value to set. 

94 """ 

95 self._value = value 

96 

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

98 """ 

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

100 the internal name and optional value. 

101 

102 :return: Formatted argument. 

103 :raises ValueError: If internal name is None. 

104 """ 

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

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

107 

108 pattern = self._pattern if self._value is None else self._patternWithValue 

109 return pattern.format(self._name, self._value) 

110 

111 def __str__(self) -> str: 

112 return f"\"{self.AsArgument()}\"" 

113 

114 __repr__ = __str__ 

115 

116 

117@export 

118class ShortOptionalValuedFlag(OptionalValuedFlag, pattern="-{0}", patternWithValue="-{0}={1}"): 

119 """ 

120 Represents a :py:class:`OptionalValuedFlag` with a single dash. 

121 

122 Example: ``-optimizer=on`` 

123 """ 

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

125 kwargs["pattern"] = pattern 

126 kwargs["patternWithValue"] = patternWithValue 

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

128 

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

130 if cls is ShortOptionalValuedFlag: 

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

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

133 

134 

135@export 

136class LongOptionalValuedFlag(OptionalValuedFlag, pattern="--{0}", patternWithValue="--{0}={1}"): 

137 """ 

138 Represents a :py:class:`OptionalValuedFlag` with a double dash. 

139 

140 Example: ``--optimizer=on`` 

141 """ 

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

143 kwargs["pattern"] = pattern 

144 kwargs["patternWithValue"] = patternWithValue 

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

146 

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

148 if cls is LongOptionalValuedFlag: 

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

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

151 

152 

153@export 

154class WindowsOptionalValuedFlag(OptionalValuedFlag, pattern="/{0}", patternWithValue="/{0}:{1}"): 

155 """ 

156 Represents a :py:class:`OptionalValuedFlag` with a single slash. 

157 

158 Example: ``/optimizer:on`` 

159 """ 

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

161 kwargs["pattern"] = pattern 

162 kwargs["patternWithValue"] = patternWithValue 

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

164 

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

166 if cls is WindowsOptionalValuedFlag: 

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

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