forked from NavicoOS/ac2git
-
Notifications
You must be signed in to change notification settings - Fork 1
/
accurev.py
executable file
·2842 lines (2386 loc) · 135 KB
/
accurev.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/python3
# ################################################################################################ #
# AccuRev utility script #
# Author: Lazar Sumar #
# Date: 06/11/2014 #
# #
# This script is a library that is intended to expose a Python API to the AccuRev commands and #
# command result data structures. #
# ################################################################################################ #
import sys
import subprocess
import xml.etree.ElementTree as ElementTree
import datetime
import re
import sqlite3
# ################################################################################################ #
# Script Globals #
# ################################################################################################ #
# ################################################################################################ #
# Script Classes #
# ################################################################################################ #
def GetXmlContents(xmlElement):
if xmlElement is not None:
text = ''
if xmlElement.text is not None:
text = xmlElement.text
return text + ''.join(ElementTree.tostring(e) for e in xmlElement)
return None
def IntOrNone(value):
if value is None:
return None
return int(value)
def UTCDateTimeOrNone(value):
if value is None:
return None
if isinstance(value, str) or isinstance(value, int) or isinstance(value, float):
value = float(value)
return datetime.datetime.utcfromtimestamp(value)
if isinstance(value, datetime.datetime):
return value
raise Exception("UTCDateTimeOrNone(value={0}) - Invalid conversion!".format(value))
def GetTimestamp(datetimeValue):
if datetimeValue is None:
return None
if type(datetimeValue) is not datetime.datetime:
raise Exception('Invalid argument. Expected a datetime type.')
timestamp = (datetimeValue - datetime.datetime(1970, 1, 1)).total_seconds()
return timestamp
# ################################################################################################ #
# Script Objects #
# ################################################################################################ #
class obj:
class Bool(object):
def __init__(self, value):
if type(value) is bool:
self.value = value
self.originalStr = None
elif type(value) is str:
self.value = obj.Bool.string2bool(value)
self.originalStr = value
else:
raise Exception("Unknown type to convert to obj.Bool")
def __nonzero__(self):
return self.value
def __bool__(self):
return self.value
def __repr__(self):
if self.originalStr is None:
return self.toString()
else:
return self.originalStr
def toString(self, toTrueFalse=True, toYesNo=False, toUpper=False, toLower=False):
rv = None
if toTrueFalse:
if self.value:
rv = "True"
else:
rv = "False"
else: # toYesNo:
if self.value:
rv = "Yes"
else:
rv = "No"
if toLower:
rv = rv.lower()
elif toUpper:
rv = rv.upper()
return rv
@staticmethod
def string2bool(string):
rv = None
string = string.lower()
if string == "yes" or string == "true":
rv = True
elif string == "no" or string == "false":
rv = False
else:
raise Exception("Bool value invalid")
return rv
@classmethod
def fromstring(cls, string):
if string is not None:
rv = obj.Bool.string2bool(string)
return cls(rv)
return None
class TimeSpec(object):
timeSpecRe = None
timeSpecPartRe = None
def __init__(self, start, end=None, limit=None):
self.start = start
self.end = end
self.limit = limit
def __repr__(self):
rv = repr(self.start)
if self.end is not None:
rv += '-{0}'.format(repr(self.end))
if self.limit is not None:
rv += '.{0}'.format(repr(self.limit))
return rv
@staticmethod
def is_keyword(obj):
if isinstance(obj, str):
try:
obj = int(obj)
except:
pass
if isinstance(obj, int):
return False
elif obj in [ 'highest', 'now' ]:
return True
else:
return None
@staticmethod
def compare_transaction_specs(lhs, rhs):
# Force them to be ints if they can be.
try:
lhs = int(lhs)
except:
pass
try:
rhs = int(rhs)
except:
pass
# highest > now > any transaction number
if lhs == rhs:
return 0
elif lhs == 'highest':
return 1
elif rhs == 'highest':
return -1
elif lhs == 'now':
return 1
elif rhs == 'now':
return -1
elif lhs > rhs:
return 1
elif lhs < rhs:
return -1
elif lhs is None or rhs is None:
raise Exception('Can\'t compare to None')
else:
raise Exception('How did you get here?')
def is_asc(self):
try:
return obj.TimeSpec.compare_transaction_specs(self.start, self.end) < 0
except:
return False
def is_desc(self):
try:
return obj.TimeSpec.compare_transaction_specs(self.start, self.end) > 0
except:
return False
def reversed(self):
return obj.TimeSpec.reverse(self)
def is_cacheable(self):
cacheable = self.start is not None and obj.TimeSpec.is_keyword(self.start) == False
cacheable = cacheable and (self.end is not None and obj.TimeSpec.is_keyword(self.end) == False)
return cacheable
@classmethod
def reverse(cls, timespec):
rv = None
if isinstance(timespec, cls):
rv = cls(start=timespec.end, end=timespec.start, limit=timespec.limit)
return rv
@staticmethod
def parse_simple(timespec):
rv = None
if timespec is not None:
if isinstance(timespec, str):
if obj.TimeSpec.timeSpecPartRe is None:
obj.TimeSpec.timeSpecPartRe = re.compile(r'^ *(?:(?P<transaction>\d+)|(?P<keyword>now|highest)|(?P<datetime>(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2}) +(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2}))) *$')
timeSpecPartMatch = obj.TimeSpec.timeSpecPartRe.search(timespec)
if timeSpecPartMatch is not None:
timeSpecPartDict = timeSpecPartMatch.groupdict()
if 'keyword' in timeSpecPartDict and timeSpecPartDict['keyword'] is not None:
rv = timeSpecPartDict['keyword']
elif 'transaction' in timeSpecPartDict and timeSpecPartDict['transaction'] is not None:
rv = int(timeSpecPartDict['transaction'])
elif 'datetime' in timeSpecPartDict and timeSpecPartDict['datetime'] is not None:
rv = datetime.datetime(year=int(timeSpecPartDict['year']), month=int(timeSpecPartDict['month']), day=int(timeSpecPartDict['day']), hour=int(timeSpecPartDict['hour']), minute=int(timeSpecPartDict['minute']), second=int(timeSpecPartDict['second']))
elif isinstance(timespec, datetime.datetime):
rv = timespec
elif isinstance(timespec, int):
rv = timespec
else:
raise Exception("Unsupported type ({t}) of timespec ({ts}) part!".format(t=type(timespec), ts=str(timespec)))
return rv
@classmethod
def fromstring(cls, string):
if string is not None:
if isinstance(string, int):
return cls(start=string)
elif isinstance(string, datetime.datetime):
return cls(start=string)
elif isinstance(string, str):
if obj.TimeSpec.timeSpecRe is None:
obj.TimeSpec.timeSpecRe = re.compile(r'^(?P<start>.*?) *(?:- *(?P<end>.*?))?(?:\.(?P<limit>\d+))?$')
timeSpecMatch = obj.TimeSpec.timeSpecRe.search(string)
if timeSpecMatch is not None:
timeSpecDict = timeSpecMatch.groupdict()
start = end = limit = None
if 'start' in timeSpecDict:
start = obj.TimeSpec.parse_simple(timeSpecDict['start'])
if 'end' in timeSpecDict:
end = obj.TimeSpec.parse_simple(timeSpecDict['end'])
if 'limit' in timeSpecDict:
limit = timeSpecDict['limit']
return cls(start=start, end=end, limit=IntOrNone(limit))
else:
raise Exception("Unsupported type ({t}) of string ({s}) that was presented as a timespec.".format(t=type(string), s=str(string)))
return None
class Login(object):
def __init__(self, errorMessage):
self.errorMessage = errorMessage
def __repr__(self):
if self.errorMessage is None or len(self.errorMessage) == 0:
return "Login success"
else:
return self.errorMessage
def __nonzero__(self):
return (self.errorMessage is None or len(self.errorMessage) == 0)
def __bool__(self):
return self.__nonzero__()
class Workspace(object):
def __init__(self, storage, host, targetTransaction, fileModTime, EOL, Type):
self.storage = storage
self.host = host
self.targetTransaction = IntOrNone(targetTransaction)
self.fileModTime = UTCDateTimeOrNone(fileModTime)
self.EOL = EOL
self.Type = Type
def __repr__(self):
str = "Workspace(storage=" + repr(self.storage)
str += ", host=" + repr(self.host)
str += ", targetTransaction=" + repr(self.targetTransaction)
str += ", fileModTime=" + repr(self.fileModTime)
str += ", EOL=" + repr(self.EOL)
str += ", Type=" + repr(self.Type)
str += ")"
return str
@classmethod
def fromxmlelement(cls, xmlElement):
if xmlElement is not None and xmlElement.tag == 'wspace':
storage = xmlElement.attrib.get('Storage')
host = xmlElement.attrib.get('Host')
targetTransaction = xmlElement.attrib.get('Target_trans')
fileModTime = xmlElement.attrib.get('fileModTime')
EOL = xmlElement.attrib.get('EOL')
Type = xmlElement.attrib.get('Type')
return cls(storage, host, targetTransaction, fileModTime, EOL, Type)
return None
class Stream(object):
def __init__(self, name, streamNumber, depotName, Type, basis=None, basisStreamNumber=None, time=None, prevTime=None, prevBasis=None, prevBasisStreamNumber=None, prevName=None, workspace=None, startTime=None, isDynamic=None, hasDefaultGroup=None):
self.name = name
self.streamNumber = IntOrNone(streamNumber)
self.depotName = depotName
self.Type = Type
self.basis = basis
self.basisStreamNumber = IntOrNone(basisStreamNumber)
self.time = UTCDateTimeOrNone(time) # Represents the timelock
self.prevTime = UTCDateTimeOrNone(prevTime)
self.prevBasis = prevBasis
self.prevBasisStreamNumber = IntOrNone(prevBasisStreamNumber)
self.prevName = prevName
self.workspace = workspace
self.startTime = UTCDateTimeOrNone(startTime) # The time at which the last mkstream or chstream transaction was recorded for this stream
self.isDynamic = obj.Bool.fromstring(isDynamic)
self.hasDefaultGroup = obj.Bool.fromstring(hasDefaultGroup)
def __repr__(self):
str = "Stream(name=" + repr(self.name)
str += ", streamNumber=" + repr(self.streamNumber)
str += ", depotName=" + repr(self.depotName)
str += ", Type=" + repr(self.Type)
str += ", basis=" + repr(self.basis)
str += ", basisStreamNumber=" + repr(self.basisStreamNumber)
str += ", time=" + repr(self.time)
str += ", prevTime=" + repr(self.prevTime)
str += ", prevBasis=" + repr(self.prevBasis)
str += ", prevBasisStreamNumber=" + repr(self.prevBasisStreamNumber)
str += ", prevName=" + repr(self.prevName)
str += ", workspace=" + repr(self.workspace)
str += ", startTime=" + repr(self.startTime)
str += ", isDynamic=" + repr(self.isDynamic)
str += ", hasDefaultGroup=" + repr(self.hasDefaultGroup)
str += ")"
return str
@classmethod
def fromxmlelement(cls, xmlElement):
if xmlElement is not None and xmlElement.tag == 'stream':
name = xmlElement.attrib.get('name')
streamNumber = xmlElement.attrib.get('streamNumber')
if streamNumber is None:
streamNumber = xmlElement.attrib.get('id')
depotName = xmlElement.attrib.get('depotName')
Type = xmlElement.attrib.get('type')
basis = xmlElement.attrib.get('basis')
basisStreamNumber = xmlElement.attrib.get('basisStreamNumber')
time = xmlElement.attrib.get('time')
prevTime = xmlElement.attrib.get('prevTime')
prevBasis = xmlElement.attrib.get('prevBasis')
prevBasisStreamNumber = xmlElement.attrib.get('prevBasisStreamNumber')
prevName = xmlElement.attrib.get('prevName')
startTime = xmlElement.attrib.get('startTime')
isDynamic = xmlElement.attrib.get('isDynamic')
hasDefaultGroup = xmlElement.attrib.get('hasDefaultGroup')
wspaceElement = xmlElement.find('wspace')
workspace = obj.Workspace.fromxmlelement(wspaceElement)
return cls(name=name, streamNumber=streamNumber, depotName=depotName, Type=Type, basis=basis, basisStreamNumber=basisStreamNumber, time=time, prevTime=prevTime, prevBasis=prevBasis, prevBasisStreamNumber=prevBasisStreamNumber, prevName=prevName, workspace=workspace, startTime=startTime, isDynamic=isDynamic, hasDefaultGroup=hasDefaultGroup)
return None
class Move(object):
def __init__(self, dest = None, source = None):
self.dest = dest
self.source = source
def __repr__(self):
str = "Move(dest=" + repr(self.dest)
str += ", source=" + repr(self.source)
str += ")"
return str
@classmethod
def fromxmlelement(cls, xmlElement):
if xmlElement is not None and xmlElement.tag == 'move':
dest = xmlElement.attrib.get('dest')
source = xmlElement.attrib.get('source')
return cls(dest, source)
return None
class Version(object):
def __init__(self, stream=None, version=None):
self.stream = stream
self.version = version
def __repr__(self):
return '{0}/{1}'.format(self.stream, self.version)
@classmethod
def fromstring(cls, versionString):
if versionString is not None:
versionParts = versionString.replace('\\', '/').split('/')
if len(versionParts) == 2:
stream = versionParts[0]
if re.match('^[0-9]+$', stream):
stream = int(stream)
version = int(versionParts[1])
return cls(stream, version)
return None
class Transaction(object):
class Version(object):
class RevertSegment(object):
def __init__(self, headStream=None, headStreamName=None, headVersion=None, basisStream=None, basisStreamName=None, basisVersion=None, isTipVersion=None):
self.headStream = IntOrNone(headStream)
self.headStreamName = headStreamName
self.headVersion = IntOrNone(headVersion)
self.basisStream = IntOrNone(basisStream)
self.basisStreamName = basisStreamName
self.basisVersion = IntOrNone(basisVersion)
self.isTipVersion = obj.Bool.fromstring(isTipVersion)
def __repr__(self):
str = "obj.Transaction.Version.RevertSegment("
str += "headStream=" + repr(self.headStream)
str += ", headStreamName=" + repr(self.headStreamName)
str += ", headVersion=" + repr(self.headVersion)
str += ", basisStream=" + repr(self.basisStream)
str += ", basisStreamName=" + repr(self.basisStreamName)
str += ", basisVersion=" + repr(self.basisVersion)
str += ", isTipVersion=" + repr(self.isTipVersion)
return str
@classmethod
def fromxmlelement(cls, xmlElement):
if xmlElement is not None and xmlElement.tag == 'segment':
headStream = xmlElement.attrib.get('head_stream')
headStreamName = xmlElement.attrib.get('head_stream_name')
headVersion = xmlElement.attrib.get('head_version')
basisStream = xmlElement.attrib.get('basis_stream')
basisStreamName = xmlElement.attrib.get('basis_stream_name')
basisVersion = xmlElement.attrib.get('basis_version')
isTipVersion = xmlElement.attrib.get('is_tip_version')
return cls(headStream=headStream, headStreamName=headStreamName, headVersion=headVersion, basisStream=basisStream, basisStreamName=basisStreamName, basisVersion=basisVersion, isTipVersion=isTipVersion)
return None
def __init__(self, path, eid, virtual, real, virtualNamedVersion, realNamedVersion, ancestor=None, ancestorNamedVersion=None, mergedAgainst=None, mergedAgainstNamedVersion=None, elemType=None, dir=None, mtime=None, checksum=None, size=None, revertSegments=None):
self.path = path
self.eid = IntOrNone(eid)
self.virtual = obj.Version.fromstring(virtual)
self.real = obj.Version.fromstring(real)
self.virtualNamedVersion = obj.Version.fromstring(virtualNamedVersion)
self.realNamedVersion = obj.Version.fromstring(realNamedVersion)
self.ancestor = obj.Version.fromstring(ancestor)
self.ancestorNamedVersion = obj.Version.fromstring(ancestorNamedVersion)
self.mergedAgainst = obj.Version.fromstring(mergedAgainst)
self.mergedAgainstNamedVersion = obj.Version.fromstring(mergedAgainstNamedVersion)
self.elemType = elemType
self.dir = obj.Bool.fromstring(dir)
self.mtime = UTCDateTimeOrNone(mtime)
self.checksum = checksum
self.size = size
self.revertSegments = revertSegments # Either None or a list of revert segments
def __repr__(self):
str = "Transaction.Version(path=" + repr(self.path)
str += ", eid=" + repr(self.eid)
str += ", virtual=" + repr(self.virtual)
str += ", real=" + repr(self.real)
str += ", virtualNamedVersion=" + repr(self.virtualNamedVersion)
str += ", realNamedVersion=" + repr(self.realNamedVersion)
if self.ancestor is not None or self.ancestorNamedVersion is not None:
str += ", ancestor=" + repr(self.ancestor)
str += ", ancestorNamedVersion=" + repr(self.ancestorNamedVersion)
if self.mergedAgainst is not None or self.mergedAgainstNamedVersion is not None:
str += ", mergedAgainst=" + repr(self.mergedAgainst)
str += ", mergedAgainstNamedVersion=" + repr(self.mergedAgainstNamedVersion)
str += ", elemType=" + repr(self.elemType)
str += ", dir=" + repr(self.dir)
if self.mtime is not None:
str += ", mtime=" + repr(self.mtime)
if self.checksum is not None:
str += ", cksum=" + repr(self.checksum)
if self.size is not None:
str += ", size=" + repr(self.size)
if self.revertSegments is not None:
str += ", revertSegments=" + repr(self.revertSegments)
str += ")"
return str
@classmethod
def fromxmlelement(cls, xmlElement):
if xmlElement is not None and xmlElement.tag == 'version':
path = xmlElement.attrib.get('path')
eid = xmlElement.attrib.get('eid')
virtual = xmlElement.attrib.get('virtual')
real = xmlElement.attrib.get('real')
virtualNamedVersion = xmlElement.attrib.get('virtualNamedVersion')
realNamedVersion = xmlElement.attrib.get('realNamedVersion')
ancestor = xmlElement.attrib.get('ancestor')
ancestorNamedVersion = xmlElement.attrib.get('ancestorNamedVersion')
mergedAgainst = xmlElement.attrib.get('merged_against')
mergedAgainstNamedVersion = xmlElement.attrib.get('mergedAgainstNamedVersion')
elemType = xmlElement.attrib.get('elem_type')
dir = xmlElement.attrib.get('dir')
mtime = xmlElement.attrib.get('mtime')
cksum = xmlElement.attrib.get('cksum')
sz = xmlElement.attrib.get('sz')
revertSegments = None
revertSegmentsElem = xmlElement.find('revertSegments')
if revertSegmentsElem is not None:
revertSegments = []
segmentsElemList = revertSegmentsElem.findall('segment')
for segmentElem in segmentsElemList:
revertSegments.append(obj.Transaction.Version.RevertSegment.fromxmlelement(segmentElem))
return cls(path, eid, virtual, real, virtualNamedVersion, realNamedVersion, ancestor, ancestorNamedVersion, mergedAgainst, mergedAgainstNamedVersion, elemType, dir, mtime, cksum, sz, revertSegments)
return None
def __init__(self, id, Type, time, user, comment, streamName=None, streamNumber=None, fromStreamName=None, fromStreamNumber=None, versions = [], moves = [], stream = None):
self.id = IntOrNone(id)
self.Type = Type
self.time = UTCDateTimeOrNone(time)
self.user = user
self.streamName = streamName
self.streamNumber = IntOrNone(streamNumber)
self.fromStreamName = fromStreamName
self.fromStreamNumber = IntOrNone(fromStreamNumber)
self.comment = comment
self.versions = versions
self.moves = moves
self.stream = stream
def __repr__(self):
str = "Transaction(id=" + repr(self.id)
str += ", Type=" + repr(self.Type)
str += ", time=" + repr(self.time)
str += ", user=" + repr(self.user)
if self.streamName is not None:
str += ", streamName=" + repr(self.streamName)
if self.streamNumber is not None:
str += ", streamNumber=" + repr(self.streamNumber)
if self.fromStreamName is not None:
str += ", fromStreamName=" + repr(self.fromStreamName)
if self.fromStreamNumber is not None:
str += ", fromStreamNumber=" + repr(self.fromStreamNumber)
str += ", comment=" + repr(self.comment)
if len(self.versions) > 0:
str += ", versions=" + repr(self.versions)
if len(self.moves) > 0:
str += ", moves=" + repr(self.moves)
if self.stream is not None:
str += ", stream=" + repr(self.stream)
str += ")"
return str
# Extension method which returns the name or number of the stream
# which is affected by this transaction (the stream on which the
# transaction was performed). i.e. A promote to a stream called
# Stream1 whose id is 1734 would return ("Stream1", 1734).
def affectedStream(self):
streamName = self.streamName
streamNumber = self.streamNumber
if streamName is None and streamNumber is None:
if self.versions is not None and len(self.versions) > 0:
version = self.versions[0]
if version.virtualNamedVersion is not None:
streamName = version.virtualNamedVersion.stream
if version.virtual is not None:
streamNumber = int(version.virtual.stream)
elif self.stream is not None:
streamName = self.stream.name
streamNumber = self.stream.streamNumber
return (streamName, streamNumber)
def toStream(self):
return self.affectedStream()
def fromStream(self):
fromStreamName = self.fromStreamName
fromStreamNumber = self.fromStreamNumber
return (fromStreamName, fromStreamNumber)
@classmethod
def fromxmlelement(cls, xmlElement):
if xmlElement is not None and xmlElement.tag == 'transaction':
id = xmlElement.attrib.get('id')
Type = xmlElement.attrib.get('type')
time = xmlElement.attrib.get('time')
user = xmlElement.attrib.get('user')
streamName = xmlElement.attrib.get('streamName')
streamNumber = xmlElement.attrib.get('streamNumber')
fromStreamName = xmlElement.attrib.get('fromStreamName')
fromStreamNumber = xmlElement.attrib.get('fromStreamNumber')
comment = GetXmlContents(xmlElement.find('comment'))
versions = []
for versionElement in xmlElement.findall('version'):
versions.append(obj.Transaction.Version.fromxmlelement(versionElement))
moves = []
for moveElement in xmlElement.findall('move'):
moves.append(obj.Move.fromxmlelement(moveElement))
streamElement = xmlElement.find('stream')
stream = obj.Stream.fromxmlelement(streamElement)
return cls(id=id, Type=Type, time=time, user=user, comment=comment, streamName=streamName, streamNumber=streamNumber, fromStreamName=fromStreamName, fromStreamNumber=fromStreamNumber, versions=versions, moves=moves, stream=stream)
return None
class History(object):
def __init__(self, taskId = None, transactions = [], streams = []):
self.taskId = IntOrNone(taskId)
self.transactions = transactions
self.streams = streams
def __repr__(self):
str = "History(taskId=" + repr(self.taskId)
str += ", transactions=" + repr(self.transactions)
str += ", streams=" + repr(self.streams)
str += ")"
return str
@classmethod
def fromxmlstring(cls, xmlText):
try:
# Load the XML
xmlRoot = ElementTree.fromstring(xmlText)
#xpathPredicate = ".//AcResponse[@Command='hist']"
except ElementTree.ParseError:
return None
if xmlRoot is not None and xmlRoot.tag == "AcResponse" and xmlRoot.get("Command") == "hist":
# Build the class
taskId = xmlRoot.attrib.get('TaskId')
transactions = []
for transactionElement in xmlRoot.findall('transaction'):
transactions.append(obj.Transaction.fromxmlelement(transactionElement))
streams = []
streamsElement = xmlRoot.find('streams')
if streamsElement is not None:
for streamElement in streamsElement:
streams.append(obj.Stream.fromxmlelement(streamElement))
return cls(taskId=taskId, transactions=transactions, streams=streams)
else:
# Invalid XML for an AccuRev hist command response.
return None
# Returns a list of (streamName, streamNumber) tuples that directly correspond to the
# destination streams of the transactions. i.e. If there are 5 transactions there would
# be 5 tuples (even if they are all for the same stream). The 4th tuple is the destination
# stream for the 4th transaction.
def toStreams(self):
toStreams = []
toStreamName, toStreamNumber = None, None
if self.transactions is None:
# Can't workout the source stream for a None transaction.
return None, None
elif self.streams is not None and len(self.streams) == 1:
for tr in self.transactions:
toStreams.append( (self.streams[0].name, self.streams[0].streamNumber) )
else:
for tr in self.transactions:
toStreamName, toStreamNumber = tr.toStream()
toStreams.append( (toStreamName, toStreamNumber) )
return toStreams
def toStream(self):
if self.streams is not None and len(self.streams) == 1:
return self.streams[0].name, self.streams[0].streamNumber
else:
toStreams = self.toStreams()
if len(toStreams) > 1:
raise Exception("Error! Could not determine which of the many destination streams was the destination stream!")
return toStreams[0]
# Pre accurev 6.1 determining the from stream was difficult since the fromStreamName attribute of the transaction
# was missing. However, if you only queried a single transaction (i.e. `accurev hist -p Depot -t 71 -fex`) then
# there would be one transaction but two streams listed. From this we can work out which stream things were promoted
# to and infer that the other stream that is included is the stream from which the promote came from.
# Hence, since both the transactions and streams are required to do this, the History object should do it for this one
# very specific case.
def fromStream(self):
if self.transactions is None:
# Can't workout the source stream for a None transaction.
return None, None
elif len(self.transactions) != 1:
# Can't work out the source stream for multiple transactions.
return None, None
fromStreamName, fromStreamNumber = self.transactions[0].fromStream()
if fromStreamName is None:
toStreamName, toStreamNumber = self.toStream()
if toStreamName is not None and toStreamNumber is not None and self.streams is not None and len(self.streams) == 2:
fromStream = None
if self.streams[0].streamNumber == toStreamNumber:
fromStream = self.streams[1]
elif self.streams[1].streamNumber == toStreamNumber:
fromStream = self.streams[0]
else:
raise Exception("Error! Failed to match destination stream {s} (id {n}) to either of the two affected streams {s1} (id {s1num}) and {s2} (id {s2num}).".format(s=toStreamName, n=toStreamNumber, s1=self.streams[0].name, s1num=self.streams[0].streamNumber, s2=self.streams[1].name, s2num=self.streams[1].streamNumber))
fromStreamName, fromStreamNumber = fromStream.name, fromStream.streamNumber
else:
# Error! Could not determine the source stream.
return None, None
return (fromStreamName, fromStreamNumber)
class Stat(object):
class Element(object):
def __init__(self, location=None, isDir=False, isExecutable=False, id=None, elemType=None, size=None, modTime=None, hierType=None, virtualVersion=None, namedVersion=None, realVersion=None, status=None):
self.location = location
self.isDir = obj.Bool.fromstring(isDir)
self.isExecutable = obj.Bool.fromstring(isExecutable)
self.id = IntOrNone(id)
self.elemType = elemType
self.size = IntOrNone(size)
self.modTime = UTCDateTimeOrNone(modTime)
self.hierType = hierType
self.virtualVersion = obj.Version.fromstring(virtualVersion)
self.namedVersion = obj.Version.fromstring(namedVersion)
self.realVersion = obj.Version.fromstring(realVersion)
self.status = status
self.statusList = self._ParseStatusIntoList(status)
def __repr__(self):
str = "Stat.Element(location=" + repr(self.location)
str += ", isDir=" + repr(self.isDir)
str += ", isExecutable=" + repr(self.isExecutable)
str += ", id=" + repr(self.id)
str += ", elemType=" + repr(self.elemType)
str += ", size=" + repr(self.size)
str += ", modTime=" + repr(self.modTime)
str += ", hierType=" + repr(self.hierType)
str += ", virtualVersion=" + repr(self.virtualVersion)
str += ", namedVersion=" + repr(self.namedVersion)
str += ", realVersion=" + repr(self.realVersion)
str += ", status=" + repr(self.status)
str += ", statusList=" + repr(self.statusList)
str += ")"
return str
def _ParseStatusIntoList(self, status):
if status is not None:
statusList = []
statusItem = None
# The following regex takes a parenthesised text like (member)(defunct) and matches it
# putting the first matched parenthesised expression (of which there could be more than one)
# into the capture group one.
# Regex: Match open bracket, consume all characters that are NOT a closed bracket, match the
# closed bracket and return the capture group.
reStatusToken = re.compile("(\\([^\\)]+\\))")
matchObj = reStatusToken.match(status)
while matchObj and len(status) > 0:
statusItem = matchObj.group(1)
statusList.append(statusItem)
status = status[len(statusItem):]
matchObj = reStatusToken.match(status)
if len(status) != 0:
sys.stderr.write("Error: invalidly parsed status! Remaining text is \"{0}\"\n".format(status))
return None
return statusList
return None
@classmethod
def fromxmlelement(cls, xmlElement):
if xmlElement is not None and xmlElement.tag == "element":
location = xmlElement.attrib.get('location')
isDir = xmlElement.attrib.get('dir')
isExecutable = xmlElement.attrib.get('executable')
id = xmlElement.attrib.get('id')
elemType = xmlElement.attrib.get('elemType')
size = xmlElement.attrib.get('size')
modTime = xmlElement.attrib.get('modTime')
hierType = xmlElement.attrib.get('hierType')
virtualVersion = xmlElement.attrib.get('Virtual')
namedVersion = xmlElement.attrib.get('namedVersion')
realVersion = xmlElement.attrib.get('Real')
status = xmlElement.attrib.get('status')
return cls(location=location, isDir=isDir, isExecutable=isExecutable, id=id, elemType=elemType, size=size, modTime=modTime, hierType=hierType, virtualVersion=virtualVersion, namedVersion=namedVersion, realVersion=realVersion, status=status)
else:
return None
def __init__(self, taskId=None, directory=None, elements=[]):
self.taskId = IntOrNone(taskId)
self.directory = directory
self.elements = elements
def __repr__(self):
str = "Stat(taskId=" + repr(self.taskId)
str += ", directory=" + repr(self.directory)
str += ", elements=" + repr(self.elements)
str += ")"
return str
@classmethod
def fromxmlstring(cls, xmlText):
try:
xmlRoot = ElementTree.fromstring(xmlText)
except ElementTree.ParseError:
return None
if xmlRoot is not None and xmlRoot.tag == "AcResponse" and xmlRoot.get("Command") == "stat":
taskId = xmlRoot.attrib.get('TaskId')
directory = xmlRoot.attrib.get('Directory')
elements = []
for element in xmlRoot.findall('element'):
elements.append(obj.Stat.Element.fromxmlelement(element))
return cls(taskId=taskId, directory=directory, elements=elements)
else:
return None
class Change(object):
class Stream(object):
def __init__(self, name, eid, version, namedVersion, isDir, elemType):
self.name = name
self.eid = IntOrNone(eid)
self.version = obj.Version.fromstring(version)
self.namedVersion = obj.Version.fromstring(namedVersion)
self.isDir = obj.Bool.fromstring(isDir)
self.elemType = elemType
def __repr__(self):
str = "Change.Stream(name=" + repr(self.name)
str += ", eid=" + repr(self.eid)
str += ", version=" + repr(self.version)
str += ", namedVersion=" + repr(self.namedVersion)
str += ", isDir=" + repr(self.isDir)
str += ", elemType=" + repr(self.elemType)
str += ")"
return str
@classmethod
def fromxmlelement(cls, xmlElement):
if xmlElement is not None and re.match('^Stream[12]$', xmlElement.tag) is not None:
name = xmlElement.attrib.get('Name')
eid = xmlElement.attrib.get('eid')
version = xmlElement.attrib.get('Version')
namedVersion = xmlElement.attrib.get('NamedVersion')
isDir = xmlElement.attrib.get('IsDir')
elemType = xmlElement.attrib.get('elemType')
return cls(name=name, eid=eid, version=version, namedVersion=namedVersion, isDir=isDir, elemType=elemType)
return None
def __init__(self, what, stream1, stream2):
self.what = what
self.stream1 = stream1
self.stream2 = stream2
def __repr__(self):
str = "Change(what=" + repr(self.what)
str += ", stream1=" + repr(self.stream1)
str += ", stream2=" + repr(self.stream2)
str += ")"
return str
@classmethod
def fromxmlelement(cls, xmlElement):
if xmlElement is not None and xmlElement.tag == 'Change':
what = xmlElement.attrib.get('What')
stream1Elem = xmlElement.find('Stream1')
stream1 = obj.Change.Stream.fromxmlelement(stream1Elem)
stream2Elem = xmlElement.find('Stream2')
stream2 = obj.Change.Stream.fromxmlelement(stream2Elem)
return cls(what=what, stream1=stream1, stream2=stream2)
return None
class Diff(object):
class Element(object):
def __init__(self, changes = []):
self.changes = changes
def __repr__(self):
str = "Diff.Element(changes=" + repr(self.changes)
str += ")"
return str
@classmethod
def fromxmlelement(cls, xmlElement):
if xmlElement is not None and xmlElement.tag == 'Element':
changes = []
for change in xmlElement.findall('Change'):
changes.append(obj.Change.fromxmlelement(change))
return cls(changes=changes)
return None
def __init__(self, taskId, elements=[]):
self.taskId = IntOrNone(taskId)
self.elements = elements
def __repr__(self):
str = "Diff(taskId=" + repr(self.taskId)
str += ", elements=" + repr(self.elements)
str += ")"
return str
@classmethod
def fromxmlstring(cls, xmlText):
# This parser has been made from an example given by running:
# accurev diff -a -i -v Stream -V Stream -t 11-16 -fx
try:
xmlRoot = ElementTree.fromstring(xmlText)
except ElementTree.ParseError:
return None
if xmlRoot is not None and xmlRoot.tag == "AcResponse" and xmlRoot.get("Command") == "diff":
taskId = xmlRoot.attrib.get('TaskId')
elements = []
for element in xmlRoot.findall('Element'):
elements.append(obj.Diff.Element.fromxmlelement(element))
return cls(taskId=taskId, elements=elements)
else:
return None
class User(object):
def __init__(self, number = None, name = None, kind = None):
self.number = IntOrNone(number)
self.name = name
self.kind = kind
def __repr__(self):
str = "User(number=" + repr(self.number)
str += ", name=" + repr(self.name)
str += ", kind=" + repr(self.kind)
str += ")"
return str
@classmethod
def fromxmlelement(cls, xmlElement):
if xmlElement is not None and xmlElement.tag == 'Element':
number = xmlElement.attrib.get('Number')
name = xmlElement.attrib.get('Name')
kind = xmlElement.attrib.get('Kind')
return cls(number, name, kind)
return None
class Show(object):
class Users(object):
def __init__(self, taskId = None, users = []):
self.taskId = IntOrNone(taskId)
self.users = users
def __repr__(self):
str = "Show.Users(taskId=" + repr(self.taskId)
str += ", users=" + repr(self.users)