-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseqdiagbuilder.py
1725 lines (1369 loc) · 77.3 KB
/
seqdiagbuilder.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
import traceback, re, ast, importlib, inspect
import webbrowser
import os
import copy
from inspect import signature
import collections
SEQDIAG_LOOP_START_END_TAG = ':seqdiag_loop_start_end'
SEQDIAG_LOOP_END_TAG = ':seqdiag_loop_end'
SEQDIAG_LOOP_START_TAG = ':seqdiag_loop_start'
BIG_COMMENT_LENGTH = 100
SEQDIAG_RETURN_TAG = ":seqdiag_return"
SEQDIAG_SELECT_METHOD_TAG = ":seqdiag_select_method"
SEQDIAG_NOTE_TAG = ":seqdiag_note"
SEQDIAG_METHOD_RETURN_NOTE_TAG = ":seqdiag_return_note"
SEQDIAG_RETURN_TAG_PATTERN = r"%s (.*)" % SEQDIAG_RETURN_TAG
SEQDIAG_SELECT_METHOD_TAG_PATTERN = r"%s(.*)" % SEQDIAG_SELECT_METHOD_TAG
PYTHON_FILE_AND_FUNC_PATTERN = r"([\w:\\]+\\)(\w+)\.py, line (\d*) in (.*)"
FRAME_PATTERN = r"(?:<FrameSummary file ([\w:\\,._\s]+)(?:>, |>\]))"
SEQDIAG_NOTE_TAG_PATTERN = r"%s (.*)" % SEQDIAG_NOTE_TAG
SEQDIAG_METHOD_RETURN_NOTE_TAG_PATTERN = r"%s (.*)" % SEQDIAG_METHOD_RETURN_NOTE_TAG
TAB_CHAR = '\t'
class FlowEntry:
def __init__(self, fromClass='', fromMethod='', toClass='', toMethod='', toMethodCalledFromLineNumber='',
toSignature='', toMethodNote='', toReturnType='', toReturnNote=''):
'''
:param fromClass: class containing the fromMethod
:param fromMethod: method calling the toMethod
:param toClass: class containing the toMethod
:param toMethod: method called from the fromMethod
:param toMethodCalledFromLineNumber: line number in the fromMethod from which
the toMethod was called
:param toSignature: toMethod signature
:param toMethodNote toMethod note
:param toReturnType: return type of the toMethod
:param toReturnNote: return type note
'''
self.fromClass = fromClass
self.fromMethod = fromMethod
self.toClass = toClass
self.toMethod = toMethod
self.toMethodCalledFromLineNumber = toMethodCalledFromLineNumber
self.toSignature = toSignature
self.toMethodNote = toMethodNote
self.toReturnType = toReturnType
self.toReturnNote = toReturnNote
def __eq__(self, other):
return self.fromClass == other.fromClass and \
self.fromMethod == other.fromMethod and \
self.toClass == other.toClass and \
self.toMethod == other.toMethod and \
self.toMethodCalledFromLineNumber == other.toMethodCalledFromLineNumber and \
self.toSignature == other.toSignature and \
self.toMethodNote == other.toMethodNote and \
self.toReturnType == other.toReturnType and \
self.toReturnNote == other.toReturnNote
def isEntryPoint(self, targetClass, targetMethod):
'''
Returns True if the passed targetClass/targetMethod are equal to the toClass and
toMethod of the flow entry, which means the flow entry corresponds to the seq diag
entry point.
:param targetClass:
:param targetMethod:
:return:
'''
return self.toClass == targetClass and \
self.toMethod == targetMethod
def equalFrom(self, entry):
return self.fromClass == entry.fromClass and self.fromMethod == entry.fromMethod
def differByLineNumberOnly(self, entry):
'''
Return True if entry and self denote the same class.method but called from a
different location
:param entry:
:return:
'''
return self.equalFrom(entry) and self.toMethodCalledFromLineNumber != entry.toMethodCalledFromLineNumber
def getCallDepth(self):
'''
Calculate current call depth. This info will be used to determine the
number of time the Plant UML command must be indented aswell as for
managing loop end command insertion.
:return:
'''
return self.toMethodCalledFromLineNumber.count('-')
def createReturnType(self, maxArgNum, maxReturnTypeCharLen):
'''
Return a return type string which has no more arguments than maxArgNum and is not
longer than maxReturnTypeCharLen.
:param maxArgNum:
:param maxReturnTypeCharLen:
:return:
'''
# applying first the max return type arg number constraint
if self.toReturnType == '':
return self.toReturnType
else:
returnTypeStr = self.toReturnType
if maxArgNum != None:
if maxArgNum == 0:
return '...'
tentativeReturnTypeArgNum = self.toReturnType.count(',') + 1
if maxArgNum < tentativeReturnTypeArgNum:
# here, the return type must be reduced to maxArgNum arguments
returnTypeArgList = returnTypeStr.split(',')
returnTypeStr = ','.join(returnTypeArgList[:maxArgNum])
returnTypeStr = returnTypeStr + ', ...'
# applying then the max return type length number constraint
if maxReturnTypeCharLen != None:
if returnTypeStr == '...' or len(returnTypeStr) <= maxReturnTypeCharLen:
return returnTypeStr
if '...' in returnTypeStr:
returnTypeStr = returnTypeStr[:-5] # removing , ...
returnTypeArgList = returnTypeStr.split(', ')
returnTypeStr = '...'
tentativeReturnType = ''
tentativeReturnTypeArgNum = 0
for arg in returnTypeArgList:
if tentativeReturnTypeArgNum == 0:
tentativeReturnType += arg
else:
tentativeReturnType = tentativeReturnType + ', ' + arg
tentativeReturnType = tentativeReturnType + ', ...'
rtLen = len(tentativeReturnType)
if rtLen > maxReturnTypeCharLen:
return returnTypeStr
elif rtLen == maxReturnTypeCharLen:
return tentativeReturnType
else:
returnTypeStr = tentativeReturnType
tentativeReturnType = returnTypeStr[:-5]
tentativeReturnTypeArgNum += 1
return returnTypeStr
def createSignature(self, maxSigArgNum, maxSigCharLen):
'''
Return a signature which has no more arguments than maxSigArgNum and is not
longer than maxSigCharLen.
:param maxSigArgNum:
:param maxSigCharLen:
:return:
'''
# applying first the max signature arg number constraint
if self.toSignature == '()':
return self.toSignature
else:
returnedSignature = self.toSignature
if maxSigArgNum != None:
if maxSigArgNum == 0:
return '(...)'
tentativeSigArgNum = self.toSignature.count(',') + 1
if maxSigArgNum < tentativeSigArgNum:
# here, the signature must be reduced to maxSigArgNum arguments
returnedSignature = returnedSignature[1:-1] # removing parenthesis
sigArgList = returnedSignature.split(',')
returnedSignature = ','.join(sigArgList[:maxSigArgNum])
returnedSignature = '(' + returnedSignature + ', ...)'
# applying then the max signature length number constraint
if maxSigCharLen != None:
if returnedSignature == '(...)' or len(returnedSignature) <= maxSigCharLen:
return returnedSignature
if '...' in returnedSignature:
returnedSignature = returnedSignature[1:-6] # removing parenthesis and , ...
else:
returnedSignature = returnedSignature[1:-1] # removing parenthesis
sigArgList = returnedSignature.split(', ')
returnedSignature = '(...)'
tentativeSignature = ''
tentativeSigArgNum = 0
for arg in sigArgList:
if tentativeSigArgNum == 0:
tentativeSignature += arg
else:
tentativeSignature = tentativeSignature + ', ' + arg
tentativeSignature = '(' + tentativeSignature + ', ...)'
sigLen = len(tentativeSignature)
if sigLen > maxSigCharLen:
return returnedSignature
elif sigLen == maxSigCharLen:
return tentativeSignature
else:
returnedSignature = tentativeSignature
tentativeSignature = returnedSignature[1:-6]
tentativeSigArgNum += 1
return returnedSignature
def __str__(self):
return "{}.{}, {}.{}{}, {}, {}, {}, {}".format(self.fromClass, self.fromMethod, self.toClass, self.toMethod, self.toSignature, self.toMethodCalledFromLineNumber, self.toMethodNote, self.toReturnType, self.toMethodReturnNote)
def getToMethodCallLineNumber(self):
'''
Returns the line number in fromMethod of the call to toMethod.
:return:
'''
lineNumberList = self.toMethodCalledFromLineNumber.split('-')
return lineNumberList[-1]
class RecordedFlowPath:
'''
This class stores in a flowEntryList of FlowEntry the succession of embedded method calls whic occurred
until the point in a leaf method containing the SeqDiagBuilder.recordFlow() instruction.
'''
def __init__(self, entryClass, entryMethod):
'''
:param entryClass: class containing the entry method
:param entryMethod: method from which the embedded method calls are recorded in the
RecordedFlowPath. entryClass.entryMethod are labelled as entry point
and are stored as a FlowEntry in the internal RecordedFlowPath flowEntryList.
'''
self.entryClass = entryClass
self.entryMethod = entryMethod
self.entryPointReached = False
self.flowEntryList = []
def addIfNotIn(self, newFlowEntry):
'''
This method adds a flow entry to the internal flowEntryList if the internal flowEntryList
already contains the entry point and provided this flow entry is not already in the
flowEntryList.
The addition is only possible if the entry point was reached. For example, if
we have TestClass.testCaseMethod() --> A.f() --> A.g() --> B.h() and the entry class
and entry method is A.f(), flow entries will be added only once A.f() was reached and was
added to the flowEntryList.
:param newFlowEntry:
:return:
'''
if not self.entryPointReached:
if newFlowEntry.isEntryPoint(self.entryClass, self.entryMethod):
self.entryPointReached = True
else:
# exiting the method ignores flow entries preceeding the entry point
return
if self.flowEntryList == []:
# the first encountered occurrence of entry point is added
self.flowEntryList.append(newFlowEntry)
return
# exiting the method if the current flow entry is already in the flowEntryList
for flowEntry in self.flowEntryList:
if flowEntry == newFlowEntry:
return
self.flowEntryList.append(newFlowEntry)
def size(self):
return len(self.flowEntryList)
def isEmpty(self):
return self.size() == 0
def __str__(self):
outStr = ''
for flowEntry in self.flowEntryList:
outStr += str(flowEntry) + '\n'
return outStr
class Stack:
'''
Stack base class
'''
def __init__(self):
self.stack = []
def pop(self):
if self.isEmpty():
return None
else:
return self.stack.pop()
def push(self, entry):
self.stack.append(entry)
return self.stack
def peek(self):
if self.isEmpty():
return None
else:
return self.stack[-1]
def size(self):
return len(self.stack)
def isEmpty(self):
return self.size() == 0
class SeqDiagCommandStack(Stack):
'''
This flowEntryList stores the embedded calls used to build the sequence diagram commands. It is
used to build the return commands of the diagram.
'''
def containsFromCall(self, flowEntry):
'''
Return True if the passed flow entry is in the SeqDiagCommandStack.
:param flowEntry:
:return:
'''
for entry in self.stack:
if entry.equalFrom(flowEntry):
return True
return False
class LoopCommandStack(Stack):
'''
Stacks the seqdiag loop start and seqdiag loop start end commands so that
when required, an end UML tag can be added into the PlantUML sequence diagram
command file.
'''
class ConstructorArgsProvider:
def __init__(self, classArgDic):
'''
:param classArgDic: class cnstructor arguments dictionary
classArgDic format:
{
'classNameA_usage_2': ['a_arg21', 'a_arg22'], #args used at second instanciation
'classNameA_usage_1': ['a_arg11', 'a_arg12'], #args used at first instanciation
'classNameB': ['b_arg1']
'classNameC_usage_1': ['c_arg1'],
'classNameC_usage_3': ['c_arg3'],
'classNameC_usage_2': ['c_arg2']
}
'''
self.classArgDic = classArgDic
# making a copy of the classArgDic so it can be added to a warning message to make it clearer.
# Doing a deep copy does not seem necessary for now, but in the future ...
self.savedClassArgDic = copy.deepcopy(classArgDic)
def getArgsForClassConstructor(self, className):
'''
Return a list containing the ctor arguments for the passed className. If className is
not found in the internal classArgDic, None is returned.
:param className:
:return: list containing the ctor arguments in their usage order, None if no entry exist
for the passed className
'''
# collecting all the keys in the classArgDic which are for the className.
# The keys may contain a digit, which indicates that the entry can only be
# used once to instanciate className
keys = self.classArgDic.keys()
keyList = []
for key in keys:
if className in key:
keyList.append(key)
if len(keyList) == 0:
# here, no ctor arg definition for className found in the classArgDic
return None
elif len(keyList) == 1:
classNameFromDic = keyList[0]
if any(c.isdigit() for c in classNameFromDic):
args = self.classArgDic[classNameFromDic]
# since an entry in the classArgDic keyed by a key conttaining a digit
# can be consumed only once, it must be deleted from the classArgDic
del self.classArgDic[classNameFromDic]
return args
else:
# here, the ctor argument(s) are reusable and need not be removed from the classArgDic
return self.classArgDic.get(className, None)
# here, the keyList contains more than one key, which means that several sets of ctor
# arguments were specified for className, which means that at each instanciation, the used
# entry must be removed from the classArgDic.
orderedKeyList = sorted(keyList)
firstKey = orderedKeyList[0]
firstKeyArgs = self.classArgDic[firstKey]
del self.classArgDic[firstKey]
return firstKeyArgs
class LoopCommandManager():
'''
This class manages the seqdiag loop commands inserted in the body of the
methods called within the control flow recorded by SeqDiagBuilder. The
informations stored are the class and method name containing seqdiag loop
commands and their line number associated to the seqdiag loop command type:
start, startEnd and end.
The concept behind the LoopCommandManager is that it is used at 2 steps of
SeqDiagBuilder working: at execution flow record time and when generating
the PlantUML command file. At flow record time, the current source file is
parsed in order to add in the LoopCommandManager internal dictionary the
instruction lines on which a seqdiag loop annotation exists.
Later, at PlantUML command file generation time, the info stored in the
internal dictionary is used to add loop and end commands.
Each time a loop command is added, the instruction line info is stacked
into the internal stack so it can be unstacked after method call return
in order to add an end command.
'''
_loopIndexDic = None
_loopCommandStack = None
def __init__(self):
self._loopIndexDic = {}
self._loopCommandStack = LoopCommandStack()
def storeLoopCommands(self, fromClassName, fromMethodName, currentMethodStartLineNumber, methodBodyLines):
'''
Find in the passed methodBodyLines the seqdiag loop commands and
store them in the internal _loopIndexDic.
:return: loopStartCommandNumber, loopEndCommandNumber used by caller to
issue an error msg if those 2 values differs !
'''
loopStartCommandNumber = 0
loopEndCommandNumber = 0
for methodBodyLineNb, line in enumerate(methodBodyLines[0]):
loopCommandTupleList = self.extractLoopCommandsFromLine(line)
if loopCommandTupleList:
# adding to the currentMethodStartLineNumber the current line
# number gives the line number on whichsthe seqdiag loop
# command is located
loopCommandLineNb = currentMethodStartLineNumber + methodBodyLineNb
toMethodName = self.extractTargetMethodNameFromLoopCommandLine(line)
dicKey = self._buildKey(fromClassName, fromMethodName, toMethodName, loopCommandLineNb)
# Since the storeLoopCommands() method is called at every for loop
# execution, this test is necessary since we only want to store the
# seqdiag commands once for a line of code containing them.
if dicKey in self._loopIndexDic:
continue
for loopCommandTuple in loopCommandTupleList:
loopCommandComment = loopCommandTuple[1]
loopCommand = loopCommandTuple[0]
if loopCommand == SEQDIAG_LOOP_START_TAG:
loopStartCommandNumber += 1
elif loopCommand == SEQDIAG_LOOP_END_TAG:
loopEndCommandNumber += 1
self.addKeyValue(dicKey, loopCommand, loopCommandComment)
return loopStartCommandNumber, loopEndCommandNumber
def extractLoopCommandsFromLine(self, lineStr):
'''
This method returns a list of seqdiag loop commands defined on the passed lineStr.
What is returned in fact is a list of 2 elements sub lists. Each sub list
contains 2 strings: one for the seqdiag loop command itself and one for the
seqdiag loop command comment (may be an empty string !).
:param lineStr:
:return: list of list(s) denoting loop commands or None if no loop command
was found on the passed lineStr
'''
seqdiagLoopPattern = r"(:seqdiag_loop[\w]+)\s*([\w ]*)"
commandTupleList = re.findall(seqdiagLoopPattern, lineStr)
# converting list of tuples into a list of lists so that
# it is possible to modify the elements (see stripping below !)
listOfCommandList = [list(elem) for elem in commandTupleList]
for commandList in listOfCommandList:
# stripping any end space from the comment part of the seqdiag loop command
commandList[1] = commandList[1].strip()
if listOfCommandList == []:
listOfCommandList = None
return listOfCommandList
def _buildKey(self, fromClassName, fromMethodName, toMethodName, methodCallLineNumber):
'''
Builds the dictionary key, enforcing the internal format of the
dictionary.
:param fromClassName:
:param fromMethodName:
:param toMethodName:
:param methodCallLineNumber:
:return: dictionary key
'''
return fromClassName + "." + fromMethodName + "->" + toMethodName + ": " + str(
methodCallLineNumber)
def splitKey(self, keyStr):
'''
Split the internal dictionary keyStr into its components and return them.
:param fromClassName:
:param fromMethodName:
:param toMethodName:
:param methodCallLineNumber:
:return: dictionary keyStr
'''
keyPattern = r'(\w+).(\w+)->(\w+): (\d+)'
match = re.match(keyPattern, keyStr)
fromClassName = ''
fromMethodName = ''
toMethodName = ''
methodCallLineNumber = ''
if match:
fromClassName = match.groups()[0]
fromMethodName = match.groups()[1]
toMethodName = match.groups()[2]
methodCallLineNumber = match.groups()[3]
return fromClassName, fromMethodName, toMethodName, methodCallLineNumber
def extractTargetMethodNameFromLoopCommandLine(self, seqdiagTagLine):
'''
Extract from the seqdiag loop command line the target method name.
:param seqdiagTagLine: line on which the seqdiag loop command is located
:return: target method name
'''
pattern = r'.([\w _]+)\('
match = re.search(pattern, seqdiagTagLine)
return match.group(1)
def addKeyValue(self, dicKey, seqdiagLoopTag, seqdiagLoopComment):
'''
Add to the internal dictionary the seqdiag loop tag and seqdiag loop comment
for the passed dicKey.
The value associated to a key is a list of two entries lists. This
is adapted to the case where more than one seqdiag loop tag are on the same
line, like, for example,
#:seqdiag_loop_start 3 times :seqdiag_loop_start_end 5 times.
Each seqdiag loop command is composed of three elements: the command
itself, the loop comment (which generally indicates the loop execution
time and may be None) and a boolean which indicates if the entry has been
consumed at seqdiag loop tag generation time in the Plant UML command file.
:param dicKey:
:param seqdiagLoopTag:
:param seqdiagLoopComment: may be None. Generally indicates the loop
execution time
:return:
'''
loopTagEntryList = [seqdiagLoopTag, seqdiagLoopComment, False]
if dicKey in self._loopIndexDic:
self._loopIndexDic[dicKey].append(loopTagEntryList)
else:
self._loopIndexDic[dicKey] = [loopTagEntryList]
def getLoopCommandList(self, fromClassName, fromMethodName, toMethodName, lineNb):
'''
Return a list containing one or more 2 element list representing
a seqdiag loop command. In case more than one seqdiag loop command
are defined on the instruction line, the returned list contains more
than one sublist. Each seqdiag loop command is represented by a 2
element list. Example: [':seqdiag_loop_start_end', '5 times'] or
[':seqdiag_loop_start_end', None]
:param fromClassName:
:param fromMethodName:
:param toMethodName:
:param lineNb:
:return: list containing one or more 2 element list representing a
seqdiag loop command or None if no entry found for the input
parms provided
'''
key = self._buildKey(fromClassName, fromMethodName, toMethodName, lineNb)
if key in self._loopIndexDic:
return self._loopIndexDic[key]
else:
return None
def stackLoopEndCommand(self, fromClassName, fromMethodName, toMethodName, toMethodCallLineNb):
loopCommandInfo = self._buildKey(fromClassName, fromMethodName, toMethodName, toMethodCallLineNb)
self._loopCommandStack.push(loopCommandInfo)
def unstackTopLoopEndCommand(self):
'''
Unstacks the last (top) stacked loop end command info.
:return:
'''
self._loopCommandStack.pop()
def peekLoopEndEntry(self, fromClassName, fromMethodName, toMethodName, toMethodCallLineNb):
loopCommandInfo = self._buildKey(fromClassName, fromMethodName, toMethodName, toMethodCallLineNb)
return loopCommandInfo == self._loopCommandStack.peek()
def setLoopCommandIsOnFlow(self, loopCommandIndex, fromClassName, fromMethodName, toMethodName, toMethodCallLineNb):
'''
Sets the 3rd element of the loopCommandIndex sub list in the loop command list attached to
the passed key components to True. This indicates that the loop command is
located on a method which execution belongs to the SeqDiagBuillder recorded
flow.
A precondition of the method is that there's a loop command list in the internal dictionary.
So, no test is done on the existence of the list.
:param loopCommandIndex: index of the loop command sub list
:param fromClassName:
:param fromMethodName:
:param toMethodName:
:param toMethodCallLineNb:
:return:
'''
key = self._buildKey(fromClassName, fromMethodName, toMethodName, toMethodCallLineNb)
loopCommandList = self._loopIndexDic[key]
loopCommandList[loopCommandIndex][2] = True
def getOutOfRecordedFlowLoopCommandList(self):
'''
Returns a list of loop command entries stored in the internal loop command
dictionary which have NOT been handled at PlantUML command file generation
time to generate a seqDiag loop command.
If all entries were handled, None is returned.
:return:
'''
outOfFlowLoopCommandList = []
for loopCommandKey, loopCommandValue in self._loopIndexDic.items():
for loopCommandEntry in loopCommandValue:
if not loopCommandEntry[2]:
outOfFlowLoopCommandList.append([loopCommandKey, loopCommandValue[0]])
if outOfFlowLoopCommandList == []:
return None
else:
return outOfFlowLoopCommandList
class SeqDiagBuilder:
'''
This class contains a static utility methods used to build a sequence diagram from the
call flowEntryList as at the point in the python code were it is called.
To build the diagram, type seqdiag -Tsvg flowEntryList.txt in a command line window.
This build a svg file which can be displayed in a browsxer.
'''
_seqDiagWarningList = []
_projectPath = None
_isActive = False
_recordFlowCalled = False
_seqDiagEntryClass = None
_seqDiagEntryMethod = None
_recordedFlowPath = None
_participantDocOrderedDic = None
__loopCommandMgrconstructorArgProvider = None
_loopCommandMgr = None
_throwAwayGeneratedSeqDiagCommands = False
@staticmethod
def activate(projectPath, entryClass, entryMethod, classArgDic = None):
'''
Initialise and activate SeqDiagBuilder. This method must be called before calling any method
on the entry class.
:param projectPath: for example 'D:\\Development\\Python\\seqdiagbuilder' or
'D:/Development/Python/seqdiagbuilder'
:param entryClass:
:param entryMethod:
:param classArgDic: class cnstructor arguments dictionary
classArgDic format:
{
'classNameA_usage_2': ['a_arg21', 'a_arg22'], #args used at second instanciation
'classNameA_usage_1': ['a_arg11', 'a_arg12'], #args used at first instanciation
'classNameB': ['b_arg1']
'classNameC_usage_1': ['c_arg1'],
'classNameC_usage_3': ['c_arg3'],
'classNameC_usage_2': ['c_arg2']
}
:return:
'''
SeqDiagBuilder._projectPath = projectPath
SeqDiagBuilder._seqDiagEntryClass = entryClass
SeqDiagBuilder._seqDiagEntryMethod = entryMethod
SeqDiagBuilder._recordedFlowPath = RecordedFlowPath(SeqDiagBuilder._seqDiagEntryClass, SeqDiagBuilder._seqDiagEntryMethod)
SeqDiagBuilder._isActive = True
SeqDiagBuilder._participantDocOrderedDic = collections.OrderedDict()
SeqDiagBuilder._loopCommandMgr = LoopCommandManager()
if classArgDic:
SeqDiagBuilder._constructorArgProvider = ConstructorArgsProvider(classArgDic)
@staticmethod
def deactivate():
'''
Reinitialise the class level seq diag variables and data structures and sets its
build mode to False
:return:
'''
SeqDiagBuilder._seqDiagEntryClass = None
SeqDiagBuilder._seqDiagEntryMethod = None
SeqDiagBuilder._recordedFlowPath = None
SeqDiagBuilder._seqDiagWarningList = []
SeqDiagBuilder._isActive = False
SeqDiagBuilder._recordFlowCalled = False
SeqDiagBuilder._participantDocOrderedDic = collections.OrderedDict()
SeqDiagBuilder._constructorArgProvider = None
SeqDiagBuilder._loopCommandMgr = None
SeqDiagBuilder._throwAwayGeneratedSeqDiagCommands = False
@staticmethod
def _buildCommandFileHeaderSection():
'''
This toMethod create the first line of the PlantUML command file,
adding a header section in case of warnings.
:return:
'''
commandFileHeaderSectionStr = "@startuml\n"
warningNb = len(SeqDiagBuilder._seqDiagWarningList)
if warningNb > 0:
# building a header containing the warnings. If several warnings are issued, they are numbered.
commandFileHeaderSectionStr += "center header\n<b><font color=red size=20> Warnings</font></b>\n"
warningIndex = 0
if warningNb > 1:
warningIndex = 1
for warning in SeqDiagBuilder._seqDiagWarningList:
if warningIndex:
commandFileHeaderSectionStr += "<b><font color=red size=20> {}</font></b>\n".format(warningIndex)
warningIndex += 1
commandFileHeaderSectionStr += SeqDiagBuilder._splitLongWarningToFormattedLines(warning)
commandFileHeaderSectionStr += "endheader\n\n"
return commandFileHeaderSectionStr
@staticmethod
def _splitNoteToLines(oneLineNote, maxNoteLineLen):
'''
Splits the oneLineNote string into lines not exceeding maxNoteLineLen and returns the lines
into a list.
:param oneLineNote:
:param maxNoteLineLen:
:return:
'''
if oneLineNote == '':
return []
noteWordList = oneLineNote.split(' ')
noteLine = noteWordList[0]
noteLineLen = len(noteLine)
noteLineList = []
for word in noteWordList[1:]:
wordLen = len(word)
if noteLineLen + wordLen + 1 > maxNoteLineLen:
noteLineList.append(noteLine)
noteLine = word
noteLineLen = wordLen
else:
noteLine += ' ' + word
noteLineLen += wordLen + 1
noteLineList.append(noteLine)
return noteLineList
@staticmethod
def _buildParticipantSection(participantDocOrderedDic, maxNoteCharLen):
classNoteSectionStr = ''
for className, classNote in participantDocOrderedDic.items():
if classNote == '':
participantEntry = 'participant {}\n'.format(className)
else:
classNoteLineList = SeqDiagBuilder._splitNoteToLines(classNote, maxNoteCharLen * 1.5)
#adding a '/' before 'note over ...' causes PlantUML to position participant notes on the same line !
participantEntry = 'participant {}\n{}/note over of {}\n'.format(className, TAB_CHAR, className)
for classNoteLine in classNoteLineList:
participantEntry += '{}{}{}\n'.format(TAB_CHAR, TAB_CHAR, classNoteLine)
participantEntry += '{}end note\n'.format(TAB_CHAR)
classNoteSectionStr += participantEntry
return classNoteSectionStr
@staticmethod
def _splitLongWarningToFormattedLines(warningStr):
'''
:param warningStr:
:return:
'''
formattedWarnings = ''
lines = warningStr.split('\n')
for line in lines:
formattedWarnings += '<b><font color=red size=14> {}</font></b>\n'.format(line)
return formattedWarnings
@staticmethod
def createDiagram(targetDriveDirName, actorName, title=None, maxSigArgNum=None, maxSigCharLen=BIG_COMMENT_LENGTH, maxNoteCharLen=BIG_COMMENT_LENGTH):
'''
This method create a Plant UML command file, launch Plant UML on it and open the
created sequence diagram svg file in a browser.
:param targetDriveDirName: folder in which the generated command file and svg diagram
are saved. Ex: c:/temp.
:param actorName: name of the sequence diagram actor.
:param title: title of the sequence diagram.
:param maxSigArgNum: maximum arguments number of a called toMethod
toSignature. Applies to return type aswell.
:param maxSigCharLen: maximum length a method signature can occupy.
Applies to return type aswell.
:param maxNoteCharLen: maximum length a method or participant note can occupy.
:return: nothing.
'''
seqDiagCommands = SeqDiagBuilder.createSeqDiaqCommands(actorName, maxSigArgNum, maxSigCharLen, maxNoteCharLen)
targetCommandFileName = SeqDiagBuilder._seqDiagEntryMethod + '.txt'
targetDriveDirName = targetDriveDirName.replace('\\','/')
if targetDriveDirName[-1] != '/':
targetDriveDirName = targetDriveDirName + '/'
targetCommandFilePathName = '{}{}'.format(targetDriveDirName, targetCommandFileName)
with open(targetCommandFilePathName, "w") as f:
f.write(seqDiagCommands)
os.chdir(targetDriveDirName)
os.system('java -jar plantuml.jar -tsvg ' + targetCommandFileName)
webbrowser.open("file:///{}{}.svg".format(targetDriveDirName, SeqDiagBuilder._seqDiagEntryMethod))
@staticmethod
def createSeqDiaqCommands(actorName, title=None, maxSigArgNum=None, maxSigCharLen=BIG_COMMENT_LENGTH, maxNoteCharLen=BIG_COMMENT_LENGTH):
'''
This method uses the control flow data collected during execution to create
the commands Plantuml will use to draw the sequence diagram.
To build the diagram itself, type java -jar plantuml.jar -tsvg seqdiagcommands.txt
in a command line window. This build a svg file which can be displayed in a browser.
:param actorName: name of the sequence diagram actor.
:param title: title of the sequence diagram.
:param maxSigArgNum: maximum arguments number of a called toMethod
toSignature. Applies to return type aswell.
:param maxSigCharLen: maximum length a toMethod toSignature can occupy.
Applies to return type aswell.
:param maxNoteCharLen: maximum length a method or participant note can occupy.
:return: nothing.
'''
isFlowRecorded = True
if SeqDiagBuilder._recordedFlowPath == None:
isEntryPointReached = False
isFlowRecorded = False
SeqDiagBuilder._issueNoFlowRecordedWarning(isEntryPointReached)
elif SeqDiagBuilder._recordedFlowPath.isEmpty():
isEntryPointReached = SeqDiagBuilder._recordedFlowPath.entryPointReached
isFlowRecorded = False
SeqDiagBuilder._issueNoFlowRecordedWarning(isEntryPointReached)
seqDiagCommandStr = ''
if isFlowRecorded:
classMethodReturnStack = SeqDiagCommandStack()
if title:
seqDiagCommandStr += "\ntitle {}\n".format(title)
seqDiagCommandStr += "actor {}\n".format(actorName)
else:
seqDiagCommandStr += "\nactor {}\n".format(actorName)
participantSection = SeqDiagBuilder._buildParticipantSection(SeqDiagBuilder._participantDocOrderedDic, maxNoteCharLen)
seqDiagCommandStr += participantSection
firstFlowEntry = SeqDiagBuilder._recordedFlowPath.flowEntryList[0]
firstFlowEntry.fromClass = actorName
fromClass = firstFlowEntry.fromClass
loopDepth = 0
forwardCommandStr = SeqDiagBuilder._handleSeqDiagForwardMesssageCommand(fromClass=fromClass,
flowEntry=firstFlowEntry,
classMethodReturnStack=classMethodReturnStack,
maxSigArgNum=maxSigArgNum,
maxSigCharLen=maxSigCharLen,
maxNoteCharLen=maxNoteCharLen,
loopDepth=loopDepth)
seqDiagCommandStr += forwardCommandStr
fromClass = firstFlowEntry.toClass
for flowEntry in SeqDiagBuilder._recordedFlowPath.flowEntryList[1:]:
if not classMethodReturnStack.containsFromCall(flowEntry):
loopStartCommandStr, loopDepth = SeqDiagBuilder._handledSeqDiagLoopStartCommand(fromClassName=fromClass,
fromMethodName=flowEntry.fromMethod,
toMethodName=flowEntry.toMethod,
toMethodCallLineNb=flowEntry.getToMethodCallLineNumber(),
callDepth=flowEntry.getCallDepth(),
loopDepth=loopDepth)
seqDiagCommandStr += loopStartCommandStr
forwardCommandStr = SeqDiagBuilder._handleSeqDiagForwardMesssageCommand(fromClass=fromClass,
flowEntry=flowEntry,
classMethodReturnStack=classMethodReturnStack,
maxSigArgNum=maxSigArgNum,
maxSigCharLen=maxSigCharLen,
maxNoteCharLen=maxNoteCharLen,
loopDepth=loopDepth)
seqDiagCommandStr += forwardCommandStr
fromClass = flowEntry.toClass
else:
stopUnfolding = False
while not stopUnfolding and classMethodReturnStack.containsFromCall(flowEntry):