-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsz_command
More file actions
executable file
·2466 lines (1943 loc) · 98 KB
/
Copy pathsz_command
File metadata and controls
executable file
·2466 lines (1943 loc) · 98 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
#! /usr/bin/env python3
import argparse
import cmd
import functools
import glob
import json
import os
import pathlib
import re
import shlex
import sys
import textwrap
import time
from typing import Any, Callable, Dict, List, TypeVar, Union, cast
from _tool_helpers import (
Colors,
colorize_cmd_prompt,
colorize_output,
colorize_str,
do_help,
do_history,
do_shell,
get_engine_config,
get_engine_flag_names,
get_engine_flags_as_int,
history_disabled,
history_setup,
in_docker,
print_debug,
print_error,
print_info,
print_response,
print_warning,
response_reformat_json,
response_to_clipboard,
response_to_file,
)
from senzing import SzError
from senzing_core import SzAbstractFactoryCore, SzConfigCore
_WrappedFunc = TypeVar("_WrappedFunc", bound=Callable[..., Any])
MODULE_NAME = pathlib.Path(__file__).stem
PER_CMD_SETTINGS = ["json", "jsonl", "color", "colour", "nocolor", "nocolour", "debug", "timer", "scroll"]
DEFAULT_CONFIG = {
"format_json": True,
"color_output": True,
"timer": False,
"theme": "TERMINAL",
"scroll_output": False,
"debug_sdk_call": False,
"debug_sz_engine": False,
"history_file": True,
}
# Map per command settings to configuration dictionary keys
SETTINGS_TO_CONFIG_MAP = {
"json": ["format_json", True],
"jsonl": ["format_json", False],
"color": ["color_output", True],
"colour": ["color_output", True],
"nocolor": ["color_output", False],
"nocolour": ["color_output", False],
"debug": ["debug_sdk_call", True],
"debug_sdk": ["debug_sdk_call", True],
"timer": ["timer", True],
"scroll": ["scroll_output", True],
}
# Don't overwrite last command if we still need to use it
CMDS_NOT_TO_SET_LAST_COMMAND = [
"response_reformat_json",
"response_to_clipboard",
"response_to_file",
]
CONFIG_SETTINGS: Dict[str, Dict[str, Any]] = {
"format_json": {
"values": ["off", "on"],
"description": "Format JSON responses",
},
"color_output": {
"values": ["off", "on"],
"description": "Color output",
},
"timer": {
"values": ["off", "on"],
"description": "Display approximate timings for command execution",
},
"theme": {
"values": [c.lower() for c in Colors.AVAILABLE_THEMES],
"description": "Set color scheme to use",
},
"scroll_output": {
"values": ["off", "on"],
"description": "Use a pager for content larger than the terminal",
},
"debug_sdk_call": {
"values": ["off", "on"],
"description": "Display the call sent to the Senzing SDK",
},
"debug_sz_engine": {
"values": ["off", "on"],
"description": "Display debug tracing from the Senzing engine",
},
"history_file": {"values": ["off", "on"], "description": "Use a history file", "value": None},
}
# Due to the way the Cmd module works, don't want doc strings on everything
# pylint: disable=missing-function-docstring
# -------------------------------------------------------------------------
# Decorators
# -------------------------------------------------------------------------
def do_methods_decorator(do_method: _WrappedFunc) -> _WrappedFunc:
@functools.wraps(do_method)
def wrapper(self, *args: Any, **kwargs: Any) -> Any:
# Remove do_ from wrapped method
sdk_method_name = do_method.__name__[3:]
# Set the pre command config to handle jsonl, nocolor. etc
self.set_pre_cmd_settings(args[0])
# Remove any per cmd line settings such as jsonl, nocolor, etc
cmd_args = self.remove_per_cmd_settings(args[0])
do_debug = self.per_cmd_config["debug_sdk_call"]
do_timer = self.per_cmd_config["timer"]
if do_debug:
sdk_engine = ""
if sdk_method_name in dir(self.sz_config):
sdk_engine = "SzConfig."
elif sdk_method_name in dir(self.sz_configmgr):
sdk_engine = "SzConfigManager."
elif sdk_method_name in dir(self.sz_diagnostic):
sdk_engine = "SzDiagnostic."
elif sdk_method_name in dir(self.sz_engine):
sdk_engine = "SzEngine."
elif sdk_method_name in dir(self.sz_product):
sdk_engine = "SzProduct."
sdk_call = f"{sdk_engine}{sdk_method_name}"
sdk_call_dict = {}
# If there is a parser for the method it takes arguments
if sdk_method_name in self.subparsers.choices:
try:
# Parse arguments for a command and add to kwargs to use in calling do_ method
# Returns an argparse.Namespace, make a dict for logic checking and less complaints from mypy!
kwargs["parsed_args"] = self.parser.parse_args([f"{sdk_method_name}"] + self.parse(cmd_args))
# Get the argparse.Namespace as a dictionary to change any modified arguments for debug
if do_debug:
sdk_call_dict = kwargs["parsed_args"].__dict__.copy()
# If the command has flags get the int value
if hasattr(kwargs["parsed_args"], "flags") and kwargs["parsed_args"].flags:
kwargs["flags"] = get_engine_flags_as_int(kwargs["parsed_args"].flags)
if do_debug:
sdk_call_dict["flags"] = kwargs["flags"]
# If the command uses *record_keys build the expected list of tuples for the SDK
if hasattr(kwargs["parsed_args"], "record_keys") or hasattr(kwargs["parsed_args"], "avoid_record_keys"):
rk_type = "record_keys" if "record_keys" in kwargs["parsed_args"] else "avoid_record_keys"
record_keys = getattr(kwargs["parsed_args"], rk_type)
# 1 list element == str from quotes: get_virtual_entity_by_record_id 'REFERENCE 2012 customers 1001'
# >1 list elements == list such as: find_path_by_record_id ...-a customers 1001 reference 2001
# Split single str list element into multiple elements
if len(record_keys) == 1:
record_keys = record_keys[0].split()
if len(record_keys) % 2 != 0:
print_error(f"Uneven number of data source codes and record IDs: {record_keys}")
return None
# Build the list of tuples for the SDK: [('REFERENCE', '2012'), ('CUSTOMERS', '1001')]
kwargs[locals()["rk_type"]] = [tuple(record_keys[i : i + 2]) for i in range(0, len(record_keys), 2)]
if do_debug:
sdk_call_dict[locals()["rk_type"]] = kwargs[locals()["rk_type"]]
# If the method uses entity_ids build the list for the SDK
# avoid_entity_ids doesn't need to be checked, it is parsed as a list
if hasattr(kwargs["parsed_args"], "entity_ids"):
entity_ids = kwargs["parsed_args"].entity_ids
if len(entity_ids) == 1:
entity_ids = entity_ids[0].replace(",", " ")
entity_ids = entity_ids.split()
try:
kwargs["entity_ids"] = [int(i) for i in entity_ids]
except ValueError:
non_ints = [id for id in entity_ids if not id.isdigit()]
print_error(f"Entity IDs should be integers: {', '.join(non_ints)}")
return None
if do_debug:
sdk_call_dict["entity_ids"] = kwargs["entity_ids"]
# Catch argument errors from parser.parse_args and display the commands help
# Argparse parser error method is subclassed by SzCommandArgumentParser and displays the error
except SystemExit:
self.do_help(do_method.__name__)
return None
# Catch parsing errors such as missing single quote around JSON, the error is displayed by parse()
except ValueError:
return None
# Catch errors from methods such as get_engine_flags
except (KeyError, SzError) as err:
print_error(err)
return None
if do_timer:
timer_start = time.perf_counter()
# Run the decorated method passing back kwargs for use in SDK call
try:
if do_debug:
sdk_call_args = ", ".join([f"{k} = {repr(v)}" for k, v in sdk_call_dict.items() if v])
sdk_call_all = f"{sdk_call}({sdk_call_args})"
print_debug(sdk_call_all)
result = do_method(self, **kwargs)
except (SzError, IOError, ValueError) as err:
result = None
print_error(err)
finally:
if do_timer:
exec_time = time.perf_counter() - timer_start
print_info(f"Approximate execution time (s): {exec_time:.5f}", info_prefix=False)
return result
return cast(_WrappedFunc, wrapper)
# -------------------------------------------------------------------------
# Classes
# -------------------------------------------------------------------------
class SzCommandArgumentParser(argparse.ArgumentParser):
"""Subclass ArgumentParser, override error() with custom message"""
def error(self, message: str) -> None:
self.exit(
2,
print_error(message),
)
class SzCmdShell(cmd.Cmd):
"""Main Cmd class"""
def __init__(
self,
engine_settings: str,
# cli_args: argparse.Namespace,
debug_reinit: Dict[str, bool],
):
super().__init__()
self.engine_settings = engine_settings
self.debug_reinit = debug_reinit
# Configuration file for this tool
self.config = DEFAULT_CONFIG.copy()
self.per_cmd_config = DEFAULT_CONFIG.copy()
self.config_file = pathlib.Path(f"~/.{MODULE_NAME}{'.json'}").expanduser()
self.config_file_exists = pathlib.Path(self.config_file).exists()
# Display the can't read/write config message once, not at all in container
self.config_error = False
self.docker_launched = in_docker()
# Read the config file
if not self.docker_launched and self.config_file_exists:
self.read_config()
# Create config file if one doesn't exist and write it again if it exists. read_config() merges DEFAULT_CONFIG
# with the config file incase new config settings are added to DEFAULT_CONFIG in a new release of the tool
self.write_config()
# Acquire Senzing engines and information
# NOTE Don't change the ordering of the create_*() calls to the factory, for verbose_logging
verbose_logging = 1 if any([self.debug_reinit["verbose_logging"], self.config["debug_sz_engine"]]) else 0
try:
self.sz_factory = SzAbstractFactoryCore(
MODULE_NAME,
self.engine_settings,
verbose_logging=verbose_logging,
)
self.sz_engine = self.sz_factory.create_engine()
self.sz_diagnostic = self.sz_factory.create_diagnostic()
self.sz_config = SzConfigCore()
self.sz_configmgr = self.sz_factory.create_configmanager()
self.sz_product = self.sz_factory.create_product()
# Collect attributes from configuration
self.attrs = self.get_config_attr_codes()
# Get Senzing engine flag names for use in auto completion
self.engine_flags_list = get_engine_flag_names(["_SZ_WITHOUT_INFO"])
except SzError as err:
print_error(err)
sys.exit(1)
# If default config ID changes reinitialize
self.reinitialize = False
# Could be deprecated, undocumented, not supported, experimental or not relevant
self.__hidden_cmds = (
"do_EOF",
"do_find_interesting_entities_by_entity_id",
"do_find_interesting_entities_by_record_id",
"do_get_redo_record",
"do_get_feature",
"do_hidden",
"do_shell",
)
# Used to change the theme and for setting cmd prompt, use the default colors set by the terminal
self.themes = Colors.AVAILABLE_THEMES
Colors.set_theme("TERMINAL")
# Cmd module settings
self.intro = ""
self.prompt_str = "szcmd"
self.prompt_color = "info"
self.prompt = colorize_cmd_prompt(self.prompt_str, self.prompt_color, self.config["color_output"]) # type: ignore[arg-type]
# Prior response and command for post command functions
self.last_response = ""
self.last_command = ""
# History file
self.history_file: Union[None, pathlib.Path] = None
self.history_file_error = False
# -------------------------------------------------------------------------
# do_* method parsers
# -------------------------------------------------------------------------
self.parser = SzCommandArgumentParser(
add_help=False,
prog=MODULE_NAME,
usage=argparse.SUPPRESS,
)
self.subparsers = self.parser.add_subparsers()
# szconfig parsers
get_config_parser = self.subparsers.add_parser("get_config", usage=argparse.SUPPRESS)
get_config_parser.add_argument("config_id", type=int)
# szconfigmanager parsers
replace_default_config_id_parser = self.subparsers.add_parser(
"replace_default_config_id", usage=argparse.SUPPRESS
)
replace_default_config_id_parser.add_argument("current_default_config_id", type=int)
replace_default_config_id_parser.add_argument("new_default_config_id", type=int)
set_default_config_id_parser = self.subparsers.add_parser("set_default_config_id", usage=argparse.SUPPRESS)
set_default_config_id_parser.add_argument("config_id", type=int)
# szdiagnostic parsers
check_repository_performance_parser = self.subparsers.add_parser(
"check_repository_performance", usage=argparse.SUPPRESS
)
check_repository_performance_parser.add_argument("seconds_to_run", default=3, nargs="?", type=int)
get_feature_parser = self.subparsers.add_parser("get_feature", usage=argparse.SUPPRESS)
get_feature_parser.add_argument("featureID", type=int)
purge_repository_parser = self.subparsers.add_parser("purge_repository", usage=argparse.SUPPRESS)
purge_repository_parser.add_argument(
"-FORCEPURGE",
"--FORCEPURGE",
action="store_true",
default=False,
dest="force_purge",
required=False,
)
# szengine parsers
add_record_parser = self.subparsers.add_parser("add_record", usage=argparse.SUPPRESS)
add_record_parser.add_argument("data_source_code")
add_record_parser.add_argument("record_id")
add_record_parser.add_argument("record_definition")
add_record_parser.add_argument("-f", "--flags", nargs="+", required=False)
delete_record_parser = self.subparsers.add_parser("delete_record", usage=argparse.SUPPRESS)
delete_record_parser.add_argument("data_source_code")
delete_record_parser.add_argument("record_id")
delete_record_parser.add_argument("-f", "--flags", nargs="+", required=False)
export_csv_entity_report_parser = self.subparsers.add_parser(
"export_csv_entity_report", usage=argparse.SUPPRESS
)
export_csv_entity_report_parser.add_argument("output_file")
export_csv_entity_report_parser.add_argument("-f", "--flags", nargs="+", required=False)
export_csv_entity_report_parser.add_argument("-t", "--csv_column_list", required=False, type=str)
export_json_entity_report_parser = self.subparsers.add_parser(
"export_json_entity_report", usage=argparse.SUPPRESS
)
export_json_entity_report_parser.add_argument("output_file")
export_json_entity_report_parser.add_argument("-f", "--flags", nargs="+", required=False)
find_interesting_entities_by_entity_id_parser = self.subparsers.add_parser(
"find_interesting_entities_by_entity_id", usage=argparse.SUPPRESS
)
find_interesting_entities_by_entity_id_parser.add_argument("entity_id", type=int)
find_interesting_entities_by_entity_id_parser.add_argument("-f", "--flags", nargs="+", required=False)
find_interesting_entities_by_record_id_parser = self.subparsers.add_parser(
"find_interesting_entities_by_record_id", usage=argparse.SUPPRESS
)
find_interesting_entities_by_record_id_parser.add_argument("data_source_code")
find_interesting_entities_by_record_id_parser.add_argument("record_id")
find_interesting_entities_by_record_id_parser.add_argument("-f", "--flags", nargs="+", required=False)
find_network_by_entity_id_parser = self.subparsers.add_parser(
"find_network_by_entity_id", usage=argparse.SUPPRESS
)
find_network_by_entity_id_parser.add_argument("entity_ids", nargs="+")
find_network_by_entity_id_parser.add_argument("max_degrees", type=int)
find_network_by_entity_id_parser.add_argument("build_out_degrees", type=int)
find_network_by_entity_id_parser.add_argument("build_out_max_entities", type=int)
find_network_by_entity_id_parser.add_argument("-f", "--flags", nargs="+", required=False)
find_network_by_record_id_parser = self.subparsers.add_parser(
"find_network_by_record_id", usage=argparse.SUPPRESS
)
find_network_by_record_id_parser.add_argument("record_keys", nargs="+")
find_network_by_record_id_parser.add_argument("max_degrees", type=int)
find_network_by_record_id_parser.add_argument("build_out_degrees", type=int)
find_network_by_record_id_parser.add_argument("build_out_max_entities", type=int)
find_network_by_record_id_parser.add_argument("-f", "--flags", nargs="+", required=False)
find_path_by_entity_id_parser = self.subparsers.add_parser("find_path_by_entity_id", usage=argparse.SUPPRESS)
find_path_by_entity_id_parser.add_argument("start_entity_id", type=int)
find_path_by_entity_id_parser.add_argument("end_entity_id", type=int)
find_path_by_entity_id_parser.add_argument("max_degrees", type=int)
find_path_by_entity_id_parser.add_argument(
"-a", "--avoid_entity_ids", default=[], nargs="+", required=False, type=int
)
find_path_by_entity_id_parser.add_argument(
"-r",
"--required_data_sources",
default=[],
nargs="+",
required=False,
)
find_path_by_entity_id_parser.add_argument("-f", "--flags", nargs="+", required=False)
find_path_by_record_id_parser = self.subparsers.add_parser("find_path_by_record_id", usage=argparse.SUPPRESS)
find_path_by_record_id_parser.add_argument("start_data_source_code")
find_path_by_record_id_parser.add_argument("start_record_id")
find_path_by_record_id_parser.add_argument("end_data_source_code")
find_path_by_record_id_parser.add_argument("end_record_id")
find_path_by_record_id_parser.add_argument("max_degrees", type=int)
find_path_by_record_id_parser.add_argument("-a", "--avoid_record_keys", default=[], nargs="+", required=False)
find_path_by_record_id_parser.add_argument(
"-r", "--required_data_sources", default=[], nargs="+", required=False
)
find_path_by_record_id_parser.add_argument("-f", "--flags", nargs="+", required=False)
get_entity_by_entity_id_parser = self.subparsers.add_parser("get_entity_by_entity_id", usage=argparse.SUPPRESS)
get_entity_by_entity_id_parser.add_argument("entity_id", type=int)
get_entity_by_entity_id_parser.add_argument("-f", "--flags", nargs="+", required=False)
get_entity_by_record_id_parser = self.subparsers.add_parser("get_entity_by_record_id", usage=argparse.SUPPRESS)
get_entity_by_record_id_parser.add_argument("data_source_code")
get_entity_by_record_id_parser.add_argument("record_id")
get_entity_by_record_id_parser.add_argument("-f", "--flags", nargs="+", required=False)
get_record_parser = self.subparsers.add_parser("get_record", usage=argparse.SUPPRESS)
get_record_parser.add_argument("data_source_code")
get_record_parser.add_argument("record_id")
get_record_parser.add_argument("-f", "--flags", nargs="+", required=False)
get_record_preview_parser = self.subparsers.add_parser("get_record_preview", usage=argparse.SUPPRESS)
get_record_preview_parser.add_argument("record_definition")
get_record_preview_parser.add_argument("-f", "--flags", nargs="+", required=False)
get_virtual_entity_by_record_id_parser = self.subparsers.add_parser(
"get_virtual_entity_by_record_id", usage=argparse.SUPPRESS
)
get_virtual_entity_by_record_id_parser.add_argument("record_keys", nargs="+")
get_virtual_entity_by_record_id_parser.add_argument("-f", "--flags", nargs="+", required=False)
how_entity_by_entity_id_parser = self.subparsers.add_parser("how_entity_by_entity_id", usage=argparse.SUPPRESS)
how_entity_by_entity_id_parser.add_argument("entity_id", type=int)
how_entity_by_entity_id_parser.add_argument("-f", "--flags", nargs="+", required=False)
process_redo_record_parser = self.subparsers.add_parser("process_redo_record", usage=argparse.SUPPRESS)
process_redo_record_parser.add_argument("redo_record")
process_redo_record_parser.add_argument("-f", "--flags", nargs="+", required=False)
reevaluate_entity_parser = self.subparsers.add_parser("reevaluate_entity", usage=argparse.SUPPRESS)
reevaluate_entity_parser.add_argument("entity_id", type=int)
reevaluate_entity_parser.add_argument("-f", "--flags", nargs="+", required=False)
reevaluate_record_parser = self.subparsers.add_parser("reevaluate_record", usage=argparse.SUPPRESS)
reevaluate_record_parser.add_argument("data_source_code")
reevaluate_record_parser.add_argument("record_id")
reevaluate_record_parser.add_argument("-f", "--flags", nargs="+", required=False)
search_by_attributes_parser = self.subparsers.add_parser("search_by_attributes", usage=argparse.SUPPRESS)
search_by_attributes_parser.add_argument("attributes")
search_by_attributes_parser.add_argument("search_profile", default="SEARCH", nargs="?", type=str.upper)
search_by_attributes_parser.add_argument("-f", "--flags", nargs="+", required=False)
why_entities_parser = self.subparsers.add_parser("why_entities", usage=argparse.SUPPRESS)
why_entities_parser.add_argument("entity_id_1", type=int)
why_entities_parser.add_argument("entity_id_2", type=int)
why_entities_parser.add_argument("-f", "--flags", nargs="+", required=False)
why_record_in_entity_parser = self.subparsers.add_parser("why_record_in_entity", usage=argparse.SUPPRESS)
why_record_in_entity_parser.add_argument("data_source_code")
why_record_in_entity_parser.add_argument("record_id")
why_record_in_entity_parser.add_argument("-f", "--flags", nargs="+", required=False)
why_records_parser = self.subparsers.add_parser("why_records", usage=argparse.SUPPRESS)
why_records_parser.add_argument("data_source_code_1")
why_records_parser.add_argument("record_id_1")
why_records_parser.add_argument("data_source_code_2")
why_records_parser.add_argument("record_id_2")
why_records_parser.add_argument("-f", "--flags", nargs="+", required=False)
why_search_parser = self.subparsers.add_parser("why_search", usage=argparse.SUPPRESS)
why_search_parser.add_argument("attributes")
why_search_parser.add_argument("entity_id", type=int)
why_search_parser.add_argument("search_profile", default="SEARCH", nargs="?", type=str.upper)
why_search_parser.add_argument("-f", "--flags", nargs="+", required=False)
# Utility parsers
response_to_file_parser = self.subparsers.add_parser("response_to_file", usage=argparse.SUPPRESS)
response_to_file_parser.add_argument("file_path")
response_to_file_parser.add_argument(
"-a", "--append", action="store_true", default=False, dest="append_to_file", required=False
)
response_to_file_parser.add_argument(
"-c", "--command", action="store_true", default=False, dest="add_command", required=False
)
set_theme_parser = self.subparsers.add_parser("set_theme", usage=argparse.SUPPRESS)
set_theme_parser.add_argument("theme", choices=self.themes, nargs=1)
def get_config_attr_codes(self) -> List[str]:
try:
config_id = self.sz_engine.get_active_config_id()
sz_config = self.sz_configmgr.create_config_from_config_id(config_id)
config_json = json.loads(sz_config.export())
cfg_attr = config_json["G2_CONFIG"]["CFG_ATTR"]
attr_codes = [attr["ATTR_CODE"] for attr in cfg_attr if attr["INTERNAL"].lower() == "no"]
except (SzError, json.JSONDecodeError):
attr_codes = []
return attr_codes
# Call helper function to format and print command responses with constant values
def output_response(self, response: Union[int, str], color: str = "") -> str:
formatted_response: str = print_response(
response,
self.per_cmd_config["format_json"], # type: ignore[arg-type]
self.per_cmd_config["scroll_output"], # type: ignore[arg-type]
self.per_cmd_config["color_output"], # type: ignore[arg-type]
color=color,
)
return formatted_response
# -------------------------------------------------------------------------
# Cmd module methods
# -------------------------------------------------------------------------
# Override function from cmd module to make command completion case-insensitive
def completenames(self, text: str, *ignored: Any) -> List[str]:
do_text = "do_" + text
return [a[3:] for a in self.get_names() if a.lower().startswith(do_text.lower())]
def do_exit(self, _) -> bool: # type: ignore[no-untyped-def]
self.do_quit(_)
return True
@staticmethod
def do_quit(_) -> bool: # type: ignore[no-untyped-def] # pylint: disable=unused-argument
return True
def do_shell(self, line: str) -> None:
do_shell(self, line)
# Handle unknown commands
def default(self, line: str) -> None:
print_warning("Unknown command, type help or ?")
# Do nothing if line is empty
def emptyline(self) -> bool:
return False
# Override in cmd module to return methods for autocomplete and help
# ignoring any hidden commands
def get_names(self, include_hidden: bool = False) -> List[str]:
if not include_hidden:
return [n for n in dir(self.__class__) if n not in self.__hidden_cmds]
return list(dir(self.__class__))
def postcmd(self, stop: bool, line: str) -> bool:
# If do_set() turned on engine verbose logging, exit and reinitialize everything
if self.debug_reinit["reinitialize"]:
del self.sz_factory
return True
# Update last_command
if line and not line.startswith("!") and line.split()[0] not in CMDS_NOT_TO_SET_LAST_COMMAND:
self.last_command = self.remove_per_cmd_settings(line)
# Default configuration ID was changed by set_default_config_id or replace_default_config_id, sz_command
# doesn't modify the configuration so reinitialize. Update attributes from the new default configuration
# for auto-completion
if self.reinitialize:
print_info("Default configuration ID has changed, reinitializing...", info_prefix=False)
try:
config_id = self.sz_configmgr.get_default_config_id()
self.sz_factory.reinitialize(config_id)
self.reinitialize = False
except SzError as err:
print_error(err)
sys.exit(1)
self.attrs = self.get_config_attr_codes()
return cmd.Cmd.postcmd(self, stop, line)
def preloop(self) -> None:
# Setup history file use if settings are enabled
if self.config["history_file"]:
self.enable_history()
if self.debug_reinit["prior_instance_reinitialized"]:
print_response("Senzing engines were reinitialized due to a configuration change", color="success")
else:
print_info(f"Type help or ? for help", info_prefix=False)
# -------------------------------------------------------------------------
# Non-interactive input methods
# -------------------------------------------------------------------------
def commands_from_cli(self, commands: List[List[str]]) -> None:
"""
Run command(s) from the command line, here could be multiple commands and associated arguments in
commands[]. Command formatters (jsonl, json, etc) are permitted and are handled by sz_cmds_decorator
"""
number_of_commands = len(commands)
for each_cmd in commands:
requested_cmd = each_cmd[0]
# Build a new list without the requested command resulting in any arguments for the command
# Due to the way argparse builds the list with the -C argument, also repr() a list item (command argument)
# if it looks like JSON otherwise the single quotes around the JSON are lost and characters such as space
# in the JSON string break parsing in the do_* methods
requested_args = [
repr(i) if i.strip().startswith("{") and i.strip().endswith("}") else i
for i in each_cmd
if i != requested_cmd
]
# Turn the arguments back into a single string for further parsing and call the requested command
try:
if number_of_commands > 1:
print(f"\n----- {' '.join(each_cmd)} -----")
cmd_args = " ".join(requested_args)
self.onecmd(f"{requested_cmd} {cmd_args}")
except (ValueError, TypeError) as err:
print_error(f"Problem with command: {err}")
def commands_from_file(self, file_name: str) -> None:
"""
Read commands from a file and call the matching commands. Command formatters (jsonl, json, etc) are
permitted and are handled by sz_cmds_decorator
"""
try:
with open(file_name, encoding="utf-8") as cmds_file:
for each_cmd in cmds_file:
each_cmd = each_cmd.strip()
# Skip blank lines and comment prefixes
if not each_cmd or each_cmd[0:1] in ("#", "-", "/"):
continue
(requested_cmd, *requested_args) = each_cmd.split()
try:
cmd_args = " ".join(requested_args)
print(f"\n----- {each_cmd} -----")
self.onecmd(f"{requested_cmd} {cmd_args}")
except (ValueError, TypeError) as err:
print_error(f"Problem with command: {err}")
except OSError as err:
print_error(err)
# -------------------------------------------------------------------------
# Custom help
# -------------------------------------------------------------------------
def do_help(self, arg: str = "") -> None:
do_help(self, arg)
def help_all(self) -> None:
self.do_help()
@staticmethod
def help_overview() -> None:
print(
textwrap.dedent(
f"""
{colorize_str('This utility allows you to interact with the Senzing SDK', 'dim')}
{colorize_str('Help', 'highlight2')}
{colorize_str('- View help for a command:', 'dim')} help COMMAND
{colorize_str('- View all commands:', 'dim')} help all
{colorize_str('Tab Completion', 'highlight2')}
{colorize_str('- Tab completion is available for commands, files, engine flags, etc', 'dim')}
{colorize_str('- Hit tab on a blank line to see all commands', 'dim')}
{colorize_str('JSON Formatting', 'highlight2')}
{colorize_str('- Change JSON formatting by adding "json" or "jsonl" to the end of a command', 'dim')}
- get_entity_by_entity_id 1001 jsonl
{colorize_str('- Can be combined with color formatting options', 'dim')}
- get_entity_by_entity_id 1001 jsonl nocolor
{colorize_str('- Convert last response output between json and jsonl', 'dim')}
- response_reformat_json
{colorize_str('Color Formatting', 'highlight2')}
{colorize_str('- Add or remove colors from JSON formatting by adding "color", "colour", "nocolor" or "nocolour" to the end of a command', 'dim')}
- get_entity_by_entity_id 1001 color
{colorize_str('- Can be combined with JSON formatting options', 'dim')}
- get_entity_by_entity_id 1001 color jsonl
{colorize_str('Capturing Output', 'highlight2')}
{colorize_str('- Capture the last response output to a file or the clipboard', 'dim')}
- response_to_clipboard
- response_to_file /tmp/myoutput.json
{colorize_str('Configuration', 'highlight2')}
{colorize_str('- Configuration options are stored in a configuration file', 'dim')}
{colorize_str('- To see the current configuration or to change it use the set command', 'dim')}
- set
- set format_json off
{colorize_str('- The current configuration can be modified on a per command basis', 'dim')}
{colorize_str('- Per command configuration settings only affect that command', 'dim')}
{colorize_str('- See the output from the set command for descriptions of the settings', 'dim')}
{colorize_str('- The available per command settings are:', 'dim')}
- json
- jsonl
- color / colour
- nocolor / nocolour
- debug
- timer
- scroll
{colorize_str('- Examples:', 'dim')}
- get_entity_by_entity_id 1001 jsonl
- get_entity_by_entity_id 1001 jsonl nocolor
- get_entity_by_entity_id 1001 jsonl nocolor timer debug
{colorize_str('History', 'highlight2')}
{colorize_str('- Arrow keys to cycle through history of commands', 'dim')}
{colorize_str('- Ctrl-r can be used to search history', 'dim')}
{colorize_str('- Display history:', 'dim')} history
{colorize_str('Shell', 'highlight2')}
{colorize_str('- Run basic OS shell commands', 'dim')}
- ! ls
{colorize_str('Support', 'highlight2')}
{colorize_str('- Senzing Support:', 'dim')} {colorize_str('https://senzing.zendesk.com/hc/en-us/requests/new', 'highlight1,underline')}
{colorize_str('- Senzing Knowledge Center:', 'dim')} {colorize_str('https://senzing.zendesk.com/hc/en-us', 'highlight1,underline')}
{colorize_str('- SDK Docs:', 'dim')} {colorize_str('https://docs.senzing.com', 'highlight1,underline')}
"""
)
)
# -----------------------------------------------------------------------------
# szconfig commands
# -----------------------------------------------------------------------------
@do_methods_decorator
def do_get_template_config(self) -> None:
"""
Get a template configuration
Syntax:
get_template_config
"""
sz_config = self.sz_configmgr.create_config_from_template()
response = sz_config.export()
self.last_response = self.output_response(response)
# -----------------------------------------------------------------------------
# szconfigmanager commands
# -----------------------------------------------------------------------------
@do_methods_decorator
def do_get_config(self, **kwargs: Any) -> None:
"""
Get a configuration
Syntax:
get_config config_id
Example:
get_config 4180061352
Arguments:
config_id = Configuration identifier
Notes:
- Retrieve the active configuration identifier with get_active_config_id
- Retrieve a list of configurations and identifiers with get_config_registry"""
sz_config = self.sz_configmgr.create_config_from_config_id(kwargs["parsed_args"].config_id)
response = sz_config.export()
self.last_response = self.output_response(response)
@do_methods_decorator
def do_get_config_registry(self) -> None:
"""
Get details of current registered configurations
Syntax:
get_config_registry"""
response = self.sz_configmgr.get_config_registry()
self.last_response = self.output_response(response)
@do_methods_decorator
def do_get_default_config_id(self) -> None:
"""
Get the default configuration ID
Syntax:
get_default_config_id"""
response = self.sz_configmgr.get_default_config_id()
self.last_response = self.output_response(response, "success")
@do_methods_decorator
def do_replace_default_config_id(self, **kwargs: Any) -> None:
"""
Replace the default configuration ID
Syntax:
replace_default_config_id current_default_config_id new_default_config_id
Example:
replace_default_config_id 4180061352 2787925967
Arguments:
current_default_config_id = Configuration identifier
new_default_config_id = Configuration identifier
Notes:
- Retrieve a list of configurations and identifiers with get_config_registry"""
self.sz_configmgr.replace_default_config_id(
kwargs["parsed_args"].current_default_config_id,
kwargs["parsed_args"].new_default_config_id,
)
self.output_response("Default config ID replaced", "success")
self.reinitialize = True
@do_methods_decorator
def do_set_default_config_id(self, **kwargs: Any) -> None:
"""
Set the default configuration ID
Syntax:
set_default_config_id config_id
Example:
set_default_config_id 4180061352
Arguments:
config_id = Configuration identifier
Notes:
- Retrieve a list of configurations and identifiers with get_configList"""
self.sz_configmgr.set_default_config_id(kwargs["parsed_args"].config_id)
self.output_response("Default config ID set", "success")
self.reinitialize = True
# -----------------------------------------------------------------------------
# szdiagnostic commands
# -----------------------------------------------------------------------------
@do_methods_decorator
def do_check_repository_performance(self, **kwargs: Any) -> None:
"""
Run a performance check on the repository
Syntax:
check_repository_performance [seconds_to_run]
check_repository_performance
Arguments:
seconds_to_run = Time in seconds to run the check, default is 3"""
response = self.sz_diagnostic.check_repository_performance(kwargs["parsed_args"].seconds_to_run)
self.last_response = self.output_response(response)
@do_methods_decorator
def do_get_repository_info(self) -> None:
"""
Get repository information
Syntax:
get_repository_info"""
response = self.sz_diagnostic.get_repository_info()
self.last_response = self.output_response(response)
@do_methods_decorator
def do_get_feature(self, **kwargs: Any) -> None:
"""
Get feature information
Syntax:
get_feature feature_id
Examples:
get_feature 1
Arguments:
feature_id = Identifier of feature"""
response = self.sz_diagnostic.get_feature(kwargs["parsed_args"].featureID)
self.last_response = self.output_response(response)
@do_methods_decorator
def do_purge_repository(self, **kwargs: Any) -> None:
"""
Purge Senzing database of all data
Syntax:
purge_repository [--FORCEPURGE]
Example:
purge_repository
Arguments:
--FORCEPURGE = Don't prompt before purging. USE WITH CAUTION!
Caution:
- This deletes all data in the Senzing database!"""
purge_msg = colorize_output(
textwrap.dedent(
"""
********** WARNING **********
This will purge all currently loaded data from the senzing database!
Before proceeding, all instances of senzing (custom code, rest api, redoer, etc.) must be shut down.
********** WARNING **********
Are you sure you want to purge the Senzing database? Type YESPURGESENZING to purge: """
),
"warning",
)