oarepo-runtime 1.10.3__py3-none-any.whl → 2.0.0.dev3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. oarepo_runtime/__init__.py +24 -0
  2. oarepo_runtime/api.py +111 -0
  3. oarepo_runtime/cli/__init__.py +10 -21
  4. oarepo_runtime/cli/search.py +34 -0
  5. oarepo_runtime/config.py +86 -13
  6. oarepo_runtime/ext.py +64 -82
  7. oarepo_runtime/proxies.py +21 -5
  8. oarepo_runtime/records/__init__.py +11 -50
  9. oarepo_runtime/records/drafts.py +24 -18
  10. oarepo_runtime/records/mapping.py +84 -0
  11. oarepo_runtime/records/pid_providers.py +43 -7
  12. oarepo_runtime/records/systemfields/__init__.py +15 -33
  13. oarepo_runtime/records/systemfields/mapping.py +41 -24
  14. oarepo_runtime/records/systemfields/publication_status.py +59 -0
  15. oarepo_runtime/services/__init__.py +12 -0
  16. oarepo_runtime/services/config/__init__.py +15 -21
  17. oarepo_runtime/services/config/link_conditions.py +69 -75
  18. oarepo_runtime/services/config/permissions.py +62 -0
  19. oarepo_runtime/services/records/__init__.py +14 -1
  20. oarepo_runtime/services/records/links.py +21 -11
  21. oarepo_runtime/services/records/mapping.py +42 -0
  22. oarepo_runtime/services/results.py +98 -109
  23. oarepo_runtime/services/schema/__init__.py +12 -44
  24. oarepo_runtime/services/schema/i18n.py +47 -22
  25. oarepo_runtime/services/schema/i18n_ui.py +61 -24
  26. {oarepo_runtime-1.10.3.dist-info → oarepo_runtime-2.0.0.dev3.dist-info}/METADATA +9 -21
  27. oarepo_runtime-2.0.0.dev3.dist-info/RECORD +30 -0
  28. {oarepo_runtime-1.10.3.dist-info → oarepo_runtime-2.0.0.dev3.dist-info}/WHEEL +1 -2
  29. oarepo_runtime-2.0.0.dev3.dist-info/entry_points.txt +5 -0
  30. oarepo_runtime/cli/assets.py +0 -145
  31. oarepo_runtime/cli/base.py +0 -25
  32. oarepo_runtime/cli/cf.py +0 -15
  33. oarepo_runtime/cli/check.py +0 -167
  34. oarepo_runtime/cli/configuration.py +0 -51
  35. oarepo_runtime/cli/fixtures.py +0 -167
  36. oarepo_runtime/cli/index.py +0 -272
  37. oarepo_runtime/cli/permissions/__init__.py +0 -6
  38. oarepo_runtime/cli/permissions/base.py +0 -26
  39. oarepo_runtime/cli/permissions/evaluate.py +0 -63
  40. oarepo_runtime/cli/permissions/list.py +0 -239
  41. oarepo_runtime/cli/permissions/search.py +0 -121
  42. oarepo_runtime/cli/validate.py +0 -150
  43. oarepo_runtime/datastreams/__init__.py +0 -38
  44. oarepo_runtime/datastreams/asynchronous.py +0 -247
  45. oarepo_runtime/datastreams/catalogue.py +0 -150
  46. oarepo_runtime/datastreams/datastreams.py +0 -152
  47. oarepo_runtime/datastreams/errors.py +0 -54
  48. oarepo_runtime/datastreams/ext.py +0 -41
  49. oarepo_runtime/datastreams/fixtures.py +0 -265
  50. oarepo_runtime/datastreams/json.py +0 -4
  51. oarepo_runtime/datastreams/readers/__init__.py +0 -39
  52. oarepo_runtime/datastreams/readers/attachments.py +0 -51
  53. oarepo_runtime/datastreams/readers/excel.py +0 -123
  54. oarepo_runtime/datastreams/readers/json.py +0 -27
  55. oarepo_runtime/datastreams/readers/service.py +0 -54
  56. oarepo_runtime/datastreams/readers/yaml.py +0 -14
  57. oarepo_runtime/datastreams/semi_asynchronous.py +0 -91
  58. oarepo_runtime/datastreams/synchronous.py +0 -70
  59. oarepo_runtime/datastreams/transformers.py +0 -18
  60. oarepo_runtime/datastreams/types.py +0 -323
  61. oarepo_runtime/datastreams/utils.py +0 -131
  62. oarepo_runtime/datastreams/writers/__init__.py +0 -21
  63. oarepo_runtime/datastreams/writers/attachments_file.py +0 -92
  64. oarepo_runtime/datastreams/writers/attachments_service.py +0 -118
  65. oarepo_runtime/datastreams/writers/publish.py +0 -70
  66. oarepo_runtime/datastreams/writers/service.py +0 -175
  67. oarepo_runtime/datastreams/writers/utils.py +0 -30
  68. oarepo_runtime/datastreams/writers/validation_errors.py +0 -20
  69. oarepo_runtime/datastreams/writers/yaml.py +0 -56
  70. oarepo_runtime/ext_config.py +0 -67
  71. oarepo_runtime/i18n/__init__.py +0 -3
  72. oarepo_runtime/info/__init__.py +0 -0
  73. oarepo_runtime/info/check.py +0 -95
  74. oarepo_runtime/info/permissions/__init__.py +0 -0
  75. oarepo_runtime/info/permissions/debug.py +0 -191
  76. oarepo_runtime/info/views.py +0 -586
  77. oarepo_runtime/profile.py +0 -60
  78. oarepo_runtime/records/dumpers/__init__.py +0 -8
  79. oarepo_runtime/records/dumpers/edtf_interval.py +0 -38
  80. oarepo_runtime/records/dumpers/multilingual_dumper.py +0 -34
  81. oarepo_runtime/records/entity_resolvers/__init__.py +0 -13
  82. oarepo_runtime/records/entity_resolvers/proxies.py +0 -57
  83. oarepo_runtime/records/mappings/__init__.py +0 -0
  84. oarepo_runtime/records/mappings/rdm_parent_mapping.json +0 -483
  85. oarepo_runtime/records/owners/__init__.py +0 -3
  86. oarepo_runtime/records/owners/registry.py +0 -22
  87. oarepo_runtime/records/relations/__init__.py +0 -22
  88. oarepo_runtime/records/relations/base.py +0 -296
  89. oarepo_runtime/records/relations/internal.py +0 -46
  90. oarepo_runtime/records/relations/lookup.py +0 -28
  91. oarepo_runtime/records/relations/pid_relation.py +0 -102
  92. oarepo_runtime/records/systemfields/featured_file.py +0 -45
  93. oarepo_runtime/records/systemfields/has_draftcheck.py +0 -47
  94. oarepo_runtime/records/systemfields/icu.py +0 -371
  95. oarepo_runtime/records/systemfields/owner.py +0 -115
  96. oarepo_runtime/records/systemfields/record_status.py +0 -35
  97. oarepo_runtime/records/systemfields/selectors.py +0 -98
  98. oarepo_runtime/records/systemfields/synthetic.py +0 -130
  99. oarepo_runtime/resources/__init__.py +0 -4
  100. oarepo_runtime/resources/config.py +0 -12
  101. oarepo_runtime/resources/file_resource.py +0 -15
  102. oarepo_runtime/resources/json_serializer.py +0 -27
  103. oarepo_runtime/resources/localized_ui_json_serializer.py +0 -54
  104. oarepo_runtime/resources/resource.py +0 -53
  105. oarepo_runtime/resources/responses.py +0 -20
  106. oarepo_runtime/services/components.py +0 -429
  107. oarepo_runtime/services/config/draft_link.py +0 -23
  108. oarepo_runtime/services/config/permissions_presets.py +0 -174
  109. oarepo_runtime/services/config/service.py +0 -117
  110. oarepo_runtime/services/custom_fields/__init__.py +0 -80
  111. oarepo_runtime/services/custom_fields/mappings.py +0 -188
  112. oarepo_runtime/services/entity/__init__.py +0 -0
  113. oarepo_runtime/services/entity/config.py +0 -14
  114. oarepo_runtime/services/entity/schema.py +0 -9
  115. oarepo_runtime/services/entity/service.py +0 -48
  116. oarepo_runtime/services/expansions/__init__.py +0 -0
  117. oarepo_runtime/services/expansions/expandable_fields.py +0 -21
  118. oarepo_runtime/services/expansions/service.py +0 -4
  119. oarepo_runtime/services/facets/__init__.py +0 -33
  120. oarepo_runtime/services/facets/base.py +0 -12
  121. oarepo_runtime/services/facets/date.py +0 -72
  122. oarepo_runtime/services/facets/enum.py +0 -11
  123. oarepo_runtime/services/facets/facet_groups_names.py +0 -17
  124. oarepo_runtime/services/facets/max_facet.py +0 -13
  125. oarepo_runtime/services/facets/multilingual_facet.py +0 -33
  126. oarepo_runtime/services/facets/nested_facet.py +0 -32
  127. oarepo_runtime/services/facets/params.py +0 -192
  128. oarepo_runtime/services/facets/year_histogram.py +0 -200
  129. oarepo_runtime/services/files/__init__.py +0 -8
  130. oarepo_runtime/services/files/components.py +0 -62
  131. oarepo_runtime/services/files/service.py +0 -16
  132. oarepo_runtime/services/generators.py +0 -10
  133. oarepo_runtime/services/permissions/__init__.py +0 -3
  134. oarepo_runtime/services/permissions/generators.py +0 -103
  135. oarepo_runtime/services/relations/__init__.py +0 -0
  136. oarepo_runtime/services/relations/components.py +0 -15
  137. oarepo_runtime/services/relations/errors.py +0 -18
  138. oarepo_runtime/services/relations/mapping.py +0 -38
  139. oarepo_runtime/services/schema/cf.py +0 -13
  140. oarepo_runtime/services/schema/i18n_validation.py +0 -7
  141. oarepo_runtime/services/schema/marshmallow.py +0 -44
  142. oarepo_runtime/services/schema/marshmallow_to_json_schema.py +0 -72
  143. oarepo_runtime/services/schema/oneofschema.py +0 -192
  144. oarepo_runtime/services/schema/polymorphic.py +0 -21
  145. oarepo_runtime/services/schema/rdm.py +0 -146
  146. oarepo_runtime/services/schema/rdm_ui.py +0 -156
  147. oarepo_runtime/services/schema/ui.py +0 -251
  148. oarepo_runtime/services/schema/validation.py +0 -70
  149. oarepo_runtime/services/search.py +0 -282
  150. oarepo_runtime/services/service.py +0 -61
  151. oarepo_runtime/tasks.py +0 -6
  152. oarepo_runtime/translations/cs/LC_MESSAGES/messages.mo +0 -0
  153. oarepo_runtime/translations/cs/LC_MESSAGES/messages.po +0 -95
  154. oarepo_runtime/translations/default_translations.py +0 -6
  155. oarepo_runtime/translations/en/LC_MESSAGES/messages.mo +0 -0
  156. oarepo_runtime/translations/en/LC_MESSAGES/messages.po +0 -97
  157. oarepo_runtime/translations/messages.pot +0 -100
  158. oarepo_runtime/uow.py +0 -146
  159. oarepo_runtime/utils/__init__.py +0 -0
  160. oarepo_runtime/utils/functools.py +0 -37
  161. oarepo_runtime/utils/identity_utils.py +0 -35
  162. oarepo_runtime/utils/index.py +0 -11
  163. oarepo_runtime/utils/path.py +0 -97
  164. oarepo_runtime-1.10.3.dist-info/RECORD +0 -163
  165. oarepo_runtime-1.10.3.dist-info/entry_points.txt +0 -16
  166. oarepo_runtime-1.10.3.dist-info/top_level.txt +0 -2
  167. tests/marshmallow_to_json/__init__.py +0 -0
  168. tests/marshmallow_to_json/test_datacite_ui_schema.py +0 -1410
  169. tests/marshmallow_to_json/test_simple_schema.py +0 -52
  170. tests/pkg_data/__init__.py +0 -0
  171. {oarepo_runtime-1.10.3.dist-info → oarepo_runtime-2.0.0.dev3.dist-info}/licenses/LICENSE +0 -0
