dcicutils 8.13.2__tar.gz → 8.13.3.1b1__tar.gz

Sign up to get free protection for your applications and to get access to all the features.
Files changed (81) hide show
  1. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/PKG-INFO +3 -3
  2. dcicutils-8.13.3.1b1/dcicutils/scripts/update_portal_object.py +430 -0
  3. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/scripts/view_portal_object.py +186 -130
  4. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/pyproject.toml +6 -5
  5. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/LICENSE.txt +0 -0
  6. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/README.rst +0 -0
  7. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/__init__.py +0 -0
  8. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/base.py +0 -0
  9. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/beanstalk_utils.py +0 -0
  10. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/bundle_utils.py +0 -0
  11. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/captured_output.py +0 -0
  12. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/cloudformation_utils.py +0 -0
  13. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/codebuild_utils.py +0 -0
  14. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/command_utils.py +0 -0
  15. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/common.py +0 -0
  16. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/contribution_scripts.py +0 -0
  17. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/contribution_utils.py +0 -0
  18. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/creds_utils.py +0 -0
  19. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/data_readers.py +0 -0
  20. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/data_utils.py +0 -0
  21. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/datetime_utils.py +0 -0
  22. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/deployment_utils.py +0 -0
  23. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/diff_utils.py +0 -0
  24. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/docker_utils.py +0 -0
  25. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/ecr_scripts.py +0 -0
  26. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/ecr_utils.py +0 -0
  27. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/ecs_utils.py +0 -0
  28. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/env_base.py +0 -0
  29. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/env_manager.py +0 -0
  30. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/env_scripts.py +0 -0
  31. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/env_utils.py +0 -0
  32. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/env_utils_legacy.py +0 -0
  33. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/es_utils.py +0 -0
  34. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/exceptions.py +0 -0
  35. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/ff_mocks.py +0 -0
  36. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/ff_utils.py +0 -0
  37. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/file_utils.py +0 -0
  38. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/function_cache_decorator.py +0 -0
  39. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/glacier_utils.py +0 -0
  40. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/hack_for_elasticsearch_numpy_usage.py +0 -0
  41. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/http_utils.py +0 -0
  42. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/jh_utils.py +0 -0
  43. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/kibana/dashboards.json +0 -0
  44. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/kibana/readme.md +0 -0
  45. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/lang_utils.py +0 -0
  46. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/license_policies/c4-infrastructure.jsonc +0 -0
  47. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/license_policies/c4-python-infrastructure.jsonc +0 -0
  48. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/license_policies/park-lab-common-server.jsonc +0 -0
  49. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/license_policies/park-lab-common.jsonc +0 -0
  50. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/license_policies/park-lab-gpl-pipeline.jsonc +0 -0
  51. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/license_policies/park-lab-pipeline.jsonc +0 -0
  52. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/license_utils.py +0 -0
  53. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/log_utils.py +0 -0
  54. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/misc_utils.py +0 -0
  55. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/obfuscation_utils.py +0 -0
  56. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/opensearch_utils.py +0 -0
  57. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/portal_object_utils.py +0 -0
  58. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/portal_utils.py +0 -0
  59. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/progress_bar.py +0 -0
  60. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/project_utils.py +0 -0
  61. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/qa_checkers.py +0 -0
  62. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/qa_utils.py +0 -0
  63. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/redis_tools.py +0 -0
  64. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/redis_utils.py +0 -0
  65. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/s3_utils.py +0 -0
  66. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/schema_utils.py +0 -0
  67. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/scripts/publish_to_pypi.py +0 -0
  68. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/scripts/run_license_checker.py +0 -0
  69. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/secrets_utils.py +0 -0
  70. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/sheet_utils.py +0 -0
  71. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/snapshot_utils.py +0 -0
  72. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/ssl_certificate_utils.py +0 -0
  73. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/structured_data.py +0 -0
  74. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/submitr/progress_constants.py +0 -0
  75. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/submitr/ref_lookup_strategy.py +0 -0
  76. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/task_utils.py +0 -0
  77. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/tmpfile_utils.py +0 -0
  78. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/trace_utils.py +0 -0
  79. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/validation_utils.py +0 -0
  80. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/variant_utils.py +0 -0
  81. {dcicutils-8.13.2 → dcicutils-8.13.3.1b1}/dcicutils/zip_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: dcicutils
