-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathhier.py
More file actions
355 lines (281 loc) · 10.2 KB
/
hier.py
File metadata and controls
355 lines (281 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#!/usr/bin/env python
'''
Classes to construct a hierarchy holding infoblocks.
'''
# This file is part of python-keepass and is Copyright (C) 2012 Brett Viren.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
import datetime
def path2list(path):
'''
Maybe convert a '/' separated string into a list.
'''
if isinstance(path,str):
path = path.split('/')
if path[-1] == '': path.pop() # remove trailing '/'
return path
return list(path) # make copy
class Visitor(object):
'''
A class that can visit group/entry hierarchy via hier.visit().
A visitor should be a callable with the signature
visitor(obj) -> (value, bail)
The obj is either the node's group or one of it's entries or None.
The return values control the descent
If value is ever non-None it is assumed the descent is over
and this value is returned.
If bail is ever True, the current node is abandoned in the
descent. This can be used to avoid sub trees that are not
interesting to the visitor.
'''
def __call__(self):
notimplemented
pass
class Walker(object):
'''
A class that can visit the node hierarchy
Like a visitor, this callable should return a tuple of
(value,bail). non-None to abort the descent and return that value.
If bail is True, then drop the current node and move to its next
sister.
'''
def __call__(self,node):
notimplemented
pass
class NodeDumper(Walker):
def __call__(self,node):
if not node.group:
print 'Top'
return None, False
print ' '*node.level()*2,node.group.name(),node.group.groupid,\
len(node.entries),len(node.nodes)
return None, False
class FindGroupNode(object):
'''Return the node holding the group of the given name. If name
has any slashes it will be interpreted as a path ending in that
group'''
def __init__(self,path, stop_on_first = True):
self._collected = []
self.best_match = None
self.path = path2list(path)
self.stop_on_first = stop_on_first
return
def __call__(self,node):
if not self.path:
return (None,True)
if not node.group:
if self.path[0] == "" or self.path[0] == "None" or self.path[0] is None:
self.path.pop(0)
return (None,None)
top_name = self.path[0]
obj_name = node.group.name()
groupid = node.group.groupid
from infoblock import GroupInfo
if top_name != obj_name:
return (None,True) # bail on the current node
self.best_match = node
if len(self.path) == 1: # we have a full match
if self.stop_on_first:
return node,True # got it!
else: # might have a matching sister
self._collected.append(node)
return (None,None)
pass
self.path.pop(0)
return (None,None) # keep going
class CollectVisitor(Visitor):
'''
A callable visitor that will collect the groups and entries into
flat lists. After the descent the results are available in the
.groups and .entries data members.
'''
def __init__(self):
self.groups = []
self.entries = []
return
def __call__(self,g_or_e):
if g_or_e is None: return (None,None)
from infoblock import GroupInfo
if isinstance(g_or_e,GroupInfo):
self.groups.append(g_or_e)
else:
self.entries.append(g_or_e)
return (None,None)
pass
class PathVisitor(Visitor):
'''
A callable visitor to descend via hier.visit() method and
return the group or the entry matching a given path.
The path is a list of group names with the last element being
either a group name or an entry title. The path can be a list
object or a string interpreted to be delimited by slashes (think
UNIX pathspec).
If stop_on_first is False, the visitor will not abort after the
first match but will instead keep collecting all matches. This
can be used to collect groups or entries that are degenerate in
their group_name or title, respectively. After the descent the
collected values can be retrieved from PathVisitor.results()
This visitor also maintains a best match. In the event of failure
(return of None) the .best_match data member will hold the group
object that was located where the path diverged from what was
found. The .path data member will retain the remain part of the
unmatched path.
'''
def __init__(self,path,stop_on_first = True):
self._collected = []
self.best_match = None
self.stop_on_first = stop_on_first
self.path = path2list(path)
return
def results(self):
'Return a list of the matched groups or entries'
return self._collected
def __call__(self,g_or_e):
if not self.path: return (None,None)
top_name = self.path[0] or "None"
obj_name = "None"
if g_or_e: obj_name = g_or_e.name()
groupid = None
if g_or_e: groupid = g_or_e.groupid
from infoblock import GroupInfo
if top_name != obj_name:
if isinstance(g_or_e,GroupInfo):
return (None,True) # bail on the current node
else:
return (None,None) # keep going
self.best_match = g_or_e
if len(self.path) == 1: # we have a full match
if self.stop_on_first:
return g_or_e,True # got it!
else: # might have a matching sister
self._collected.append(g_or_e)
return (None,None)
pass
self.path.pop(0)
return (None,None) # keep going
class Node(object):
'''
A node in the group hierarchy.
This basically associates entries to their group
Holds:
* zero or one group - zero implies top of hierarchy
* zero or more nodes
* zero or more entries
'''
def __init__(self,group=None,entries=None,nodes=None):
self.group = group
self.nodes = nodes or list()
self.entries = entries or list()
return
def level(self):
'Return the level of the group or -1 if have no group'
if self.group: return self.group.level
return -1
def __str__(self):
return self.pretty()
def name(self):
'Return name of group or None if no group'
if self.group: return self.group.group_name
return None
def pretty(self,depth=0):
'Pretty print this Node and its contents'
tab = ' '*depth
me = "%s%s (%d entries) (%d subnodes)\n"%\
(tab,self.name(),len(self.entries),len(self.nodes))
children=[]
for e in self.entries:
s = "%s%s(%s: %s)\n"%(tab,tab,e.title,e.username)
children.append(s)
continue
for n in self.nodes:
children.append(n.pretty(depth+1))
continue
return me + ''.join(children)
def node_with_group(self,group):
'Return the child node holding the given group'
if self.group == group:
return self
for child in self.nodes:
ret = child.node_with_group(group)
if ret: return ret
continue
return None
pass
def visit(node,visitor):
'''
Depth-first descent into the group/entry hierarchy.
The order of visiting objects is: this node's group,
recursively calling this function on any child nodes followed
by this node's entries.
See docstring for hier.Visitor for information on the given visitor.
'''
val,bail = visitor(node.group)
if val is not None or bail: return val
for n in node.nodes:
val = visit(n,visitor)
if val is not None: return val
continue
for e in node.entries:
val,bail = visitor(e)
if val is not None or bail: return val
continue
return None
def walk(node,walker):
'''
Depth-first descent into the node hierarchy.
See docstring for hier.Walker for information on the given visitor.
'''
value,bail = walker(node)
if value is not None or bail: return value
for sn in node.nodes:
value = bail = walk(sn,walker)
if value is not None: return value
continue
return None
def mkdir(top, path, gen_groupid):
'''
Starting at given top node make nodes and groups to satisfy the
given path, where needed. Return the node holding the leaf group.
@param gen_groupid: Group ID factory from kpdb.Database instance.
'''
import infoblock
path = path2list(path)
pathlen = len(path)
fg = FindGroupNode(path)
node = walk(top,fg)
if not node: # make remaining intermediate folders
node = fg.best_match or top
pathlen -= len(fg.path)
for group_name in fg.path:
# fixme, this should be moved into a new constructor
new_group = infoblock.GroupInfo()
new_group.groupid = gen_groupid()
new_group.group_name = group_name
new_group.imageid = 1
new_group.creation_time = datetime.datetime.now()
new_group.last_mod_time = datetime.datetime.now()
new_group.last_acc_time = datetime.datetime.now()
new_group.expiration_time = datetime.datetime(2999, 12, 28, 23, 59, 59) # KeePassX 0.4.3 default
new_group.level = pathlen
new_group.flags = 0
new_group.order = [(1, 4),
(2, len(new_group.group_name) + 1),
(3, 5),
(4, 5),
(5, 5),
(6, 5),
(7, 4),
(8, 2),
(9, 4),
(65535, 0)]
pathlen += 1
new_node = Node(new_group)
node.nodes.append(new_node)
node = new_node
group = new_group
continue
pass
return node