-
Notifications
You must be signed in to change notification settings - Fork 69
/
__main__.py
3546 lines (3309 loc) · 111 KB
/
__main__.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
# Site packages
import sys
import click
try:
import git
except ImportError:
sys.exit(click.style("Git executable cannot be found, or is invalid", fg="red"))
import copy
import functools
import logging
import os
from pathlib import Path
from typing import IO, Any, Dict, Iterable, Tuple, Union
import typer
from pkg_resources import DistributionNotFound, get_distribution
from demisto_sdk.commands.common.configuration import Configuration
from demisto_sdk.commands.common.constants import (
ENV_DEMISTO_SDK_MARKETPLACE,
FileType,
MarketplaceVersions,
)
from demisto_sdk.commands.common.content_constant_paths import (
ALL_PACKS_DEPENDENCIES_DEFAULT_PATH,
CONTENT_PATH,
)
from demisto_sdk.commands.common.cpu_count import cpu_count
from demisto_sdk.commands.common.handlers import DEFAULT_JSON_HANDLER as json
from demisto_sdk.commands.common.hook_validations.readme import ReadMeValidator
from demisto_sdk.commands.common.logger import handle_deprecated_args, logging_setup
from demisto_sdk.commands.common.tools import (
find_type,
get_last_remote_release_version,
get_release_note_entries,
is_external_repository,
is_sdk_defined_working_offline,
parse_marketplace_kwargs,
)
from demisto_sdk.commands.content_graph.commands.create import create
from demisto_sdk.commands.content_graph.commands.get_relationships import (
get_relationships,
)
from demisto_sdk.commands.content_graph.commands.update import update
from demisto_sdk.commands.content_graph.objects.repository import all_content_repo
from demisto_sdk.commands.generate_modeling_rules import generate_modeling_rules
from demisto_sdk.commands.prepare_content.prepare_upload_manager import (
PrepareUploadManager,
)
from demisto_sdk.commands.split.ymlsplitter import YmlSplitter
from demisto_sdk.commands.test_content.test_modeling_rule import (
init_test_data,
test_modeling_rule,
)
from demisto_sdk.commands.upload.upload import upload_content_entity
from demisto_sdk.utils.utils import check_configuration_file
SDK_OFFLINE_ERROR_MESSAGE = (
"[red]An internet connection is required for this command. If connected to the "
"internet, un-set the DEMISTO_SDK_OFFLINE_ENV environment variable.[/red]"
)
logger = logging.getLogger("demisto-sdk")
# Third party packages
# Common tools
class PathsParamType(click.Path):
"""
Defines a click options type for use with the @click.option decorator
The type accepts a string of comma-separated values where each individual value adheres
to the definition for the click.Path type. The class accepts the same parameters as the
click.Path type, applying those arguments for each comma-separated value in the list.
See https://click.palletsprojects.com/en/8.0.x/parameters/#implementing-custom-types for
more details.
"""
def convert(self, value, param, ctx):
if "," not in value:
return super().convert(value, param, ctx)
split_paths = value.split(",")
# check the validity of each of the paths
_ = [
super(PathsParamType, self).convert(path, param, ctx)
for path in split_paths
]
return value
class VersionParamType(click.ParamType):
"""
Defines a click options type for use with the @click.option decorator
The type accepts a string represents a version number.
"""
name = "version"
def convert(self, value, param, ctx):
version_sections = value.split(".")
if len(version_sections) == 3 and all(
version_section.isdigit() for version_section in version_sections
):
return value
else:
self.fail(
f"Version {value} is not according to the expected format. "
f"The format of version should be in x.y.z format, e.g: <2.1.3>",
param,
ctx,
)
class DemistoSDK:
"""
The core class for the SDK.
"""
def __init__(self):
self.configuration = None
pass_config = click.make_pass_decorator(DemistoSDK, ensure=True)
def logging_setup_decorator(func, *args, **kwargs):
def get_context_arg(args):
for arg in args:
if type(arg) == click.core.Context:
return arg
print( # noqa: T201
"Error: Cannot find the Context arg. Is the command configured correctly?"
)
return None
@click.option(
"--console-log-threshold",
help="Minimum logging threshold for the console logger."
" Possible values: DEBUG, INFO, WARNING, ERROR.",
)
@click.option(
"--file-log-threshold",
help="Minimum logging threshold for the file logger."
" Possible values: DEBUG, INFO, WARNING, ERROR.",
)
@click.option(
"--log-file-path",
help="Path to the log file. Default: Content root path.",
)
@functools.wraps(func)
def wrapper(*args, **kwargs):
logging_setup(
console_log_threshold=kwargs.get("console-log-threshold") or logging.INFO,
file_log_threshold=kwargs.get("file-log-threshold") or logging.DEBUG,
log_file_path=kwargs.get("log-file-path") or None,
)
handle_deprecated_args(get_context_arg(args).args)
return func(*args, **kwargs)
return wrapper
@click.group(
invoke_without_command=True,
no_args_is_help=True,
context_settings=dict(max_content_width=100),
)
@click.help_option("-h", "--help")
@click.option(
"-v",
"--version",
help="Get the demisto-sdk version.",
is_flag=True,
default=False,
show_default=True,
)
@click.option(
"-rn",
"--release-notes",
help="Get the release notes of the current demisto-sdk version.",
is_flag=True,
default=False,
show_default=True,
)
@pass_config
@click.pass_context
def main(ctx, config, version, release_notes, **kwargs):
logging_setup(
console_log_threshold=kwargs.get("console-log-threshold", logging.INFO),
file_log_threshold=kwargs.get("file-log-threshold", logging.DEBUG),
log_file_path=kwargs.get("log-file-path"),
)
global logger
logger = logging.getLogger("demisto-sdk")
handle_deprecated_args(ctx.args)
config.configuration = Configuration()
import dotenv
dotenv.load_dotenv(CONTENT_PATH / ".env", override=True) # type: ignore # load .env file from the cwd
if (
(not os.getenv("DEMISTO_SDK_SKIP_VERSION_CHECK")) or version
) and not is_sdk_defined_working_offline(): # If the key exists/called to version
try:
__version__ = get_distribution("demisto-sdk").version
except DistributionNotFound:
__version__ = "dev"
logger.info(
"[yellow]Could not find the version of the demisto-sdk. This usually happens when running in a development environment.[/yellow]"
)
else:
last_release = ""
if not os.environ.get(
"CI"
): # Check only when not running in CI (e.g running locally).
last_release = get_last_remote_release_version()
logger.info(f"[yellow]You are using demisto-sdk {__version__}.[/yellow]")
if last_release and __version__ != last_release:
logger.info(
f"[yellow]however version {last_release} is available.\n"
f"To update, run pip3 install --upgrade demisto-sdk[/yellow]"
)
if release_notes:
rn_entries = get_release_note_entries(__version__)
if not rn_entries:
logger.warning(
"\n[yellow]Could not get the release notes for this version.[/yellow]"
)
else:
logger.info(
"\nThe following are the release note entries for the current version:\n"
)
for rn in rn_entries:
logger.info(rn)
logger.info("")
# ====================== split ====================== #
@main.command(
context_settings=dict(
ignore_unknown_options=True,
allow_extra_args=True,
)
)
@click.help_option("-h", "--help")
@click.option("-i", "--input", help="The yml/json file to extract from", required=True)
@click.option(
"-o",
"--output",
help="The output dir to write the extracted code/description/image/json to.",
)
@click.option(
"--no-demisto-mock",
help="Don't add an import for demisto mock. (only for yml files)",
is_flag=True,
show_default=True,
)
@click.option(
"--no-common-server",
help="Don't add an import for CommonServerPython. (only for yml files)",
is_flag=True,
show_default=True,
)
@click.option(
"--no-auto-create-dir",
help="Don't auto create the directory if the target directory ends with *Integrations/*Scripts/*Dashboards"
"/*GenericModules.",
is_flag=True,
show_default=True,
)
@click.option(
"--new-module-file",
help="Create a new module file instead of editing the existing file. (only for json files)",
is_flag=True,
show_default=True,
)
@pass_config
@click.pass_context
@logging_setup_decorator
def split(ctx, config, **kwargs):
"""Split the code, image and description files from a Demisto integration or script yaml file
to multiple files(To a package format - https://demisto.pan.dev/docs/package-dir).
"""
from demisto_sdk.commands.split.jsonsplitter import JsonSplitter
check_configuration_file("split", kwargs)
file_type: FileType = find_type(kwargs.get("input", ""), ignore_sub_categories=True)
if file_type not in [
FileType.INTEGRATION,
FileType.SCRIPT,
FileType.GENERIC_MODULE,
FileType.MODELING_RULE,
FileType.PARSING_RULE,
]:
logger.info(
"[red]File is not an Integration, Script, Generic Module, Modeling Rule or Parsing Rule.[/red]"
)
return 1
if file_type in [
FileType.INTEGRATION,
FileType.SCRIPT,
FileType.MODELING_RULE,
FileType.PARSING_RULE,
]:
yml_splitter = YmlSplitter(
configuration=config.configuration, file_type=file_type.value, **kwargs
)
return yml_splitter.extract_to_package_format()
else:
json_splitter = JsonSplitter(
input=kwargs.get("input"), # type: ignore[arg-type]
output=kwargs.get("output"), # type: ignore[arg-type]
no_auto_create_dir=kwargs.get("no_auto_create_dir"), # type: ignore[arg-type]
new_module_file=kwargs.get("new_module_file"), # type: ignore[arg-type]
)
return json_splitter.split_json()
# ====================== extract-code ====================== #
@main.command(hidden=True)
@click.help_option("-h", "--help")
@click.option("--input", "-i", help="The yml file to extract from", required=True)
@click.option(
"--output", "-o", required=True, help="The output file to write the code to"
)
@click.option(
"--no-demisto-mock",
help="Don't add an import for demisto mock, false by default",
is_flag=True,
show_default=True,
)
@click.option(
"--no-common-server",
help="Don't add an import for CommonServerPython."
"If not specified will import unless this is CommonServerPython",
is_flag=True,
show_default=True,
)
@pass_config
@click.pass_context
@logging_setup_decorator
def extract_code(ctx, config, **kwargs):
"""Extract code from a Demisto integration or script yaml file."""
from demisto_sdk.commands.split.ymlsplitter import YmlSplitter
check_configuration_file("extract-code", kwargs)
file_type: FileType = find_type(kwargs.get("input", ""), ignore_sub_categories=True)
if file_type not in [FileType.INTEGRATION, FileType.SCRIPT]:
logger.info("[red]File is not an Integration or Script.[/red]")
return 1
extractor = YmlSplitter(
configuration=config.configuration, file_type=file_type.value, **kwargs
)
return extractor.extract_code(kwargs["outfile"])
# ====================== prepare-content ====================== #
@main.command(name="prepare-content")
@click.help_option("-h", "--help")
@click.option(
"-i",
"--input",
help="Comma-separated list of paths to directories or files to unify.",
required=False,
type=PathsParamType(dir_okay=True, exists=True),
)
@click.option(
"-a",
"--all",
is_flag=True,
help="Run prepare-content on all content packs. If no output path is given, will dump the result in the current working path.",
)
@click.option(
"-g",
"--graph",
help="Whether use the content graph",
is_flag=True,
default=False,
)
@click.option(
"--skip-update",
help="Whether to skip updating the content graph (used only when graph is true)",
is_flag=True,
default=False,
)
@click.option(
"-o", "--output", help="The output dir to write the unified yml to", required=False
)
@click.option(
"-c",
"--custom",
help="Add test label to unified yml id/name/display",
required=False,
)
@click.option(
"-f",
"--force",
help="Forcefully overwrites the preexisting yml if one exists",
is_flag=True,
show_default=False,
)
@click.option(
"-ini",
"--ignore-native-image",
help="Whether to ignore the addition of the nativeimage key to the yml of a script/integration",
is_flag=True,
show_default=False,
default=False,
)
@click.option(
"-mp",
"--marketplace",
help="The marketplace the content items are created for, that determines usage of marketplace "
"unique text. Default is the XSOAR marketplace.",
default="xsoar",
type=click.Choice([mp.value for mp in list(MarketplaceVersions)] + ["v2"]),
)
@click.pass_context
@logging_setup_decorator
def prepare_content(ctx, **kwargs):
"""
This command is used to prepare the content to be used in the platform.
"""
assert (
sum([bool(kwargs["all"]), bool(kwargs["input"])]) == 1
), "Exactly one of the '-a' or '-i' parameters must be provided."
if kwargs["all"]:
content_DTO = all_content_repo()
output_path = kwargs.get("output", ".") or "."
content_DTO.dump(
dir=Path(output_path, "prepare-content-tmp"),
marketplace=parse_marketplace_kwargs(kwargs),
)
return 0
inputs = []
if input_ := kwargs["input"]:
inputs = input_.split(",")
if output_path := kwargs["output"]:
if "." in Path(output_path).name: # check if the output path is a file
if len(inputs) > 1:
raise ValueError(
"When passing multiple inputs, the output path should be a directory and not a file."
)
else:
dest_path = Path(output_path)
dest_path.mkdir(exist_ok=True)
for input_content in inputs:
if output_path and len(inputs) > 1:
path_name = Path(input_content).name
kwargs["output"] = str(Path(output_path, path_name))
if click.get_current_context().info_name == "unify":
kwargs["unify_only"] = True
check_configuration_file("unify", kwargs)
# Input is of type Path.
kwargs["input"] = str(input_content)
file_type = find_type(kwargs["input"])
if marketplace := kwargs.get("marketplace"):
os.environ[ENV_DEMISTO_SDK_MARKETPLACE] = marketplace.lower()
if file_type == FileType.GENERIC_MODULE:
from demisto_sdk.commands.prepare_content.generic_module_unifier import (
GenericModuleUnifier,
)
# pass arguments to GenericModule unifier and call the command
generic_module_unifier = GenericModuleUnifier(**kwargs)
generic_module_unifier.merge_generic_module_with_its_dashboards()
else:
PrepareUploadManager.prepare_for_upload(**kwargs)
return 0
main.add_command(prepare_content, name="unify")
# ====================== zip-packs ====================== #
@main.command(
context_settings=dict(
ignore_unknown_options=True,
allow_extra_args=True,
)
)
@click.help_option("-h", "--help")
@click.option(
"-i",
"--input",
help="The packs to be zipped as csv list of pack paths.",
type=PathsParamType(exists=True, resolve_path=True),
required=True,
)
@click.option(
"-o",
"--output",
help="The destination directory to create the packs.",
type=click.Path(file_okay=False, resolve_path=True),
required=True,
)
@click.option(
"-v",
"--content-version",
help="The content version in CommonServerPython.",
default="0.0.0",
)
@click.option(
"-u",
"--upload",
is_flag=True,
help="Upload the unified packs to the marketplace.",
default=False,
)
@click.option(
"--zip-all", is_flag=True, help="Zip all the packs in one zip file.", default=False
)
@click.pass_context
@logging_setup_decorator
def zip_packs(ctx, **kwargs) -> int:
"""Generating zipped packs that are ready to be uploaded to Cortex XSOAR machine."""
from demisto_sdk.commands.upload.uploader import Uploader
from demisto_sdk.commands.zip_packs.packs_zipper import (
EX_FAIL,
EX_SUCCESS,
PacksZipper,
)
check_configuration_file("zip-packs", kwargs)
# if upload is true - all zip packs will be compressed to one zip file
should_upload = kwargs.pop("upload", False)
zip_all = kwargs.pop("zip_all", False) or should_upload
marketplace = parse_marketplace_kwargs(kwargs)
packs_zipper = PacksZipper(
zip_all=zip_all, pack_paths=kwargs.pop("input"), quiet_mode=zip_all, **kwargs
)
zip_path, unified_pack_names = packs_zipper.zip_packs()
if should_upload and zip_path:
return Uploader(
input=Path(zip_path), pack_names=unified_pack_names, marketplace=marketplace
).upload()
return EX_SUCCESS if zip_path is not None else EX_FAIL
# ====================== validate ====================== #
@main.command(
context_settings=dict(
ignore_unknown_options=True,
allow_extra_args=True,
)
)
@click.help_option("-h", "--help")
@click.option(
"--no-conf-json",
is_flag=True,
default=False,
show_default=True,
help="Skip conf.json validation.",
)
@click.option(
"-s",
"--id-set",
is_flag=True,
default=False,
show_default=True,
help="Perform validations using the id_set file.",
)
@click.option(
"-idp",
"--id-set-path",
help="The path of the id-set.json used for validations.",
type=click.Path(resolve_path=True),
)
@click.option(
"-gr",
"--graph",
is_flag=True,
default=False,
show_default=True,
help="Perform validations on content graph.",
)
@click.option(
"--prev-ver", help="Previous branch or SHA1 commit to run checks against."
)
@click.option(
"--no-backward-comp",
is_flag=True,
show_default=True,
help="Whether to check backward compatibility or not.",
)
@click.option(
"-g",
"--use-git",
is_flag=True,
show_default=True,
default=False,
help="Validate changes using git - this will check current branch's changes against origin/master or origin/main. "
"If the --post-commit flag is supplied: validation will run only on the current branch's changed files "
"that have been committed. "
"If the --post-commit flag is not supplied: validation will run on all changed files in the current branch, "
"both committed and not committed. ",
)
@click.option(
"-pc",
"--post-commit",
is_flag=True,
help="Whether the validation should run only on the current branch's committed changed files. "
"This applies only when the -g flag is supplied.",
)
@click.option(
"-st",
"--staged",
is_flag=True,
help="Whether the validation should ignore unstaged files."
"This applies only when the -g flag is supplied.",
)
@click.option(
"-iu",
"--include-untracked",
is_flag=True,
help="Whether to include untracked files in the validation. "
"This applies only when the -g flag is supplied.",
)
@click.option(
"-a",
"--validate-all",
is_flag=True,
show_default=True,
default=False,
help="Whether to run all validation on all files or not.",
)
@click.option(
"-i",
"--input",
type=PathsParamType(
exists=True, resolve_path=True
), # PathsParamType allows passing a list of paths
help="The path of the content pack/file to validate specifically.",
)
@click.option(
"--skip-pack-release-notes",
is_flag=True,
help="Skip validation of pack release notes.",
)
@click.option(
"--print-ignored-errors", is_flag=True, help="Print ignored errors as warnings."
)
@click.option(
"--print-ignored-files",
is_flag=True,
help="Print which files were ignored by the command.",
)
@click.option(
"--no-docker-checks", is_flag=True, help="Whether to run docker image validation."
)
@click.option(
"--silence-init-prints",
is_flag=True,
help="Whether to skip the initialization prints.",
)
@click.option(
"--skip-pack-dependencies",
is_flag=True,
help="Skip validation of pack dependencies.",
)
@click.option(
"--create-id-set", is_flag=True, help="Whether to create the id_set.json file."
)
@click.option(
"-j",
"--json-file",
help="The JSON file path to which to output the command results.",
)
@click.option(
"--skip-schema-check", is_flag=True, help="Whether to skip the file schema check."
)
@click.option(
"--debug-git", is_flag=True, help="Whether to print debug logs for git statuses."
)
@click.option(
"--print-pykwalify", is_flag=True, help="Whether to print the pykwalify log errors."
)
@click.option(
"--quiet-bc-validation",
help="Set backwards compatibility validation's errors as warnings.",
is_flag=True,
)
@click.option(
"--allow-skipped",
help="Don't fail on skipped integrations or when all test playbooks are skipped.",
is_flag=True,
)
@click.option(
"--no-multiprocessing",
help="run validate all without multiprocessing, for debugging purposes.",
is_flag=True,
default=False,
)
@click.option(
"-sv",
"--run-specific-validations",
help="Run specific validations by stating the error codes.",
is_flag=False,
)
@click.argument("file_paths", nargs=-1, type=click.Path(exists=True, resolve_path=True))
@pass_config
@click.pass_context
@logging_setup_decorator
def validate(ctx, config, file_paths: str, **kwargs):
"""Validate your content files. If no additional flags are given, will validated only committed files."""
from demisto_sdk.commands.validate.validate_manager import ValidateManager
if is_sdk_defined_working_offline():
logger.error(SDK_OFFLINE_ERROR_MESSAGE)
sys.exit(1)
if file_paths and not kwargs["input"]:
# If file_paths is given as an argument, use it as the file_paths input (instead of the -i flag). If both, input wins.
kwargs["input"] = ",".join(file_paths)
run_with_mp = not kwargs.pop("no_multiprocessing")
check_configuration_file("validate", kwargs)
sys.path.append(config.configuration.env_dir)
file_path = kwargs["input"]
if kwargs["post_commit"] and kwargs["staged"]:
logger.info(
"[red]Could not supply the staged flag with the post-commit flag[/red]"
)
sys.exit(1)
try:
is_external_repo = is_external_repository()
# default validate to -g --post-commit
if not kwargs.get("validate_all") and not kwargs["use_git"] and not file_path:
kwargs["use_git"] = True
kwargs["post_commit"] = True
validator = ValidateManager(
is_backward_check=not kwargs["no_backward_comp"],
only_committed_files=kwargs["post_commit"],
prev_ver=kwargs["prev_ver"],
skip_conf_json=kwargs["no_conf_json"],
use_git=kwargs["use_git"],
file_path=file_path,
validate_all=kwargs.get("validate_all"),
validate_id_set=kwargs["id_set"],
validate_graph=kwargs.get("graph"),
skip_pack_rn_validation=kwargs["skip_pack_release_notes"],
print_ignored_errors=kwargs["print_ignored_errors"],
is_external_repo=is_external_repo,
print_ignored_files=kwargs["print_ignored_files"],
no_docker_checks=kwargs["no_docker_checks"],
silence_init_prints=kwargs["silence_init_prints"],
skip_dependencies=kwargs["skip_pack_dependencies"],
id_set_path=kwargs.get("id_set_path"),
staged=kwargs["staged"],
create_id_set=kwargs.get("create_id_set"),
json_file_path=kwargs.get("json_file"),
skip_schema_check=kwargs.get("skip_schema_check"),
debug_git=kwargs.get("debug_git"),
include_untracked=kwargs.get("include_untracked"),
quiet_bc=kwargs.get("quiet_bc_validation"),
multiprocessing=run_with_mp,
check_is_unskipped=not kwargs.get("allow_skipped", False),
specific_validations=kwargs.get("run_specific_validations"),
)
return validator.run_validation()
except (git.InvalidGitRepositoryError, git.NoSuchPathError, FileNotFoundError) as e:
logger.info(f"[red]{e}[/red]")
logger.info(
"\n[red]You may not be running `demisto-sdk validate` command in the content directory.\n"
"Please run the command from content directory[red]"
)
sys.exit(1)
# ====================== create-content-artifacts ====================== #
@main.command(hidden=True)
@click.help_option("-h", "--help")
@click.option(
"-a",
"--artifacts_path",
help="Destination directory to create the artifacts.",
type=click.Path(file_okay=False, resolve_path=True),
required=True,
)
@click.option("--zip/--no-zip", help="Zip content artifacts folders", default=True)
@click.option(
"--packs",
help="Create only content_packs artifacts. "
"Used for server version 5.5.0 and earlier.",
is_flag=True,
)
@click.option(
"-v",
"--content_version",
help="The content version in CommonServerPython.",
default="0.0.0",
)
@click.option(
"-s",
"--suffix",
help="Suffix to add all yaml/json/yml files in the created artifacts.",
)
@click.option(
"--cpus",
help="Number of cpus/vcpus available - only required when os not reflect number of cpus (CircleCI"
"always show 32, but medium has 3.",
hidden=True,
default=cpu_count(),
)
@click.option(
"-idp",
"--id-set-path",
help="The full path of id_set.json",
hidden=True,
type=click.Path(exists=True, resolve_path=True),
)
@click.option(
"-p",
"--pack-names",
help=(
"Packs to create artifacts for. Optional values are: `all` or "
"csv list of packs. "
"Default is set to `all`"
),
default="all",
hidden=True,
)
@click.option(
"-sk",
"--signature-key",
help="Base64 encoded signature key used for signing packs.",
hidden=True,
)
@click.option(
"-sd",
"--sign-directory",
help="Path to the signDirectory executable file.",
type=click.Path(exists=True, resolve_path=True),
hidden=True,
)
@click.option(
"-rt",
"--remove-test-playbooks",
is_flag=True,
help="Should remove test playbooks from content packs or not.",
default=True,
hidden=True,
)
@click.option(
"-mp",
"--marketplace",
help="The marketplace the artifacts are created for, that "
"determines which artifacts are created for each pack. "
"Default is the XSOAR marketplace, that has all of the packs "
"artifacts.",
default="xsoar",
type=click.Choice(["xsoar", "marketplacev2", "v2", "xpanse"]),
)
@click.option(
"-fbi",
"--filter-by-id-set",
is_flag=True,
help="Whether to use the id set as content items guide, meaning only include in the packs the "
"content items that appear in the id set.",
default=False,
hidden=True,
)
@click.option(
"-af",
"--alternate-fields",
is_flag=True,
help="Use the alternative fields if such are present in the yml or json of the content item.",
default=False,
hidden=True,
)
@click.pass_context
@logging_setup_decorator
def create_content_artifacts(ctx, **kwargs) -> int:
"""Generating the following artifacts:
1. content_new - Contains all content objects of type json,yaml (from_version < 6.0.0)
2. content_packs - Contains all packs from Packs - Ignoring internal files (to_version >= 6.0.0).
3. content_test - Contains all test scripts/playbooks (from_version < 6.0.0)
4. content_all - Contains all from content_new and content_test.
5. uploadable_packs - Contains zipped packs that are ready to be uploaded to Cortex XSOAR machine.
"""
from demisto_sdk.commands.create_artifacts.content_artifacts_creator import (
ArtifactsManager,
)
check_configuration_file("create-content-artifacts", kwargs)
if marketplace := kwargs.get("marketplace"):
os.environ[ENV_DEMISTO_SDK_MARKETPLACE] = marketplace.lower()
artifacts_conf = ArtifactsManager(**kwargs)
return artifacts_conf.create_content_artifacts()
# ====================== secrets ====================== #
@main.command(
context_settings=dict(
ignore_unknown_options=True,
allow_extra_args=True,
)
)
@click.help_option("-h", "--help")
@click.option("-i", "--input", help="Specify file of to check secret on.")
@click.option(
"--post-commit",
is_flag=True,
show_default=True,
help="Whether the secretes is done after you committed your files, "
"this will help the command to determine which files it should check in its "
"run. Before you commit the files it should not be used. Mostly for build "
"validations.",
)
@click.option(
"-ie",
"--ignore-entropy",
is_flag=True,
help="Ignore entropy algorithm that finds secret strings (passwords/api keys).",
)
@click.option(
"-wl",
"--whitelist",
default="./Tests/secrets_white_list.json",
show_default=True,
help='Full path to whitelist file, file name should be "secrets_white_list.json"',
)
@click.option("--prev-ver", help="The branch against which to run secrets validation.")
@click.argument("file_paths", nargs=-1, type=click.Path(exists=True, resolve_path=True))
@pass_config
@click.pass_context
@logging_setup_decorator
def secrets(ctx, config, file_paths: str, **kwargs):
"""Run Secrets validator to catch sensitive data before exposing your code to public repository.
Attach path to whitelist to allow manual whitelists.
"""
if file_paths and not kwargs["input"]:
# If file_paths is given as an argument, use it as the file_paths input (instead of the -i flag). If both, input wins.
kwargs["input"] = ",".join(file_paths)
from demisto_sdk.commands.secrets.secrets import SecretsValidator
check_configuration_file("secrets", kwargs)
sys.path.append(config.configuration.env_dir)
secrets_validator = SecretsValidator(
configuration=config.configuration,
is_circle=kwargs["post_commit"],
ignore_entropy=kwargs["ignore_entropy"],
white_list_path=kwargs["whitelist"],
input_path=kwargs.get("input"),
)
return secrets_validator.run()
# ====================== lint ====================== #
@main.command(
context_settings=dict(
ignore_unknown_options=True,
allow_extra_args=True,
)
)
@click.help_option("-h", "--help")
@click.option(
"-i",
"--input",
help="Specify directory(s) of integration/script",
type=PathsParamType(exists=True, resolve_path=True),
)
@click.option("-g", "--git", is_flag=True, help="Will run only on changed packages")
@click.option(
"-a",
"--all-packs",
is_flag=True,
help="Run lint on all directories in content repo",
)
@click.option(
"-p",
"--parallel",
default=1,
help="Run tests in parallel",