@@ -1,239 +0,0 @@
1
- from typing import get_type_hints
2
-
3
- import click
4
-
5
- from oarepo_runtime.info.permissions.debug import add_debugging
6
-
7
- from .base import permissions
8
-
9
-
10
- @permissions.command(name="list")
11
- @click.option("--workflow", "-w", help="Workflow name")
12
- @click.option("--community", "-c", help="Community name")
13
- @click.option("--service", "-s", help="Service name")
14
- def list_permissions(workflow, community, service):
15
- """List all permissions for a given workflow, community or service."""
16
- # intentionally import here to enable oarepo-runtime to be used
17
- # without oarepo-workflows and oarepo-communities
18
- from invenio_communities.communities.records.api import Community
19
- from invenio_communities.communities.records.models import CommunityMetadata
20
- from oarepo_workflows.proxies import current_oarepo_workflows
21
-
22
- if workflow:
23
- wf = current_oarepo_workflows.record_workflows[workflow]
24
- permission_policy = wf.permission_policy_cls
25
- elif community:
26
- community_db = CommunityMetadata.query.filter_by(slug=community).one()
27
- community_obj = Community(community_db.data, model=community_db)
28
- workflow = community_obj["custom_fields"].get("workflow", "default")
29
- wf = current_oarepo_workflows.record_workflows[workflow]
30
- permission_policy = wf.permission_policy_cls
31
- elif service:
32
- from invenio_records_resources.proxies import current_service_registry
33
-
34
- swc = current_service_registry.get(service)
35
- permission_policy = swc.config.permission_policy_cls
36
- else:
37
- raise click.UsageError(
38
- "You must specify either --workflow, --community or --service."
39
- )
40
-
41
- add_debugging()
42
-
43
- p = permission_policy("read")
44
-
45
- for action_name in dir(permission_policy):
46
- if not action_name.startswith("can_"):
47
- continue
48
- action_permission_generators = getattr(p, action_name)
49
- debugs = []
50
- for x in action_permission_generators:
51
- debugs.append(x.to_debug_dict())
52
-
53
- print("")
54
- print(f"## {action_name}")
55
- print(get_permission_documentation(permission_policy, action_name))
56
- for perm in debugs:
57
- print_permission_markdown(perm)
58
-
59
-
60
- def is_simple_dict(d):
61
- return all(isinstance(v, (str, int, float, bool)) for v in d.values())
62
-
63
-
64
- def format_simple_dict_values(d):
65
- # returns k=v, k=v, ...
66
- return ", ".join(f"{k}={v}" for k, v in d.items())
67
-
68
-
69
- def print_permission_markdown(p, level=0):
70
- for k, v in p.items():
71
- prologue = " " * level + f"- {k}"
72
- if v is None or v == {} or v == []:
73
- print(prologue)
74
- continue
75
- elif isinstance(v, dict):
76
- if is_simple_dict(v):
77
- print(f"{prologue}: {format_simple_dict_values(v)}")
78
- else:
79
- print(prologue)
80
- print_permission_markdown(v, level + 1)
81
- elif isinstance(v, list):
82
- print(prologue)
83
- for x in v:
84
- print_permission_markdown(x, level + 1)
85
- else:
86
- print(" " * (level + 1) + f"{v}")
87
-
88
-
89
- def get_permission_documentation(policy, permission_can_name):
90
- type_hints = get_type_hints(policy, include_extras=True)
91
- annotation = type_hints.get(permission_can_name)
92
- if annotation:
93
- for md in annotation.__metadata__:
94
- if isinstance(md, str):
95
- return md
96
- ret = default_permissions_documentation.get(permission_can_name, "")
97
- return "\n".join(x.strip() for x in ret.split("\n"))
98
-
99
-
100
- default_permissions_documentation = {
101
- # records
102
- "can_create": """
103
- Grants users the ability to create new records in the
104
- repository, often assigned to roles like submitters, owners, or curators.
105
- The result of this action is typically a draft record.
106
- """,
107
- "can_read": """
108
- Allows users to view or access records, with access
109
- possibly dependent on the record's state (e.g., draft or published) and the
110
- user's role.
111
- """,
112
- "can_read_deleted": """
113
- Permission to view or access records, including soft-deleted ones. This
114
- permission is used to filter search results. It should include an
115
- `IfRecordDeleted` permission generator, which grants access to deleted
116
- records to a subset of users (e.g., owners, curators, etc.). For
117
- `service.read`, this permission is applied when record is deleted and
118
- `include_deleted` is passed; otherwise, a `RecordDeletedException` is raised.
119
- """,
120
- "can_search": """
121
- Grants users the ability to search for records within the
122
- repository, typically available to all users. The search results are
123
- filtered based on the can_read_deleted permission for published records (/api/datasets)
124
- and the can_read_draft permission for draft records (/api/user/datasets).
125
- """,
126
- "can_update": """
127
- Grants users the ability to update or modify published records.
128
- In NRP repositories, this is normally disabled as updates are performed
129
- on draft records, which are then published.
130
- """,
131
- "can_delete": """
132
- Grants users the ability to delete records, often restricted
133
- to owners, curators, or specific roles, and dependent on the record's
134
- state (e.g., draft). For published records, the deletion is performed
135
- via a specialized request, not directly.
136
- """,
137
- "can_new_version": """
138
- Allows users to create a new version of a record. In NRP,
139
- this is not used directly but always via a request, which is mostly
140
- auto-approved.
141
- """,
142
- "can_edit": """
143
- Grants users the ability to modify the metadata of a record. In NRP, this
144
- is not used directly but always via a request, which is mostly auto-approved.
145
- """,
146
- "can_manage": """
147
- Grants users the ability to manage records. Currently it is used just
148
- for reindexing records with latest version first (reindex_latest_first)
149
- service call, not mapped to REST API.
150
- """,
151
- "can_manage_record_access": """
152
- Grants users the ability to manage record access.
153
- """,
154
- # draft records
155
- "can_read_draft": """
156
- Enables users to view or access draft records, typically equivalent to
157
- the general 'can_read' permission but specific to drafts.
158
- """,
159
- "can_delete_draft": """
160
- Allows users to delete draft records, typically equivalent to the general
161
- 'can_delete' permission but specific to drafts.
162
- """,
163
- "can_update_draft": """
164
- Allows users to update draft records. It is typically granted to record
165
- owner, but can be restricted by the record status (such as records submitted
166
- to review being locked).
167
- """,
168
- "can_publish": """
169
- Grants users the ability to publish records, making them publicly
170
- available or finalizing their state. In NRP repositories, this is
171
- not used directly but always via a request.
172
- """,
173
- # files
174
- "can_read_files": """
175
- Grants users the ability to view or access file metadata associated with records,
176
- with access dependent on the record's state and the user's role.
177
- """,
178
- "can_create_files": """
179
- Enables users to create new files within published records in the repository.
180
- Normally disabled as files are created in draft records and then published.
181
- """,
182
- "can_delete_files": """
183
- Enables users to delete files associated with published records in the repository.
184
- Normally disabled as files can not be deleted from published records.
185
- """,
186
- "can_update_files": """
187
- Enables users to update or modify files within published records in the repository.
188
- Normally disabled as files are updated in draft records and then published.
189
- """,
190
- "can_commit_files": """
191
- Allows users to finalize file upload to published records in the repository.
192
- Normally disabled as files are uploaded to draft records and then published.
193
- """,
194
- "can_get_content_files": """
195
- Allows users to access or retrieve the content of files on records published
196
- in the repository, with access depending on the record's state and the user's role.
197
- """,
198
- "can_manage_files": """
199
- Grants users the ability to manage files (that is, change if the files are
200
- required on the record or not).
201
- """,
202
- "can_read_deleted_files": """
203
- Allows users to view or access files associated with deleted records,
204
- often restricted to specific conditions.
205
- """,
206
- "can_set_content_files": """
207
- Enables users to upload files to published records. Normally disabled as files
208
- are uploaded to draft records and then published.
209
- """,
210
- # draft files
211
- "can_draft_read_files": """
212
- Allows users to view or access file metadata associated with draft records,
213
- typically equivalent to the general 'can_read_files' permission but specific
214
- to drafts.
215
- """,
216
- "can_draft_create_files": """
217
- Allows users to create files specifically for draft records.
218
- """,
219
- "can_draft_get_content_files": """
220
- Allows users to access or retrieve the content of files on draft records.
221
- """,
222
- "can_draft_set_content_files": """
223
- Allows users to upload files to draft records.
224
- """,
225
- "can_draft_commit_files": """
226
- Allows users to finalize file upload to draft records.
227
- """,
228
- "can_draft_update_files": """
229
- Allows users to update or modify files within draft records.
230
- """,
231
- "can_draft_delete_files": """
232
- Allows users to delete files associated with draft records.
233
- """,
234
- # misc
235
- "can_create_or_update_many": """
236
- Allows bulk creation or updating of multiple records or files.
237
- Not used at the moment.
238
- """,
239
- }
@@ -1,121 +0,0 @@
1
- import json
2
- import sys
3
-
4
- import click
5
- import yaml
6
- from invenio_records_resources.proxies import current_service_registry
7
-
8
- from oarepo_runtime.info.permissions.debug import add_debugging, merge_communities
9
-
10
- from .base import get_user_and_identity, permissions
11
-
12
-
13
- @permissions.command(name="search")
14
- @click.argument("user_id_or_email")
15
- @click.argument("service_name")
16
- @click.option("--explain/--no-explain", default=False)
17
- @click.option("--user/--published", "user_call", default=False)
18
- @click.option("--full-query/--query-filters", default=False)
19
- @click.option("--merge-communities", "do_merge_communities", is_flag=True)
20
- @click.option("--json/--yaml", "as_json", default=False)
21
- def search_permissions(
22
- user_id_or_email,
23
- service_name,
24
- explain,
25
- user_call,
26
- full_query,
27
- do_merge_communities,
28
- as_json,
29
- ):
30
- """Get search parameters for a given service."""
31
- try:
32
- service = current_service_registry.get(service_name)
33
- except KeyError:
34
- raise click.UsageError(
35
- f"Service {service_name} not found in {current_service_registry._services.keys()}"
36
- )
37
- user, identity = get_user_and_identity(user_id_or_email)
38
-
39
- permission_policy = service.config.permission_policy_cls
40
-
41
- add_debugging(print_search=explain, print_needs=False, print_excludes=False)
42
-
43
- if full_query:
44
- previous_search = service._search
45
-
46
- class NoExecute:
47
- def __init__(self, query):
48
- self.query = query
49
-
50
- def execute(self):
51
- return self.query
52
-
53
- def _patched_search(*args, **kwargs):
54
- ret = previous_search(*args, **kwargs)
55
- return NoExecute(ret)
56
-
57
- def _patched_result_list(self, identity, results, params, **kwargs):
58
- return results
59
-
60
- service._search = _patched_search
61
- service.result_list = _patched_result_list
62
-
63
- if user_call:
64
- ret = service.search_drafts(identity)
65
- else:
66
- ret = service.search(identity)
67
- ret = ret.to_dict()
68
- if do_merge_communities:
69
- ret = merge_communities(ret)
70
- ret = {
71
- "query": ret["query"],
72
- }
73
- dump_dict(ret, as_json)
74
- else:
75
-
76
- over = {}
77
- if explain:
78
- over["debug_identity"] = identity
79
- print("## Explaining search:")
80
-
81
- if user_call:
82
- p = permission_policy("read_draft", identity=identity, **over)
83
- else:
84
- p = permission_policy("read_deleted", identity=identity, **over)
85
- query_filters = p.query_filters
86
-
87
- print()
88
- print("## Query filters:")
89
- for qf in query_filters:
90
- dict_qf = qf.to_dict()
91
- if explain:
92
- dict_qf = merge_communities(dict_qf)
93
- dump_dict(dict_qf, as_json)
94
- print(json.dumps(dict_qf, indent=2))
95
-
96
-
97
- def merge_name(d):
98
- if isinstance(d, list):
99
- return [merge_name(x) for x in d]
100
- if isinstance(d, dict):
101
- ret = {}
102
- for k, v in d.items():
103
- v = merge_name(v)
104
- if isinstance(v, dict) and "_name" in v:
105
- _name = v.pop("_name")
106
- _name = _name.split("@")[0].strip()
107
- k = f"{k}[{_name}]"
108
- ret[k] = v
109
- return ret
110
- return d
111
-
112
-
113
- def dump_dict(d, as_json=False):
114
- if as_json:
115
- print(json.dumps(d, indent=2))
116
- else:
117
- yaml.safe_dump(
118
- merge_name(json.loads(json.dumps(d))),
119
- sys.stdout,
120
- default_flow_style=False,
121
- )
@@ -1,150 +0,0 @@
1
- import sys
2
- import traceback
3
-
4
- import click
5
- import yaml
6
- from flask.cli import with_appcontext
7
- from invenio_db import db
8
- from invenio_records import Record
9
- from invenio_records_resources.proxies import current_service_registry
10
- from tqdm import tqdm
11
-
12
- from .base import oarepo
13
-
14
- try:
15
- import json5 as json
16
- except ImportError:
17
- import json
18
-
19
- from io import StringIO
20
-
21
-
22
- class CheckOk(Exception):
23
- pass
24
-
25
-
26
- def dump_data(d):
27
- io = StringIO()
28
- yaml.safe_dump(d, io, allow_unicode=True)
29
- return io.getvalue()
30
-
31
-
32
- @oarepo.command(
33
- help="Validate a record. Takes one or two parameters - service name as "
34
- "the first one, file name or stdin with record data as the second"
35
- )
36
- @click.argument("service-name")
37
- @click.argument("record-file", required=False)
38
- @click.option("--community", help="Community name")
39
- @click.option("--verbose/--no-verbose", is_flag=True)
40
- @click.option("--with-stacktrace", is_flag=True)
41
- @click.option(
42
- "--fail-on-error",
43
- is_flag=True,
44
- help="Fail on the first error (for multiple records)",
45
- )
46
- @with_appcontext
47
- def validate(
48
- service_name, record_file, community, verbose, with_stacktrace, fail_on_error
49
- ):
50
- try:
51
- service = current_service_registry.get(service_name)
52
- except KeyError:
53
- click.secho(f"Service {service_name} not found. Existing services:")
54
- for existing in sorted(current_service_registry._services):
55
- click.secho(f" - {existing}")
56
- sys.exit(1)
57
-
58
- config = service.config
59
- schema = config.schema
60
-
61
- if not record_file:
62
- file_content = sys.stdin.read().strip()
63
- else:
64
- with open(record_file) as f:
65
- file_content = f.read()
66
-
67
- if file_content.startswith("{"):
68
- data = json.loads(file_content)
69
- else:
70
- data = list(yaml.safe_load_all(StringIO(file_content)))
71
-
72
- if not isinstance(data, list):
73
- data = [data]
74
-
75
- errors_count = 0
76
- for idx, d in enumerate(tqdm(data)):
77
- if community:
78
- d.setdefault("parent", {}).setdefault("communities", {})[
79
- "default"
80
- ] = community
81
- try:
82
- loaded = schema().load(d)
83
- except Exception as e:
84
- click.secho(
85
- f"Marshmallow validation of record idx {idx + 1} failed",
86
- fg="red",
87
- )
88
- click.secho(dump_data(d))
89
- click.secho(e)
90
- if with_stacktrace:
91
- traceback.print_exc()
92
- if fail_on_error:
93
- sys.exit(1)
94
- errors_count += 1
95
- continue
96
-
97
- if verbose:
98
- click.secho(
99
- f"Marshmallow validation of record idx {idx+1} has been successful",
100
- fg="green",
101
- )
102
-
103
- if hasattr(config, "draft_cls"):
104
- record_cls = config.draft_cls
105
- else:
106
- record_cls = config.record_cls
107
-
108
- # Run pre create extensions to check vocabularies
109
- try:
110
- with db.session.begin_nested():
111
-
112
- rec: Record = record_cls(
113
- loaded, model=record_cls.model_cls(id=None, data=data)
114
- )
115
- if record_cls.parent_record_cls:
116
- parent = record_cls.parent_record_cls(loaded["parent"])
117
- rec.parent = parent
118
-
119
- for e in rec._extensions:
120
- e.pre_commit(rec)
121
- raise CheckOk()
122
- except CheckOk:
123
- if verbose:
124
- click.secho(
125
- f"Pre-commit hook of record idx {idx+1} has been successful",
126
- fg="green",
127
- )
128
- except Exception as e:
129
- click.secho(
130
- f"Pre-commit validation of record idx {idx + 1} failed",
131
- fg="red",
132
- )
133
- click.secho(dump_data(d))
134
- click.secho(e)
135
- if with_stacktrace:
136
- traceback.print_exc()
137
- if fail_on_error:
138
- sys.exit(1)
139
- errors_count += 1
140
- continue
141
-
142
- if verbose:
143
- yaml.safe_dump(loaded, sys.stdout, allow_unicode=True)
144
-
145
- if errors_count:
146
- click.secho(f"Validation finished with {errors_count} errors", fg="red")
147
- sys.exit(1)
148
- else:
149
- click.secho("Validation finished successfully", fg="green")
150
- sys.exit(0)
@@ -1,38 +0,0 @@
1
- from .asynchronous import AsynchronousDataStream
2
- from .catalogue import DataStreamCatalogue
3
- from .datastreams import AbstractDataStream
4
- from .errors import (
5
- DataStreamCatalogueError,
6
- DataStreamError,
7
- ReaderError,
8
- TransformerError,
9
- WriterError,
10
- )
11
- from .json import JSON, JSONObject
12
- from .readers import BaseReader
13
- from .semi_asynchronous import SemiAsynchronousDataStream
14
- from .synchronous import SynchronousDataStream
15
- from .transformers import BaseTransformer
16
- from .types import DataStreamCallback, StreamBatch, StreamEntry
17
- from .writers import BaseWriter
18
-
19
- __all__ = [
20
- "JSONObject",
21
- "JSON",
22
- "StreamEntry",
23
- "DataStreamCatalogue",
24
- "BaseReader",
25
- "BaseWriter",
26
- "BaseTransformer",
27
- "DataStreamCatalogueError",
28
- "ReaderError",
29
- "WriterError",
30
- "TransformerError",
31
- "StreamBatch",
32
- "DataStreamError",
33
- "DataStreamCallback",
34
- "SynchronousDataStream",
35
- "AbstractDataStream",
36
- "AsynchronousDataStream",
37
- "SemiAsynchronousDataStream",
38
- ]