3
- Version: 8.13.2
3
+ Version: 8.13.3.1b1
4
4
  Summary: Utility package for interacting with the 4DN Data Portal and other 4DN resources
5
5
  Home-page: https://github.com/4dn-dcic/utils
6
6
  License: MIT
@@ -26,8 +26,8 @@ Requires-Dist: PyJWT (>=2.6.0,<3.0.0)
26
26
  Requires-Dist: PyYAML (>=6.0.1,<7.0.0)
27
27
  Requires-Dist: appdirs (>=1.4.4,<2.0.0)
28
28
  Requires-Dist: aws-requests-auth (>=0.4.2,<1)
29
- Requires-Dist: boto3 (>=1.34.136,<2.0.0)
30
- Requires-Dist: botocore (>=1.34.136,<2.0.0)
29
+ Requires-Dist: boto3 (>=1.34.144,<2.0.0)
30
+ Requires-Dist: botocore (>=1.34.144,<2.0.0)
31
31
  Requires-Dist: chardet (>=5.2.0,<6.0.0)
32
32
  Requires-Dist: docker (>=4.4.4,<5.0.0)
33
33
  Requires-Dist: elasticsearch (==7.13.4)
@@ -0,0 +1,430 @@
1
+ # ------------------------------------------------------------------------------------------------------
2
+ # Command-line utility to update (post, patch, upsert) portal objects for SMaHT/CGAP/Fourfront.
3
+ # ------------------------------------------------------------------------------------------------------
4
+ # Example commands:
5
+ # update-portal-object --post file_format.json
6
+ # update-portal-object --upsert directory-with-schema-named-dot-json-files
7
+ # update-portal-object --patch file-not-named-for-schema-name.json --schema UnalignedReads
8
+ # --------------------------------------------------------------------------------------------------
9
+
10
+ import argparse
11
+ from functools import lru_cache
12
+ import glob
13
+ import io
14
+ import json
15
+ import os
16
+ import sys
17
+ from typing import Callable, List, Optional, Tuple, Union
18
+ from dcicutils.command_utils import yes_or_no
19
+ from dcicutils.common import ORCHESTRATED_APPS, APP_SMAHT
20
+ from dcicutils.ff_utils import delete_metadata, purge_metadata
21
+ from dcicutils.misc_utils import get_error_message, PRINT
22
+ from dcicutils.portal_utils import Portal as PortalFromUtils
23
+
24
+
25
+ class Portal(PortalFromUtils):
26
+
27
+ def delete_metadata(self, object_id: str) -> Optional[dict]:
28
+ if isinstance(object_id, str) and object_id and self.key:
29
+ return delete_metadata(obj_id=object_id, key=self.key)
30
+ return None
31
+
32
+ def purge_metadata(self, object_id: str) -> Optional[dict]:
33
+ if isinstance(object_id, str) and object_id and self.key:
34
+ return purge_metadata(obj_id=object_id, key=self.key)
35
+ return None
36
+
37
+
38
+ _DEFAULT_APP = "smaht"
39
+ _SMAHT_ENV_ENVIRON_NAME = "SMAHT_ENV"
40
+
41
+ # Schema properties to ignore (by default) for the view schema usage.
42
+ _SCHEMAS_IGNORE_PROPERTIES = [
43
+ "date_created",
44
+ "last_modified",
45
+ "principals_allowed",
46
+ "submitted_by",
47
+ "schema_version"
48
+ ]
49
+
50
+ _SCHEMA_ORDER = [ # See: smaht-portal/src/encoded/project/loadxl.py
51
+ "access_key",
52
+ "user",
53
+ "consortium",
54
+ "submission_center",
55
+ "file_format",
56
+ "quality_metric",
57
+ "output_file",
58
+ "reference_file",
59
+ "reference_genome",
60
+ "software",
61
+ "tracking_item",
62
+ "workflow",
63
+ "workflow_run",
64
+ "meta_workflow",
65
+ "meta_workflow_run",
66
+ "image",
67
+ "document",
68
+ "static_section",
69
+ "page",
70
+ "filter_set",
71
+ "higlass_view_config",
72
+ "ingestion_submission",
73
+ "ontology_term",
74
+ "protocol",
75
+ "donor",
76
+ "demographic",
77
+ "medical_history",
78
+ "diagnosis",
79
+ "exposure",
80
+ "family_history",
81
+ "medical_treatment",
82
+ "death_circumstances",
83
+ "tissue_collection",
84
+ "tissue",
85
+ "histology",
86
+ "cell_line",
87
+ "cell_culture",
88
+ "cell_culture_mixture",
89
+ "preparation_kit",
90
+ "treatment",
91
+ "sample_preparation",
92
+ "tissue_sample",
93
+ "cell_culture_sample",
94
+ "cell_sample",
95
+ "analyte",
96
+ "analyte_preparation",
97
+ "assay",
98
+ "library",
99
+ "library_preparation",
100
+ "sequencer",
101
+ "basecalling",
102
+ "sequencing",
103
+ "file_set",
104
+ "unaligned_reads",
105
+ "aligned_reads",
106
+ "variant_calls",
107
+ ]
108
+
109
+
110
+ def main():
111
+
112
+ parser = argparse.ArgumentParser(description="View Portal object.")
113
+ parser.add_argument("--env", "-e", type=str, required=False, default=None,
114
+ help=f"Environment name (key from ~/.smaht-keys.json).")
115
+ parser.add_argument("--app", type=str, required=False, default=None,
116
+ help=f"Application name (one of: smaht, cgap, fourfront).")
117
+ parser.add_argument("--schema", type=str, required=False, default=None,
118
+ help="Use named schema rather than infer from post/patch/upsert file name.")
119
+ parser.add_argument("--post", type=str, required=False, default=None, help="POST data.")
120
+ parser.add_argument("--patch", type=str, required=False, default=None, help="PATCH data.")
121
+ parser.add_argument("--upsert", type=str, required=False, default=None, help="Upsert data.")
122
+ parser.add_argument("--delete", type=str, required=False, default=None, help="Delete data.")
123
+ parser.add_argument("--purge", type=str, required=False, default=None, help="Purge data.")
124
+ parser.add_argument("--confirm", action="store_true", required=False, default=False, help="Confirm before action.")
125
+ parser.add_argument("--verbose", action="store_true", required=False, default=False, help="Verbose output.")
126
+ parser.add_argument("--quiet", action="store_true", required=False, default=False, help="Quiet output.")
127
+ parser.add_argument("--debug", action="store_true", required=False, default=False, help="Debugging output.")
128
+ args = parser.parse_args()
129
+
130
+ def usage(message: Optional[str] = None) -> None:
131
+ nonlocal parser
132
+ _print(message) if isinstance(message, str) else None
133
+ parser.print_help()
134
+ sys.exit(1)
135
+
136
+ if app := args.app:
137
+ if (app not in ORCHESTRATED_APPS) and ((app := app.lower()) not in ORCHESTRATED_APPS):
138
+ usage(f"ERROR: Unknown app name; must be one of: {' | '.join(ORCHESTRATED_APPS)}")
139
+ else:
140
+ app = APP_SMAHT
141
+
142
+ portal = _create_portal(env=args.env, app=app, verbose=args.verbose, debug=args.debug)
143
+
144
+ if explicit_schema_name := args.schema:
145
+ schema, explicit_schema_name = _get_schema(portal, explicit_schema_name)
146
+ if not schema:
147
+ usage(f"ERROR: Unknown schema name: {args.schema}")
148
+
149
+ if not (args.post or args.patch or args.upsert or args.delete or args.purge):
150
+ usage()
151
+
152
+ if args.post:
153
+ _post_or_patch_or_upsert(portal=portal,
154
+ file_or_directory=args.post,
155
+ explicit_schema_name=explicit_schema_name,
156
+ update_function=post_data,
157
+ update_action_name="POST",
158
+ confirm=args.confirm, verbose=args.verbose, quiet=args.quiet, debug=args.debug)
159
+ if args.patch:
160
+ _post_or_patch_or_upsert(portal=portal,
161
+ file_or_directory=args.patch,
162
+ explicit_schema_name=explicit_schema_name,
163
+ update_function=patch_data,
164
+ update_action_name="PATCH",
165
+ confirm=args.confirm, verbose=args.verbose, quiet=args.quiet, debug=args.debug)
166
+ if args.upsert:
167
+ _post_or_patch_or_upsert(portal=portal,
168
+ file_or_directory=args.upsert,
169
+ explicit_schema_name=explicit_schema_name,
170
+ update_function=upsert_data,
171
+ update_action_name="UPSERT",
172
+ confirm=args.confirm, verbose=args.verbose, quiet=args.quiet, debug=args.debug)
173
+
174
+ if args.delete:
175
+ if not portal.get_metadata(args.delete, raise_exception=False):
176
+ _print(f"Cannot find given object: {args.delete}")
177
+ sys.exit(1)
178
+ if yes_or_no(f"Do you really want to delete this item: {args.delete} ?"):
179
+ portal.delete_metadata(args.delete)
180
+
181
+ if args.purge:
182
+ if not portal.get_metadata(args.purge, raise_exception=False):
183
+ _print(f"Cannot find given object: {args.purge}")
184
+ sys.exit(1)
185
+ if yes_or_no(f"Do you really want to purge this item: {args.purge} ?"):
186
+ portal.delete_metadata(args.purge)
187
+ portal.purge_metadata(args.purge)
188
+
189
+
190
+ def _post_or_patch_or_upsert(portal: Portal, file_or_directory: str,
191
+ explicit_schema_name: str,
192
+ update_function: Callable, update_action_name: str,
193
+ confirm: bool = False, verbose: bool = False,
194
+ quiet: bool = False, debug: bool = False) -> None:
195
+
196
+ def is_schema_name_list(portal: Portal, keys: list) -> bool:
197
+ if isinstance(keys, list):
198
+ for key in keys:
199
+ if portal.get_schema(key) is None:
200
+ return False
201
+ return True
202
+ return False
203
+
204
+ def post_or_patch_or_upsert(portal: Portal, file: str, schema_name: Optional[str],
205
+ confirm: bool = False, verbose: bool = False,
206
+ quiet: bool = False, debug: bool = False) -> None:
207
+
208
+ nonlocal update_function, update_action_name
209
+ if not quiet:
210
+ _print(f"Processing {update_action_name} file: {file}")
211
+ if data := _read_json_from_file(file):
212
+ if isinstance(data, dict):
213
+ if isinstance(schema_name, str) and schema_name:
214
+ if debug:
215
+ _print(f"DEBUG: File ({file}) contains an object of type: {schema_name}")
216
+ update_function(portal, data, schema_name, confirm=confirm,
217
+ file=file, verbose=verbose, debug=debug)
218
+ elif is_schema_name_list(portal, list(data.keys())):
219
+ if debug:
220
+ _print(f"DEBUG: File ({file}) contains a dictionary of schema names.")
221
+ for schema_name in data:
222
+ if isinstance(schema_data := data[schema_name], list):
223
+ if debug:
224
+ _print(f"DEBUG: Processing {update_action_name}s for type: {schema_name}")
225
+ for index, item in enumerate(schema_data):
226
+ update_function(portal, item, schema_name, confirm=confirm,
227
+ file=file, index=index, verbose=verbose, debug=debug)
228
+ else:
229
+ _print(f"WARNING: File ({file}) contains schema item which is not a list: {schema_name}")
230
+ else:
231
+ _print(f"WARNING: File ({file}) contains unknown item type.")
232
+ elif isinstance(data, list):
233
+ if debug:
234
+ _print(f"DEBUG: File ({file}) contains a list of objects of type: {schema_name}")
235
+ for index, item in enumerate(data):
236
+ update_function(portal, item, schema_name, confirm=confirm,
237
+ file=file, index=index, verbose=verbose, debug=debug)
238
+ if debug:
239
+ _print(f"DEBUG: Processing {update_action_name} file done: {file}")
240
+
241
+ if os.path.isdir(file_or_directory):
242
+ if ((files := glob.glob(os.path.join(file_or_directory, "*.json"))) and
243
+ (files_and_schemas := _file_names_to_ordered_file_and_schema_names(portal, files))): # noqa
244
+ for file_and_schema in files_and_schemas:
245
+ if not (file := file_and_schema[0]):
246
+ continue
247
+ if not (schema_name := file_and_schema[1]) and not (schema_name := explicit_schema_name):
248
+ _print(f"ERROR: Schema cannot be inferred from file name and --schema not specified: {file}")
249
+ continue
250
+ post_or_patch_or_upsert(portal, file_and_schema[0], schema_name=schema_name,
251
+ confirm=confirm, quiet=quiet, verbose=verbose, debug=debug)
252
+ elif os.path.isfile(file := file_or_directory):
253
+ if ((schema_name := _get_schema_name_from_schema_named_json_file_name(portal, file)) or
254
+ (schema_name := explicit_schema_name)): # noqa
255
+ post_or_patch_or_upsert(portal, file, schema_name=schema_name,
256
+ confirm=confirm, quiet=quiet, verbose=verbose, debug=debug)
257
+ else:
258
+ post_or_patch_or_upsert(portal, file, schema_name=schema_name,
259
+ confirm=confirm, quiet=quiet, verbose=verbose, debug=debug)
260
+ # _print(f"ERROR: Schema cannot be inferred from file name and --schema not specified: {file}")
261
+ # return
262
+ else:
263
+ _print(f"ERROR: Cannot find file or directory: {file_or_directory}")
264
+
265
+
266
+ def post_data(portal: Portal, data: dict, schema_name: str, confirm: bool = False,
267
+ file: Optional[str] = None, index: int = 0,
268
+ verbose: bool = False, debug: bool = False) -> None:
269
+ if not (identifying_path := portal.get_identifying_path(data, portal_type=schema_name)):
270
+ if isinstance(file, str) and isinstance(index, int):
271
+ _print(f"ERROR: Item for POST has no identifying property: {file} (#{index + 1})")
272
+ else:
273
+ _print(f"ERROR: Item for POST has no identifying property.")
274
+ return
275
+ if portal.get_metadata(identifying_path, raise_exception=False):
276
+ _print(f"ERROR: Item for POST already exists: {identifying_path}")
277
+ return
278
+ if (confirm is True) and not yes_or_no(f"POST data for: {identifying_path} ?"):
279
+ return
280
+ if verbose:
281
+ _print(f"POST {schema_name} item: {identifying_path}")
282
+ try:
283
+ portal.post_metadata(schema_name, data)
284
+ if debug:
285
+ _print(f"DEBUG: POST {schema_name} item done: {identifying_path}")
286
+ except Exception as e:
287
+ _print(f"ERROR: Cannot POST {schema_name} item: {identifying_path}")
288
+ _print(get_error_message(e))
289
+ return
290
+
291
+
292
+ def patch_data(portal: Portal, data: dict, schema_name: str, confirm: bool = False,
293
+ file: Optional[str] = None, index: int = 0,
294
+ verbose: bool = False, debug: bool = False) -> None:
295
+ if not (identifying_path := portal.get_identifying_path(data, portal_type=schema_name)):
296
+ if isinstance(file, str) and isinstance(index, int):
297
+ _print(f"ERROR: Item for PATCH has no identifying property: {file} (#{index + 1})")
298
+ else:
299
+ _print(f"ERROR: Item for PATCH has no identifying property.")
300
+ return
301
+ if not portal.get_metadata(identifying_path, raise_exception=False):
302
+ _print(f"ERROR: Item for PATCH does not already exist: {identifying_path}")
303
+ return
304
+ if (confirm is True) and not yes_or_no(f"PATCH data for: {identifying_path}"):
305
+ return
306
+ if verbose:
307
+ _print(f"PATCH {schema_name} item: {identifying_path}")
308
+ try:
309
+ portal.patch_metadata(identifying_path, data)
310
+ if debug:
311
+ _print(f"DEBUG: PATCH {schema_name} item OK: {identifying_path}")
312
+ except Exception as e:
313
+ _print(f"ERROR: Cannot PATCH {schema_name} item: {identifying_path}")
314
+ _print(e)
315
+ return
316
+
317
+
318
+ def upsert_data(portal: Portal, data: dict, schema_name: str, confirm: bool = False,
319
+ file: Optional[str] = None, index: int = 0,
320
+ verbose: bool = False, debug: bool = False) -> None:
321
+ if not (identifying_path := portal.get_identifying_path(data, portal_type=schema_name)):
322
+ if isinstance(file, str) and isinstance(index, int):
323
+ _print(f"ERROR: Item for UPSERT has no identifying property: {file} (#{index + 1})")
324
+ else:
325
+ _print(f"ERROR: Item for UPSERT has no identifying property.")
326
+ return
327
+ exists = portal.get_metadata(identifying_path, raise_exception=False)
328
+ if ((confirm is True) and not yes_or_no(f"{'PATCH' if exists else 'POST'} data for: {identifying_path} ?")):
329
+ return
330
+ if verbose:
331
+ _print(f"{'PATCH' if exists else 'POST'} {schema_name} item: {identifying_path}")
332
+ try:
333
+ portal.post_metadata(schema_name, data) if not exists else portal.patch_metadata(identifying_path, data)
334
+ if debug:
335
+ _print(f"DEBUG: UPSERT {schema_name} item OK: {identifying_path}")
336
+ except Exception as e:
337
+ _print(f"ERROR: Cannot UPSERT {schema_name} item: {identifying_path}")
338
+ _print(e)
339
+ return
340
+
341
+
342
+ def _create_portal(env: Optional[str] = None, app: Optional[str] = None,
343
+ verbose: bool = False, debug: bool = False) -> Optional[Portal]:
344
+
345
+ env_from_environ = None
346
+ if not env and (app == APP_SMAHT):
347
+ if env := os.environ.get(_SMAHT_ENV_ENVIRON_NAME):
348
+ env_from_environ = True
349
+ if not (portal := Portal(env, app=app) if env or app else None):
350
+ return None
351
+ if verbose:
352
+ if (env := portal.env) or (env := os.environ(_SMAHT_ENV_ENVIRON_NAME)):
353
+ _print(f"Portal environment"
354
+ f"{f' (from {_SMAHT_ENV_ENVIRON_NAME})' if env_from_environ else ''}: {portal.env}")
355
+ if portal.keys_file:
356
+ _print(f"Portal keys file: {portal.keys_file}")
357
+ if portal.key_id:
358
+ _print(f"Portal key prefix: {portal.key_id[0:2]}******")
359
+ if portal.server:
360
+ _print(f"Portal server: {portal.server}")
361
+ return portal
362
+
363
+
364
+ def _read_json_from_file(file: str) -> Optional[dict]:
365
+ try:
366
+ if not os.path.exists(file):
367
+ return None
368
+ with io.open(file, "r") as f:
369
+ try:
370
+ return json.load(f)
371
+ except Exception:
372
+ _print(f"ERROR: Cannot load JSON from file: {file}")
373
+ return None
374
+ except Exception:
375
+ _print(f"ERROR: Cannot open file: {file}")
376
+ return None
377
+
378
+
379
+ def _file_names_to_ordered_file_and_schema_names(portal: Portal,
380
+ files: Union[List[str], str]) -> List[Tuple[str, Optional[str]]]:
381
+ results = []
382
+ if isinstance(files, str):
383
+ files = [files]
384
+ if not isinstance(files, list):
385
+ return results
386
+ for file in files:
387
+ if isinstance(file, str) and file:
388
+ results.append((file, _get_schema_name_from_schema_named_json_file_name(portal, file)))
389
+ ordered_results = []
390
+ for schema_name in _SCHEMA_ORDER:
391
+ schema_name = portal.schema_name(schema_name)
392
+ if result := next((item for item in results if item[1] == schema_name), None):
393
+ ordered_results.append(result)
394
+ results.remove(result)
395
+ ordered_results.extend(results) if results else None
396
+ return ordered_results
397
+
398
+
399
+ def _get_schema_name_from_schema_named_json_file_name(portal: Portal, value: str) -> Optional[str]:
400
+ try:
401
+ if not value.endswith(".json"):
402
+ return None
403
+ _, schema_name = _get_schema(portal, os.path.basename(value[:-5]))
404
+ return schema_name
405
+ except Exception:
406
+ return False
407
+
408
+
409
+ @lru_cache(maxsize=1)
410
+ def _get_schemas(portal: Portal) -> Optional[dict]:
411
+ return portal.get_schemas()
412
+
413
+
414
+ @lru_cache(maxsize=100)
415
+ def _get_schema(portal: Portal, name: str) -> Tuple[Optional[dict], Optional[str]]:
416
+ if portal and name and (name := name.replace("_", "").replace("-", "").strip().lower()):
417
+ if schemas := _get_schemas(portal):
418
+ for schema_name in schemas:
419
+ if schema_name.replace("_", "").replace("-", "").strip().lower() == name.lower():
420
+ return schemas[schema_name], schema_name
421
+ return None, None
422
+
423
+
424
+ def _print(*args, **kwargs) -> None:
425
+ PRINT(*args, **kwargs)
426
+ sys.stdout.flush()
427
+
428
+
429
+ if __name__ == "__main__":
430
+ main()