/
tracking.py
1227 lines (1073 loc) · 40.1 KB
/
tracking.py
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Encoding: iso-8859-1
# -----------------------------------------------------------------------------
# Project : Sink
# -----------------------------------------------------------------------------
# Author : Sebastien Pierre <sebastien@type-z.org>
# -----------------------------------------------------------------------------
# License : BSD License (revised)
# -----------------------------------------------------------------------------
# Creation date : 09-Dec-2003
# Last mod. : 29-Sep-2009
# -----------------------------------------------------------------------------
# Notes : NodeStates SHOULD not be created directly, because they
# MUST be cached (signature and location) in their
# containing state to be processable by the change
# tracker.
# -----------------------------------------------------------------------------
import os, hashlib, stat, time, fnmatch, getopt, simplejson, uuid
# Error messages
BAD_DOCUMENT_ELEMENT = "Bad document element"
NO_LOCATION = "No `location' attribute."
UNKNOWN_ELEMENT = "Unknown element %s"
#------------------------------------------------------------------------------
#
# File system node
#
#------------------------------------------------------------------------------
FILE_SYSTEM_ATTRIBUTES = (
"Size", "Creation", "Modification", "Owner", "Group", "Permissions",
)
class NodeState:
"""The abstract class for representing the state of filesystem files
and directories."""
ADDED = "+"
REMOVED = "-"
MODIFIED = "m"
COUNTER = 0
def __init__( self, state, location, usesSignature=True, accepts=(),
rejects=() ):
"""Creates a file system node with the given location. The location
is relative to the state root. The usesSignature parameter allows to
specify wether the node should use a signature or not. Large file nodes may take
too long to compute their signature, in which case this attributes
comes in handy.
The `update' method should be called to initilize the signature and
attributes attributes from the local filesystem, but this implies that the
nodes exists on the file system. Otherwise the `_attributes' and `_contentSignature'
attributes can be set by hand."""
self._uid = "N%s" % (NodeState.COUNTER)
self._parent = None
self._accepts = accepts
self._rejects = rejects
self._attributes = {}
self._tags = {}
self._contentSignature = None
self._attributesSignature = None
self._usesSignature = usesSignature
self._belongsToState( state )
NodeState.COUNTER += 1
self.location( location )
assert type(self._accepts) in (tuple, list)
assert type(self._rejects) in (tuple, list)
state.onNodeCreated(self)
def exportToDict( self ):
result = {
"parent":self._parent and self._parent.location(),
"type": self.__class__.__name__,
"uid": self._uid,
"accepts":self._accepts,
"rejects":self._rejects,
"attributes":self._attributes,
"tags":self._tags,
"contentSignature":self._contentSignature,
"attributesSignature":self._usesSignature,
}
return result
def importFromDict( self, data ):
self._accepts = data["accepts"]
self._rejects = data["rejects"]
self._attributes = data["attributes"]
self._tags = data["tags"]
self._contentSignature = data["contentSignature"]
self._attributesSignature = data["attributesSignature"]
return self
def isDirectory( self ):
"""Tells wether the node is a directory or not."""
return False
def hasChildren( self ):
"""Tells if this node has any children."""
return 0
def children( self ):
"""Returns the children of this node."""
return ()
def doOnParents(self, function):
"""Apply this function on this node parent, on the parent parent...
until the root node is reached."""
if self._parent:
function(self._parent)
self._parent.doOnParents(function)
def usesSignature( self ):
"""Tells wether this node should copmute its SHA-1 signature when updated."""
return self._usesSignature
def _appendToWalkPath( self, walkPath ):
"""Appends this node to the given walk path. This allows to iterate
nodes using the given `walkPath', which is a list."""
walkPath.append(self)
def _belongsToState( self, state ):
"""Tells that this node belongs to the given state. This clears the node
cache."""
self._state = state
self._cached = False
def _setParent( self, nodeState ):
"""Sets the parent NodeState for this node."""
self._parent = nodeState
# Tagging___________________________________________________________________
def tag(self, _name=None, **tags):
"""Tags the given node with the following list of tags (given as named
arguments). If a single argument is given, then the value of the given
tag is returned."""
if _name:
return self._tags.get(_name)
else:
for key in tags:
self._tags[key] = tags[key]
return True
# Caching__________________________________________________________________
def isCached( self, value=None ):
"""Tells wether the node is cached, or not."""
if value == None:
return self._cached
else:
self._iscached = value
def location( self, location=None ):
"""Sets the location that this node represents, relatively to the state
root"""
if location == None:
return self._attributes["Location"]
else:
location = os.path.normpath(location)
self._attributes["Location"] = location
def name(self):
"""Returns the name of this node. This corresponds to the basename of
this node location."""
return os.path.basename(self.location())
def getAbsoluteLocation( self ):
"""Returns the node location, which implies that the location has been
assigned a state."""
assert self._state != None
return self._state.getAbsoluteLocation(self.location())
def exists( self ):
"""Returns true if the node exists on the local filesystem"""
return os.path.exists( self.getAbsoluteLocation() )
def update( self, signatureFilter=lambda x:True ):
"""Creates the node by making the proper initilisation. The node MUST
be available on the local filesystem when this method is run."""
# Links may point to unexisting locations
assert os.path.islink(self.getAbsoluteLocation()) or self.exists()
self._updateAttributes()
if self._usesSignature: self._updateSignature()
self._state.cacheNodeState(self)
def _updateAttributes( self ):
"""Gathers the attributes related to this file system node."""
path = self.getAbsoluteLocation()
assert self.exists()
stat_info = map(lambda x:str(x), os.stat(path))
self._attributes["Size"] = stat_info[stat.ST_SIZE]
self._attributes["Creation"] = stat_info[stat.ST_CTIME]
self._attributes["Modification"] = stat_info[stat.ST_MTIME]
self._attributes["Owner"] = stat_info[stat.ST_UID]
self._attributes["Group"] = stat_info[stat.ST_GID]
self._attributes["Permissions"] = stat_info[stat.ST_MODE]
def getAttribute( self, info ):
"""Returns the attributes information with the given name"""
return self._attributes[info]
def getAttributes( self ):
"""Returns the attributes of this node."""
return self._attributes
def getSize( self ):
"""Alias to 'getAttribute("Size")'"""
return self.getAttribute("Size")
def getCreation( self ):
"""Alias to 'getAttribute("Creation")'"""
return self.getAttribute("Creation")
def getModification( self ):
"""Alias to 'getAttribute("Modification")'"""
return self.getAttribute("Modification")
def _attributeInSignature( self, attributeName ):
"""Tells wether the given attribute name should be used in the computation
of the signature."""
if attributeName not in ( "Creation" ):
return True
else:
return False
def _updateSignature( self ):
"""Creates the signature of this file system node."""
# The content signature is up to concrete subclasses, so we only
# set it to None (which is its default value)
self._contentSignature = None
# Updates the attributes signature
items = self._attributes.items()
items.sort()
signature = []
for key, value in items:
# Creation attribute does not appear in the attributes signature
if self._attributeInSignature(key):
signature.append(str(key)+str(value))
self._attributesSignature = hashlib.sha1("".join(signature)).hexdigest()
def getContentSignature( self ):
if self._contentSignature == None: self._updateSignature()
return self._contentSignature
def getAttributesSignature( self ):
"""Returns the signature of the attributes. Attributes listed in
ATTRIBUTES_NOT_IN_SIGNATURE are not taken into account in the
computation of the node signature."""
if self._attributesSignature == None: self._updateSignature()
return self._attributesSignature
def getSignature( self ):
"""Returns the concatenation of the content signature and the
attributes signature, separated by a dash."""
assert self.usesSignature(), "Node does not use signature:" + str(self)
return str(self.getContentSignature())+"-"+str(self.getAttributesSignature())
def __repr__(self):
return os.path.basename(self.location()) + " " + repr(self._tags)
#------------------------------------------------------------------------------
#
# DirectoryNodeState
#
#------------------------------------------------------------------------------
class DirectoryNodeState(NodeState):
"""A node representing a directory on the filesystem"""
def __init__( self, state, location, accepts=(), rejects=() ):
"""Creates a new directory node.
Same operations as the file system node."""
# The list of child nodes
self._children = []
NodeState.__init__(self, state, location, usesSignature=False,
accepts=accepts, rejects=rejects )
def exportToDict( self ):
result = NodeState.exportToDict(self)
result["children"] = tuple(n.exportToDict() for n in self._children)
return result
def importFromDict( self, data ):
result = NodeState.importFromDict(self, data)
for child in data["children"]:
child_type = child["type"]
if child_type == DirectoryNodeState.__name__:
assert None
elif child_type == NodeState.__name__:
assert None
else:
assert None, "Unsuported child type"
return self
def isDirectory( self ):
"""Returns True."""
return True
def hasChildren( self ):
return len(self._children)
def children( self ):
return self._children
def _belongsToState( self, state ):
"""Sets the given state as this node state. This invalidates makes the
node uncached."""
NodeState._belongsToState(self, state)
for child in self.getChildren(): child._belongsToState(state)
def update( self, nodeSignatureFilter=lambda x:True ):
"""Updates the given directory node signature and attributes-information. The
directory node location MUST exist.
The nodeSignatureFilter allows to filter each node and decided wether its signature
should be computed or not. By default, every node has its signature computed.
WARNING: Updating a directory nodes updates its children list according
to the local file system, so new nodes are always created for new
directories and files."""
# We ensure that the directory exists
assert self.exists()
# We retrieve an order list of the directory content
content=os.listdir(self.getAbsoluteLocation())
self._children = []
# We create new nodes for each content
for element_loc in content:
# We ensure that the node is accepted
matched = True
for a in self._accepts:
if not fnmatch.fnmatch(element_loc, a):
matched = False
break
for a in self._rejects:
if fnmatch.fnmatch(element_loc, a):
matched = False
break
if not matched:
continue
element_loc = os.path.join( self.location(), element_loc )
abs_element_loc = self._state.getAbsoluteLocation(element_loc)
# Skips symlinks
if os.path.islink( abs_element_loc):
continue
elif os.path.isdir( abs_element_loc ):
node = DirectoryNodeState( self._state, element_loc,
accepts=self._accepts, rejects=self._rejects )
node.update(nodeSignatureFilter)
else:
if nodeSignatureFilter(abs_element_loc):
node = FileNodeState( self._state, element_loc, True )
else:
node = FileNodeState( self._state, element_loc, False )
node.update()
if node: self.appendChild(node)
# This is VERY IMPORTANT : we ensure that the children are canonicaly
# sorted
self._children.sort(lambda x,y: cmp(x.location(), y.location()))
# We can only update the node after children were added, see
# _updateSignature
NodeState.update(self)
def _appendToWalkPath( self, walkPath ):
"""Appends this node to the given walk path. This allows to iterate
nodes using the given `walkPath', which is a list.
Directory node is appended first, then children are appended in
alphabetical order."""
NodeState._appendToWalkPath(self, walkPath)
for child in self._children: child._appendToWalkPath(walkPath)
def walkChildren( self, function, context=None ):
"""Applies the given function to every child of this node."""
for child in self._children:
if context != None:
function(child, context)
else:
function(child)
if child.hasChildren():
child.walkChildren(function, context)
def getChildren( self, types = None ):
"""Returns the children of this directory. The optional `types' list
enumerates the classes of the the returned children, acting as a type
filter. By default, types are DirectoryNodeState and FileNodeState."""
if types == None: types = ( DirectoryNodeState, FileNodeState )
# Returns only elements of the listed types
def typefilter(x):
for atype in types:
if isinstance(x,atype): return True
return False
# We execute the filter
return filter( typefilter, self._children )
def appendChild( self, child ):
"""Appends a child node to this directory. The list of children is
automatically maintained as sorted."""
self._children.append(child)
child._setParent(self)
# We make sure the list of children is sorted.
self._children.sort()
def _attributeInSignature( self, attributeName ):
"""Tells wether the given attribute name should be used in the computation
of the signature."""
if attributeName not in ( "Creation", "Modification" ):
return True
else:
return False
def _updateSignature( self ):
"""A directory signature is the signature of the string composed of the
names of all of its elements."""
NodeState._updateSignature(self)
children = []
for child in self.getChildren():
children.append(os.path.basename(child.location()))
self._contentSignature = hashlib.sha1("".join(children)).hexdigest()
def __repr__(self):
def indent(text, value = " ", firstLine=False):
res = ""
for line in text.split("\n"):
if firstLine:
res += value + line + "\n"
else:
firstLine = True
res += line + "\n"
return res
name = "[ ] " + NodeState.__repr__(self) + "\n"
for child in self._children:
name += " +-- " + indent(repr(child), " ", False)
return name
#------------------------------------------------------------------------------
#
# FileNodeState
#
#------------------------------------------------------------------------------
class FileNodeState(NodeState):
"""A node representing a file on the filesystem."""
def isDirectory( self ):
"""Returns False."""
return False
def getData( self ):
"""Returns the data contained in this file as a string."""
fd = None
try:
fd = open(self.getAbsoluteLocation(), "r")
assert fd!=None
data = fd.read()
fd.close()
except IOError:
data = ""
return data
def _updateSignature( self ):
"""A file signature is the signature of its content."""
NodeState._updateSignature(self)
# We only compute the content signature if the node is said to. This
# allows to perform quick changes detection when large files are
# involved.
# if self.usesSignature():
self._contentSignature = hashlib.sha1(self.getData()).hexdigest()
#------------------------------------------------------------------------------
#
# Ancestor guessing
#
#------------------------------------------------------------------------------
def guessNodeStateAncestors( node, nodes ):
"""Returns an order list of (percentage, nodes) indicating the
probability for each node to be an ancestor of the current node.
You should look at the source code for more information on how the
percentage is avaluated."""
# TODO: Make more test and try to explain why this should work. I think
# this should be tuned by usage.
assert len(nodes)>0
# Computes the difference between the given node and the current node
# attributes information value
def difference( node, info ):
return abs(int(node.getAttribute(info)) - int(node.getAttribute(info)))
# Initialises the maxima table for the given attributes info
maxima = {
"Creation":difference(nodes[0], "Creation"),
"Size":difference(nodes[0], "Size")
}
# We get the maxima for each attributes info
for attributes in ("Creation", "Size"):
for node in nodes:
maxima[attributes] = max(maxima[attributes], difference(node, attributes))
# We calculate the possible ancestry rate
result = []
for node in nodes:
node_rate = 0.0
# Same class, rate 40%
if node.__class__ == node.__class__:
node_rate += 0.40
# Creation rate, up to 25%
creation_rate = 0.25 * ( 1 - float(difference(node, "Creation")) /
maxima["Creation"] )
# Divided by two if rated node creation date is > to current node
# creation date
if node.getAttribute("Creation") > \
node.getAttribute("Creation"):
creation_rate = creation_rate / 2.0
node_rate += creation_rate
# If modification date is < to current modification date, add 15%
if node.getAttribute("Modification") < \
node.getAttribute("Modification"):
node_rate += 0.15
# Size rate, up to 10%
node_rate += 0.10 * ( 1 - float(difference(node, "Size")) /
maxima["Size"] )
# If owner is the same then add 3%
if node.getAttribute("Owner") ==\
node.getAttribute("Owner"):
node_rate += 0.03
# If group is the same then add 3%
if node.getAttribute("Group") ==\
node.getAttribute("Group"):
node_rate += 0.03
# If permissions are the same then add 3%
if node.getAttribute("Permissions") ==\
node.getAttribute("Permissions"):
node_rate += 0.03
result.append((node_rate, node))
result.sort(lambda x,y: cmp(x[0], y[0]))
return result
#------------------------------------------------------------------------------
#
# File system state
#
#------------------------------------------------------------------------------
class State:
"""A state object reflects the state of a particular file system location by
creating node objects (NodeStates) that represent the file system state at a
particular moment.. These nodes can be later queried by location and
signature."""
def __init__( self, rootLocation, rootNodeState=None, populate=False,
accepts=(), rejects=() ):
"""Creates a new state with the given location as the root. If the populate
variable is set to True, then the state is populated with the data gathered
from the fielsystem.
Note that the given rootNodeState is NOT UPDATED automatically, because
it may not exist on the local filesystem.
By default, no root node is created, you can create one with the
'populate' method."""
# Signatures and locations are used by the change tracking system
# Signatures is a map with signatures as key and a list of file system
# nodes as values.
self._contentSignatures = {}
# Locations is a map with location as keys and file system nodes as
# values.
self._accepts = []
self._rejects = []
self._locations = {}
self._rootNodeState = None
if rootLocation: self.location(os.path.abspath(rootLocation))
else: self.location(None)
self.root(rootNodeState)
self.accepts(accepts)
self.rejects(rejects)
if populate:
self.populate()
def exportToDict( self ):
locations = {}
for k,v in self._locations.items():
locations[k] = v._uid
result = {
"accepts":self._accepts,
"rejects":self._rejects,
"locations":locations,
"rootNodeState":self._rootNodeState and self._rootNodeState.exportToDict()
}
return result
def onNodeCreated( self, node ):
"""A callback placeholder that can be used to output stuff when a node
is created."""
return None
def accepts( self, a ):
"""Specifies the GLOBS (as strings) that all inserted node must
match."""
if type(a) in (tuple,list): self._accepts.extend(a)
else: self._accepts.append(a)
def rejects( self, a ):
"""Specifies the GLOBS (as strings) that tell which node should never be
added."""
if type(a) in (tuple,list): self._rejects.extend(a)
else: self._rejects.append(a)
def populate( self, nodeSignatureFilter=lambda x:True):
"""Creates the root node for this state. This node will be
automatically updated and cached.
The nodeSignatureFilter is a predicate which tells if a node at the
given location should compute its signature or not.
"""
rootNodeState = DirectoryNodeState(self, "", accepts=self._accepts,
rejects=self._rejects)
rootNodeState.update(nodeSignatureFilter)
self._creationTime = time.localtime()
self.root(rootNodeState)
def root( self, node=None ):
"""Returns this state root node."""
if node != None: self._rootNodeState = node
else: return self._rootNodeState
def getCreationTime( self ):
"""Returns the time at which this state was created"""
return self._creationTime
def location( self, path=None ):
"""Returns the absolute location of this state in the local
filesystem."""
if path == None:
return self._rootLocation
else:
self._rootLocation = path
def getAbsoluteLocation( self, location ):
"""Returns the absolute location of the given relative location"""
return os.path.normpath(self.location() + os.sep + location)
def cacheNodeState( self, node ):
"""Caches a node information in this state. This registers the node
signature and location so that it can be processed by the change
tracking."""
self._locations[node.location()] = node
result = None
# We make sure that the singature exists
if node.usesSignature():
try:
result = self._contentSignatures[node.getContentSignature()]
except:
result = []
self._contentSignatures[node.getContentSignature()] = result
# And we append the node
result.append(node)
node.isCached(True)
return node
def cacheNodeStates( self ):
assert self.root()
for node in self.root().walkNodeStates():
if not node.isCached():
self.cacheNodeState(node)
def nodes( self ):
"""Returns the list of all nodes registered in this state"""
return self._locations.values()
def nodesWithContentSignature( self, signature ):
"""Returns a list of nodes with the given content signature. The node
may not exist, in which case None is returned."""
try:
return self._contentSignatures[signature]
except:
return ()
def nodeWithLocation( self, location ):
"""Returns the node with the given location. The node may not exist, in
which case None is returned."""
return self._locations.get(location)
def nodesByLocation( self ):
return self._locations
def nodesByContentSignature( self ):
return self._contentSignatures
def __repr__(self):
return repr(self.root())
#------------------------------------------------------------------------------
#
# Change tracking
#
#------------------------------------------------------------------------------
def sets( firstSet, secondSet, objectAccessor=lambda x:x ):
"""
Returns elements that are unique to first and second set, then elements
that are common to both.
Returns the following sets:
- elements only in first set
- elements only in second set
- elements common to both sets
The objectAccessor operation is used on each object of the set to access
the element that will be used as a comparison basis. By default, it is the
element itself."""
# We precompute the maps
set_first_acc = map(objectAccessor, firstSet)
set_second_acc = map(objectAccessor, secondSet)
# Declare the filtering predicates
# First set elements not in second set
def first_only(x): return objectAccessor(x) not in set_second_acc
# Second set elements not in first set
def second_only(x): return objectAccessor(x) not in set_first_acc
# First sets elements in second set == second set elts in first set
def common(x): return objectAccessor(x) in set_second_acc
# Compute the result
return filter(first_only, firstSet),\
filter(second_only, secondSet),\
filter(common, firstSet)
class Change:
"""A change represents differences between two states."""
def __init__ ( self, newState, previousState ):
# created+copied+moved = total of nodes only in new state
self._created = [] # Only in NEW
self._copied = [] # Only in NEW
self._moved = [] # Only in NEW
# removed = total of nodes only in old state
self._removed = [] # Only in OLD
# changed + unchanged = total of nodes in both STATES
self._modified = []
self._unmodified = []
# We do not count untracked, because this is a superset
self._all = [
self._created,
self._copied,
self._moved,
self._removed,
self._modified,
self._unmodified
]
self.newState = newState
self.previousState = previousState
def anyChanges( self ):
"""Tells wether there were any changes"""
for group in self._all[:-1]:
if group: return True
return False
def removeLocation( self, location ):
"""Removes the nodes that start with the given location from this
change set."""
if location == None: return
for _set in self._all:
i = 0
# We cannot iterate on the array, because we may remove the
# iterated value, which seems to fuck up the iteration
while i < len(_set):
node = _set[i]
if node.location().find(location) == 0:
_set.pop(i)
else:
i += 1
def getOnlyInNewState( self ):
res = []
res.extend(self._created)
res.extend(self._copied)
res.extend(self._moved)
return res
def getOnlyInOldState( self ):
return self._removed
def getOnlyInBothStates( self ):
res = []
res.extend(self._modified)
res.extend(self._unmodified)
def getCreated( self ):
return self._created
def getCopied( self ):
return self._copied
def getRemoved( self ):
return self._removed
def getMoved( self ):
return self._moved
def getModified( self ):
return self._modified
def getUnmodified( self ):
return self._unmodified
def _filterAll( self, f ):
result = []
for _set in self._all: result.extend(filter(f,_set))
return result
def count( self ):
"""Returns the number of elements in this change."""
# FIXME: This is false !
count = 0
for _set in self._all: count += len(_set)
return count
class Tracker:
"""Creates a change object that characterises the difference between the
two states."""
TIME = "Time"
SHA1 = "SHA-1"
def detectChanges( self, newState, previousState, method=TIME ):
"""Detects the changes between the new state and the previous state. This
returns a Change object representing all changes."""
changes = Change(newState, previousState)
# We look for new nodes, nodes that are only in the previous location,
# and nodes that are still there
new_locations, prev_locations, same_locations = sets(
newState.nodesByLocation().items(),
previousState.nodesByLocation().items(),
lambda x:x[0]
)
# TODO: This should be improved with copied and moved files, but this
# would require a GUI
# TODO: changes._all, ._new and ._old are not space efficient
for location, node in new_locations:
self.onCreated(node)
changes._created.append(node)
for location, node in prev_locations:
self.onRemoved(node)
changes._removed.append(node)
for location, node in same_locations:
previous_node = previousState.nodeWithLocation(location)
if method == Tracker.SHA1:
assert previous_node.getContentSignature()
assert node.getContentSignature()
if previous_node.getContentSignature() != node.getContentSignature():
changes._modified.append(node)
self.onModified(previous_node, node)
else:
changes._unmodified.append(node)
self.onUnmodified(previous_node, node)
else:
ptime = previous_node.getAttribute("Modification")
ntime = node.getAttribute("Modification")
if ptime != ntime:
changes._modified.append(node)
self.onModified(previous_node, node)
else:
changes._unmodified.append(node)
self.onUnmodified(previous_node, node)
# We make sure that we classified every node of the state
assert len(new_locations) + len(prev_locations) + len(same_locations)\
== changes.count()
return changes
def onCreated( self, node ):
"""Handler called when a node was created, ie. it is present in the new
state and not in the old one."""
node.tag(event=NodeState.ADDED)
node.doOnParents(lambda x:x.tag("event") == None and x.tag(event=NodeState.MODIFIED))
def onModified(self, newNode, oldNode):
"""Handler called when a node was modified, ie. it is not the same in
the new and in the old state."""
newNode.tag(event=NodeState.MODIFIED)
oldNode.tag(event=NodeState.MODIFIED)
def onUnmodified(self, newNode, oldNode):
newNode.tag(event=None)
oldNode.tag(event=None)
def onRemoved(self, node):
"""Handler called when a node was removed, ie. it is not the in
the new state but is in the old state."""
node.tag(event=NodeState.REMOVED)
#------------------------------------------------------------------------------
#
# File system node
#
#------------------------------------------------------------------------------
#TODO: Describe -d option
USAGE = """\
sink [-d] [OPTIONS] [OPERATION] ORIGIN COMPARED...
ORIGIN is the directory to which we want to compare the others
COMPARED is a list of directories that will be compared to ORIGIN
Options:
-c, --content (DEF) Uses content analysis to detect changes
-t, --time Uses timestamp to detect changes
-nNUM Compares the file at line NUM in the listing
--ignore-spaces Ignores the spaces when analyzing the content
--ignore GLOBS Ignores the files that match the glob
--only GLOBS Only accepts the file that match glob
--difftool TOOL Specifies a specific too for the -n option
You can also specify what you want to be listed in the diff:
[-+]A Hides/Shows ALL files [=]
[-+]s Hides/Shows SAME files [=]
[-+]a Hides/Shows ADDED files [+]
[-+]r Hides/Shows REMOVED files [-]
[-+]m Hides/Shows MODIFIED files [>] or [<]
[-+]N Hides/Shows NEWER files [>]
[-+]o Hides/Shows OLDER files [<]
GLOBS understand '*' and '?', will refer to the basename and can be
separated by commas. If a directory matches the glob, it will not be
traversed (ex: --ignore '*.pyc,*.bak,.[a-z]*')
Legend:
[=] no changes [+] file added [>] changed/newer
[-] file removed [<] changed/older
! file missing
"""
CONTENT_MODE = True
TIME_MODE = False
ADDED = "[+]"
REMOVED = "[-]"
NEWER = "[>]"
OLDER = "[<]"
SAME = "[=]"
ABSENT = " ! "
class Engine:
"""Implements operations used by the Sink main command-line interface."""
def __init__( self, logger, config=None ):
self.logger = logger
self.mode = CONTENT_MODE
self.ignore_spaces = True
self.rejects = []
self.accepts = []
self.diffs = []
self.show = {}
if config: self.setup(config)
def setup( self, config ):
"""Sets up the engine using the given configuration object."""
self.mode = config["sink.mode"]
self.diff_command = config["sink.diff"]
self.diffs = []
self.accepts = config["filters.accepts"]
self.rejects = config["filters.rejects"]
self.ignore_spaces = config["sink.whitespace"]
if os.environ.get("DIFF"): self.diff_command = os.environ.get("DIFF")
self.show = {}
def run( self, arguments ):
"""Runs the command using the given list of arguments (a list of
strings)."""
logger = self.logger
accepts = self.accepts
rejects = self.rejects
show = self.show
diffs = self.diffs
command, arguments = arguments[0], arguments[1:]
# We extract the arguments
try:
optlist, args = getopt.getopt( arguments, "cthVvln:iarsmNo",\
["version", "help", "verbose", "list", "checkin", "checkout",
"modified",
"time", "content", "ignore-spaces", "ignorespaces", "diff=", "ignore=",
"ignores=", "accept=", "accepts=", "filter", "only="])
except Exception, e: