d6cb40f714af329645250f3915388df849ad8625
[csit.git] / resources / libraries / python / OptionString.py
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:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
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.
13
14 """Utility function for handling options without doubled or trailing spaces."""
15
16
17 class OptionString(object):
18     """Class serving as a builder for option strings.
19
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).
23
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.
30
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).
34
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.
37     """
38
39     def __init__(self, prefix="", *args):
40         """Create instance with listed strings as parts to use.
41
42         Prefix will be converted to string and stripped.
43         The typical (nonempty) prefix values are "-" and "--".
44
45         :param prefix: Subtring to prepend to every parameter (not value).
46         :param args: List of positional arguments to become parts.
47         :type prefix: object
48         :type args: list of object
49         """
50         self.prefix = str(prefix).strip()  # Not worth to call change_prefix.
51         self.parts = list(args)
52
53     def __repr__(self):
54         """Return string executable as Python constructor call.
55
56         :returns: Executable constructor call as string.
57         :rtype: str
58         """
59         return "".join([
60             "OptionString(prefix=", repr(self.prefix), ",",
61             repr(self.parts)[1:-1], ")"])
62
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.
66
67     def change_prefix(self, prefix):
68         """Change the prefix field from the initialized value.
69
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.
76
77         :param prefix: New prefix value, to be converted and tripped.
78         :type prefix: object
79         :returns: Self, to enable method chaining.
80         :rtype: OptionString
81         """
82         self.prefix = str(prefix).strip()
83
84     def extend(self, other):
85         """Extend self by contents of other option string.
86
87         :param other: Another instance to add to the end of self.
88         :type other: OptionString
89         :returns: Self, to enable method chaining.
90         :rtype: OptionString
91         """
92         self.parts.extend(other.parts)
93         return self
94
95     def _check_and_add(self, part, prefixed):
96         """Convert to string, strip, add conditionally prefixed if non-empty.
97
98         Emptiness is tested before adding prefix.
99
100         :param part: Unchecked part to add to list of parts.
101         :param prefixed: Whether to add prefix when adding.
102         :type part: object
103         :type prefixed: object
104         :returns: The converted part without prefix, empty means not added.
105         :rtype: str
106         """
107         part = str(part).strip()
108         if part:
109             prefixed_part = self.prefix + part if prefixed else part
110             self.parts.append(prefixed_part)
111         return part
112
113     def add(self, parameter):
114         """Add parameter if nonempty to the list of parts.
115
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.
119
120         :param parameter: Parameter object, usually a word starting with dash.
121         :type variable: object
122         :returns: Self, to enable method chaining.
123         :rtype: OptionString
124         """
125         self._check_and_add(parameter, prefixed=True)
126         return self
127
128     def add_if(self, parameter, condition):
129         """Add parameter if nonempty and condition is true to the list of parts.
130
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.
135
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.
141         :rtype: OptionString
142         """
143         if condition:
144             self.add(parameter)
145         return self
146
147     def add_with_value(self, parameter, value):
148         """Add parameter, if followed by a value to the list of parts.
149
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.
153
154         :param parameter: Parameter object, usually a word starting with dash.
155         :param value: Value object. Prefix is never added.
156         :type variable: object
157         :type value: object
158         :returns: Self, to enable method chaining.
159         :rtype: OptionString
160         """
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):
167                 self.extend(temp)
168         return self
169
170     def add_equals(self, parameter, value):
171         """Add parameter=value to the list of parts.
172
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.
176
177         :param parameter: Parameter object, usually a word starting with dash.
178         :param value: Value object. Prefix is never added.
179         :type variable: object
180         :type value: object
181         :returns: Self, to enable method chaining.
182         :rtype: OptionString
183         """
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))
189         return self
190
191     def add_with_value_if(self, parameter, value, condition):
192         """Add parameter and value if condition is true and nothing is empty.
193
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.
198
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
203         :type value: object
204         :type condition: object
205         :returns: Self, to enable method chaining.
206         :rtype: OptionString
207         """
208         if condition:
209             self.add_with_value(parameter, value)
210         return self
211
212     def add_equals_if(self, parameter, value, condition):
213         """Add parameter=value to the list of parts if condition is true.
214
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.
219
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
224         :type value: object
225         :type condition: object
226         :returns: Self, to enable method chaining.
227         :rtype: OptionString
228         """
229         if condition:
230             self.add_equals(parameter, value)
231         return self
232
233     def add_with_value_from_dict(self, parameter, key, mapping, default=""):
234         """Add parameter with value from dict under key, or default.
235
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.
240
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
246         :type key: str
247         :type mapping: dict
248         :type default: object
249         :returns: Self, to enable method chaining.
250         :rtype: OptionString
251         """
252         value = mapping.get(key, default)
253         return self.add_with_value(parameter, value)
254
255     def add_equals_from_dict(self, parameter, key, mapping, default=""):
256         """Add parameter=value to options where value is from dict.
257
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.
262
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
268         :type key: str
269         :type mapping: dict
270         :type default: object
271         :returns: Self, to enable method chaining.
272         :rtype: OptionString
273         """
274         value = mapping.get(key, default)
275         return self.add_equals(parameter, value)
276
277     def add_if_from_dict(self, parameter, key, mapping, default="False"):
278         """Add parameter based on if the condition in dict is true.
279
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.
285
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
291         :type key: str
292         :type mapping: dict
293         :type default: object
294         :returns: Self, to enable method chaining.
295         :rtype: OptionString
296         """
297         condition = mapping.get(key, default)
298         return self.add_if(parameter, condition)
299
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.
303
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.
309
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
316         :type value: object
317         :type key: str
318         :type mapping: dict
319         :type default: object
320         :returns: Self, to enable method chaining.
321         :rtype: OptionString
322         """
323         condition = mapping.get(key, default)
324         return self.add_with_value_if(parameter, value, condition)
325
326     def add_equals_if_from_dict(
327             self, parameter, value, key, mapping, default="False"):
328         """Add parameter=value based on condition in dict.
329
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.
335
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
342         :type value: object
343         :type key: str
344         :type mapping: dict
345         :type default: object
346         :returns: Self, to enable method chaining.
347         :rtype: OptionString
348         """
349         condition = mapping.get(key, default)
350         return self.add_equals_if(parameter, value, condition)
351
352     def __str__(self):
353         """Return space separated string of nonempty parts.
354
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.
358
359         :returns: Space separated string of options.
360         :rtype: str
361         """
362         return " ".join(self.parts)