forked from demisto/demisto-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathold_validate_manager.py
2932 lines (2580 loc) · 112 KB
/
old_validate_manager.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 os
from concurrent.futures._base import Future, as_completed
from configparser import ConfigParser
from pathlib import Path
from typing import Callable, List, Optional, Set, Tuple
import pebble
from git import GitCommandError, InvalidGitRepositoryError
from packaging import version
from demisto_sdk.commands.common import tools
from demisto_sdk.commands.common.configuration import Configuration
from demisto_sdk.commands.common.constants import (
API_MODULES_PACK,
AUTHOR_IMAGE_FILE_NAME,
CONTENT_ENTITIES_DIRS,
DEFAULT_CONTENT_ITEM_TO_VERSION,
DEMISTO_GIT_PRIMARY_BRANCH,
DEMISTO_GIT_UPSTREAM,
GENERIC_FIELDS_DIR,
GENERIC_TYPES_DIR,
IGNORED_PACK_NAMES,
LISTS_DIR,
OLDEST_SUPPORTED_VERSION,
PACK_METADATA_REQUIRE_RN_FIELDS,
PACKS_DIR,
PACKS_PACK_META_FILE_NAME,
SKIP_RELEASE_NOTES_FOR_TYPES,
VALIDATION_USING_GIT_IGNORABLE_DATA,
XSIAM_DASHBOARDS_DIR,
FileType,
FileType_ALLOWED_TO_DELETE,
PathLevel,
)
from demisto_sdk.commands.common.content import Content
from demisto_sdk.commands.common.content_constant_paths import (
CONTENT_PATH,
DEFAULT_ID_SET_PATH,
)
from demisto_sdk.commands.common.cpu_count import cpu_count
from demisto_sdk.commands.common.errors import (
FOUND_FILES_AND_ERRORS,
FOUND_FILES_AND_IGNORED_ERRORS,
PRESET_ERROR_TO_CHECK,
PRESET_ERROR_TO_IGNORE,
Errors,
get_all_error_codes,
)
from demisto_sdk.commands.common.git_util import GitUtil
from demisto_sdk.commands.common.handlers import DEFAULT_JSON_HANDLER as json
from demisto_sdk.commands.common.hook_validations.author_image import (
AuthorImageValidator,
)
from demisto_sdk.commands.common.hook_validations.base_validator import (
BaseValidator,
error_codes,
)
from demisto_sdk.commands.common.hook_validations.classifier import ClassifierValidator
from demisto_sdk.commands.common.hook_validations.conf_json import ConfJsonValidator
from demisto_sdk.commands.common.hook_validations.correlation_rule import (
CorrelationRuleValidator,
)
from demisto_sdk.commands.common.hook_validations.dashboard import DashboardValidator
from demisto_sdk.commands.common.hook_validations.deprecation import (
DeprecationValidator,
)
from demisto_sdk.commands.common.hook_validations.description import (
DescriptionValidator,
)
from demisto_sdk.commands.common.hook_validations.generic_definition import (
GenericDefinitionValidator,
)
from demisto_sdk.commands.common.hook_validations.generic_field import (
GenericFieldValidator,
)
from demisto_sdk.commands.common.hook_validations.generic_module import (
GenericModuleValidator,
)
from demisto_sdk.commands.common.hook_validations.generic_type import (
GenericTypeValidator,
)
from demisto_sdk.commands.common.hook_validations.graph_validator import GraphValidator
from demisto_sdk.commands.common.hook_validations.id import IDSetValidations
from demisto_sdk.commands.common.hook_validations.image import ImageValidator
from demisto_sdk.commands.common.hook_validations.incident_field import (
IncidentFieldValidator,
)
from demisto_sdk.commands.common.hook_validations.incident_type import (
IncidentTypeValidator,
)
from demisto_sdk.commands.common.hook_validations.indicator_field import (
IndicatorFieldValidator,
)
from demisto_sdk.commands.common.hook_validations.integration import (
IntegrationValidator,
)
from demisto_sdk.commands.common.hook_validations.job import JobValidator
from demisto_sdk.commands.common.hook_validations.layout import (
LayoutsContainerValidator,
LayoutValidator,
)
from demisto_sdk.commands.common.hook_validations.layout_rule import LayoutRuleValidator
from demisto_sdk.commands.common.hook_validations.lists import ListsValidator
from demisto_sdk.commands.common.hook_validations.mapper import MapperValidator
from demisto_sdk.commands.common.hook_validations.modeling_rule import (
ModelingRuleValidator,
)
from demisto_sdk.commands.common.hook_validations.pack_unique_files import (
PackUniqueFilesValidator,
)
from demisto_sdk.commands.common.hook_validations.parsing_rule import (
ParsingRuleValidator,
)
from demisto_sdk.commands.common.hook_validations.playbook import PlaybookValidator
from demisto_sdk.commands.common.hook_validations.pre_process_rule import (
PreProcessRuleValidator,
)
from demisto_sdk.commands.common.hook_validations.python_file import PythonFileValidator
from demisto_sdk.commands.common.hook_validations.readme import ReadMeValidator
from demisto_sdk.commands.common.hook_validations.release_notes import (
ReleaseNotesValidator,
)
from demisto_sdk.commands.common.hook_validations.release_notes_config import (
ReleaseNotesConfigValidator,
)
from demisto_sdk.commands.common.hook_validations.report import ReportValidator
from demisto_sdk.commands.common.hook_validations.reputation import ReputationValidator
from demisto_sdk.commands.common.hook_validations.script import ScriptValidator
from demisto_sdk.commands.common.hook_validations.structure import StructureValidator
from demisto_sdk.commands.common.hook_validations.test_playbook import (
TestPlaybookValidator,
)
from demisto_sdk.commands.common.hook_validations.triggers import TriggersValidator
from demisto_sdk.commands.common.hook_validations.widget import WidgetValidator
from demisto_sdk.commands.common.hook_validations.wizard import WizardValidator
from demisto_sdk.commands.common.hook_validations.xdrc_templates import (
XDRCTemplatesValidator,
)
from demisto_sdk.commands.common.hook_validations.xsiam_dashboard import (
XSIAMDashboardValidator,
)
from demisto_sdk.commands.common.hook_validations.xsiam_report import (
XSIAMReportValidator,
)
from demisto_sdk.commands.common.hook_validations.xsoar_config_json import (
XSOARConfigJsonValidator,
)
from demisto_sdk.commands.common.logger import LOG_FILE_PATH, logger
from demisto_sdk.commands.common.tools import (
_get_file_id,
detect_file_level,
find_type,
get_api_module_dependencies_from_graph,
get_api_module_ids,
get_file,
get_file_by_status,
get_pack_ignore_content,
get_pack_name,
get_pack_names_from_files,
get_relative_path_from_packs_dir,
get_remote_file,
get_yaml,
is_file_in_pack,
open_id_set_file,
run_command_os,
specify_files_from_directory,
)
from demisto_sdk.commands.create_id_set.create_id_set import IDSetCreator
SKIPPED_FILES = [
"CommonServerUserPython.py",
"demistomock.py",
"DemistoClassApiModule.py",
]
class OldValidateManager:
def __init__(
self,
is_backward_check=True,
prev_ver=None,
use_git=False,
only_committed_files=False,
print_ignored_files=False,
skip_conf_json=True,
validate_graph=False,
validate_id_set=False,
file_path=None,
validate_all=False,
is_external_repo=False,
skip_pack_rn_validation=False,
print_ignored_errors=False,
silence_init_prints=False,
no_docker_checks=False,
skip_dependencies=False,
id_set_path=None,
staged=False,
create_id_set=False,
json_file_path=None,
skip_schema_check=False,
debug_git=False,
include_untracked=False,
pykwalify_logs=False,
check_is_unskipped=True,
quiet_bc=False,
multiprocessing=True,
specific_validations=None,
):
# General configuration
self.skip_docker_checks = False
self.no_configuration_prints = silence_init_prints
self.skip_conf_json = skip_conf_json
self.is_backward_check = is_backward_check
self.is_circle = only_committed_files
self.validate_all = validate_all
self.use_git = use_git
self.skip_pack_rn_validation = skip_pack_rn_validation
self.print_ignored_files = print_ignored_files
self.print_ignored_errors = print_ignored_errors
self.skip_dependencies = skip_dependencies or not use_git
self.skip_id_set_creation = not create_id_set or skip_dependencies
self.validate_graph = validate_graph
self.compare_type = "..."
self.staged = staged
self.skip_schema_check = skip_schema_check
self.debug_git = debug_git
self.include_untracked = include_untracked
self.pykwalify_logs = pykwalify_logs
self.quiet_bc = quiet_bc
self.check_is_unskipped = check_is_unskipped
self.conf_json_data = {}
self.run_with_multiprocessing = multiprocessing
self.packs_with_mp_change = set()
self.is_possible_validate_readme = (
self.is_node_exist() or ReadMeValidator.is_docker_available()
)
if json_file_path:
self.json_file_path = (
os.path.join(json_file_path, "validate_outputs.json")
if os.path.isdir(json_file_path)
else json_file_path
)
else:
self.json_file_path = ""
self.specific_validations = specific_validations
if specific_validations:
self.specific_validations = specific_validations.split(",")
# Class constants
self.handle_error = BaseValidator(json_file_path=json_file_path).handle_error
self.should_run_validation = BaseValidator(
specific_validations=specific_validations
).should_run_validation
self.file_path = file_path
self.id_set_path = id_set_path or DEFAULT_ID_SET_PATH
# create the id_set only once per run.
self.id_set_file = self.get_id_set_file(
self.skip_id_set_creation, self.id_set_path
)
self.id_set_validations = (
IDSetValidations(
is_circle=self.is_circle,
configuration=Configuration(),
ignored_errors=None,
id_set_file=self.id_set_file,
json_file_path=json_file_path,
specific_validations=self.specific_validations,
)
if validate_id_set
else None
)
self.deprecation_validator = DeprecationValidator(id_set_file=self.id_set_file)
try:
self.git_util = Content.git_util()
self.branch_name = self.git_util.get_current_git_branch_or_hash()
except (InvalidGitRepositoryError, TypeError):
# if we are using git - fail the validation by raising the exception.
if self.use_git:
raise
# if we are not using git - simply move on.
else:
logger.info("Unable to connect to git")
self.git_util = None # type: ignore[assignment]
self.branch_name = ""
if prev_ver and not prev_ver.startswith(DEMISTO_GIT_UPSTREAM):
self.prev_ver = self.setup_prev_ver(f"{DEMISTO_GIT_UPSTREAM}/" + prev_ver)
else:
self.prev_ver = self.setup_prev_ver(prev_ver)
self.check_only_schema = False
self.always_valid = False
self.ignored_files = set()
self.new_packs = set()
self.skipped_file_types = (
FileType.CHANGELOG,
FileType.DOC_IMAGE,
FileType.MODELING_RULE_SCHEMA,
FileType.XSIAM_REPORT_IMAGE,
FileType.PIPFILE,
FileType.PIPFILE_LOCK,
FileType.TXT,
FileType.JAVASCRIPT_FILE,
FileType.POWERSHELL_FILE,
FileType.PYLINTRC,
FileType.SECRET_IGNORE,
FileType.LICENSE,
FileType.UNIFIED_YML,
FileType.PACK_IGNORE,
FileType.INI,
FileType.PEM,
FileType.METADATA,
FileType.VULTURE_WHITELIST,
FileType.CASE_LAYOUT_RULE,
FileType.CASE_LAYOUT,
FileType.CASE_FIELD,
)
self.is_external_repo = is_external_repo
if is_external_repo:
if not self.no_configuration_prints:
logger.info("Running in a private repository")
self.skip_conf_json = True
self.print_percent = False
self.completion_percentage = 0
if validate_all:
# No need to check docker images on build branch hence we do not check on -a mode
# also do not skip id set creation unless the flag is up
self.skip_docker_checks = True
self.skip_pack_rn_validation = True
self.print_percent = (
not self.run_with_multiprocessing
) # the Multiprocessing will mismatch the percent
self.check_is_unskipped = False
if no_docker_checks:
self.skip_docker_checks = True
if self.skip_conf_json:
self.check_is_unskipped = False
if not self.skip_conf_json:
self.conf_json_validator = ConfJsonValidator(
specific_validations=self.specific_validations
)
self.conf_json_data = self.conf_json_validator.conf_data
def is_node_exist(self) -> bool:
"""Check if node interpreter exists.
Returns:
bool: True if node exist, else False
"""
# Check node exist
content_path = CONTENT_PATH
stdout, stderr, exit_code = run_command_os("node -v", cwd=content_path) # type: ignore
if exit_code:
return False
return True
def print_final_report(self, valid):
if self.print_ignored_errors:
self.print_ignored_files_report()
self.print_ignored_errors_report()
if valid:
logger.info("\n[green]The files are valid[/green]")
return 0
else:
all_failing_files = "\n".join(set(FOUND_FILES_AND_ERRORS))
logger.info(
f"\n[red]=========== Found errors in the following files ===========\n\n{all_failing_files}[/red]\n"
)
if self.always_valid:
logger.info(
"[yellow]Found the errors above, but not failing build[/yellow]"
)
return 0
logger.info(
"[red]The files were found as invalid, the exact error message can be located above[/red]"
)
return 1
def run_validation(self):
"""Initiates validation in accordance with mode (i,g,a)"""
if self.validate_all:
is_valid = self.run_validation_on_all_packs()
elif self.use_git:
is_valid = self.run_validation_using_git()
elif self.file_path:
is_valid = self.run_validation_on_specific_files()
else:
# default validate to -g --post-commit
self.use_git = True
self.is_circle = True
is_valid = self.run_validation_using_git()
return self.print_final_report(is_valid)
def run_validation_on_specific_files(self):
"""Run validations only on specific files"""
files_validation_result = set()
if self.use_git:
self.setup_git_params()
files_to_validate = self.file_path.split(",")
for path in files_to_validate:
error_ignore_list = self.get_error_ignore_list(get_pack_name(path))
file_level = detect_file_level(path)
if file_level == PathLevel.FILE:
logger.info(
f"\n[cyan]================= Validating file {path} =================[/cyan]"
)
files_validation_result.add(
self.run_validations_on_file(path, error_ignore_list)
)
elif file_level == PathLevel.CONTENT_ENTITY_DIR:
logger.info(
f"\n[cyan]================= Validating content directory {path} =================[/cyan]"
)
files_validation_result.add(
self.run_validation_on_content_entities(path, error_ignore_list)
)
elif file_level == PathLevel.CONTENT_GENERIC_ENTITY_DIR:
logger.info(
f"\n[cyan]================= Validating content directory {path} =================[/cyan]"
)
files_validation_result.add(
self.run_validation_on_generic_entities(path, error_ignore_list)
)
elif file_level == PathLevel.PACK:
logger.info(
f"\n[cyan]================= Validating pack {path} =================[/cyan]"
)
files_validation_result.add(self.run_validations_on_pack(path)[0])
else:
logger.info(
f"\n[cyan]================= Validating package {path} =================[/cyan]"
)
files_validation_result.add(
self.run_validation_on_package(path, error_ignore_list)
)
if self.validate_graph:
logger.info(
"\n[cyan]================= Validating graph =================[/cyan]"
)
with GraphValidator(
specific_validations=self.specific_validations,
input_files=files_to_validate,
include_optional_deps=True,
) as graph_validator:
files_validation_result.add(graph_validator.is_valid_content_graph())
return all(files_validation_result)
def wait_futures_complete(self, futures_list: List[Future], done_fn: Callable):
"""Wait for all futures to complete, Raise exception if occurred.
Args:
futures_list: futures to wait for.
done_fn: Function to run on result.
Raises:
Exception: Raise caught exception for further cleanups.
"""
for future in as_completed(futures_list):
try:
result = future.result()
done_fn(result[0], result[1])
except Exception as e:
logger.info(
f"[red]An error occurred while tried to collect result, Error: {e}[/red]"
)
raise
def run_validation_on_all_packs(self):
"""Runs validations on all files in all packs in repo (-a option)
Returns:
bool. true if all files are valid, false otherwise.
"""
logger.info(
"\n[cyan]================= Validating all files =================[/cyan]"
)
all_packs_valid = set()
if not self.skip_conf_json:
all_packs_valid.add(self.conf_json_validator.is_valid_conf_json())
count = 1
# Filter non-pack files that might exist locally (e.g, .DS_STORE on MacOS)
all_packs = list(
filter(
os.path.isdir,
[os.path.join(PACKS_DIR, p) for p in os.listdir(PACKS_DIR)],
)
)
num_of_packs = len(all_packs)
all_packs.sort(key=str.lower)
ReadMeValidator.add_node_env_vars()
if self.is_possible_validate_readme:
with ReadMeValidator.start_mdx_server(handle_error=self.handle_error):
return self.validate_packs(
all_packs, all_packs_valid, count, num_of_packs
)
else:
return self.validate_packs(all_packs, all_packs_valid, count, num_of_packs)
def validate_packs(
self, all_packs: list, all_packs_valid: set, count: int, num_of_packs: int
) -> bool:
if self.run_with_multiprocessing:
with pebble.ProcessPool(max_workers=cpu_count()) as executor:
futures = []
for pack_path in all_packs:
futures.append(
executor.schedule(
self.run_validations_on_pack, args=(pack_path,)
)
)
self.wait_futures_complete(
futures_list=futures,
done_fn=lambda x, y: (
all_packs_valid.add(x), # type: ignore
FOUND_FILES_AND_ERRORS.extend(y), # type: ignore[func-returns-value]
),
)
else:
for pack_path in all_packs:
self.completion_percentage = format((count / num_of_packs) * 100, ".2f") # type: ignore
all_packs_valid.add(self.run_validations_on_pack(pack_path)[0])
count += 1
if self.validate_graph:
logger.info(
"\n[cyan]================= Validating graph =================[/cyan]"
)
specific_validations_list = (
self.specific_validations if self.specific_validations else []
)
with GraphValidator(
specific_validations=self.specific_validations,
include_optional_deps=(
True if "GR103" in specific_validations_list else False
),
) as graph_validator:
all_packs_valid.add(graph_validator.is_valid_content_graph())
return all(all_packs_valid)
def run_validations_on_pack(self, pack_path, skip_files: Optional[Set[str]] = None):
"""Runs validation on all files in given pack. (i,g,a)
Args:
pack_path: the path to the pack.
skip_files: a list of files to skip.
Returns:
bool. true if all files in pack are valid, false otherwise.
"""
if not skip_files:
skip_files = set()
pack_entities_validation_results = set()
pack_error_ignore_list = self.get_error_ignore_list(Path(pack_path).name)
pack_entities_validation_results.add(
self.validate_pack_unique_files(pack_path, pack_error_ignore_list)
)
for content_dir in os.listdir(pack_path):
content_entity_path = os.path.join(pack_path, content_dir)
if content_entity_path not in skip_files:
if content_dir in CONTENT_ENTITIES_DIRS:
pack_entities_validation_results.add(
self.run_validation_on_content_entities(
content_entity_path, pack_error_ignore_list
)
)
else:
self.ignored_files.add(content_entity_path)
return all(pack_entities_validation_results), FOUND_FILES_AND_ERRORS
def run_validation_on_content_entities(
self, content_entity_dir_path, pack_error_ignore_list
):
"""Gets non-pack folder and runs validation within it (Scripts, Integrations...)
Returns:
bool. true if all files in directory are valid, false otherwise.
"""
content_entities_validation_results = set()
if content_entity_dir_path.endswith(
GENERIC_FIELDS_DIR
) or content_entity_dir_path.endswith(GENERIC_TYPES_DIR):
for dir_name in os.listdir(content_entity_dir_path):
dir_path = os.path.join(content_entity_dir_path, dir_name)
if not Path(dir_path).is_file():
# should be only directories (not files) in generic types/fields directory
content_entities_validation_results.add(
self.run_validation_on_generic_entities(
dir_path, pack_error_ignore_list
)
)
else:
self.ignored_files.add(dir_path)
else:
for file_name in os.listdir(content_entity_dir_path):
file_path = os.path.join(content_entity_dir_path, file_name)
if Path(file_path).is_file():
if (
file_path.endswith(".json")
or file_path.endswith(".yml")
or file_path.endswith(".md")
or (
content_entity_dir_path.endswith(XSIAM_DASHBOARDS_DIR)
and file_path.endswith(".png")
)
):
content_entities_validation_results.add(
self.run_validations_on_file(
file_path, pack_error_ignore_list
)
)
else:
self.ignored_files.add(file_path)
else:
content_entities_validation_results.add(
self.run_validation_on_package(
file_path, pack_error_ignore_list
)
)
return all(content_entities_validation_results)
@staticmethod
def should_validate_xsiam_content(package_path):
parent_name = Path(package_path).stem
dir_name = Path(package_path).parent.stem
return (
parent_name in {"XSIAMDashboards", "XSIAMReports"}
or dir_name == "XDRCTemplates"
)
def run_validation_on_package(self, package_path, pack_error_ignore_list):
package_entities_validation_results = set()
for file_name in os.listdir(package_path):
file_path = os.path.join(package_path, file_name)
package_entities_validation_results.add(
self.run_validations_on_file(file_path, pack_error_ignore_list)
)
return all(package_entities_validation_results)
def run_validation_on_generic_entities(self, dir_path, pack_error_ignore_list):
"""
Gets a generic content entity directory (i.e a sub-directory of GenericTypes or GenericFields)
and runs validation within it.
Returns:
bool. true if all files in directory are valid, false otherwise.
"""
package_entities_validation_results = set()
for file_name in os.listdir(dir_path):
file_path = os.path.join(dir_path, file_name)
if file_path.endswith(".json"): # generic types/fields are jsons
package_entities_validation_results.add(
self.run_validations_on_file(file_path, pack_error_ignore_list)
)
else:
self.ignored_files.add(file_path)
return all(package_entities_validation_results)
@error_codes("BA114")
def is_valid_pack_name(self, file_path, old_file_path, ignored_errors):
"""
Valid pack name is currently considered to be a new pack name or an existing pack.
If pack name is changed, will return `False`.
"""
if not old_file_path:
return True
original_pack_name = get_pack_name(old_file_path)
new_pack_name = get_pack_name(file_path)
if original_pack_name != new_pack_name:
error_message, error_code = Errors.changed_pack_name(original_pack_name)
if self.handle_error(
error_message=error_message,
error_code=error_code,
file_path=file_path,
drop_line=True,
ignored_errors=ignored_errors,
):
return False
return True
@error_codes("BA102,IM110")
def is_valid_file_type(
self, file_type: FileType, file_path: str, ignored_errors: dict
):
"""
If a file_type is unsupported, will return `False`.
"""
if not file_type:
error_message, error_code = Errors.file_type_not_supported(
file_type, file_path
)
if str(file_path).endswith(".png"):
error_message, error_code = Errors.invalid_image_name_or_location()
if self.handle_error(
error_message=error_message,
error_code=error_code,
file_path=file_path,
drop_line=True,
ignored_errors=ignored_errors,
):
return False
return True
def is_skipped_file(self, file_path: str) -> bool:
"""check whether the file in the given file_path is in the 'SKIPPED_FILES' list.
Args:
file_path: the file on which to run.
Returns:
bool. true if file is in SKIPPED_FILES list, false otherwise.
"""
path = Path(file_path)
if LOG_FILE_PATH and LOG_FILE_PATH == path:
return True
return (
path.name in SKIPPED_FILES
or (
path.name == "CommonServerPython.py"
and path.parent.parent.name != "Base"
)
or (LISTS_DIR in path.parts[-3:] and path.name.endswith("_data.json"))
)
# flake8: noqa: C901
def run_validations_on_file(
self,
file_path,
pack_error_ignore_list,
is_modified=False,
old_file_path=None,
modified_files=None,
added_files=None,
):
"""Choose a validator to run for a single file. (i)
Args:
modified_files: A set of modified files - used for RN validation
added_files: A set of added files - used for RN validation
old_file_path: The old file path for renamed files
pack_error_ignore_list: A dictionary of all pack ignored errors
file_path: the file on which to run.
is_modified: whether the file is modified or added.
Returns:
bool. true if file is valid, false otherwise.
"""
if not self.is_valid_pack_name(
file_path, old_file_path, pack_error_ignore_list
):
return False
file_type = find_type(file_path)
is_added_file = file_path in added_files if added_files else False
if file_type == FileType.MODELING_RULE_TEST_DATA:
file_path = file_path.replace("_testdata.json", ".yml")
if file_path.endswith(".xif"):
file_path = file_path.replace(".xif", ".yml")
if (
file_type in self.skipped_file_types
or self.is_skipped_file(file_path)
or (self.git_util and self.git_util._is_file_git_ignored(file_path))
or detect_file_level(file_path)
in (PathLevel.PACKAGE, PathLevel.CONTENT_ENTITY_DIR)
):
self.ignored_files.add(file_path)
return True
elif not self.is_valid_file_type(file_type, file_path, pack_error_ignore_list):
return False
if file_type == FileType.XSOAR_CONFIG:
xsoar_config_validator = XSOARConfigJsonValidator(
file_path,
specific_validations=self.specific_validations,
ignored_errors=pack_error_ignore_list,
)
return xsoar_config_validator.is_valid_xsoar_config_file()
if not self.check_only_schema:
# if file_type = None, it means BA102 was ignored in an external repo.
validation_print = f"\nValidating {file_path} as {file_type.value if file_type else 'unknown-file'}"
if self.print_percent:
if FOUND_FILES_AND_ERRORS:
validation_print += f" [red][{self.completion_percentage}%][/red]"
else:
validation_print += (
f" [green][{self.completion_percentage}%][/green]"
)
logger.info(validation_print)
structure_validator = StructureValidator(
file_path,
predefined_scheme=file_type,
ignored_errors=pack_error_ignore_list,
tag=self.prev_ver,
old_file_path=old_file_path,
branch_name=self.branch_name,
is_new_file=not is_modified,
json_file_path=self.json_file_path,
skip_schema_check=self.skip_schema_check,
pykwalify_logs=self.pykwalify_logs,
quiet_bc=self.quiet_bc,
specific_validations=self.specific_validations,
)
# schema validation
if file_type not in {
FileType.TEST_PLAYBOOK,
FileType.TEST_SCRIPT,
FileType.DESCRIPTION,
}:
if not structure_validator.is_valid_file():
return False
# Passed schema validation
# if only schema validation is required - stop check here
if self.check_only_schema:
return True
# id_set validation
if (
self.id_set_validations
and not self.id_set_validations.is_file_valid_in_set(
file_path, file_type, pack_error_ignore_list
)
):
return False
# conf.json validation
valid_in_conf = True
if self.check_is_unskipped and file_type in {
FileType.INTEGRATION,
FileType.SCRIPT,
FileType.BETA_INTEGRATION,
}:
if not self.conf_json_validator.is_valid_file_in_conf_json(
structure_validator.current_file,
file_type,
file_path,
pack_error_ignore_list,
):
valid_in_conf = False
# Note: these file are not ignored but there are no additional validators for connections
if file_type == FileType.CONNECTION:
return True
# test playbooks and test scripts are using the same validation.
elif file_type in {FileType.TEST_PLAYBOOK, FileType.TEST_SCRIPT}:
return self.validate_test_playbook(
structure_validator, pack_error_ignore_list
)
elif file_type == FileType.RELEASE_NOTES:
if not self.skip_pack_rn_validation:
return self.validate_release_notes(
file_path,
added_files,
modified_files,
pack_error_ignore_list,
)
else:
logger.info("[yellow]Skipping release notes validation[/yellow]")
elif file_type == FileType.RELEASE_NOTES_CONFIG:
return self.validate_release_notes_config(file_path, pack_error_ignore_list)
elif file_type == FileType.DESCRIPTION:
return self.validate_description(file_path, pack_error_ignore_list)
elif file_type == FileType.README:
if not self.is_possible_validate_readme:
error_message, error_code = Errors.error_uninstall_node()
if self.handle_error(
error_message=error_message,
error_code=error_code,
file_path=file_path,
ignored_errors=pack_error_ignore_list,
):
return False
if not self.validate_all:
ReadMeValidator.add_node_env_vars()
if (
not ReadMeValidator.are_modules_installed_for_verify(
CONTENT_PATH # type: ignore
)
and not ReadMeValidator.is_docker_available()
): # shows warning message
return True
with ReadMeValidator.start_mdx_server(handle_error=self.handle_error):
return self.validate_readme(file_path, pack_error_ignore_list)
return self.validate_readme(file_path, pack_error_ignore_list)
elif file_type == FileType.REPORT:
return self.validate_report(structure_validator, pack_error_ignore_list)
elif file_type == FileType.PLAYBOOK:
return self.validate_playbook(
structure_validator, pack_error_ignore_list, file_type, is_modified
)
elif file_type == FileType.INTEGRATION:
return all(
[
self.validate_integration(
structure_validator,
pack_error_ignore_list,
is_modified,
file_type,
),
valid_in_conf,
]
)
elif file_type == FileType.SCRIPT:
return all(
[
self.validate_script(
structure_validator,
pack_error_ignore_list,
is_modified,
file_type,
),
valid_in_conf,
]
)
elif file_type == FileType.PYTHON_FILE:
return self.validate_python_file(file_path, pack_error_ignore_list)
elif file_type == FileType.BETA_INTEGRATION:
return self.validate_beta_integration(
structure_validator, pack_error_ignore_list
)
# Validate only images of packs
elif file_type == FileType.IMAGE:
return self.validate_image(file_path, pack_error_ignore_list)
elif file_type == FileType.AUTHOR_IMAGE:
return self.validate_author_image(file_path, pack_error_ignore_list)
elif file_type == FileType.INCIDENT_FIELD:
return self.validate_incident_field(
structure_validator, pack_error_ignore_list, is_modified, is_added_file
)
elif file_type == FileType.INDICATOR_FIELD:
return self.validate_indicator_field(
structure_validator, pack_error_ignore_list, is_modified, is_added_file
)
elif file_type == FileType.REPUTATION:
return self.validate_reputation(structure_validator, pack_error_ignore_list)
elif file_type == FileType.LAYOUT:
return self.validate_layout(structure_validator, pack_error_ignore_list)
elif file_type == FileType.LAYOUTS_CONTAINER:
return self.validate_layoutscontainer(
structure_validator, pack_error_ignore_list
)
elif file_type == FileType.PRE_PROCESS_RULES:
return self.validate_pre_process_rule(
structure_validator, pack_error_ignore_list
)