Dave Cinege Git Repo thesaurus / b5bbc86
initial commit Dave Cinege 2 years ago
6 changed file(s) with 1367 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0
1 Apache License
2 Version 2.0, January 2004
3 http://www.apache.org/licenses/
4
5 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
7 1. Definitions.
8
9 "License" shall mean the terms and conditions for use, reproduction,
10 and distribution as defined by Sections 1 through 9 of this document.
11
12 "Licensor" shall mean the copyright owner or entity authorized by
13 the copyright owner that is granting the License.
14
15 "Legal Entity" shall mean the union of the acting entity and all
16 other entities that control, are controlled by, or are under common
17 control with that entity. For the purposes of this definition,
18 "control" means (i) the power, direct or indirect, to cause the
19 direction or management of such entity, whether by contract or
20 otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 outstanding shares, or (iii) beneficial ownership of such entity.
22
23 "You" (or "Your") shall mean an individual or Legal Entity
24 exercising permissions granted by this License.
25
26 "Source" form shall mean the preferred form for making modifications,
27 including but not limited to software source code, documentation
28 source, and configuration files.
29
30 "Object" form shall mean any form resulting from mechanical
31 transformation or translation of a Source form, including but
32 not limited to compiled object code, generated documentation,
33 and conversions to other media types.
34
35 "Work" shall mean the work of authorship, whether in Source or
36 Object form, made available under the License, as indicated by a
37 copyright notice that is included in or attached to the work
38 (an example is provided in the Appendix below).
39
40 "Derivative Works" shall mean any work, whether in Source or Object
41 form, that is based on (or derived from) the Work and for which the
42 editorial revisions, annotations, elaborations, or other modifications
43 represent, as a whole, an original work of authorship. For the purposes
44 of this License, Derivative Works shall not include works that remain
45 separable from, or merely link (or bind by name) to the interfaces of,
46 the Work and Derivative Works thereof.
47
48 "Contribution" shall mean any work of authorship, including
49 the original version of the Work and any modifications or additions
50 to that Work or Derivative Works thereof, that is intentionally
51 submitted to Licensor for inclusion in the Work by the copyright owner
52 or by an individual or Legal Entity authorized to submit on behalf of
53 the copyright owner. For the purposes of this definition, "submitted"
54 means any form of electronic, verbal, or written communication sent
55 to the Licensor or its representatives, including but not limited to
56 communication on electronic mailing lists, source code control systems,
57 and issue tracking systems that are managed by, or on behalf of, the
58 Licensor for the purpose of discussing and improving the Work, but
59 excluding communication that is conspicuously marked or otherwise
60 designated in writing by the copyright owner as "Not a Contribution."
61
62 "Contributor" shall mean Licensor and any individual or Legal Entity
63 on behalf of whom a Contribution has been received by Licensor and
64 subsequently incorporated within the Work.
65
66 2. Grant of Copyright License. Subject to the terms and conditions of
67 this License, each Contributor hereby grants to You a perpetual,
68 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 copyright license to reproduce, prepare Derivative Works of,
70 publicly display, publicly perform, sublicense, and distribute the
71 Work and such Derivative Works in Source or Object form.
72
73 3. Grant of Patent License. Subject to the terms and conditions of
74 this License, each Contributor hereby grants to You a perpetual,
75 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 (except as stated in this section) patent license to make, have made,
77 use, offer to sell, sell, import, and otherwise transfer the Work,
78 where such license applies only to those patent claims licensable
79 by such Contributor that are necessarily infringed by their
80 Contribution(s) alone or by combination of their Contribution(s)
81 with the Work to which such Contribution(s) was submitted. If You
82 institute patent litigation against any entity (including a
83 cross-claim or counterclaim in a lawsuit) alleging that the Work
84 or a Contribution incorporated within the Work constitutes direct
85 or contributory patent infringement, then any patent licenses
86 granted to You under this License for that Work shall terminate
87 as of the date such litigation is filed.
88
89 4. Redistribution. You may reproduce and distribute copies of the
90 Work or Derivative Works thereof in any medium, with or without
91 modifications, and in Source or Object form, provided that You
92 meet the following conditions:
93
94 (a) You must give any other recipients of the Work or
95 Derivative Works a copy of this License; and
96
97 (b) You must cause any modified files to carry prominent notices
98 stating that You changed the files; and
99
100 (c) You must retain, in the Source form of any Derivative Works
101 that You distribute, all copyright, patent, trademark, and
102 attribution notices from the Source form of the Work,
103 excluding those notices that do not pertain to any part of
104 the Derivative Works; and
105
106 (d) If the Work includes a "NOTICE" text file as part of its
107 distribution, then any Derivative Works that You distribute must
108 include a readable copy of the attribution notices contained
109 within such NOTICE file, excluding those notices that do not
110 pertain to any part of the Derivative Works, in at least one
111 of the following places: within a NOTICE text file distributed
112 as part of the Derivative Works; within the Source form or
113 documentation, if provided along with the Derivative Works; or,
114 within a display generated by the Derivative Works, if and
115 wherever such third-party notices normally appear. The contents
116 of the NOTICE file are for informational purposes only and
117 do not modify the License. You may add Your own attribution
118 notices within Derivative Works that You distribute, alongside
119 or as an addendum to the NOTICE text from the Work, provided
120 that such additional attribution notices cannot be construed
121 as modifying the License.
122
123 You may add Your own copyright statement to Your modifications and
124 may provide additional or different license terms and conditions
125 for use, reproduction, or distribution of Your modifications, or
126 for any such Derivative Works as a whole, provided Your use,
127 reproduction, and distribution of the Work otherwise complies with
128 the conditions stated in this License.
129
130 5. Submission of Contributions. Unless You explicitly state otherwise,
131 any Contribution intentionally submitted for inclusion in the Work
132 by You to the Licensor shall be under the terms and conditions of
133 this License, without any additional terms or conditions.
134 Notwithstanding the above, nothing herein shall supersede or modify
135 the terms of any separate license agreement you may have executed
136 with Licensor regarding such Contributions.
137
138 6. Trademarks. This License does not grant permission to use the trade
139 names, trademarks, service marks, or product names of the Licensor,
140 except as required for reasonable and customary use in describing the
141 origin of the Work and reproducing the content of the NOTICE file.
142
143 7. Disclaimer of Warranty. Unless required by applicable law or
144 agreed to in writing, Licensor provides the Work (and each
145 Contributor provides its Contributions) on an "AS IS" BASIS,
146 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 implied, including, without limitation, any warranties or conditions
148 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 PARTICULAR PURPOSE. You are solely responsible for determining the
150 appropriateness of using or redistributing the Work and assume any
151 risks associated with Your exercise of permissions under this License.
152
153 8. Limitation of Liability. In no event and under no legal theory,
154 whether in tort (including negligence), contract, or otherwise,
155 unless required by applicable law (such as deliberate and grossly
156 negligent acts) or agreed to in writing, shall any Contributor be
157 liable to You for damages, including any direct, indirect, special,
158 incidental, or consequential damages of any character arising as a
159 result of this License or out of the use or inability to use the
160 Work (including but not limited to damages for loss of goodwill,
161 work stoppage, computer failure or malfunction, or any and all
162 other commercial damages or losses), even if such Contributor
163 has been advised of the possibility of such damages.
164
165 9. Accepting Warranty or Additional Liability. While redistributing
166 the Work or Derivative Works thereof, You may choose to offer,
167 and charge a fee for, acceptance of support, warranty, indemnity,
168 or other liability obligations and/or rights consistent with this
169 License. However, in accepting such obligations, You may act only
170 on Your own behalf and on Your sole responsibility, not on behalf
171 of any other Contributor, and only if You agree to indemnify,
172 defend, and hold each Contributor harmless for any liability
173 incurred by, or claims asserted against, such Contributor by reason
174 of your accepting any such warranty or additional liability.
175
176 END OF TERMS AND CONDITIONS
177
178 APPENDIX: How to apply the Apache License to your work.
179
180 To apply the Apache License to your work, attach the following
181 boilerplate notice, with the fields enclosed by brackets "[]"
182 replaced with your own identifying information. (Don't include
183 the brackets!) The text should be enclosed in the appropriate
184 comment syntax for the file format. We also recommend that a
185 file or class name and description of purpose be included on the
186 same "printed page" as the copyright notice for easier
187 identification within third-party archives.
188
189 Copyright [yyyy] [name of copyright owner]
190
191 Licensed under the Apache License, Version 2.0 (the "License");
192 you may not use this file except in compliance with the License.
193 You may obtain a copy of the License at
194
195 http://www.apache.org/licenses/LICENSE-2.0
196
197 Unless required by applicable law or agreed to in writing, software
198 distributed under the License is distributed on an "AS IS" BASIS,
199 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 See the License for the specific language governing permissions and
201 limitations under the License.
0 all:
1
2 clean:
3 -rm *.pyc *.pyo
4 -rm -R __pycache__
0 EDITTING IN PROGRESS - NOT COHERENT
1
2 ####################################################
3
4
5 Thesaurus is a mapping data type with key recursion and attribute
6 aliasing. It is a subclass of dict() and compatible as a dictionary
7 replacement baring where key path recursion may take place. In
8 that regard Thesaurus is designed to .....
9
10
11 Thesaurus prefers to be imported and called as thes() in the
12 same way you would use dict(). Thesaurus likes to think of itself
13 as a Python data type primative that should be used along side of
14 dict(), similar to the relationship between list() and tuple();
15 they are overlappingly similar but serve different purposes
16 and diverge to incompatibilities. Thesaurus is currently
17 content with not having it's own data type tokens. Hopefully
18 so are you.
19
20
21 Telegram Discussion Group
22 https://t.me/PythonThesaurus
23
24 Thesaurus works with Python 2.6 to 3.8+.
25
26
27 ThesaurusExtended
28 ThesaurusCfg
29
30 ThesaurusExtended is a subclass of Thesaurus providing additional
31 usablity methods.
32
33 ThesaurusCfg is a subclass of ThesaurusExtended providing a configuration file
34 parser and per key data cohersion methods.
35
36
37 What is attribute alaising?
38 Attribute alaising refering to redirecting the methods __getattr__()
39 and__setattr__() to __getitem__() and __setitem__() respectivly.
40
41 The effect is to syntatically reference keys like attributes.
42
43 For example:
44 t['k']
45 t.k
46 are treated the same.
47
48 Thesaurus also provides a special alias
49
50
51 What is key recursion?
52
53
54 G.gws.lv._1.gw
55
56
57 For example:
58 t = thes()
59 t.set_path('k._k.__k.___k', ','Hello')
60 t.k._k.__k.___k
61 t['k']['_k']['__k']['___k']
62
63 Becasue of the nature pof Thesaurus, keys shodul be of trype str()
64
65
66 , difference being the latter will recurse or
67 'walk the key directory tree' until
68
69
70 What is a key path?
71 A key path is a string with path elements seperated by dots.
72 t['k']
73
74
75
76 Thesaurus
77
78 Nested dictionarys which I refert to as dictionary trees (aka nested dictionaries.)
79
80 DICTIONARY DIRECTORYS
81
82 from thesaurus import thes
83 from thesaurus import thesext as thes
84
85
86 Thesaurus is a pure dictionary subclass which allows calling keys as
87 if they are class attributes and will search through nested objects
88 recursively when __getitem__ is called.
89
90 You will notice that the code is very compact. However I have found that
91 this has completely changed the way I program in Python. I've re-written some
92 exiting programs using Thesaurus, and often realized 15-30% code reduction.
93 Additionally I find the new code much easier to read.
94
95 If you find yourself programing with nested dictionaries often, fighting to
96 generate output or command lines for external programs, or wish you had
97 a dictionary that could act (sort of) like a class, Thesaurus may be for you.
98
0 ###
1 # Python Thesaurus - A different way to call a dictionary.
2 #
3 # Copyright (c) 2013-2019 Dave Cinege
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 ###
17 from __future__ import print_function
18
19 __VERSION__ = (2, 9, 0, 20191110)
20
21 from sys import version_info, getrecursionlimit
22 __PYTHON_ORDERED__ = version_info[0:2] >= (3,6) # cPython 3,6+ has ordered keys built in.
23 __MAXRECURSE = getrecursionlimit()
24
25 class Return (Exception):
26 pass
27
28 class Keypath (list):
29 """Keypath: a list-like object representing a nested path of Thesaurus
30 keys.
31
32 __hash__() is defined to allow passing this mutable object as a
33 Thesaurus key, however Keypath's should otherwise not be considered
34 reliably hashable.
35 """
36 __sep = '.'
37 def __init__ (self, keypath=None):
38 if isinstance(keypath, str):
39 if keypath.startswith(self.__sep) or keypath.endswith(self.__sep) or self.__sep*2 in keypath or keypath == '':
40 raise IndexError("'{0}' has empty keyname".format(keypath))
41 super(Keypath, self).__init__(keypath.split(self.__sep))
42 elif isinstance(keypath, list) or isinstance(keypath, tuple):
43 super(Keypath, self).__init__(keypath)
44 elif keypath is None:
45 super(Keypath, self).__init__()
46 else:
47 raise TypeError(keypath)
48 def __str__ (self):
49 l = []
50 for k in self:
51 if '.' in k:
52 l.append("['{0}']".format(k))
53 else:
54 l.append('.{0}'.format(k))
55 s = ''.join(l)
56 if s.startswith('.'):
57 s = s[1:]
58 return s
59 def __hash__(self):
60 return hash(tuple(self))
61 def grow (self,end=0):
62 for n in range(1,len(self)+1+end):
63 yield self[:n]
64 def shrink (self):
65 for n in range(len(self),0,-1):
66 yield self[:n]
67 def walk (self, *args, **kw):
68 """
69 def walk_callback(kp, key, depth, *args):
70 raise Return(ret_value)
71 return Keypath(keypath).walk(walk_callback)
72 """
73 walk_list = enumerate(self) if not kw.pop('reverse', False) else enumerate_rev(self)
74 for depth,key in walk_list:
75 try:
76 args[0](self[:depth], key, depth, *args[1:], **kw)
77 except Return as r:
78 return r
79
80 class Thesaurus (dict):
81 def __getattr__ (self, name):
82 if name.startswith('_'):
83 if name.startswith('__') and name.endswith('__'):
84 return dict.__getattr__(self, name)
85 return self.__getitem__(alias_digit_key(name))
86 return self.__getitem__(name)
87 def __setattr__ (self, name, value):
88 if name.startswith('_'):
89 return self.__setitem__(alias_digit_key(name), value)
90 return self.__setitem__(name, value)
91 def __delattr__ (self, name):
92 return self.__delitem__(name)
93 def __contains__(self, key):
94 return self.has_path(key)
95 def __getitem__ (self, key):
96 try:
97 return dict.__getitem__(self, key)
98 except:
99 keypath = Keypath(key)
100 if len(keypath) == 1:
101 return dict.__getitem__(self, keypath[0])
102 o = self
103 for depth,key in enumerate(keypath): # Walk keys recursively
104 _checkrecurse(self, depth)
105 try:
106 o = o[key] # Attempt key
107 except:
108 try:
109 o = getattr(o, key) # Attempt attr
110 except:
111 raise KeyError("'{key}' ({keypath} [depth={depth}])".format(**locals()))
112 return o # Will fall through to return self if len(keypath) == 0
113 def __setitem__ (self, key, value):
114 if not isinstance(key, str):
115 raise KeyError(type(key))
116 return dict.__setitem__(self, key, value)
117 def copy (self):
118 t = self.__class__()
119 t.overlay(self)
120 return t
121 def getitem (self, key):
122 """getitem with absolute key name and no recursion."""
123 return dict.__getitem__(self, key)
124 def has_key (self, key):
125 """has_key with absolute key name and no recursion."""
126 return dict.__contains__(self, key)
127 def has_path (self, keypath):
128 """has_key with recursion."""
129 try:
130 self.__getitem__(keypath)
131 return True
132 except KeyError:
133 return False
134 def set_path (self, keypath, value):
135 """set_path complete tree from keypath.split('.'))"""
136 keypath = Keypath(keypath)
137 o = self
138 for _key in keypath[:-1]:
139 if _key not in o:
140 o.__setitem__(_key, self.__class__())
141 elif not isinstance(o[_key], Thesaurus):
142 raise KeyError('{0}: not a Thesaurus object'.format(_key))
143 o = o[_key]
144 return o.__setitem__(keypath[-1], value)
145 def del_path (self, keypath):
146 """delete a path from end to start, walking backwards"""
147 keypath = Keypath(keypath)
148 if not self.has_path(keypath):
149 raise KeyError(keypath)
150 for kp in keypath.shrink():
151 del self[kp[:-1]][kp[-1]] # Accidently found it returns self on 0 len keypath. I claim Super Genius.
152
153 def filter (self, d):
154 # TODO
155 """self.walk()
156 if kp not in d:
157 self.del_path(kp)
158 # Can't do inplace
159 """
160 pass
161
162
163
164 # FIX ME: Rename screen to mask? Rename mesh to mask, and screen to mesh?
165 def merge (self, d=None):
166 """Recursively copy all items to self."""
167 return self.overlay(d, overwrite=True)
168 def mesh (self, d=None):
169 """Recursively copy items not existing in self."""
170 return self.overlay(d, overwrite=False)
171 def screen (self, d=None):
172 """Recursively copy items only existing in self"""
173 return self.overlay(d, overwrite=True, updateonly=True)
174
175 # FIX ME, properly copy/deepcopy items
176 def overlay (self, d, overwrite=True, updateonly=False, withcopy=True):
177 """Recursively copy a mapping onto self according
178 to parameters. dict subclasses will be converted
179 to __class__()"""
180 def recursedict(dst, src, depth=0):
181 _checkrecurse(self, depth)
182 for _key,_val in iter(src.items()):
183 if not overwrite and _key in dst:
184 continue
185 if not isinstance(_val, dict):
186 if updateonly and _key not in dst:
187 continue
188 dst.__setitem__(_key, _val)
189 else:
190 if _key not in dst:
191 if updateonly:
192 continue
193 dst.__setitem__(_key, self.__class__())
194 recursedict(dst[_key], _val, depth+1)
195 recursedict(self, d)
196
197 class ThesaurusOrdered (Thesaurus):
198 def __init__(self, *args, **kwargs):
199 Thesaurus.__init__(self)
200 self.__keyorder = list()
201 if len(args) == 1: # WARNING: mappings will not come in ordered!
202 self.update(args[0])
203 if len(kwargs) > 0:
204 self.update(kwargs)
205 def __setattr__ (self, name, value):
206 if name.startswith('_'):
207 if name.startswith('_ThesaurusOrdered__'):
208 return object.__setattr__(self, name, value)
209 name = alias_digit_key(name)
210 if name not in self.__keyorder:
211 self.__keyorder.append(name)
212 return Thesaurus.__setitem__(self, name, value)
213 def __setitem__ (self, key, value):
214 if not isinstance(key, str):
215 raise KeyError(type(key))
216 if key not in self.__keyorder:
217 self.__keyorder.append(key)
218 return Thesaurus.__setitem__(self, key, value)
219 def __delitem__ (self, key):
220 if key in self.__keyorder:
221 self.__keyorder.remove(key)
222 return Thesaurus.__delitem__(self, key)
223 def keys (self):
224 return list( self.__keyorder )
225 def values (self):
226 return list( self[key] for key in self.__keyorder )
227 def items (self):
228 return list( (key, self[key]) for key in self.__keyorder )
229 def clear (self):
230 for key in self.__keyorder:
231 del self[key]
232 del self.__keyorder[:]
233 def __iter__ (self):
234 return self.iterkeys()
235 def iterkeys (self):
236 for key in self.__keyorder:
237 yield key
238 def itervalues (self):
239 for key in self.__keyorder:
240 yield self[key]
241 def iteritems (self):
242 for key in self.__keyorder:
243 yield key, self[key]
244
245 def pop (self, key, default=None):
246 if key in self.__keyorder:
247 self.__keyorder.remove(key)
248 return Thesaurus.pop(self, key, default)
249 def popitem (self):
250 if len(self.__keyorder) == 0:
251 raise KeyError('popitem(): thesaurus is empty')
252 key = self.__keyorder.pop(-1)
253 value = self[key]
254 del self[key]
255 return key, value
256 def setdefault (self, key, default=None):
257 if key not in self.__keyorder:
258 self.__keyorder.append(key)
259 return Thesaurus.setdefault(self, key, default)
260 def update(self, *args, **kwargs):
261 d = args[0]
262 if isinstance(d, dict):
263 items = iter(d.items())
264 else:
265 items = d
266 for k,v in items:
267 if k not in self.__keyorder:
268 self.__keyorder.append(k)
269 self[k] = v
270
271
272 class ThesaurusExtension (object):
273 """Extra methods for Thesaurus that argulably don't belong in the base
274 data type.
275 """
276 def get_keys (self, value):
277 """recursively search for 'value' in tree and reply with
278 keypaths with this value or empty list.
279 """
280 return self._search_tree(None,value,0)
281 def get_values (self, key):
282 """recursively search for 'key' in tree and reply with
283 values of this key or empty list.
284 """
285 return self._search_tree(key,None,1)
286 def get_items (self, key):
287 """recursively search for 'key' in tree and reply with
288 (keypath, value) found or empty list.
289 """
290 return self._search_tree(key,None,2)
291 def get_in (self, value, val_type=False):
292 """recursively search for 'value' in values in tree and reply
293 with keypaths found or empty list. Optionally only compare
294 values of X type to prevent false positives. (IE: Finding a
295 substr in a key name)
296 """
297 return self._search_tree(None,value,5,val_type)
298 def find_key (self, key):
299 """recursively search for 'key' in tree and reply with
300 keypaths containing this key or empty list. 'key' is not
301 returned in keypaths.
302 """
303 return self._search_tree(key,None,3)
304 def find_item (self, key, value):
305 """recursively search for item (d[key] == value') in tree
306 and reply with keypaths found or empty list. 'key' is not
307 returned in keypaths.
308 """
309 return self._search_tree(key,value,4)
310 def _search_tree (self, key=None, value=None, search=0, val_type=False):
311 key_tree = list()
312 def recursedict(d, key, value, search, val_type, key_tree, _key_tree=[], depth=0):
313 _checkrecurse(self, depth)
314 for _key,_val in iter(d.items()):
315 if search == 0 and _val == value:
316 key_tree.append(key_treepath(_key_tree, _key))
317 elif search == 1 and _key == key:
318 key_tree.append(_val)
319 elif search == 2 and _key == key:
320 key_tree.append((key_treepath(_key_tree, _key), _val))
321 elif search == 3 and _key == key:
322 key_tree.append(key_treepath(_key_tree))
323 elif search == 4 and _key == key and _val == value:
324 key_tree.append(key_treepath(_key_tree))
325 elif search == 5:
326 if val_type and val_type != type(_val):
327 pass
328 else:
329 try:
330 if value in _val:
331 key_tree.append(key_treepath(_key_tree, _key))
332 except: pass
333 if isinstance(_val, dict):
334 recursedict(_val, key, value, search, val_type, key_tree, _key_tree+[_key], depth+1)
335 recursedict(self, key, value, search, val_type, key_tree)
336 return key_tree
337 def print_tree (self, tostr=False):
338 def recursedict(d, keypath, depth=0, s=''):
339 _checkrecurse(self, depth)
340 for _key,_val in iter(d.items()):
341 if not isinstance(_val, dict):
342 s += '[{depth}] {0} = {_val}\n'.format(Keypath(keypath+[_key]), **locals())
343 else:
344 keypath.append(_key)
345 s += '[{depth}] {keypath}: {0}\n'.format(type(_val), **locals())
346 s += recursedict(_val, keypath, depth+1)
347 del keypath[-1]
348 return s
349 s = recursedict(self, Keypath())
350 s = '{0} {{\n{1}}}'.format(type(self), s)
351 if tostr:
352 return s
353 print(s)
354
355 ### Define the prefered import names. Default to use ordered keys.
356 if __PYTHON_ORDERED__:
357 thes = Thesaurus
358 else:
359 thes = ThesaurusOrdered
360 ###
361
362 class ThesaurusExtended (ThesaurusExtension, thes):
363 def __getitem__ (self, key):
364 """Support int index and slicing."""
365 if isinstance (key, int) or isinstance (key, slice):
366 return list(self.values())[key]
367 return thes.__getitem__(self, key)
368
369 thesext = ThesaurusExtended
370
371
372 def key_treepath (key_tree, *keys):
373 return Keypath(key_tree+list(keys))
374
375 def alias_digit_key (name):
376 """Attribute alias for keynames starting with a digit: t._0ab == t['0ab'].
377 We check name.startswith('_') above.
378 """
379 return name[1:] if name[1:2].isdigit() else name
380
381 def enumerate_rev (arg):
382 """Generator to enumerate in reverse"""
383 return ( (n,arg[n]) for n in range(len(arg)-1,-1,-1) )
384
385 def _checkrecurse (self, depth):
386 if depth >= __MAXRECURSE:
387 raise RuntimeError('maximum recursion depth exceeded while calling a {0} object'.format(self.__class__.__name__))
388
389 if __name__ == '__main__':
390 import timeit
391 #t = thes()
392
393 #kp = Keypath('a.b.c')
394 #kp += ('c','d')
395 #kp += 'e'
396 #kp += 'f.g.h'
397
398
399 #print(kp)
400 #print(repr(kp))
401 #kp.walk(print)
402 #kp.walk(print, reverse=True)
403 """
404 def do (kp, k, depth, t):
405 if depth == 1:
406 raise Return(thes())
407 print('do',k)
408 t[k] = depth
409 t = t[k]
410 print(str(kp.walk(do, t)))
411 """
412 #print(t.__class__.__name__)
413
414 #t.set_path('a.b.c.d', 'ddd')
415 #print(t)
416
417 #ti = timeit.Timer("thes().set_path('a.b.c.d', 'ddd')", globals=locals())
418 #print(ti.timeit(number=100000))
419
420
421 """
422 te = thesext()
423 te.a = 1
424 te.b = 2
425 te.c = 3
426 print(te[1])
427 print(te[-1])
428 print(te.a)
429 print('a.b.c' in te)
430 """
431 t = thesext()
432 t.set_path('a.b.c.d', 'ddd')
433
434 kp = Keypath('a.b.c')
435 kp += ('this.host.com',)
436 print('kp:',repr(kp))
437 t.set_path(kp, 'abyss')
438
439 #t[kp] = 'abyss'
440 t.print_tree()
441 print(t[kp])
442
443 print(t.get_keys('abyss'))
444
445 print(t.get_values('c'))
446
447 print(t.get_items('d'))
448
449 print(t.a.b.c[1])
450
451 #print(t['a.b.c.d'])
452 #print(repr(t.a.b.c))
453
454 # This works
455 # del t['a.b.c']['d']
456 # del t.a.b.c.d
457
458 # This will not work
459 # del t['a.b.c.d']
460
461 #t.a.b.del_path('c.d')
462
463 """
464 del t.a.b[('c',)]['d']
465 tp = tuple()
466 kp = Keypath(tp)
467 del t.a.b[kp]['c']
468 #del t.a.b.c.d
469 print(repr(t))
470 """
471
472 import timeit
473 print(timeit.timeit(
474 "t['a.b.c.d']",
475 setup="from __main__ import thes; t = thes(); t.set_path('a.b.c.d.e.f.g.h.i.j', 'ddd')",
476 number=100000),
477 )
0 ###
1 # Python Thesaurus Config
2 #
3 # Copyright (c) 2019 Dave Cinege
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 ###
17 from __future__ import print_function
18
19 __VERSION__ = (2, 9, 9, 20190910)
20
21 import os
22 import sys
23 import re
24 import shlex
25
26 from string import Template
27
28 from thesaurus import thes, thesext, key_treepath
29
30 class cfg_types (object):
31 class __EXAMPLE (object):
32 def set (self, key, val, curval):
33 """value assignment call.
34 return value is passed to __setitem__()"""
35 return val
36 def parse (self, key, val):
37 """str value as parsed from cfg format.
38 return value is passed to __setitem__()"""
39 return val
40 def dump (self, key, val):
41 """return value is converted to str() and
42 written to cfg format"""
43 return val
44 class static (object):
45 """Return current value for setitem except
46 when *first* read from cfg"""
47 def set (self, key, val, curval):
48 return curval
49 class int (object):
50 def parse (self, key, val):
51 return int(val)
52 class static_int (static, int):
53 pass
54
55 class str_list (object):
56 def parse (self, key, val):
57 return shlex.split(val)
58 def dump (self, key, val):
59 if len(val) == 0:
60 return ''
61 s = ''
62 for i in val:
63 s += '"%s" ' % (i.replace('"','\\"').replace("'","\\'"))
64 return s[:-1]
65 class str_to_bool (object):
66 """"Support 3 values: True, False, None"""
67 def set (self, key, val, curval):
68 if val in (True, False, None):
69 return val
70 raise TypeError(s)
71 def parse (self, key, val):
72 s = val.lower()
73 if s in ('true', 'yes', 'on', '1'):
74 return True
75 if s in ('false', 'no', 'off', '0'):
76 return False
77 if s in ('none', ''):
78 return None
79 raise TypeError(s)
80 def dump (self, key, val):
81 if val == None:
82 return 'None'
83 return bool(val)
84
85 class configparser (object):
86 def __init__(self, *args, **kwargs):
87 self._thes_type = thesext
88 self._value_lstrip = True
89 self._value_rstrip_comment = True
90 self._value_rstrip = True
91 for k,v in kwargs.items():
92 setattr(self, '_'+k, v)
93 def read(self, filename=None, t=None):
94 if t == None: t = self._thes_type()
95 t = self._thes_type()
96 with open(filename, 'r') as fp:
97 return self.readfp(fp, t)
98 def readfp (self, fp=None, t=None):
99 if t == None: t = self._thes_type()
100 return self.parse(t, fp.read())
101 def parse (self, t=None, s='', func_map={}, set_map={}, parse_map={}, dump_map={}):
102 """Original trimmed text is returned, sutain for input back to parse"""
103 def full_key (root_key, key):
104 if root_key != '':
105 return root_key+'.'+key
106 return key
107 if t == None: t = self._thes_type()
108
109 comment_mline_double_pat = r'(\A|\n)""".*?"""(\Z|\n)'
110 comment_mline_single_pat = r"(\A|\n)'''.*?'''(\Z|\n)"
111 comment_line_pat = r'(\A|\n)#.*'
112 empty_head_pat = r'\A\n+?'
113 empty_tail_pat = r'\n+?\Z'
114 empty_line_pat = r'\n\n+'
115 keyval_line_pat = r'\n([^ \t].*?)\n'
116
117 s = re.sub('\r\n', '\n', s) # DOS conversion
118 s = re.sub('\r', '\n', s) # MAC conversion
119
120 # Python 2.6 doesn't accept flags= on methods, so compile all
121 s = re.compile(comment_mline_double_pat, flags=re.UNICODE|re.DOTALL).sub('', s)
122 s = re.compile(comment_mline_single_pat, flags=re.UNICODE|re.DOTALL).sub('', s)
123 s = re.compile(comment_line_pat, flags=re.UNICODE).sub('', s)
124 s = re.compile(empty_head_pat, flags=re.UNICODE|re.DOTALL).sub('', s)
125 s = re.compile(empty_tail_pat, flags=re.UNICODE|re.DOTALL).sub('', s)
126 s = re.compile(empty_line_pat, flags=re.UNICODE|re.DOTALL).sub('\n', s)
127
128 # I know this is a bad idea to touch data, but just soooo easy for now
129 evil_mline_sep = '__%%mline_sep%0A%%__'
130 s = re.compile('\n[ \t]', flags=re.UNICODE|re.DOTALL).sub(evil_mline_sep, s)
131 re_mline_sep = re.compile(evil_mline_sep, flags=re.UNICODE|re.DOTALL)
132
133 re_sep = re.compile('[=:]+?', flags=re.UNICODE)
134
135 #print(lines)
136 root_key = ''
137 for line in s.split('\n'):
138 if line.strip() == '':
139 continue
140
141 #print('A:',line,':E')
142
143 # FIX ME suport empty root sections without []
144 if line.startswith('[') and line.rstrip().endswith(']'):
145 root_key = line.rstrip()[1:-1].strip() # '[]' section resets root_key
146 if root_key != '' and root_key not in t:
147 t.set_path(root_key, self._thes_type()) # FIX me use parent class
148 continue
149
150 key,value = re_sep.split(line, 1)
151 value = re_mline_sep.sub('\n', value)
152
153 if self._value_rstrip_comment:
154 if '\n' not in value:
155 value = value.rsplit('#')[0]
156 if self._value_rstrip:
157 value = value.rstrip()
158 if self._value_lstrip:
159 value = value.lstrip()
160
161 if '(' not in key:
162 key = full_key(root_key, key.strip())
163 funcname = None
164 else:
165 key,funcvar = key.strip().split('(')
166 key = full_key(root_key, key.strip())
167 funcname = funcvar[:-1].strip()
168
169 if funcname and funcname in func_map:
170 if hasattr(func_map[funcname], 'parse'):
171 parse_map[key] = func_map[funcname]().parse
172 if key in parse_map:
173 value = parse_map[key](key, value)
174 t.set_path(key, value) # Apply parse_map prior to set. NOTE: addition applicaiton WILL applied set_map
175
176 if funcname and funcname in func_map:
177 if hasattr(func_map[funcname], 'set'):
178 set_map[key] = func_map[funcname]().set
179 if hasattr(func_map[funcname], 'dump'):
180 dump_map[key] = func_map[funcname]().dump
181
182 return t
183 def write (self, fp=None, t=None):
184 if t == None: t = self._thes_type()
185 return self.dump(t, fp.read())
186
187 def dump(self, t, sections=0, empty_sect=True, dump_map={}):
188 def recursedict(d, sections, empty_sect, dump_map, key_tree=[], depth=0, s='', r=''):
189 for k,v in iter(d.items()):
190 if hasattr(v, 'keys'):
191 key_tree.append(k)
192 r = recursedict(v, sections, empty_sect, dump_map, key_tree, depth+1)
193 if sections and depth < sections:
194 if r or empty_sect:
195 if s != '': s += '\n' # Not at top of output
196 s += '[%s]\n' % (key_treepath(key_tree))
197 elif not r and empty_sect:
198 s += '%s\n' % (key_treepath(key_tree))
199 s += r
200 key_tree.pop(-1)
201 else:
202 if sections and depth == 0 and r: # More root level values after recursing
203 s += '\n[]\n'; r = '' # Reset section so not absorbed by previous
204 if k in dump_map:
205 v = dump_map[k](k, v)
206 if '\n' in str(v):
207 v = ':\n\t%s\n' % (v.replace('\n','\n\t'))
208 else:
209 v = ' = %s\n' % (str(v))
210 if not sections:
211 s += key_treepath(key_tree, k) + v
212 else:
213 s += key_treepath(key_tree[sections:], k) + v
214 return s
215 return recursedict(t, sections, empty_sect, dump_map)
216
217 class ThesConf (object):
218 def __init__(self, *args, **kwargs):
219 self.__set_map = dict()
220 self.__parse_map = dict()
221 self.__dump_map = dict()
222
223 def read (self, filename, *args, **kwargs):
224 with open(filename, 'r') as f:
225 return self.parse(f.read(), *args, **kwargs)
226 def parse (self, data, *args, **kwargs):
227 func_map=mapper(cfg_types())
228 return configparser(thes_type=self.__class__).parse(self, data, func_map=func_map,
229 set_map=self.__set_map, parse_map=self.__parse_map, dump_map=self.__dump_map)
230 def write (self, fp, *args, **kwargs):
231 fp.write(self.dump(*args, **kwargs))
232 def dump (self, sections=0, empty_sect=True):
233 return configparser(thes_type=self.__class__).dump(self, sections, empty_sect, dump_map=self.__dump_map)
234
235
236 class ThesaurusCfg (thesext, ThesConf):
237 """A configuration file format utilizing the Thesaurus
238 data type supporting nested sections and parse, dump,
239 and assignment callbacks functions."""
240 def __init__(self, *args, **kwargs):
241 thesext.__init__(self, *args, **kwargs)
242 ThesConf.__init__(self)
243 def __setattr__ (self, name, value):
244 if name.startswith('_ThesConf__'):
245 return object.__setattr__(self, name, value)
246 if '_ThesConf__set_map' in self.__dict__ and name in self._ThesConf__set_map:
247 value = self._ThesConf__set_map[name](name, value, self[name])
248 return thesext.__setattr__(self, name, value)
249 def __setitem__ (self, key, value):
250 if '_ThesConf__set_map' in self.__dict__ and key in self._ThesConf__set_map:
251 value = self._ThesConf__set_map[key](key, value, self[key])
252 return thesext.__setitem__(self, key, value)
253
254
255 class mapper (dict):
256 """map from multiple objects:
257 '%(a)s %(b)s' % mapper(locals(), dict0, class1 ...)"""
258 def __init__ (self, *args):
259 self.__mappings = args
260 def __hasattr__ (self, name):
261 return self.__contains__(name)
262 def __getattr__ (self, name):
263 return self.__getitem__(name)
264 def __contains__(self, key):
265 try:
266 self.__getitem__(key)
267 return True
268 except:
269 return False
270 def __getitem__ (self, key):
271 for d in self.__mappings:
272 try:
273 return d[key]
274 except: pass
275 try:
276 return getattr(d, key)
277 except: pass
278 raise KeyError('can not map: {0}'.format(key))
279
280
281 def kwmapper (*args):
282 """ '{keyname}'.format(**kwmapper(locals(), dict0, class1 ... ))
283 NOTE: this can not recurse into object attributes like mapper
284 because it's copying to a single dict. :-( With that said
285 ''.format(kwmapper()) is much faster then % (printf) or string.Template
286 using mapper().
287 """
288 kw = dict()
289 for d in args:
290 if isinstance(d, dict):
291 kw.update(d)
292 elif hasattr(d, '__dict__'):
293 for k in d.__dict__:
294 if k.startswith('_'):
295 continue
296 kw[k] = getattr(d, k)
297 else:
298 raise TypeError('can not map: {0}'.format(type(d)))
299 return kw
300
301
302 """
303 Wrapper functions for .format(), % (printf), and string.Template that use the
304 last argument as the input string and all preceding arguments with kwmapper
305 or mapper(). Use it like this for very clean syntax with large block strings:
306 s = fmt(locals(), dict0, class1, thes2, '''
307 /sbin/iptables -t nat -F {chain}
308 /sbin/iptables -t nat -D {parent.chain} -j {chain}
309 /sbin/iptables -t nat -X {chain}
310 /sbin/iptables -t nat -N {chain}
311 ''')
312 """
313 def fmt (*args):
314 return args[-1].format(**kwmapper(*(args[:-1])))
315 def prtf (*args):
316 return args[-1] % mapper(*(args[:-1]))
317
318 class template (Template):
319 """add '.' and recognize digits so we can
320 recurse with Thesaurus. Must use ${} to recurse."""
321 idpattern = r'[_a-z0-9][._a-z0-9]*' # orig r'[_a-z][_a-z0-9]*'
322 delimiter = '$'
323 def tmpl (*args):
324 return template(args[-1]).substitute(mapper(*(args[:-1])))
325 def tmpl_safe (*args):
326 return template(args[-1]).safe_substitute(mapper(*(args[:-1])))
327
328 # tl;dr: use fmt() for speed unless you have f-string available (py 3.6+)
329 # t = thes() ; t.set_path('a.b.c.table', '9999'); table = '123'
330 # test_str = '''\n/sbin/iptables -t {table} -N {a.b.c.table}\n/sbin/iptables -t {table} -A\n'''
331 # 100000 Iteration performance test cPython 3.6 cPython2.7 cPython2.6
332 # tmpl(locals(), t, test_str) 1.0474729537963867 1.19237399101 1.44343900681
333 # prtf(locals(), t, test_str) 0.5701203346252441 0.709426879883 0.879161119461
334 # fmt(locals(), t, test_str) 0.4930698871612549 0.479194879532 0.610402822495
335 # fstr(test_str)
336 # test_str.format(**locals(), **t) 0.396730899810791 N/A N/A
337 # f''' (f-string) 0.2974255084991455 N/A N/A
338
339
340 def fstr (s):
341 """The poor mans' f-string for CPython2.6 -> 3.8+"""
342 return s.format(**sys._getframe(1).f_locals)
343
344 def readlineclean (s, nostrip=False, isfile=False, nocomments=True):
345 """
346 Iterate lines from str or filename, skips blanks and comments.
347 """
348 if isfile:
349 f = open(s)
350 lines = f.readlines
351 else:
352 lines = s.splitlines
353
354 for line in lines():
355 if line.strip() == '' or line.strip().startswith('#'):
356 continue
357 if nocomments:
358 line,_,_ = line.partition('#')
359 if nostrip:
360 yield line
361 else:
362 yield line.strip()
363 try:
364 f.close()
365 except: pass
366
367
368 #Define prefered import name
369 thescfg = ThesaurusCfg
370
371 if __name__ == '__main__':
372 #cp = configparser()
373 #cp.read(sys.argv[1])
374 #cp.write(None,0)
375 #cp.t.print_tree()
376
377
378 #t = thescfg()
379 #t.read('thesaurus_config.testcfg')
380 #t.read('fw.admin.cfg')
381 #t.print_tree()
382
383 a = 'Hello'
384 print(fstr('{a}! I am {__name__}'))
385 print(fstr('{a}! I am {__name__}. sys is {sys.__name__}'))
386
387 import time
388 t = thes()
389 t.set_path('a.b.c.table', '9999')
390 table = '123'
391
392 test_str = '''\n/sbin/iptables -t {table} -N {t.a.b.c.table}\n/sbin/iptables -t {table} -A\n'''
393 print(fstr(test_str))
394 sys.exit(0)
395
396 test_str = '''\n/sbin/iptables -t %(table)s -N %(a.b.c.table)s\n/sbin/iptables -t %(table)s -A\n'''
397 b = time.time()
398 for i in range(100000):
399 prtf(locals(), t, test_str)
400 print(time.time() - b)
401
402 test_str = '''\n/sbin/iptables -t {table} -N {a.b.c.table}\n/sbin/iptables -t {table} -A\n'''
403 b = time.time()
404 for i in range(100000):
405 fmt(locals(), t, test_str)
406 print(time.time() - b)
407
408 test_str = '''\n/sbin/iptables -t {table} -N {t.a.b.c.table}\n/sbin/iptables -t {table} -A\n'''
409 b = time.time()
410 for i in range(100000):
411 fstr(test_str)
412 print(time.time() - b)
413
414
415 #t.print_tree()
416 #print(t.dump(sections=2))
417 #keypaths = t.search_key('ip')
418 #print('keypaths:', keypaths)
419 #for keypath in keypaths:
420 # print(t[keypath].ip)
421
422
423
424 #print(t.myvarname)
425 #print('xyz',t.xyz,type(t.xyz))
426 #print('mybool',t.mybool,type(t.mybool))
427
428 #print('abc = 123',t.abc,type(t.abc))
429 #t.abc = 2000
430 #print('abc = 2000',t.abc,type(t.abc))
431 #t['abc'] = 4000
432 #print('abc = 4000',t.abc,type(t.abc))
433 #t['new'] = 1
434 #print(dir( mapper(cfg_types())))
435
436
437 #t.print_tree()
438 #t.dump(sections=0)
439 #print(t.dump(sections=0))
440
441 """
442 print(t.find_key('table'))
443 print(t.find_item('table', '130'))
444 print(t.get_keys('130'))
445 print(t.get_values('table'))
446 print(t.get_items('table'))
447
448 print(t.get_in('192.'))
449 """
450 """
451 t = thescfg()
452 t.set_path('a.b.c.d', 'a value')
453 #t.print_tree()
454 #t.del_path('a.b.c.d')
455
456 t.a.b.dt = dict()
457 t.a.b.dt['d1a'] = 1
458 t.a.b.dt['d1b'] = thescfg()
459
460 t.a.b.dt['d1b'].z = 3
461
462 #t.print_tree()
463
464 t1 = thescfg()
465 t1.merge(t)
466 #t1.print_tree()
467
468 #print(isinstance(t1, dict))
469
470 #Template.delimiter = r'%'
471 #print('delim',Template.delimiter)
472
473 """
474
475
476
477
478 #for line in readlineclean('thesaurus_config.testcfg', isfile=True):
479 # print(line)
0 """
1 Multi line Comments (doc strings)
2 """
3 # Single line comment
4
5 abc (static_int) = 123
6 xyz (int) = 456
7 myvarname (str_list) = "Item 1's" "'Item_2'" "Item 3" "Item_4"
8 mybool (str_to_bool) = yes
9
10
11 [defaults.gateways]
12 table = = 10
13 gatewayifname = eth0
14 gatewayrouter (ipv4) = 192.168.0.1
15 gatewaydns (ipv4) = 9.9.9.9
16 inkbps (int) = 99000
17 outkbps (int) = 99000
18 url =
19
20 # Sectional inheritance: defaults.gateways always merged first
21 [gateways:defaults.gateways]
22 TEST_10.gatewaydns =
23 TEST_10.gwsname =
24 TEST_10.table = 129
25 TEST_10.gatewayrouter = 10.10.10.1
26 LAN.gatewaydns =
27 LAN.gwsname =
28 LAN.table = 130
29 LAN.gatewayrouter = 192.168.9.1
30 LAN_US.gatewaydns =
31 LAN_US.gwsname =
32 LAN_US.table = 131
33 LAN_US.gatewayrouter = 192.168.9.2
34
35 #Reset section
36 []
37 opt.user = openvpn-noc
38 opt.ip_cmd = /bin/ip
39 opt.conntrack_cmd = /bin/conntrack
40
41 opt.hosts = saturn jupiter
42 opt.names = vpn0
43
44 saturn.ip = 1.42.1.15
45 saturn.mng_ip = 172.27.1.1
46 saturn.protos = tcp udp
47
48 jupiter.ip = 1.42.1.45
49 jupiter.mng_ip = 172.27.2.1
50 jupiter.protos = tcp udp
51
52 tcp.server = tcp-server
53 udp.server = udp
54
55
56 bld0.hosts.0.ip = 172.27.1.1
57 bld0.servers.0.ip = 172.27.2.1
58 bld1.lab.servers.0.ip = 172.27.3.1
59 bld1.lab.servers.1.ip = 172.27.4.1
60 bld1.lab.servers.2.ip = 172.27.5.1
61
62 bld2.office.0.servers.0.ip = 172.27.6.1
63 bld2.office.0.servers.1.ip = 172.27.7.1
64 bld2.office.0.servers.2.ip = 172.27.8.1
65
66
67 [vpn]
68 vpn0.name = vpn0
69 vpn0.port = 10708
70 vpn0.ifconfig = 100.64.0.1 100.64.0.2
71 vpn0.route = 100.64.0.0 255.255.255.0
72 vpn0.route_table = 8
73 vpn0.client_ipstart = 100.64.0.
74
75 vpn0.tcp.tun = 7
76 vpn0.tcp.mng_port = 5700
77
78 vpn0.udp.tun = 8
79 vpn0.udp.mng_port = 5800
80
81 #vpn0.udp.newthes
82
83 cmd.client_connect_config:
84 push "route 172.20.0.0 255.255.255.0"
85 push "dhcp-option DNS 10.27.1.1"
86 push "dhcp-option DNS 10.27.1.2"
87 push "redirect-private"
88
89 cmd.client_connect:
90 {cfg.opt.ip_cmd} route replace {client.ip} dev {ovpn.dev} table {ovpn.route_table}
91 {cfg.opt.conntrack_cmd} -D --src {client.ip}
92 {cfg.opt.conntrack_cmd} -D --dst {client.ip}
93
94 cmd.client_disconnect:
95 {cfg.opt.ip_cmd} route delete {ovpn.ifconfig_pool_remote_ip} dev {ovpn.dev} table {ovpn.route_table}
96 {cfg.opt.conntrack_cmd} -D --src {ovpn.ifconfig_pool_remote_ip}
97 {cfg.opt.conntrack_cmd} -D --dst {ovpn.ifconfig_pool_remote_ip}
98
99 #Reset section
100 []
101 aaaa = 123
102 bbbb = 456