1 # Copyright (c) 2019 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
14 """Utility function for handling options without doubled or trailing spaces."""
17 class OptionString(object):
18 """Class serving as a builder for option strings.
20 Motivation: Both manual contatenation and .join() methods
21 are prone to leaving superfluous spaces if some parts of options
22 are optional (missing, empty).
24 The scope of this class is more general than just command line options,
25 it can concatenate any string consisting of words that may be missing.
26 But options were the first usage, so method arguments are frequently
27 named "parameter" and "value".
28 To keep this generality, automated adding of dashes is optional,
29 and disabled by default.
31 Parts of the whole option string are kept as list items (string, stipped),
32 with prefix already added.
33 Empty strings are never added to the list (except by constructor).
35 The class offers many methods for adding, so that callers can pick
36 the best fitting one, without much logic near the call site.
39 def __init__(self, prefix="", *args):
40 """Create instance with listed strings as parts to use.
42 Prefix will be converted to string and stripped.
43 The typical (nonempty) prefix values are "-" and "--".
45 :param prefix: Subtring to prepend to every parameter (not value).
46 :param args: List of positional arguments to become parts.
48 :type args: list of object
50 self.prefix = str(prefix).strip() # Not worth to call change_prefix.
51 self.parts = list(args)
54 """Return string executable as Python constructor call.
56 :returns: Executable constructor call as string.
60 "OptionString(prefix=", repr(self.prefix), ",",
61 repr(self.parts)[1:-1], ")"])
63 # TODO: Would we ever need a copy() method?
64 # Currently, supersting "master" is mutable but unique,
65 # substring "slave" can be used to extend, but does not need to be mutated.
67 def change_prefix(self, prefix):
68 """Change the prefix field from the initialized value.
70 Sometimes it is more convenient to change the prefix in the middle
71 of string construction.
72 Typical use is for constructing a command, where the first part
73 (executeble filename) does not have a dash, but the other parameters do.
74 You could put the first part into constructor argument,
75 but using .add and only then enabling prefix is horizontally shorter.
77 :param prefix: New prefix value, to be converted and tripped.
79 :returns: Self, to enable method chaining.
82 self.prefix = str(prefix).strip()
84 def extend(self, other):
85 """Extend self by contents of other option string.
87 :param other: Another instance to add to the end of self.
88 :type other: OptionString
89 :returns: Self, to enable method chaining.
92 self.parts.extend(other.parts)
95 def _check_and_add(self, part, prefixed):
96 """Convert to string, strip, add conditionally prefixed if non-empty.
98 Emptiness is tested before adding prefix.
100 :param part: Unchecked part to add to list of parts.
101 :param prefixed: Whether to add prefix when adding.
103 :type prefixed: object
104 :returns: The converted part without prefix, empty means not added.
107 part = str(part).strip()
109 prefixed_part = self.prefix + part if prefixed else part
110 self.parts.append(prefixed_part)
113 def add(self, parameter):
114 """Add parameter if nonempty to the list of parts.
116 Parameter object is converted to string and stripped.
117 If parameter converts to empty string, nothing is added.
118 Parameter is prefixed before adding.
120 :param parameter: Parameter object, usually a word starting with dash.
121 :type variable: object
122 :returns: Self, to enable method chaining.
125 self._check_and_add(parameter, prefixed=True)
128 def add_if(self, parameter, condition):
129 """Add parameter if nonempty and condition is true to the list of parts.
131 If condition truth value is false, nothing is added.
132 Parameter object is converted to string and stripped.
133 If parameter converts to empty string, nothing is added.
134 Parameter is prefixed before adding.
136 :param parameter: Parameter object, usually a word starting with dash.
137 :param condition: Do not add if truth value of this is false.
138 :type variable: object
139 :type condition: object
140 :returns: Self, to enable method chaining.
147 def add_with_value(self, parameter, value):
148 """Add parameter, if followed by a value to the list of parts.
150 Parameter and value are converted to string and stripped.
151 If parameter or value converts to empty string, nothing is added.
152 If added, parameter (but not value) is prefixed.
154 :param parameter: Parameter object, usually a word starting with dash.
155 :param value: Value object. Prefix is never added.
156 :type variable: object
158 :returns: Self, to enable method chaining.
161 temp = OptionString(prefix=self.prefix)
162 # TODO: Is pylint really that ignorant?
163 # How could it not understand temp is of type of this class?
164 # pylint: disable=protected-access
165 if temp._check_and_add(parameter, prefixed=True):
166 if temp._check_and_add(value, prefixed=False):
170 def add_equals(self, parameter, value):
171 """Add parameter=value to the list of parts.
173 Parameter and value are converted to string and stripped.
174 If parameter or value converts to empty string, nothing is added.
175 If added, parameter (but not value) is prefixed.
177 :param parameter: Parameter object, usually a word starting with dash.
178 :param value: Value object. Prefix is never added.
179 :type variable: object
181 :returns: Self, to enable method chaining.
184 temp = OptionString(prefix=self.prefix)
185 # pylint: disable=protected-access
186 if temp._check_and_add(parameter, prefixed=True):
187 if temp._check_and_add(value, prefixed=False):
188 self.parts.append("=".join(temp.parts))
191 def add_with_value_if(self, parameter, value, condition):
192 """Add parameter and value if condition is true and nothing is empty.
194 If condition truth value is false, nothing is added.
195 Parameter and value are converted to string and stripped.
196 If parameter or value converts to empty string, nothing is added.
197 If added, parameter (but not value) is prefixed.
199 :param parameter: Parameter object, usually a word starting with dash.
200 :param value: Value object. Prefix is never added.
201 :param condition: Do not add if truth value of this is false.
202 :type variable: object
204 :type condition: object
205 :returns: Self, to enable method chaining.
209 self.add_with_value(parameter, value)
212 def add_equals_if(self, parameter, value, condition):
213 """Add parameter=value to the list of parts if condition is true.
215 If condition truth value is false, nothing is added.
216 Parameter and value are converted to string and stripped.
217 If parameter or value converts to empty string, nothing is added.
218 If added, parameter (but not value) is prefixed.
220 :param parameter: Parameter object, usually a word starting with dash.
221 :param value: Value object. Prefix is never added.
222 :param condition: Do not add if truth value of this is false.
223 :type variable: object
225 :type condition: object
226 :returns: Self, to enable method chaining.
230 self.add_equals(parameter, value)
233 def add_with_value_from_dict(self, parameter, key, mapping, default=""):
234 """Add parameter with value from dict under key, or default.
236 If key is missing, default is used as value.
237 Parameter and value are converted to string and stripped.
238 If parameter or value converts to empty string, nothing is added.
239 If added, parameter (but not value) is prefixed.
241 :param parameter: The parameter part to add with prefix.
242 :param key: The key to look the value for.
243 :param mapping: Mapping with keys and values to use.
244 :param default: The value to use if key is missing.
245 :type parameter: object
248 :type default: object
249 :returns: Self, to enable method chaining.
252 value = mapping.get(key, default)
253 return self.add_with_value(parameter, value)
255 def add_equals_from_dict(self, parameter, key, mapping, default=""):
256 """Add parameter=value to options where value is from dict.
258 If key is missing, default is used as value.
259 Parameter and value are converted to string and stripped.
260 If parameter or value converts to empty string, nothing is added.
261 If added, parameter (but not value) is prefixed.
263 :param parameter: The parameter part to add with prefix.
264 :param key: The key to look the value for.
265 :param mapping: Mapping with keys and values to use.
266 :param default: The value to use if key is missing.
267 :type parameter: object
270 :type default: object
271 :returns: Self, to enable method chaining.
274 value = mapping.get(key, default)
275 return self.add_equals(parameter, value)
277 def add_if_from_dict(self, parameter, key, mapping, default="False"):
278 """Add parameter based on if the condition in dict is true.
280 If key is missing, default is used as condition.
281 If condition truth value is false, nothing is added.
282 Parameter is converted to string and stripped.
283 If parameter converts to empty string, nothing is added.
284 Parameter is prefixed before adding.
286 :param parameter: The parameter part to add with prefix.
287 :param key: The key to look the value for.
288 :param mapping: Mapping with keys and values to use.
289 :param default: The value to use if key is missing.
290 :type parameter: object
293 :type default: object
294 :returns: Self, to enable method chaining.
297 condition = mapping.get(key, default)
298 return self.add_if(parameter, condition)
300 def add_with_value_if_from_dict(
301 self, parameter, value, key, mapping, default="False"):
302 """Add parameter and value based on condition in dict.
304 If key is missing, default is used as condition.
305 If condition truth value is false, nothing is added.
306 Parameter and value are converted to string and stripped.
307 If parameter or value converts to empty string, nothing is added.
308 If added, parameter (but not value) is prefixed.
310 :param parameter: The parameter part to add with prefix.
311 :param value: Value object. Prefix is never added.
312 :param key: The key to look the value for.
313 :param mapping: Mapping with keys and values to use.
314 :param default: The value to use if key is missing.
315 :type parameter: object
319 :type default: object
320 :returns: Self, to enable method chaining.
323 condition = mapping.get(key, default)
324 return self.add_with_value_if(parameter, value, condition)
326 def add_equals_if_from_dict(
327 self, parameter, value, key, mapping, default="False"):
328 """Add parameter=value based on condition in dict.
330 If key is missing, default is used as condition.
331 If condition truth value is false, nothing is added.
332 Parameter and value are converted to string and stripped.
333 If parameter or value converts to empty string, nothing is added.
334 If added, parameter (but not value) is prefixed.
336 :param parameter: The parameter part to add with prefix.
337 :param value: Value object. Prefix is never added.
338 :param key: The key to look the value for.
339 :param mapping: Mapping with keys and values to use.
340 :param default: The value to use if key is missing.
341 :type parameter: object
345 :type default: object
346 :returns: Self, to enable method chaining.
349 condition = mapping.get(key, default)
350 return self.add_equals_if(parameter, value, condition)
353 """Return space separated string of nonempty parts.
355 The format is suitable to be pasted as (part of) command line.
356 Do not call str() prematurely just to get a substring, consider
357 converting the surrounding text manipulation to OptionString as well.
359 :returns: Space separated string of options.
362 return " ".join(self.parts)