-
Notifications
You must be signed in to change notification settings - Fork 389
Expand file tree
/
Copy pathctrlcommands.py
More file actions
1711 lines (1285 loc) · 60.2 KB
/
ctrlcommands.py
File metadata and controls
1711 lines (1285 loc) · 60.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
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
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
import time
from itertools import chain
from . import settingcontrollers
from . import validators
from ..namespace.embeddedargs import EmbeddedArgsHandler
from ..namespace import namespace
from ..publish.messages import (RideSelectResource, RideFileNameChanged, RideSaving, RideSaved, RideSaveAll,
RideExcludesChanged)
from ..utils import variablematcher
BDD_ENGLISH = 'Given|When|Then|And|But'
def obtain_bdd_prefixes(language):
from robotide.lib.compat.parsing.language import Language
lang = Language.from_name(language[0] if isinstance(language, list) else language)
bdd_prefixes = [f"{x}|" for x in lang.bdd_prefixes]
bdd_prefixes = "".join(bdd_prefixes).strip('|')
return bdd_prefixes
class Occurrence(object):
def __init__(self, item, value):
self._item = item
self._value = value
self._replaced = False
self.count = 1
def __eq__(self, other):
if not isinstance(other, Occurrence):
return False
return (self.parent is other.parent and
self._in_steps() and other._in_steps())
@property
def item(self):
return self._item
@property
def source(self):
return self.datafile.source
@property
def datafile(self):
return self._item.datafile
@property
def parent(self):
if self._in_for_loop():
return self._item.parent.parent
return self._item.parent
@property
def location(self):
return self._item.parent.name
@property
def usage(self):
if self._in_variable_table():
return "Variable Table"
elif self._in_settings():
return self._item.label
elif self._in_kw_name():
return 'Keyword Name'
return 'Steps' if self.count == 1 else 'Steps (%d usages)' % self.count
def _in_settings(self):
return isinstance(self._item, settingcontrollers._SettingController)
def _in_variable_table(self):
from . import tablecontrollers
return isinstance(self._item, tablecontrollers.VariableTableController)
def _in_kw_name(self):
from .macrocontrollers import KeywordNameController
return isinstance(self._item, KeywordNameController)
def _in_steps(self):
return not (self._in_settings() or self._in_kw_name())
def _in_for_loop(self):
from .macrocontrollers import ForLoopStepController
return isinstance(self._item.parent, ForLoopStepController)
def replace_keyword(self, new_name):
# print(f"DEBUG: ctrlcommands.py Occurrence replace_keyword BEFORE new_name={new_name} value={self._value}"
# f" self._replaced={self._replaced} item={self._item}")
self._item.replace_keyword(*self._get_replace_values(new_name))
self._replaced = not self._replaced
def _get_replace_values(self, new_name):
if self._replaced:
return self._value, new_name
return new_name, self._value
def notify_value_changed(self, old_name=None, new_name=None):
self._item.notify_value_changed(old_name=old_name, new_name=new_name)
class _Command(object):
modifying = True
def execute(self, context):
raise NotImplementedError(self.__class__)
def __str__(self):
return '%s(%s)' % (self.__class__.__name__, self._params_str())
def _params_str(self):
return ', '.join(self._format_param(p) for p in self._params())
@staticmethod
def _format_param(param):
if isinstance(param, str):
return '"%s"' % param
return str(param)
def _params(self):
return []
class CopyMacroAs(_Command):
def __init__(self, new_name):
self._new_name = new_name
def execute(self, context):
context.copy(self._new_name)
def _params(self):
return [self._new_name]
class ChangeTag(_Command):
def __init__(self, tag, value):
self._tag = tag
self._value = value.strip()
def _params(self):
return self._tag, self._value
def execute(self, context):
tags = [tag for tag in context if tag.controller == context]
context.set_value(self._create_value(tags))
context.notify_value_changed()
def _create_value(self, old_values):
if old_values == [] and self._tag.is_empty():
return self._value
return ' | '.join(value for value in
self._create_value_list(old_values)
if value != '')
def _create_value_list(self, old_values):
if self._tag.is_empty():
return [v.name for v in old_values] + [self._value]
else:
new_list = []
for v in old_values:
if v != self._tag:
new_list.append(v.name)
if self._value not in new_list:
new_list += [self._value]
return new_list
class DeleteTag(_Command):
def execute(self, tag):
tag.delete()
tag.controller.notify_value_changed()
class _ReversibleCommand(_Command):
def execute(self, context):
result = self._execute_without_redo_clear(context)
context.clear_redo()
return result
def _execute_without_redo_clear(self, context):
result = self._execute(context)
context.push_to_undo(self._get_undo_command())
return result
@property
def _get_undo_command(self):
raise NotImplementedError(self.__class__.__name__)
class Undo(_Command):
def execute(self, context):
if not context.is_undo_empty():
result = context.pop_from_undo()._execute_without_redo_clear(context)
redo_command = context.pop_from_undo()
context.push_to_redo(redo_command)
return result
class Redo(_Command):
def execute(self, context):
if not context.is_redo_empty():
return context.pop_from_redo()._execute_without_redo_clear(context)
class MoveTo(_Command):
def __init__(self, destination):
self._destination = destination
def _params(self):
return [self._destination]
def execute(self, context):
context.delete()
self._destination.add_test_or_keyword(context)
class CreateNewResource(_Command):
def __init__(self, path):
self._path = path
def execute(self, context):
res = context.new_resource(self._path)
RideSelectResource(item=res).publish()
return res
class SetDataFile(_Command):
def __init__(self, datafile):
self._datafile = datafile
def execute(self, context):
context.mark_dirty()
context.set_datafile(self._datafile)
class _StepsChangingCommand(_ReversibleCommand):
def _execute(self, context):
if self.change_steps(context):
context.notify_steps_changed()
return True
return False
def change_steps(self, context):
"""Return True if steps changed, False otherwise"""
raise NotImplementedError(self.__class__.__name__)
def _step(self, context):
try:
return context.steps[self._row]
except IndexError:
return NonExistingStep()
class NonExistingStep(object):
def __getattr__(self, name):
return lambda *args: ''
class NullObserver(object):
notify = finish = lambda x: None
class RenameKeywordOccurrences(_ReversibleCommand):
def __init__(self, original_name, new_name, observer, keyword_info=None, language='En'):
self._language = language[0] if isinstance(language, list) else language
if self._language and self._language.lower() not in ['en', 'english']:
bdd_prefix = f"{obtain_bdd_prefixes(self._language)}|{BDD_ENGLISH}"
else:
bdd_prefix = BDD_ENGLISH
self._gherkin_prefix = re.compile(f'^({bdd_prefix}) ', re.IGNORECASE)
self._original_name, self._new_name = self._check_gherkin(new_name, original_name)
self._observer = observer
self._keyword_info = keyword_info
self._occurrences = None
# print(f"DEBUG: ctrlcommands.py RenameKeywordOccurrences INIT\n"
# f"{original_name=}, {new_name=}, self._original_name={self._original_name} "
# f"self._new_name={self._new_name} self._keyword_info={self._keyword_info}"
# f" self._gherkin_prefix={self._gherkin_prefix} ")
def _check_gherkin(self, new_name, original_name):
was_gherkin, keyword_name = self._get_gherkin(original_name)
is_gherkin, new_keyword_name = self._get_gherkin(new_name)
if was_gherkin and not is_gherkin:
keyword_name = original_name
if not was_gherkin and is_gherkin:
# When we change non-gherkin to gherkin, the keyword changes too.
# The workaround is not to Rename keyword, but only edit field.
new_keyword_name = new_name
if was_gherkin and is_gherkin:
# Check if the first word has changed
if original_name.split(' ', 1)[0].lower() != new_name.split(
' ', 1)[0].lower():
new_keyword_name = new_name
keyword_name = original_name
return keyword_name, new_keyword_name
def _get_gherkin(self, original_name):
keyword_value = re.sub(self._gherkin_prefix, '', original_name)
value_is_gherkin = (keyword_value != original_name)
return value_is_gherkin, keyword_value
def _params(self):
return (self._original_name, self._new_name,
self._observer, self._keyword_info)
def _execute(self, context):
self._observer.notify()
self._occurrences = self._find_occurrences(context) if self._occurrences is None else self._occurrences
# print(f"DEBUG: ctlcommands.py RenameKeywordOccurrences _execute: found occurrences= {self._occurrences}\n"
# f"CONTEXT:{context}")
self._replace_keywords_in(self._occurrences)
context.update_namespace()
self._notify_values_changed(self._occurrences, old_name=self._original_name)
self._observer.finish()
def _find_occurrences(self, context):
occurrences = []
for occ in context.execute(FindOccurrences(
self._original_name, keyword_info=self._keyword_info)):
self._observer.notify()
occurrences.append(occ)
self._observer.notify()
return occurrences
def _replace_keywords_in(self, occurrences):
for oc in occurrences:
oc.replace_keyword(self._new_name)
self._observer.notify()
def _notify_values_changed(self, occurrences, old_name=None):
for oc in occurrences:
# try:
# print(f"DEBUG: ctlcommands.py RenameKeywordOccurrences _notify_values_changed: "
# f"oc= {oc.source} {oc.item} {oc.usage} {oc._value}")
# except AttributeError:
# print(f"DEBUG: ctlcommands.py RenameKeywordOccurrences _notify_values_changed: "
# f" in AttributeError oc= {oc}")
oc.notify_value_changed(old_name=old_name, new_name=self._new_name)
self._observer.notify()
def _get_undo_command(self):
self._observer = NullObserver()
return self
class RenameTest(_ReversibleCommand):
def __init__(self, new_name):
self._new_name = new_name.strip()
def _params(self):
return self._new_name
def _execute(self, context):
old_name = context.name
if old_name == self._new_name:
return
context.test_name.rename(self._new_name)
context.test_name._item.notify_name_changed(old_name=old_name, new_name=self._new_name)
def _get_undo_command(self):
return self
class RenameFile(_Command):
def __init__(self, new_basename):
self._new_basename = new_basename
self._validator = validators.BaseNameValidator(new_basename.strip())
def execute(self, context):
validation_result = self._validator.validate(context)
if validation_result:
old_filename = context.filename
context.set_basename(self._new_basename.strip())
RideFileNameChanged(datafile=context,
old_filename=old_filename).publish()
return validation_result
class Include(_Command):
def execute(self, excluded_controller):
directory_controller = excluded_controller.remove_from_excludes()
RideExcludesChanged(old_controller=excluded_controller,
new_controller=directory_controller).publish()
class Exclude(_Command):
def execute(self, directory_controller):
excluded_controller = directory_controller.exclude()
RideExcludesChanged(old_controller=directory_controller,
new_controller=excluded_controller).publish()
class RenameResourceFile(_Command):
def __init__(self, new_basename, get_should_modify_imports):
self._new_basename = new_basename.strip()
self._should_modify_imports = get_should_modify_imports
def execute(self, context):
validation_result = validators.BaseNameValidator(
self._new_basename).validate(context)
if validation_result:
old_filename = context.filename
modify_imports = self._should_modify_imports()
if modify_imports is None:
return
if modify_imports:
context.set_basename_and_modify_imports(self._new_basename)
else:
context.set_basename(self._new_basename)
RideFileNameChanged(datafile=context,
old_filename=old_filename).publish()
return validation_result
class SortTests(_ReversibleCommand):
index_difference = None
def _execute(self, context):
index_difference = context.sort_tests()
self._undo_command = RestoreTestOrder(index_difference)
def _get_undo_command(self):
return self._undo_command
class SortKeywords(_ReversibleCommand):
index_difference = None
def __init__(self, case_insensitive=False):
self._case_insensitive = case_insensitive
def _execute(self, context):
index_difference = context.sort_keywords(case_insensitive=self._case_insensitive)
self._undo_command = RestoreKeywordOrder(index_difference)
def _get_undo_command(self):
return self._undo_command
class SortVariables(_ReversibleCommand):
index_difference = None
def _execute(self, context):
index_difference = context.sort_variables()
self._undo_command = RestoreVariableOrder(index_difference)
def _get_undo_command(self):
return self._undo_command
class RestoreTestOrder(_ReversibleCommand):
def __init__(self, index_difference):
self._index_difference = index_difference
def _execute(self, context):
context.restore_test_order(self._index_difference)
def _get_undo_command(self):
return SortTests()
class RestoreKeywordOrder(_ReversibleCommand):
def __init__(self, index_difference):
self._index_difference = index_difference
def _execute(self, context):
context.restore_keyword_order(self._index_difference)
def _get_undo_command(self):
return SortKeywords()
class RestoreVariableOrder(_ReversibleCommand):
def __init__(self, index_difference):
self._index_difference = index_difference
def _execute(self, context):
context.restore_variable_order(self._index_difference)
def _get_undo_command(self):
return SortVariables()
class _ItemCommand(_Command):
def __init__(self, item):
self._item = item
class UpdateDocumentation(_ItemCommand):
def execute(self, context):
context.editable_value = self._item
class MoveUp(_ItemCommand):
def execute(self, context):
context.move_up(self._item)
class MoveDown(_ItemCommand):
def execute(self, context):
context.move_down(self._item)
class DeleteItem(_ItemCommand):
def execute(self, context):
context.delete(self._item)
class ClearSetting(_Command):
def execute(self, context):
context.clear()
class DeleteFile(_Command):
def execute(self, context):
context.remove_from_filesystem()
context.remove()
class OpenContainingFolder(_Command):
modifying = False
def __init__(self, tool: str = None, path: str = None):
self.tool = tool
self.path = path
def execute(self, context):
context.open_filemanager(path=self.path, tool=self.tool)
class RemoveReadOnly(_Command):
def execute(self, context):
context.remove_readonly()
class DeleteFolder(_Command):
def execute(self, context):
context.remove_folder_from_filesystem()
context.remove_from_model()
class SetValues(_Command):
def __init__(self, values, comment):
self._values = values
self._comment = comment
def execute(self, context):
context.set_value(*self._values)
context.set_comment(self._comment)
class AddLibrary(_Command):
def __init__(self, values, comment):
self._values = values
self._comment = comment
def execute(self, context):
lib = context.add_library(*self._values)
lib.set_comment(self._comment)
return lib
class AddResource(_Command):
def __init__(self, values, comment):
self._values = values
self._comment = comment
def execute(self, context):
res = context.add_resource(*self._values)
res.set_comment(self._comment)
return res
class AddVariablesFileImport(_Command):
def __init__(self, values, comment):
self._values = values
self._comment = comment
def execute(self, context):
var = context.add_variables(*self._values)
var.set_comment(self._comment)
return var
class DeleteResourceAndImports(DeleteFile):
def execute(self, context):
context.remove_static_imports_to_this()
DeleteFile.execute(self, context)
class DeleteFolderAndImports(DeleteFolder):
def execute(self, context):
context.remove_static_imports_to_this()
DeleteFolder.execute(self, context)
class UpdateVariable(_Command):
def __init__(self, new_name, new_value, new_comment):
self._new_name = new_name
self._new_value = new_value
self._new_comment = new_comment
def execute(self, context):
has_data = context.has_data()
context.set_value(self._new_name, self._new_value)
context.set_comment(self._new_comment)
if has_data:
context.notify_value_changed()
else:
context.notify_variable_added()
class UpdateVariableName(_Command):
def __init__(self, new_name):
self._new_name = new_name
def execute(self, context):
context.execute(UpdateVariable(self._new_name, context.value,
context.comment))
def normalize_kw_name(name):
name = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', name)
# print(f"DEBUG: ctlcommands.py normalize_kw_name First step keyword_name={name}")
name = re.sub('([a-z0-9])([A-Z])', r'\1 \2', name).lower().replace('_', ' ')
# print(f"DEBUG: ctlcommands.py normalize_kw_name RETURN keyword_name={name}")
return name
class FindOccurrences(_Command):
modifying = False
def __init__(self, keyword_name, keyword_info=None, prefix=None):
if keyword_name.strip() == '':
raise ValueError('Keyword name can not be "%s"' % keyword_name)
self.normalized_name = normalize_kw_name(keyword_name)
# print(f"DEBUG: ctlcommands.py FindOccurrences INIT keyword_name={keyword_name}")
self._keyword_name = keyword_name
self._keyword_info = keyword_info
self.normalized_name_res = None
if self._keyword_info:
self.normalized_name_res = (keyword_name if '.' in keyword_name
else (self._keyword_info.source.replace('.robot', '').replace('.resource', '')
+"."+keyword_name))
self._keyword_source = self._keyword_info.source
# if keyword_name == self.normalized_name_res:
# self.normalized_name_res = None
else:
self._keyword_source = None
self.prefix = prefix
if self.prefix and not self.normalized_name_res:
self.normalized_name_res = f"{self.prefix}.{self._keyword_name}"
# print(f"DEBUG: ctlcommands.py FindOccurrences INIT normalized_name_res={self.normalized_name_res}"
# f"\nSOURCE={self._keyword_source} PREFIX={self.prefix}")
self._keyword_regexp = self._create_regexp(keyword_name)
@staticmethod
def _create_regexp(keyword_name):
if variablematcher.contains_scalar_variable(keyword_name) and \
not variablematcher.is_variable(keyword_name):
kw = lambda: 0
kw.arguments = None
kw.name = keyword_name
return EmbeddedArgsHandler(kw).name_regexp
else: # Certain kws are not found when with Gherkin
name_regexp = fr'^{re.escape(keyword_name)}$' # DEBUG removed (.*?) to ignore prefixed by resources
name = re.compile(name_regexp, re.IGNORECASE)
return name
def execute(self, context):
# print(f"DEBUG: ctrlcommands FindOccurrences EXECUTE context={context}")
self._keyword_source = \
self._keyword_info and self._keyword_info.source or \
self._find_keyword_source(context.datafile_controller)
""" DEBUG: this is always defined at init
if not self.normalized_name_res:
self.normalized_name_res = (self._keyword_name if '.' in self._keyword_name
else (self._keyword_source.replace('.robot', '').replace('.resource', '')
+"."+self._keyword_name))
"""
if self._keyword_name == self.normalized_name_res and '.' in self._keyword_name:
self._keyword_name = self._keyword_name.split('.')[-1]
return self._find_occurrences_in(self._items_from(context))
def _items_from(self, context):
for df in context.datafiles:
# print(f"DEBUG: ctrlcommands FindOccurrences _items_from FILENAME: df={df.source}")
self._yield_for_other_threads()
if self._items_from_datafile_should_be_checked(df):
for item in self._items_from_datafile(df):
yield item
def _items_from_datafile_should_be_checked(self, datafile):
if datafile.filename and \
os.path.basename(datafile.filename) == self._keyword_source:
return True
return self._find_keyword_source(datafile) == self._keyword_source
def _items_from_datafile(self, df):
for setting in df.settings:
yield setting
for test_items in (self._items_from_test(test) for test in df.tests):
for item in test_items:
yield item
for kw_items in (self._items_from_keyword(kw) for kw in df.keywords):
for item in kw_items:
# print(f"DEBUG: ctrlcommands FindOccurrences _items_from_datafile kw_items yield {item}"
# f"\nself._keyword_source = {self._keyword_source}")
yield item
def _items_from_keyword(self, kw):
return chain([kw.keyword_name] if kw.source == self._keyword_source
else [], kw.steps, [kw.setup] if kw.setup else [], [kw.teardown] if kw.teardown else [])
@staticmethod
def _items_from_test(test):
return chain(test.settings, test.steps)
def _find_keyword_source(self, datafile_controller):
item_info = datafile_controller.keyword_info(None, self._keyword_name)
# print(f"DEBUG: ctrlcommands _find_keyword_source datafile_controller={datafile_controller}"
# f"item_info={item_info}")
return item_info.source if item_info else None
def _find_occurrences_in(self, items):
# print(f"DEBUG: ctrlcommands _find_occurrences_in ENTER normalized_name={self.normalized_name} WITH resource"
# f" {self.normalized_name_res} PREFIX={self.prefix}\n"
# f"LIST OF ITEMS={items}")
""" DEBUG: not conditioning
if not self._keyword_source.startswith(self.prefix):
print(f"DEBUG: ctrlcommands FindOccurrences _find_occurrences_in SKIP SEARCH"
f" self._keyword_source={self._keyword_source}\n"
f"prefix={self.prefix}")
yield None
else:
"""
for item in items:
# print(f"DEBUG: ctrlcommands _find_occurrences_in searching item={item}")
if isinstance(self.normalized_name_res, str) and (self.prefix and
self.normalized_name_res.startswith(self.prefix) and
item.contains_keyword(self.normalized_name_res)):
# This block is active when finding from a cell with resource prefix
# print(f"DEBUG: ctrlcommands _find_occurrences_in searching item={item} ADD TO OCCURRENCES: FOUND "
# f"{self.normalized_name_res} "
# f"kwsource={self._keyword_source}")
yield Occurrence(item, self.normalized_name_res)
elif self._contains_exact_item(item):
# print(f"DEBUG: ctrlcommands _find_occurrences_in searching item={item} NAME={self._keyword_name}"
# f" source={self._keyword_source}\n"
# f"self.normalized_name_res={self.normalized_name_res} parent={item.parent}\n"
# f" PREFIX={self.prefix}")
# print(f"DEBUG: ctrlcommands _find_occurrences_in searching item type = {type(item)}"
# f" kwsource={self._keyword_source}")
# if self._keyword_source.startswith(self.prefix):
# print(f"DEBUG: ctrlcommands _find_occurrences_in searching ADD TO OCCURRENCES: {self._keyword_name}")
yield Occurrence(item, self._keyword_name)
def _contains_exact_item(self, item):
from .tablecontrollers import VariableTableController
match_name = self._contains_item(item)
# print(f"DEBUG: ctrlcommands _find_occurrences_in _contains_exact_item Match Name is TYPE {type(match_name)}")
if match_name and isinstance(match_name, re.Match) and '.' in match_name.string and self.prefix:
# print(f"DEBUG: ctrlcommands _find_occurrences_in _contains_exact_item PREFIXED Name={match_name}"
# f"\n groups={match_name.groups()} string={match_name.string}"
# f" RETURNS {match_name.string.startswith(self.prefix)}")
return match_name.string.startswith(self.prefix) # Avoid false positive for res prefixed
elif match_name or (not isinstance(item, VariableTableController) and
(item.contains_keyword(self.normalized_name) or
item.contains_keyword(self.normalized_name.replace(' ', '_')) or
item.contains_keyword(self._keyword_name) )):
return True
def _contains_item(self, item):
self._yield_for_other_threads()
return item.contains_keyword(self._keyword_regexp or self.normalized_name_res)
# DEBUG: self._keyword_name
@staticmethod
def _yield_for_other_threads():
# GIL !?#!!!
# THIS IS TO ENSURE THAT OTHER THREADS WILL GET SOME SPACE ALSO
time.sleep(0)
class FindVariableOccurrences(FindOccurrences):
def _contains_item(self, item):
self._yield_for_other_threads()
return item.contains_variable(self._keyword_name)
def _items_from_datafile(self, df):
for itm in FindOccurrences._items_from_datafile(self, df):
yield itm
yield df.variables
def _items_from_controller(self, ctrl):
from .macrocontrollers import TestCaseController
if isinstance(ctrl, TestCaseController):
return self._items_from_test(ctrl)
else:
return self._items_from_keyword(ctrl)
def _items_from_keyword(self, kw):
return chain([kw.keyword_name], kw.steps, kw.settings)
def _items_from(self, context):
self._context = context
if self._is_local_variable(self._keyword_name, context):
for item in self._items_from_controller(context):
yield item
else:
for df in context.datafiles:
self._yield_for_other_threads()
if self._items_from_datafile_should_be_checked(df):
for item in self._items_from_datafile(df):
yield item
def _items_from_datafile_should_be_checked(self, datafile):
if self._is_file_variable(self._keyword_name, self._context):
return datafile in [self._context.datafile_controller] + \
self._get_all_where_used(self._context)
elif self._is_imported_variable(self._keyword_name, self._context):
return datafile in [self._get_source_of_imported_var(
self._keyword_name, self._context)] + \
self._get_all_where_used(self._get_source_of_imported_var(
self._keyword_name, self._context))
else:
return True
@staticmethod
def _is_local_variable(name, context):
if isinstance(context, settingcontrollers.VariableController):
return False
return name in context.get_local_variables() or \
any(step.contains_variable_assignment(name)
for step in context.steps)
@staticmethod
def _is_file_variable(name, context):
return context.datafile_controller.variables.contains_variable(name)
def _is_imported_variable(self, name, context):
return self._get_source_of_imported_var(name, context) not in \
[None, context.datafile_controller]
@staticmethod
def _is_builtin_variable(name):
return name in list(namespace._VariableStash.global_variables.keys())
def _get_source_of_imported_var(self, name, context):
for df in self._get_all_imported(context):
if df.variables.contains_variable(name):
return df
return None
@staticmethod
def _get_all_imported(context):
files = [context.datafile_controller]
for f in files:
files += [imp.get_imported_controller()
for imp in f.imports if imp.is_resource and
imp.get_imported_controller() not in files]
return files
@staticmethod
def _get_all_where_used(context):
from .filecontrollers import ResourceFileController
files = [context.datafile_controller]
for f in files:
if isinstance(f, ResourceFileController):
files += [imp.datafile_controller
for imp in f.get_where_used()]
return files
def add_keyword_from_cells(cells):
if not cells:
raise ValueError('Keyword can not be empty')
while cells[0] == '':
cells.pop(0)
name = cells[0]
args = cells[1:]
argstr = ' | '.join(('${arg%s}' % (i + 1) for i in range(len(args))))
return AddKeyword(name, argstr)
class AddKeyword(_ReversibleCommand):
def __init__(self, new_kw_name, args=None):
self._kw_name = new_kw_name
self._args = args or []
def _execute(self, context):
kw = context.create_keyword(self._kw_name, self._args)
self._undo_command = RemoveMacro(kw)
return kw
def _get_undo_command(self):
return self._undo_command
class AddTestCase(_Command):
def __init__(self, new_test_name):
self._test_name = new_test_name
def execute(self, context):
return context.create_test(self._test_name)
class _AddDataFile(_Command):
def __init__(self, path):
self._path = path
def execute(self, context):
ctrl = self._add_data_file(context)
context.notify_suite_added(ctrl)
return ctrl
def _add_data_file(self, context):
raise NotImplementedError(self.__class__.__name__)
class AddTestCaseFile(_AddDataFile):
def _add_data_file(self, context):
return context.new_test_case_file(self._path)
class AddTestDataDirectory(_AddDataFile):
def _add_data_file(self, context):
return context.new_test_data_directory(self._path)
class CreateNewFileProject(_Command):
def __init__(self, path, tasks, lang):
self._path = path
self._tasks = tasks
self._lang = lang
def execute(self, context):