stepup-data 4.3.0a0__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.
- stepup/data/__init__.py +12 -0
- stepup/data/api.py +244 -0
- stepup/data/check_inventory.py +54 -0
- stepup/data/env_vars.py +19 -0
- stepup/data/inventory.py +515 -0
- stepup/data/make_inventory.py +290 -0
- stepup/data/pytest.py +73 -0
- stepup/data/sync_zenodo.py +2482 -0
- stepup/data/zenodo_vocabularies.yaml +9089 -0
- stepup/data/zip_inventory.py +124 -0
- stepup_data-4.3.0a0.dist-info/METADATA +93 -0
- stepup_data-4.3.0a0.dist-info/RECORD +16 -0
- stepup_data-4.3.0a0.dist-info/WHEEL +5 -0
- stepup_data-4.3.0a0.dist-info/entry_points.txt +8 -0
- stepup_data-4.3.0a0.dist-info/licenses/LICENSE +304 -0
- stepup_data-4.3.0a0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,2482 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024 Toon Verstraelen <Toon.Verstraelen@UGent.be>
|
|
2
|
+
# SPDX-License-Identifier: LGPL-3.0-or-later
|
|
3
|
+
"""Synchronization of local datasets with drafts on Zenodo.
|
|
4
|
+
|
|
5
|
+
This script synchronizes your local version of a dataset
|
|
6
|
+
with the (draft of) this dataset on Zenodo.
|
|
7
|
+
This simplifies your interaction with Zenodo to the following steps:
|
|
8
|
+
|
|
9
|
+
1. Prepare a personal token
|
|
10
|
+
2. Write metadata in a configuration file, in YAML, JSON or TOML format,
|
|
11
|
+
and a description of the dataset in a Markdown or HTML file.
|
|
12
|
+
3. Include this script in your workflow to automatically sync data.
|
|
13
|
+
4. Publish the dataset through the Zenodo web interface.
|
|
14
|
+
|
|
15
|
+
After publication, only metadata can be updated, not the actual files.
|
|
16
|
+
If you need to upload different files, change the version in the config file.
|
|
17
|
+
This will result in a new draft that you can publish when it is final.
|
|
18
|
+
|
|
19
|
+
This script offers a simplified interface to Zenodo.
|
|
20
|
+
It does not try to mirror all of Zenodo's API features.
|
|
21
|
+
|
|
22
|
+
This module talks to the InvenioRDM API of Zenodo, `/api/records`,
|
|
23
|
+
not to the legacy deposit API that https://developers.zenodo.org/ documents,
|
|
24
|
+
and not to the legacy `.zenodo.json` file that Zenodo reads for a GitHub release.
|
|
25
|
+
The three use different names for overlapping metadata,
|
|
26
|
+
which the documentation of `sd-sync-zenodo` explains in more detail.
|
|
27
|
+
Zenodo does not document the InvenioRDM API itself,
|
|
28
|
+
but InvenioRDM, the software that Zenodo runs, does:
|
|
29
|
+
|
|
30
|
+
- https://inveniordm.docs.cern.ch/reference/rest_api_index/
|
|
31
|
+
- https://inveniordm.docs.cern.ch/reference/metadata/
|
|
32
|
+
|
|
33
|
+
As observed in June 2025, the Zenodo deployment of this API was not fully stable,
|
|
34
|
+
and some of the features implemented in this module were deduced from the Zenodo web interface.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
import argparse
|
|
38
|
+
import contextlib
|
|
39
|
+
import datetime as dt
|
|
40
|
+
import functools
|
|
41
|
+
import hashlib
|
|
42
|
+
import ipaddress
|
|
43
|
+
import json
|
|
44
|
+
import os
|
|
45
|
+
import re
|
|
46
|
+
import sys
|
|
47
|
+
import tomllib
|
|
48
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
49
|
+
from importlib import resources
|
|
50
|
+
from typing import Any, get_args, get_origin
|
|
51
|
+
from urllib.parse import quote, urlparse
|
|
52
|
+
|
|
53
|
+
import attrs
|
|
54
|
+
import cattrs
|
|
55
|
+
import idutils
|
|
56
|
+
import requests
|
|
57
|
+
import yaml
|
|
58
|
+
from cattrs.errors import IterableValidationError, IterableValidationNote
|
|
59
|
+
from cattrs.gen import make_dict_structure_fn
|
|
60
|
+
from markdown_it import MarkdownIt
|
|
61
|
+
from rich.console import Console
|
|
62
|
+
from rich.json import JSON
|
|
63
|
+
|
|
64
|
+
from stepup.core.api import amend, is_offline
|
|
65
|
+
from stepup.core.exceptions import PathError
|
|
66
|
+
from stepup.core.path import Path
|
|
67
|
+
from stepup.core.utils import open_regular_file
|
|
68
|
+
from stepup.data.inventory import LinkRecord, open_inventory
|
|
69
|
+
|
|
70
|
+
__all__ = ("main",)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
CONSOLE = Console(soft_wrap=True, highlight=False)
|
|
74
|
+
|
|
75
|
+
REQUEST_TIMEOUT = 60.0
|
|
76
|
+
"""The number of seconds to wait for Zenodo, before a request is considered lost.
|
|
77
|
+
|
|
78
|
+
This bounds the wait for the connection and the wait for the next byte of the response,
|
|
79
|
+
not the time it takes to send the body of an upload,
|
|
80
|
+
so a large file may well take longer than this to transfer.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@attrs.define(frozen=True)
|
|
85
|
+
class UploadFile:
|
|
86
|
+
"""A file to upload to Zenodo, with its MD5 checksum."""
|
|
87
|
+
|
|
88
|
+
path: Path = attrs.field(converter=Path)
|
|
89
|
+
"""The local file, relative to the current working directory."""
|
|
90
|
+
|
|
91
|
+
md5: str = attrs.field()
|
|
92
|
+
"""The MD5 checksum of the file, as 32 lowercase hexadecimal digits."""
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def name(self) -> str:
|
|
96
|
+
"""The name of the file on Zenodo, which is the last component of the path."""
|
|
97
|
+
return self.path.name
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# Comparison is left to `Exception`, which compares by identity,
|
|
101
|
+
# because two errors that happen to carry the same message are not the same error.
|
|
102
|
+
@attrs.define(eq=False)
|
|
103
|
+
class RESTError(Exception):
|
|
104
|
+
"""Raised when a REST API call is not successful."""
|
|
105
|
+
|
|
106
|
+
message: str = attrs.field()
|
|
107
|
+
"""The complete diagnosis, naming the request and quoting the response of Zenodo."""
|
|
108
|
+
|
|
109
|
+
status_code: int | None = attrs.field(default=None)
|
|
110
|
+
"""The status code of the response, or `None` when the request never received one."""
|
|
111
|
+
|
|
112
|
+
def __str__(self) -> str:
|
|
113
|
+
return self.message
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class ZenodoError(Exception):
|
|
117
|
+
"""Raised when something must be corrected before the dataset can be synchronized.
|
|
118
|
+
|
|
119
|
+
The message is the complete diagnosis,
|
|
120
|
+
so `sd-sync-zenodo` reports it without a traceback and exits with a nonzero status.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@attrs.define
|
|
125
|
+
class RESTWrapper:
|
|
126
|
+
"""Wrapper for REST APIs that use JSON input (mostly) and output (always)."""
|
|
127
|
+
|
|
128
|
+
endpoint: str = attrs.field()
|
|
129
|
+
headers: dict[str, str] = attrs.field()
|
|
130
|
+
verbose: bool = attrs.field(default=False)
|
|
131
|
+
|
|
132
|
+
def request(self, method: str, loc: str, **kwargs) -> Any:
|
|
133
|
+
"""Send a HTTP request and deserialize the response as JSON.
|
|
134
|
+
|
|
135
|
+
Parameters
|
|
136
|
+
----------
|
|
137
|
+
method
|
|
138
|
+
The HTTP method: GET, POST, PUT or DELETE.
|
|
139
|
+
loc
|
|
140
|
+
The address to be appended after the endpoint.
|
|
141
|
+
kwargs
|
|
142
|
+
Keyword arguments to pass on to the `requests.request` function.
|
|
143
|
+
Headers given here are merged into the ones stored in this wrapper.
|
|
144
|
+
The timeout defaults to `REQUEST_TIMEOUT` and can be overridden here.
|
|
145
|
+
|
|
146
|
+
Returns
|
|
147
|
+
-------
|
|
148
|
+
response_data
|
|
149
|
+
Deserialized JSON response data.
|
|
150
|
+
|
|
151
|
+
Raises
|
|
152
|
+
------
|
|
153
|
+
RESTError
|
|
154
|
+
When Zenodo does not accept the request or cannot be reached.
|
|
155
|
+
"""
|
|
156
|
+
url = f"{self.endpoint}/{loc}"
|
|
157
|
+
if self.verbose:
|
|
158
|
+
CONSOLE.print(f"[b]{method} {url}[/b]")
|
|
159
|
+
if "json" in kwargs:
|
|
160
|
+
CONSOLE.print("[b]REQUEST[/b]")
|
|
161
|
+
CONSOLE.print(JSON.from_data(kwargs["json"]))
|
|
162
|
+
headers = self.headers | kwargs.pop("headers", {})
|
|
163
|
+
kwargs.setdefault("timeout", REQUEST_TIMEOUT)
|
|
164
|
+
try:
|
|
165
|
+
res = requests.request(method, url, headers=headers, **kwargs)
|
|
166
|
+
except requests.RequestException as exc:
|
|
167
|
+
# A request that never reaches Zenodo, or whose response never arrives,
|
|
168
|
+
# is reported like a refused one, so the caller has a single error to handle.
|
|
169
|
+
raise RESTError(f"Failed {method} {url}: {exc}") from exc
|
|
170
|
+
if not res.ok:
|
|
171
|
+
# The body is passed on as it arrived, because an error is not always JSON.
|
|
172
|
+
# A gateway between here and Zenodo may answer with an HTML page instead.
|
|
173
|
+
raise RESTError(
|
|
174
|
+
f"Failed {method} {url}: {res.status_code}\n{res.text}", res.status_code
|
|
175
|
+
)
|
|
176
|
+
data = None if len(res.text) == 0 else res.json()
|
|
177
|
+
if self.verbose:
|
|
178
|
+
CONSOLE.print("[b]RESPONSE[/b]")
|
|
179
|
+
CONSOLE.print(JSON.from_data(data))
|
|
180
|
+
CONSOLE.print()
|
|
181
|
+
return data
|
|
182
|
+
|
|
183
|
+
def get(self, loc: str, **kwargs):
|
|
184
|
+
"""Send a GET HTTP request. See `request` method for details."""
|
|
185
|
+
return self.request("GET", loc, **kwargs)
|
|
186
|
+
|
|
187
|
+
def post(self, loc: str, **kwargs):
|
|
188
|
+
"""Send a POST HTTP request. See `request` method for details."""
|
|
189
|
+
return self.request("POST", loc, **kwargs)
|
|
190
|
+
|
|
191
|
+
def put(self, loc: str, **kwargs):
|
|
192
|
+
"""Send a PUT HTTP request. See `request` method for details."""
|
|
193
|
+
return self.request("PUT", loc, **kwargs)
|
|
194
|
+
|
|
195
|
+
def delete(self, loc: str, **kwargs):
|
|
196
|
+
"""Send a DELETE HTTP request. See `request` method for details."""
|
|
197
|
+
return self.request("DELETE", loc, **kwargs)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
VOCABULARIES_FILENAME = "zenodo_vocabularies.yaml"
|
|
201
|
+
"""Data file holding the controlled vocabularies of Zenodo.
|
|
202
|
+
|
|
203
|
+
It is generated by `tools/update_zenodo_vocabularies.py` in the source repository.
|
|
204
|
+
"""
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@functools.cache
|
|
208
|
+
def _load_vocabularies() -> dict[str, frozenset[str]]:
|
|
209
|
+
"""Load the controlled vocabularies of Zenodo.
|
|
210
|
+
|
|
211
|
+
Returns
|
|
212
|
+
-------
|
|
213
|
+
vocabularies
|
|
214
|
+
The identifiers Zenodo accepts, for each vocabulary name in its API.
|
|
215
|
+
The keys of the data file that start with an underscore are left out,
|
|
216
|
+
because they hold bookkeeping of the refresh instead of a vocabulary.
|
|
217
|
+
"""
|
|
218
|
+
text = resources.files(__package__).joinpath(VOCABULARIES_FILENAME).read_text(encoding="utf-8")
|
|
219
|
+
return {
|
|
220
|
+
name: frozenset(ids)
|
|
221
|
+
for name, ids in yaml.safe_load(text).items()
|
|
222
|
+
if not name.startswith("_")
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _in_vocabulary(name: str) -> Callable[[Any, attrs.Attribute, str], None]:
|
|
227
|
+
"""Create a validator for an identifier taken from a controlled vocabulary of Zenodo.
|
|
228
|
+
|
|
229
|
+
Parameters
|
|
230
|
+
----------
|
|
231
|
+
name
|
|
232
|
+
The name of the vocabulary in Zenodo's API, e.g. `code:developmentStatus`.
|
|
233
|
+
|
|
234
|
+
Returns
|
|
235
|
+
-------
|
|
236
|
+
validator
|
|
237
|
+
An attrs validator rejecting identifiers outside of the vocabulary.
|
|
238
|
+
"""
|
|
239
|
+
|
|
240
|
+
def validate(instance, attribute, value):
|
|
241
|
+
if value not in _load_vocabularies()[name]:
|
|
242
|
+
raise ValueError(
|
|
243
|
+
f"Invalid identifier for '{attribute.name}': {value!r}. "
|
|
244
|
+
f"Zenodo takes it from the {name} vocabulary and matches it case-sensitively. "
|
|
245
|
+
f"See https://zenodo.org/api/vocabularies/{name} for the valid identifiers."
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
return validate
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
# See https://github.com/inveniosoftware/invenio-rdm-records/blob/master/invenio_rdm_records/config.py
|
|
252
|
+
IDENTIFIER_SCHEMES = {
|
|
253
|
+
"ark": idutils.is_ark,
|
|
254
|
+
"arxiv": idutils.is_arxiv,
|
|
255
|
+
"ads": idutils.is_ads,
|
|
256
|
+
"crossreffunderid": lambda _: True,
|
|
257
|
+
"doi": idutils.is_doi,
|
|
258
|
+
"ean13": idutils.is_ean13,
|
|
259
|
+
"eissn": idutils.is_issn,
|
|
260
|
+
"grid": lambda _: True,
|
|
261
|
+
"handle": idutils.is_handle,
|
|
262
|
+
"igsn": lambda _: True,
|
|
263
|
+
"isbn": idutils.is_isbn,
|
|
264
|
+
"isni": idutils.is_isni,
|
|
265
|
+
"issn": idutils.is_issn,
|
|
266
|
+
"istc": idutils.is_istc,
|
|
267
|
+
"lissn": idutils.is_issn,
|
|
268
|
+
"lsid": idutils.is_lsid,
|
|
269
|
+
"pmid": idutils.is_pmid,
|
|
270
|
+
"purl": idutils.is_purl,
|
|
271
|
+
"upc": lambda _: True,
|
|
272
|
+
"url": idutils.is_url,
|
|
273
|
+
"urn": idutils.is_urn,
|
|
274
|
+
"w3id": lambda _: True,
|
|
275
|
+
"other": lambda _: True,
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _check_scheme(name: str, scheme: str):
|
|
280
|
+
"""Check the name of an identifier scheme.
|
|
281
|
+
|
|
282
|
+
Parameters
|
|
283
|
+
----------
|
|
284
|
+
name
|
|
285
|
+
The name of the attribute holding the scheme, used in the error message.
|
|
286
|
+
scheme
|
|
287
|
+
The scheme to check.
|
|
288
|
+
|
|
289
|
+
Raises
|
|
290
|
+
------
|
|
291
|
+
ValueError
|
|
292
|
+
When Zenodo does not know the scheme.
|
|
293
|
+
"""
|
|
294
|
+
if scheme not in IDENTIFIER_SCHEMES:
|
|
295
|
+
raise ValueError(
|
|
296
|
+
f"Unknown identifier scheme for '{name}': {scheme!r}. "
|
|
297
|
+
f"Zenodo reads one of: {', '.join(sorted(IDENTIFIER_SCHEMES))}."
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _check_identifier(scheme: str, identifier: str):
|
|
302
|
+
"""Check an identifier against the format of its scheme.
|
|
303
|
+
|
|
304
|
+
Parameters
|
|
305
|
+
----------
|
|
306
|
+
scheme
|
|
307
|
+
The scheme of the identifier, which Zenodo must know.
|
|
308
|
+
identifier
|
|
309
|
+
The identifier to check.
|
|
310
|
+
|
|
311
|
+
Raises
|
|
312
|
+
------
|
|
313
|
+
ValueError
|
|
314
|
+
When the identifier does not have the format of the scheme.
|
|
315
|
+
"""
|
|
316
|
+
if not IDENTIFIER_SCHEMES[scheme](identifier):
|
|
317
|
+
raise ValueError(
|
|
318
|
+
f"Invalid identifier for scheme {scheme}: {identifier!r}. "
|
|
319
|
+
"Please check the identifier format."
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _to_zenodo_object(**values: Any) -> dict[str, Any]:
|
|
324
|
+
"""Build a JSON object for Zenodo, leaving out the keys whose value is not set.
|
|
325
|
+
|
|
326
|
+
Parameters
|
|
327
|
+
----------
|
|
328
|
+
values
|
|
329
|
+
The candidate keys of the object, with the value of the corresponding attribute.
|
|
330
|
+
|
|
331
|
+
Returns
|
|
332
|
+
-------
|
|
333
|
+
object
|
|
334
|
+
The keys whose value is set, in the order in which they were given.
|
|
335
|
+
"""
|
|
336
|
+
return {key: value for key, value in values.items() if value is not None and value != []}
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
@attrs.define
|
|
340
|
+
class Organization:
|
|
341
|
+
"""A subset of InvenioRDM affiliation / funder."""
|
|
342
|
+
|
|
343
|
+
name: str | None = attrs.field(
|
|
344
|
+
default=None,
|
|
345
|
+
validator=attrs.validators.optional(attrs.validators.min_len(1)),
|
|
346
|
+
)
|
|
347
|
+
"""Name of the organization, e.g. a university, research institute or funding agency."""
|
|
348
|
+
|
|
349
|
+
ror: str | None = attrs.field(default=None)
|
|
350
|
+
"""The Research Organization Registry identifier."""
|
|
351
|
+
|
|
352
|
+
@ror.validator
|
|
353
|
+
def _validate_ror(self, attribute, value):
|
|
354
|
+
"""Validate the ROR identifiers."""
|
|
355
|
+
if not (value is None or idutils.is_ror(value)):
|
|
356
|
+
raise ValueError(
|
|
357
|
+
f"Invalid ROR identifier for '{attribute.name}': {value!r}. "
|
|
358
|
+
"Zenodo reads nine characters starting with a zero, e.g. '03yrm5c26'."
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
def __attrs_post_init__(self):
|
|
362
|
+
if not ((self.name is None) ^ (self.ror is None)):
|
|
363
|
+
raise ValueError("Exactly one of 'name' or 'ror' must be set for an organization.")
|
|
364
|
+
|
|
365
|
+
def to_zenodo(self) -> dict[str, Any]:
|
|
366
|
+
"""Convert the organization to a dictionary suitable for Zenodo."""
|
|
367
|
+
return {"name": self.name} if self.ror is None else {"id": self.ror}
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
CREATOR_IDENTIFIER_SCHEMES = ("orcid", "isni")
|
|
371
|
+
"""The identifier schemes that `sd-sync-zenodo` deposits for a creator."""
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
@attrs.define
|
|
375
|
+
class Creator:
|
|
376
|
+
"""A subset of InvenioRDM creator."""
|
|
377
|
+
|
|
378
|
+
family_name: str = attrs.field(validator=attrs.validators.min_len(1))
|
|
379
|
+
"""Family name.
|
|
380
|
+
|
|
381
|
+
Zenodo requires this, because creators are deposited as persons, not as organizations.
|
|
382
|
+
"""
|
|
383
|
+
|
|
384
|
+
given_name: str | None = attrs.field(default=None)
|
|
385
|
+
"""Given name."""
|
|
386
|
+
|
|
387
|
+
identifiers: dict[str, str] = attrs.field(factory=dict)
|
|
388
|
+
"""Identifiers of the creator, keyed by scheme.
|
|
389
|
+
|
|
390
|
+
The scheme is one of `CREATOR_IDENTIFIER_SCHEMES`.
|
|
391
|
+
The value is the identifier itself, without a URL prefix,
|
|
392
|
+
e.g. '0000-0001-9288-5608' instead of 'https://orcid.org/0000-0001-9288-5608'.
|
|
393
|
+
"""
|
|
394
|
+
|
|
395
|
+
@identifiers.validator
|
|
396
|
+
def _validate_identifiers(self, attribute, value):
|
|
397
|
+
"""Validate the identifiers."""
|
|
398
|
+
for scheme in value:
|
|
399
|
+
if scheme not in CREATOR_IDENTIFIER_SCHEMES:
|
|
400
|
+
raise ValueError(
|
|
401
|
+
f"Unknown identifier scheme for '{attribute.name}': {scheme!r}. "
|
|
402
|
+
f"Zenodo reads one of: {', '.join(CREATOR_IDENTIFIER_SCHEMES)}."
|
|
403
|
+
)
|
|
404
|
+
# `idutils` accepts both identifiers with a URL prefix, as observed with `idutils` 1.7.2,
|
|
405
|
+
# so the prefix is rejected explicitly.
|
|
406
|
+
orcid = value.get("orcid")
|
|
407
|
+
if orcid is not None and not (idutils.is_orcid(orcid) and not orcid.startswith("http")):
|
|
408
|
+
raise ValueError(
|
|
409
|
+
f"Invalid ORCID for '{attribute.name}': {orcid!r}. "
|
|
410
|
+
"Zenodo reads sixteen characters in groups of four, "
|
|
411
|
+
"ending in a check character and without a URL prefix, "
|
|
412
|
+
"e.g. '0000-0001-9288-5608'."
|
|
413
|
+
)
|
|
414
|
+
isni = value.get("isni")
|
|
415
|
+
if isni is not None and not (idutils.is_isni(isni) and not isni.startswith("http")):
|
|
416
|
+
raise ValueError(
|
|
417
|
+
f"Invalid ISNI for '{attribute.name}': {isni!r}. "
|
|
418
|
+
"Zenodo reads sixteen characters ending in a check character "
|
|
419
|
+
"and without a URL prefix, e.g. '0000 0001 6785 333X'."
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
affiliations: list[Organization] = attrs.field(factory=list)
|
|
423
|
+
"""The affiliation of the creator, e.g. a university or research institute."""
|
|
424
|
+
|
|
425
|
+
def to_zenodo(self) -> dict[str, Any]:
|
|
426
|
+
"""Convert the creator to a dictionary suitable for Zenodo."""
|
|
427
|
+
return _to_zenodo_object(
|
|
428
|
+
person_or_org=_to_zenodo_object(
|
|
429
|
+
type="personal",
|
|
430
|
+
family_name=self.family_name,
|
|
431
|
+
given_name=self.given_name,
|
|
432
|
+
identifiers=[
|
|
433
|
+
{"scheme": key, "identifier": value} for key, value in self.identifiers.items()
|
|
434
|
+
],
|
|
435
|
+
),
|
|
436
|
+
affiliations=[aff.to_zenodo() for aff in self.affiliations],
|
|
437
|
+
)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
@attrs.define
|
|
441
|
+
class Access:
|
|
442
|
+
"""A subset of InvenioRDM Access.
|
|
443
|
+
|
|
444
|
+
https://inveniordm.docs.cern.ch/reference/metadata/#access
|
|
445
|
+
|
|
446
|
+
The record itself is always public, because Zenodo does not allow restricted records.
|
|
447
|
+
"""
|
|
448
|
+
|
|
449
|
+
files: str = attrs.field(
|
|
450
|
+
default="public",
|
|
451
|
+
validator=attrs.validators.in_(["public", "restricted"]),
|
|
452
|
+
)
|
|
453
|
+
"""The access level of the files.
|
|
454
|
+
|
|
455
|
+
Public means that the files are visible to everyone.
|
|
456
|
+
"""
|
|
457
|
+
|
|
458
|
+
def to_zenodo(self) -> dict[str, str]:
|
|
459
|
+
"""Convert the access configuration to a dictionary suitable for Zenodo."""
|
|
460
|
+
return {
|
|
461
|
+
"record": "public",
|
|
462
|
+
"files": self.files,
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
@attrs.define
|
|
467
|
+
class Identifier:
|
|
468
|
+
"""An identifier of something Zenodo does not store as a record, e.g. an award."""
|
|
469
|
+
|
|
470
|
+
identifier: str = attrs.field()
|
|
471
|
+
"""The identifier itself, e.g. '10.5281/zenodo.1234567'."""
|
|
472
|
+
|
|
473
|
+
scheme: str | None = attrs.field(default=None)
|
|
474
|
+
"""The scheme of the identifier, e.g. 'doi' or 'url'.
|
|
475
|
+
|
|
476
|
+
Zenodo derives the scheme from the identifier when it is not given.
|
|
477
|
+
"""
|
|
478
|
+
|
|
479
|
+
@scheme.validator
|
|
480
|
+
def _validate_scheme(self, attribute, value):
|
|
481
|
+
"""Validate the scheme and the identifier it describes."""
|
|
482
|
+
if value is None:
|
|
483
|
+
return
|
|
484
|
+
_check_scheme(attribute.name, value)
|
|
485
|
+
_check_identifier(value, self.identifier)
|
|
486
|
+
|
|
487
|
+
def to_zenodo(self) -> dict[str, Any]:
|
|
488
|
+
"""Convert the identifier to a dictionary suitable for Zenodo."""
|
|
489
|
+
return _to_zenodo_object(scheme=self.scheme, identifier=self.identifier)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
@attrs.define
|
|
493
|
+
class Related:
|
|
494
|
+
"""A subset of InvenioRDM related identifier."""
|
|
495
|
+
|
|
496
|
+
scheme: str = attrs.field()
|
|
497
|
+
"""The scheme of the identifier, e.g. 'doi' or 'arxiv'."""
|
|
498
|
+
|
|
499
|
+
@scheme.validator
|
|
500
|
+
def _validate_scheme(self, attribute, value):
|
|
501
|
+
"""Validate the scheme."""
|
|
502
|
+
_check_scheme(attribute.name, value)
|
|
503
|
+
|
|
504
|
+
identifier: str = attrs.field()
|
|
505
|
+
"""The identifier itself, e.g. '10.5281/zenodo.1234567'."""
|
|
506
|
+
|
|
507
|
+
@identifier.validator
|
|
508
|
+
def _validate_identifier(self, attribute, value):
|
|
509
|
+
"""Validate the identifier."""
|
|
510
|
+
_check_identifier(self.scheme, value)
|
|
511
|
+
|
|
512
|
+
relation_type: str = attrs.field(validator=_in_vocabulary("relationtypes"))
|
|
513
|
+
"""How the record relates to the identified resource, e.g. 'issupplementto'."""
|
|
514
|
+
|
|
515
|
+
resource_type: str | None = attrs.field(
|
|
516
|
+
default=None,
|
|
517
|
+
validator=attrs.validators.optional(_in_vocabulary("resourcetypes")),
|
|
518
|
+
)
|
|
519
|
+
"""The kind of resource the identifier points to, e.g. 'publication-article'."""
|
|
520
|
+
|
|
521
|
+
def to_zenodo(self) -> dict[str, Any]:
|
|
522
|
+
"""Convert the related identifier to a dictionary suitable for Zenodo."""
|
|
523
|
+
result = {
|
|
524
|
+
"scheme": self.scheme,
|
|
525
|
+
"identifier": self.identifier,
|
|
526
|
+
"relation_type": {"id": self.relation_type},
|
|
527
|
+
}
|
|
528
|
+
if self.resource_type is not None:
|
|
529
|
+
result["resource_type"] = {"id": self.resource_type}
|
|
530
|
+
return result
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
@attrs.define
|
|
534
|
+
class Award:
|
|
535
|
+
"""A subset of InvenioRDM award information."""
|
|
536
|
+
|
|
537
|
+
id: str | None = attrs.field(default=None)
|
|
538
|
+
"""The award ID, e.g. '123456'."""
|
|
539
|
+
|
|
540
|
+
title: str | None = attrs.field(default=None)
|
|
541
|
+
"""The title of the award, e.g. 'Research Excellence Award'."""
|
|
542
|
+
|
|
543
|
+
number: str | None = attrs.field(default=None)
|
|
544
|
+
"""The award number, e.g. 'RE-123456'."""
|
|
545
|
+
|
|
546
|
+
identifiers: list[Identifier] = attrs.field(factory=list)
|
|
547
|
+
"""Identifiers of the award, e.g. its DOI or the URL of its description."""
|
|
548
|
+
|
|
549
|
+
def __attrs_post_init__(self):
|
|
550
|
+
if not ((self.id is None) ^ (self.title is None and self.number is None)):
|
|
551
|
+
raise ValueError(
|
|
552
|
+
"An award is described either by 'id', "
|
|
553
|
+
"or by 'title' and 'number', of which at least one must be given. "
|
|
554
|
+
"Zenodo fills in the title and the number of an award it already knows, "
|
|
555
|
+
"so free text next to an 'id' would be ignored."
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
def to_zenodo(self) -> dict[str, Any]:
|
|
559
|
+
"""Convert the award information to a dictionary suitable for Zenodo."""
|
|
560
|
+
return _to_zenodo_object(
|
|
561
|
+
id=self.id,
|
|
562
|
+
title=None if self.title is None else {"en": self.title},
|
|
563
|
+
number=self.number,
|
|
564
|
+
identifiers=[identifier.to_zenodo() for identifier in self.identifiers],
|
|
565
|
+
)
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
@attrs.define
|
|
569
|
+
class Funding:
|
|
570
|
+
"""A subset of InvenioRDM funding information."""
|
|
571
|
+
|
|
572
|
+
funder: Organization = attrs.field()
|
|
573
|
+
"""The funder of the project leading to the record, e.g. a research council or a foundation."""
|
|
574
|
+
|
|
575
|
+
award: Award = attrs.field()
|
|
576
|
+
"""The award associated with the funding, if any."""
|
|
577
|
+
|
|
578
|
+
def to_zenodo(self) -> dict[str, Any]:
|
|
579
|
+
"""Convert the funding information to a dictionary suitable for Zenodo."""
|
|
580
|
+
return {
|
|
581
|
+
"funder": self.funder.to_zenodo(),
|
|
582
|
+
"award": self.award.to_zenodo(),
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _convert_license(arg):
|
|
587
|
+
"""Lower case the license identifiers, which Zenodo takes from SPDX in lower case."""
|
|
588
|
+
return [lic.lower() for lic in arg]
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
@attrs.define
|
|
592
|
+
class Metadata:
|
|
593
|
+
"""A subset of InvenioRDM metadata.
|
|
594
|
+
|
|
595
|
+
https://inveniordm.docs.cern.ch/reference/metadata/#metadata
|
|
596
|
+
|
|
597
|
+
Zenodo requires `title`, `resource_type` and `creators`,
|
|
598
|
+
and enforces the length bounds checked below.
|
|
599
|
+
These requirements were read on 2026-08-30 from `MetadataSchema` in
|
|
600
|
+
`invenio_rdm_records/services/schemas/metadata.py`.
|
|
601
|
+
A deposit that violates them fails, so they are checked before contacting Zenodo.
|
|
602
|
+
"""
|
|
603
|
+
|
|
604
|
+
title: str = attrs.field(validator=attrs.validators.min_len(3))
|
|
605
|
+
|
|
606
|
+
version: str = attrs.field(
|
|
607
|
+
validator=[attrs.validators.min_len(1), attrs.validators.max_len(191)]
|
|
608
|
+
)
|
|
609
|
+
"""The version of the dataset, in any convention you like.
|
|
610
|
+
|
|
611
|
+
Zenodo stores this as free text and does not order the versions of a dataset by it,
|
|
612
|
+
so `sd-sync-zenodo` only tests it for equality with the versions published on Zenodo,
|
|
613
|
+
to decide whether a new version has to be created.
|
|
614
|
+
It must be non-empty, because it is the only thing identifying the local version.
|
|
615
|
+
"""
|
|
616
|
+
|
|
617
|
+
resource_type: str = attrs.field(validator=_in_vocabulary("resourcetypes"))
|
|
618
|
+
|
|
619
|
+
publisher: str = attrs.field(validator=attrs.validators.min_len(1))
|
|
620
|
+
"""The name under which the dataset is made available, e.g. `Zenodo`.
|
|
621
|
+
|
|
622
|
+
Zenodo accepts a draft without a publisher but refuses to publish it,
|
|
623
|
+
because it needs one to register a DOI,
|
|
624
|
+
so a publisher is required here to fail before the record is created.
|
|
625
|
+
"""
|
|
626
|
+
|
|
627
|
+
creators: list[Creator] = attrs.field(validator=attrs.validators.min_len(1))
|
|
628
|
+
|
|
629
|
+
keywords: list[str] = attrs.field(factory=list)
|
|
630
|
+
"""A list of keywords to describe the dataset.
|
|
631
|
+
|
|
632
|
+
Zenodo has no keyword field and stores these as free text subjects.
|
|
633
|
+
"""
|
|
634
|
+
|
|
635
|
+
license: list[str] = attrs.field(
|
|
636
|
+
factory=list,
|
|
637
|
+
converter=_convert_license,
|
|
638
|
+
validator=attrs.validators.deep_iterable(_in_vocabulary("licenses")),
|
|
639
|
+
)
|
|
640
|
+
|
|
641
|
+
copyright: str | None = attrs.field(
|
|
642
|
+
default=None,
|
|
643
|
+
validator=attrs.validators.optional(attrs.validators.min_len(1)),
|
|
644
|
+
)
|
|
645
|
+
|
|
646
|
+
languages: list[str] = attrs.field(
|
|
647
|
+
factory=list, validator=attrs.validators.deep_iterable(_in_vocabulary("languages"))
|
|
648
|
+
)
|
|
649
|
+
"""A list of ISO 639-3 language codes, e.g. `eng` for English or `fra` for French."""
|
|
650
|
+
|
|
651
|
+
related: list[Related] = attrs.field(factory=list)
|
|
652
|
+
|
|
653
|
+
funding: list[Funding] = attrs.field(factory=list)
|
|
654
|
+
|
|
655
|
+
def to_zenodo(self, description: str, publication_date: str | None = None) -> dict[str, Any]:
|
|
656
|
+
"""Convert the metadata to a dictionary suitable for Zenodo.
|
|
657
|
+
|
|
658
|
+
Parameters
|
|
659
|
+
----------
|
|
660
|
+
description
|
|
661
|
+
The description of the dataset, in HTML.
|
|
662
|
+
publication_date
|
|
663
|
+
The publication date to send to Zenodo, in ISO format.
|
|
664
|
+
When `None`, today's date is used,
|
|
665
|
+
which is the only sensible guess for a record that is not published yet.
|
|
666
|
+
"""
|
|
667
|
+
if publication_date is None:
|
|
668
|
+
publication_date = dt.date.today().isoformat()
|
|
669
|
+
return _to_zenodo_object(
|
|
670
|
+
title=self.title,
|
|
671
|
+
version=self.version,
|
|
672
|
+
resource_type={"id": self.resource_type},
|
|
673
|
+
publisher=self.publisher,
|
|
674
|
+
subjects=[{"subject": keyword} for keyword in self.keywords],
|
|
675
|
+
rights=[{"id": lic} for lic in self.license],
|
|
676
|
+
copyright=self.copyright,
|
|
677
|
+
languages=[{"id": lang} for lang in self.languages],
|
|
678
|
+
description=description,
|
|
679
|
+
creators=[creator.to_zenodo() for creator in self.creators],
|
|
680
|
+
publication_date=publication_date,
|
|
681
|
+
related_identifiers=[rel.to_zenodo() for rel in self.related],
|
|
682
|
+
funding=[fund.to_zenodo() for fund in self.funding],
|
|
683
|
+
)
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
URL_SCHEMES = frozenset(["http", "https", "ftp", "ftps"])
|
|
687
|
+
"""The URL schemes that Zenodo accepts."""
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def _is_acceptable_host(host: str) -> bool:
|
|
691
|
+
"""Tell whether Zenodo accepts a host name."""
|
|
692
|
+
if host == "localhost":
|
|
693
|
+
return True
|
|
694
|
+
try:
|
|
695
|
+
ipaddress.ip_address(host)
|
|
696
|
+
except ValueError:
|
|
697
|
+
pass
|
|
698
|
+
else:
|
|
699
|
+
return True
|
|
700
|
+
labels = host.split(".")
|
|
701
|
+
return len(labels) > 1 and all(labels) and len(labels[-1]) >= 2
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
# Zenodo validates these URLs with `marshmallow.validate.URL`,
|
|
705
|
+
# reached through `_valid_url` in `invenio_rdm_records/services/schemas/metadata.py`.
|
|
706
|
+
# As observed on 2026-08-30, that accepts `http`, `https`, `ftp` and `ftps`,
|
|
707
|
+
# and requires a host that carries a top level domain of at least two characters,
|
|
708
|
+
# or is `localhost`, or is an IP literal.
|
|
709
|
+
# The check below deliberately differs on one point:
|
|
710
|
+
# an internationalized host name such as `https://académie.fr` passes here,
|
|
711
|
+
# while Zenodo rejects it, because an IDNA round trip is more machinery than this check deserves.
|
|
712
|
+
def _validate_url(instance, attribute, value):
|
|
713
|
+
"""Validate a URL that Zenodo stores as a plain string."""
|
|
714
|
+
try:
|
|
715
|
+
parsed = urlparse(value)
|
|
716
|
+
ok = parsed.scheme in URL_SCHEMES and parsed.hostname is not None
|
|
717
|
+
ok = ok and _is_acceptable_host(parsed.hostname)
|
|
718
|
+
except ValueError:
|
|
719
|
+
# `urlparse` rejects a malformed IPv6 literal such as `https://[::1/x`.
|
|
720
|
+
ok = False
|
|
721
|
+
if not ok:
|
|
722
|
+
raise ValueError(
|
|
723
|
+
f"Invalid URL for '{attribute.name}': {value!r}. "
|
|
724
|
+
"Zenodo reads an http, https, ftp or ftps URL "
|
|
725
|
+
"whose host name carries a top level domain of at least two characters."
|
|
726
|
+
)
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def _to_vocabulary_id(value: str) -> dict[str, str]:
|
|
730
|
+
"""Convert an identifier into the object Zenodo expects for a single vocabulary term."""
|
|
731
|
+
return {"id": value}
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def _to_vocabulary_ids(values: list[str]) -> list[dict[str, str]]:
|
|
735
|
+
"""Convert identifiers into the objects Zenodo expects for repeated vocabulary terms."""
|
|
736
|
+
return [{"id": value} for value in values]
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def _to_nested(value: Any) -> dict[str, Any]:
|
|
740
|
+
"""Convert a nested value object into the JSON object Zenodo expects."""
|
|
741
|
+
return value.to_zenodo()
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
@attrs.define
|
|
745
|
+
class Journal:
|
|
746
|
+
"""The journal in which the resource appeared."""
|
|
747
|
+
|
|
748
|
+
title: str | None = attrs.field(default=None)
|
|
749
|
+
"""The name of the journal."""
|
|
750
|
+
|
|
751
|
+
issue: str | None = attrs.field(default=None)
|
|
752
|
+
"""The issue in which the resource appeared, e.g. '3'."""
|
|
753
|
+
|
|
754
|
+
volume: str | None = attrs.field(default=None)
|
|
755
|
+
"""The volume in which the resource appeared, e.g. '42'."""
|
|
756
|
+
|
|
757
|
+
pages: str | None = attrs.field(default=None)
|
|
758
|
+
"""The pages of the resource within the issue, e.g. '123-145'."""
|
|
759
|
+
|
|
760
|
+
issn: str | None = attrs.field(default=None)
|
|
761
|
+
"""The International Standard Serial Number of the journal, e.g. '0378-5955'."""
|
|
762
|
+
|
|
763
|
+
@issn.validator
|
|
764
|
+
def _validate_issn(self, attribute, value):
|
|
765
|
+
"""Validate the ISSN, which Zenodo checks with `idutils.is_issn`."""
|
|
766
|
+
if not (value is None or idutils.is_issn(value)):
|
|
767
|
+
raise ValueError(
|
|
768
|
+
f"Invalid ISSN for '{attribute.name}': {value!r}. "
|
|
769
|
+
"Zenodo reads eight digits ending in a check digit, e.g. '0378-5955'."
|
|
770
|
+
)
|
|
771
|
+
|
|
772
|
+
def to_zenodo(self) -> dict[str, Any]:
|
|
773
|
+
"""Convert the journal reference to a dictionary suitable for Zenodo."""
|
|
774
|
+
return _to_zenodo_object(
|
|
775
|
+
title=self.title,
|
|
776
|
+
issue=self.issue,
|
|
777
|
+
volume=self.volume,
|
|
778
|
+
pages=self.pages,
|
|
779
|
+
issn=self.issn,
|
|
780
|
+
)
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
@attrs.define
|
|
784
|
+
class Meeting:
|
|
785
|
+
"""The meeting at which the resource was presented."""
|
|
786
|
+
|
|
787
|
+
title: str | None = attrs.field(default=None)
|
|
788
|
+
"""The full title of the meeting."""
|
|
789
|
+
|
|
790
|
+
acronym: str | None = attrs.field(default=None)
|
|
791
|
+
"""The short name of the meeting, e.g. 'ESOF24'."""
|
|
792
|
+
|
|
793
|
+
dates: str | None = attrs.field(default=None)
|
|
794
|
+
"""The dates of the meeting as free text, which Zenodo stores without parsing it."""
|
|
795
|
+
|
|
796
|
+
place: str | None = attrs.field(default=None)
|
|
797
|
+
"""The location of the meeting, e.g. 'Ghent, Belgium'."""
|
|
798
|
+
|
|
799
|
+
session: str | None = attrs.field(default=None)
|
|
800
|
+
"""The session of the meeting, e.g. 'VI'."""
|
|
801
|
+
|
|
802
|
+
session_part: str | None = attrs.field(default=None)
|
|
803
|
+
"""The part within the session, e.g. '1'."""
|
|
804
|
+
|
|
805
|
+
url: str | None = attrs.field(
|
|
806
|
+
default=None,
|
|
807
|
+
validator=attrs.validators.optional(_validate_url),
|
|
808
|
+
)
|
|
809
|
+
"""The website of the meeting."""
|
|
810
|
+
|
|
811
|
+
identifiers: list[Identifier] = attrs.field(factory=list)
|
|
812
|
+
"""Identifiers of the meeting, e.g. the DOI of its proceedings."""
|
|
813
|
+
|
|
814
|
+
def to_zenodo(self) -> dict[str, Any]:
|
|
815
|
+
"""Convert the meeting to a dictionary suitable for Zenodo."""
|
|
816
|
+
return _to_zenodo_object(
|
|
817
|
+
title=self.title,
|
|
818
|
+
acronym=self.acronym,
|
|
819
|
+
dates=self.dates,
|
|
820
|
+
place=self.place,
|
|
821
|
+
session=self.session,
|
|
822
|
+
session_part=self.session_part,
|
|
823
|
+
url=self.url,
|
|
824
|
+
identifiers=[identifier.to_zenodo() for identifier in self.identifiers],
|
|
825
|
+
)
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
@attrs.define
|
|
829
|
+
class Imprint:
|
|
830
|
+
"""The book or report in which the resource appeared."""
|
|
831
|
+
|
|
832
|
+
title: str | None = attrs.field(default=None)
|
|
833
|
+
"""The title of the book in which the resource appeared as a chapter."""
|
|
834
|
+
|
|
835
|
+
isbn: str | None = attrs.field(default=None)
|
|
836
|
+
"""The International Standard Book Number, e.g. '978-3-16-148410-0'."""
|
|
837
|
+
|
|
838
|
+
@isbn.validator
|
|
839
|
+
def _validate_isbn(self, attribute, value):
|
|
840
|
+
"""Validate the ISBN, which Zenodo checks with `idutils.is_isbn`."""
|
|
841
|
+
if not (value is None or idutils.is_isbn(value)):
|
|
842
|
+
raise ValueError(
|
|
843
|
+
f"Invalid ISBN for '{attribute.name}': {value!r}. "
|
|
844
|
+
"Zenodo reads a ten or thirteen digit number ending in a check digit, "
|
|
845
|
+
"e.g. '978-3-16-148410-0'."
|
|
846
|
+
)
|
|
847
|
+
|
|
848
|
+
pages: str | None = attrs.field(default=None)
|
|
849
|
+
"""The pages of the resource within the book, e.g. '15-30'."""
|
|
850
|
+
|
|
851
|
+
place: str | None = attrs.field(default=None)
|
|
852
|
+
"""The place of publication, e.g. 'Ghent, Belgium'."""
|
|
853
|
+
|
|
854
|
+
edition: str | None = attrs.field(default=None)
|
|
855
|
+
"""The edition of the book, e.g. '2nd'."""
|
|
856
|
+
|
|
857
|
+
def to_zenodo(self) -> dict[str, Any]:
|
|
858
|
+
"""Convert the imprint to a dictionary suitable for Zenodo."""
|
|
859
|
+
return _to_zenodo_object(
|
|
860
|
+
title=self.title,
|
|
861
|
+
isbn=self.isbn,
|
|
862
|
+
pages=self.pages,
|
|
863
|
+
place=self.place,
|
|
864
|
+
edition=self.edition,
|
|
865
|
+
)
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
PLAIN_DATE_PATTERN = re.compile(r"^\d{4}(-\d{2}(-\d{2})?)?$")
|
|
869
|
+
"""A date written as a year, a year and a month, or a full calendar date."""
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
# Zenodo validates the thesis dates as EDTF level 2,
|
|
873
|
+
# which also covers uncertain and approximate expressions such as `1984~` or `1984-06-uu`.
|
|
874
|
+
# That grammar is more than this module wants to reimplement,
|
|
875
|
+
# so only a value that looks like a plain calendar date is checked here.
|
|
876
|
+
# Anything else is passed on to Zenodo, which has the final say.
|
|
877
|
+
def _validate_edtf_date(instance, attribute, value):
|
|
878
|
+
"""Validate a date that Zenodo reads as an EDTF level 2 expression."""
|
|
879
|
+
if value is None or PLAIN_DATE_PATTERN.match(value) is None:
|
|
880
|
+
return
|
|
881
|
+
parts = [int(part) for part in value.split("-")]
|
|
882
|
+
parts.extend([1] * (3 - len(parts)))
|
|
883
|
+
try:
|
|
884
|
+
dt.date(*parts)
|
|
885
|
+
except ValueError as exc:
|
|
886
|
+
raise ValueError(
|
|
887
|
+
f"Impossible date for '{attribute.name}': {value!r}. {exc}. "
|
|
888
|
+
"Zenodo reads a date as an EDTF level 2 expression, "
|
|
889
|
+
"e.g. '2024-06-15', '2024-06', '2024' or '1984~'."
|
|
890
|
+
) from exc
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
@attrs.define
|
|
894
|
+
class Thesis:
|
|
895
|
+
"""The dissertation of which the resource is the outcome."""
|
|
896
|
+
|
|
897
|
+
university: str | None = attrs.field(default=None)
|
|
898
|
+
"""The institution that awarded the degree."""
|
|
899
|
+
|
|
900
|
+
department: str | None = attrs.field(default=None)
|
|
901
|
+
"""The department within the institution."""
|
|
902
|
+
|
|
903
|
+
type: str | None = attrs.field(default=None)
|
|
904
|
+
"""The kind of thesis, e.g. 'PhD' or 'Master'."""
|
|
905
|
+
|
|
906
|
+
date_submitted: str | None = attrs.field(default=None, validator=_validate_edtf_date)
|
|
907
|
+
"""The date on which the thesis was submitted, e.g. '2024-06-15'."""
|
|
908
|
+
|
|
909
|
+
date_defended: str | None = attrs.field(default=None, validator=_validate_edtf_date)
|
|
910
|
+
"""The date on which the thesis was defended, e.g. '2024-09-23'."""
|
|
911
|
+
|
|
912
|
+
def to_zenodo(self) -> dict[str, Any]:
|
|
913
|
+
"""Convert the thesis to a dictionary suitable for Zenodo."""
|
|
914
|
+
return _to_zenodo_object(
|
|
915
|
+
university=self.university,
|
|
916
|
+
department=self.department,
|
|
917
|
+
type=self.type,
|
|
918
|
+
date_submitted=self.date_submitted,
|
|
919
|
+
date_defended=self.date_defended,
|
|
920
|
+
)
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
CUSTOM_FIELD = "custom_field"
|
|
924
|
+
"""Metadata key under which an attribute of `CustomFields` stores its `CustomFieldSpec`."""
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
@attrs.define(frozen=True)
|
|
928
|
+
class CustomFieldSpec:
|
|
929
|
+
"""How an attribute of `CustomFields` maps onto a custom field of Zenodo."""
|
|
930
|
+
|
|
931
|
+
name: str = attrs.field()
|
|
932
|
+
"""The name of the custom field in Zenodo's API, e.g. `code:codeRepository`."""
|
|
933
|
+
|
|
934
|
+
to_zenodo: Callable[[Any], Any] = attrs.field(default=lambda value: value)
|
|
935
|
+
"""Convert the value of the attribute into the JSON value that Zenodo expects."""
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
@attrs.define
|
|
939
|
+
class CustomFields:
|
|
940
|
+
"""A subset of the custom fields with which Zenodo extends the InvenioRDM record.
|
|
941
|
+
|
|
942
|
+
Attributes are named as in the config file,
|
|
943
|
+
which is more intuitive than the namespaced names Zenodo uses.
|
|
944
|
+
Each attribute carries a `CustomFieldSpec` in its metadata,
|
|
945
|
+
holding the Zenodo name and the conversion to the JSON value Zenodo expects.
|
|
946
|
+
An attribute left at its default is not sent to Zenodo,
|
|
947
|
+
and neither is a nested object all of whose keys are unset,
|
|
948
|
+
because Zenodo expects at least one key in such an object.
|
|
949
|
+
|
|
950
|
+
The shapes below were read on 2026-08-30 from the software Zenodo runs:
|
|
951
|
+
the `code:` and `dc:` fields from `site/zenodo_rdm/custom_fields` in `zenodo/zenodo-rdm`,
|
|
952
|
+
and the four object fields from `invenio_rdm_records/contrib` in `invenio-rdm-records`.
|
|
953
|
+
A field whose name starts with `legacy:` is deliberately absent:
|
|
954
|
+
only the loader that reads a `.zenodo.json` of a GitHub release understands those,
|
|
955
|
+
so the InvenioRDM API used here would drop them without saying so.
|
|
956
|
+
"""
|
|
957
|
+
|
|
958
|
+
code_repository: str | None = attrs.field(
|
|
959
|
+
default=None,
|
|
960
|
+
validator=attrs.validators.optional(_validate_url),
|
|
961
|
+
metadata={CUSTOM_FIELD: CustomFieldSpec("code:codeRepository")},
|
|
962
|
+
)
|
|
963
|
+
"""URL of the repository in which the code is hosted."""
|
|
964
|
+
|
|
965
|
+
development_status: str | None = attrs.field(
|
|
966
|
+
default=None,
|
|
967
|
+
validator=attrs.validators.optional(_in_vocabulary("code:developmentStatus")),
|
|
968
|
+
metadata={CUSTOM_FIELD: CustomFieldSpec("code:developmentStatus", _to_vocabulary_id)},
|
|
969
|
+
)
|
|
970
|
+
"""The development status of the software."""
|
|
971
|
+
|
|
972
|
+
programming_languages: list[str] = attrs.field(
|
|
973
|
+
factory=list,
|
|
974
|
+
validator=attrs.validators.deep_iterable(_in_vocabulary("code:programmingLanguages")),
|
|
975
|
+
metadata={CUSTOM_FIELD: CustomFieldSpec("code:programmingLanguage", _to_vocabulary_ids)},
|
|
976
|
+
)
|
|
977
|
+
"""The programming languages in which the software is written."""
|
|
978
|
+
|
|
979
|
+
rights_holder: list[str] = attrs.field(
|
|
980
|
+
factory=list,
|
|
981
|
+
metadata={CUSTOM_FIELD: CustomFieldSpec("dc:rightsHolder")},
|
|
982
|
+
)
|
|
983
|
+
"""The parties that hold the rights to the resource.
|
|
984
|
+
|
|
985
|
+
Use this for a rights holder that is not one of the creators,
|
|
986
|
+
e.g. the institution that employs them.
|
|
987
|
+
"""
|
|
988
|
+
|
|
989
|
+
journal: Journal | None = attrs.field(
|
|
990
|
+
default=None,
|
|
991
|
+
metadata={CUSTOM_FIELD: CustomFieldSpec("journal:journal", _to_nested)},
|
|
992
|
+
)
|
|
993
|
+
"""The journal in which the resource appeared."""
|
|
994
|
+
|
|
995
|
+
meeting: Meeting | None = attrs.field(
|
|
996
|
+
default=None,
|
|
997
|
+
metadata={CUSTOM_FIELD: CustomFieldSpec("meeting:meeting", _to_nested)},
|
|
998
|
+
)
|
|
999
|
+
"""The meeting at which the resource was presented."""
|
|
1000
|
+
|
|
1001
|
+
imprint: Imprint | None = attrs.field(
|
|
1002
|
+
default=None,
|
|
1003
|
+
metadata={CUSTOM_FIELD: CustomFieldSpec("imprint:imprint", _to_nested)},
|
|
1004
|
+
)
|
|
1005
|
+
"""The book or report in which the resource appeared."""
|
|
1006
|
+
|
|
1007
|
+
thesis: Thesis | None = attrs.field(
|
|
1008
|
+
default=None,
|
|
1009
|
+
metadata={CUSTOM_FIELD: CustomFieldSpec("thesis:thesis", _to_nested)},
|
|
1010
|
+
)
|
|
1011
|
+
"""The dissertation of which the resource is the outcome."""
|
|
1012
|
+
|
|
1013
|
+
def to_zenodo(self) -> dict[str, Any]:
|
|
1014
|
+
"""Convert the custom fields to a dictionary suitable for Zenodo."""
|
|
1015
|
+
result = {}
|
|
1016
|
+
for attribute in attrs.fields(type(self)):
|
|
1017
|
+
value = getattr(self, attribute.name)
|
|
1018
|
+
if value is None:
|
|
1019
|
+
continue
|
|
1020
|
+
spec = attribute.metadata[CUSTOM_FIELD]
|
|
1021
|
+
converted = spec.to_zenodo(value)
|
|
1022
|
+
if not converted:
|
|
1023
|
+
continue
|
|
1024
|
+
result[spec.name] = converted
|
|
1025
|
+
return result
|
|
1026
|
+
|
|
1027
|
+
|
|
1028
|
+
def _convert_endpoint(arg: str) -> str:
|
|
1029
|
+
"""Remove the trailing slashes of an endpoint URL."""
|
|
1030
|
+
return arg.rstrip("/")
|
|
1031
|
+
|
|
1032
|
+
|
|
1033
|
+
PRODUCTION_ENDPOINT = "https://zenodo.org/api"
|
|
1034
|
+
"""The endpoint of the Zenodo instance on which datasets are published."""
|
|
1035
|
+
|
|
1036
|
+
SANDBOX_ENDPOINT = "https://sandbox.zenodo.org/api"
|
|
1037
|
+
"""The endpoint of the Zenodo sandbox, which Zenodo provides for testing.
|
|
1038
|
+
|
|
1039
|
+
As stated in the Testing section of https://developers.zenodo.org/ in November 2026,
|
|
1040
|
+
it issues test DOIs, its records may be deleted at any time,
|
|
1041
|
+
and it has accounts and tokens of its own.
|
|
1042
|
+
"""
|
|
1043
|
+
|
|
1044
|
+
|
|
1045
|
+
@attrs.define
|
|
1046
|
+
class Config:
|
|
1047
|
+
"""Configuration of the sync-zenodo script.
|
|
1048
|
+
|
|
1049
|
+
An object of this class is created from data loaded from a local config file.
|
|
1050
|
+
"""
|
|
1051
|
+
|
|
1052
|
+
path_record_id: Path = attrs.field(converter=Path)
|
|
1053
|
+
metadata: Metadata = attrs.field()
|
|
1054
|
+
endpoint: str = attrs.field(converter=_convert_endpoint, validator=_validate_url)
|
|
1055
|
+
custom_fields: CustomFields = attrs.field(factory=CustomFields)
|
|
1056
|
+
access: Access = attrs.field(factory=Access)
|
|
1057
|
+
|
|
1058
|
+
def to_zenodo(
|
|
1059
|
+
self,
|
|
1060
|
+
description: str,
|
|
1061
|
+
files: Sequence[UploadFile],
|
|
1062
|
+
publication_date: str | None = None,
|
|
1063
|
+
) -> dict[str, Any]:
|
|
1064
|
+
"""Convert the configuration to a dictionary suitable for Zenodo.
|
|
1065
|
+
|
|
1066
|
+
Parameters
|
|
1067
|
+
----------
|
|
1068
|
+
description
|
|
1069
|
+
The description of the dataset, in HTML.
|
|
1070
|
+
files
|
|
1071
|
+
The files to be uploaded to Zenodo.
|
|
1072
|
+
The first one is selected as the default preview.
|
|
1073
|
+
When it is not among the files of the record yet,
|
|
1074
|
+
Zenodo drops the preview with a soft error instead of refusing the request,
|
|
1075
|
+
as observed on the Zenodo sandbox on 2026-11-21.
|
|
1076
|
+
Pass an empty sequence to select no default preview.
|
|
1077
|
+
publication_date
|
|
1078
|
+
The publication date to send to Zenodo, in ISO format.
|
|
1079
|
+
When `None`, today's date is used.
|
|
1080
|
+
|
|
1081
|
+
Notes
|
|
1082
|
+
-----
|
|
1083
|
+
The files are always enabled, because Zenodo has no metadata only records.
|
|
1084
|
+
"""
|
|
1085
|
+
# As of 2026-11-21, observed on the Zenodo sandbox,
|
|
1086
|
+
# Zenodo silently drops `files.order` from a metadata update
|
|
1087
|
+
# and lists the files alphabetically on the landing page,
|
|
1088
|
+
# so sending an order would have no effect.
|
|
1089
|
+
files_options: dict[str, Any] = {"enabled": True}
|
|
1090
|
+
if len(files) > 0:
|
|
1091
|
+
files_options["default_preview"] = files[0].name
|
|
1092
|
+
return {
|
|
1093
|
+
"access": self.access.to_zenodo(),
|
|
1094
|
+
"metadata": self.metadata.to_zenodo(description, publication_date),
|
|
1095
|
+
"custom_fields": self.custom_fields.to_zenodo(),
|
|
1096
|
+
"files": files_options,
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
|
|
1100
|
+
INVENIORDM_MIMETYPE = "application/vnd.inveniordm.v1+json"
|
|
1101
|
+
"""The representation of a record that this module asks Zenodo for.
|
|
1102
|
+
|
|
1103
|
+
Without this Accept header, Zenodo answers with its legacy record schema,
|
|
1104
|
+
which names and shapes several fields differently.
|
|
1105
|
+
As observed on 2026-08-30, the two differ in the fields this module reads:
|
|
1106
|
+
`files` is an object with an `entries` mapping here and a list in the legacy schema,
|
|
1107
|
+
and a published record is marked with `is_published` here and with `submitted` there.
|
|
1108
|
+
"""
|
|
1109
|
+
|
|
1110
|
+
|
|
1111
|
+
MD5_PREFIX = "md5:"
|
|
1112
|
+
"""The algorithm with which Zenodo prefixes the checksum of a file."""
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
SEARCH_PAGE_SIZE = 100
|
|
1116
|
+
"""The number of records requested per page when a paginated search result is collected.
|
|
1117
|
+
|
|
1118
|
+
As observed on 2026-08-30, Zenodo refuses a page larger than this.
|
|
1119
|
+
"""
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
MAX_SEARCH_PAGES = 100
|
|
1123
|
+
"""The number of pages to request before a paginated search result is considered endless.
|
|
1124
|
+
|
|
1125
|
+
This bounds the work of collecting a search result,
|
|
1126
|
+
also when Zenodo keeps sending full pages.
|
|
1127
|
+
"""
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
def _file_loc(rid: str, name: str) -> str:
|
|
1131
|
+
"""Build the address of one file of a draft record.
|
|
1132
|
+
|
|
1133
|
+
Parameters
|
|
1134
|
+
----------
|
|
1135
|
+
rid
|
|
1136
|
+
The id of the record.
|
|
1137
|
+
name
|
|
1138
|
+
The name of the file.
|
|
1139
|
+
It becomes a single path segment, so every character that delimits a URL is escaped.
|
|
1140
|
+
|
|
1141
|
+
Returns
|
|
1142
|
+
-------
|
|
1143
|
+
loc
|
|
1144
|
+
The address of the file, to be appended after the endpoint.
|
|
1145
|
+
"""
|
|
1146
|
+
return f"records/{rid}/draft/files/{quote(name, safe='')}"
|
|
1147
|
+
|
|
1148
|
+
|
|
1149
|
+
@attrs.define
|
|
1150
|
+
class ZenodoWrapper:
|
|
1151
|
+
"""Python interface to a subset of the Zenodo API."""
|
|
1152
|
+
|
|
1153
|
+
token: str = attrs.field()
|
|
1154
|
+
endpoint: str = attrs.field()
|
|
1155
|
+
verbose: bool = attrs.field(default=False)
|
|
1156
|
+
rest: RESTWrapper = attrs.field(init=False)
|
|
1157
|
+
|
|
1158
|
+
@rest.default
|
|
1159
|
+
def _default_rest(self):
|
|
1160
|
+
"""Set the default REST wrapper."""
|
|
1161
|
+
headers = {
|
|
1162
|
+
"Authorization": f"Bearer {self.token}",
|
|
1163
|
+
"Accept": INVENIORDM_MIMETYPE,
|
|
1164
|
+
}
|
|
1165
|
+
return RESTWrapper(self.endpoint, headers, verbose=self.verbose)
|
|
1166
|
+
|
|
1167
|
+
# Main API methods
|
|
1168
|
+
|
|
1169
|
+
def create_new_record(self, config: Config, description: str) -> dict[str, Any]:
|
|
1170
|
+
"""Create a new record on Zenodo, which remains in draft until it is published manually.
|
|
1171
|
+
|
|
1172
|
+
The new record has no files and no default preview.
|
|
1173
|
+
"""
|
|
1174
|
+
data = config.to_zenodo(description, [])
|
|
1175
|
+
return self.rest.post("records", json=data)
|
|
1176
|
+
|
|
1177
|
+
def get_record(self, rid: str) -> dict[str, Any]:
|
|
1178
|
+
"""Get an (un)published record with given id.
|
|
1179
|
+
|
|
1180
|
+
The draft is preferred, because it carries the changes that are not published yet.
|
|
1181
|
+
Only a record without a draft is read as a published one,
|
|
1182
|
+
so that a refused or lost request is not mistaken for a published dataset.
|
|
1183
|
+
An open edit of a published record is returned as a draft
|
|
1184
|
+
that still reports `is_published: true`.
|
|
1185
|
+
"""
|
|
1186
|
+
try:
|
|
1187
|
+
res = self.rest.get(f"records/{rid}/draft")
|
|
1188
|
+
except RESTError as exc:
|
|
1189
|
+
if exc.status_code != 404:
|
|
1190
|
+
raise
|
|
1191
|
+
res = self.rest.get(f"records/{rid}")
|
|
1192
|
+
return res
|
|
1193
|
+
|
|
1194
|
+
def update_metadata(
|
|
1195
|
+
self,
|
|
1196
|
+
rid: str,
|
|
1197
|
+
config: Config,
|
|
1198
|
+
description: str,
|
|
1199
|
+
files: Sequence[UploadFile],
|
|
1200
|
+
publication_date: str | None = None,
|
|
1201
|
+
) -> dict[str, Any]:
|
|
1202
|
+
"""Update the metadata of a record.
|
|
1203
|
+
|
|
1204
|
+
This is applicable to draft records and published records in edit mode.
|
|
1205
|
+
The publication date of a record that is already published
|
|
1206
|
+
must be passed in, because it is not part of the local configuration
|
|
1207
|
+
and a metadata update would otherwise move it to today.
|
|
1208
|
+
The first of the `files` is selected as the default preview,
|
|
1209
|
+
as explained in `Config.to_zenodo()`.
|
|
1210
|
+
"""
|
|
1211
|
+
data = config.to_zenodo(description, files, publication_date)
|
|
1212
|
+
return self.rest.put(f"records/{rid}/draft", json=data)
|
|
1213
|
+
|
|
1214
|
+
def edit_record(self, rid: str):
|
|
1215
|
+
"""Put a published record into edit mode."""
|
|
1216
|
+
self.rest.post(f"records/{rid}/draft")
|
|
1217
|
+
|
|
1218
|
+
def publish_record(self, rid: str):
|
|
1219
|
+
"""Publish a draft record or a record in edit mode."""
|
|
1220
|
+
self.rest.post(f"records/{rid}/draft/actions/publish")
|
|
1221
|
+
|
|
1222
|
+
def start_uploads(self, rid: str, files: Sequence[UploadFile]):
|
|
1223
|
+
"""Declare the files that will be uploaded to a record in draft mode."""
|
|
1224
|
+
self.rest.post(f"records/{rid}/draft/files", json=[{"key": file.name} for file in files])
|
|
1225
|
+
|
|
1226
|
+
def upload_file(self, rid: str, file: UploadFile):
|
|
1227
|
+
"""Upload a file to a record that is in draft mode.
|
|
1228
|
+
|
|
1229
|
+
The checksum that Zenodo computed is compared to the one in the inventory,
|
|
1230
|
+
which detects both a damaged upload
|
|
1231
|
+
and a file that changed after the inventory was written.
|
|
1232
|
+
"""
|
|
1233
|
+
loc = _file_loc(rid, file.name)
|
|
1234
|
+
with open(file.path, "rb") as fh:
|
|
1235
|
+
self.rest.put(f"{loc}/content", data=fh)
|
|
1236
|
+
res = self.rest.post(f"{loc}/commit")
|
|
1237
|
+
size = file.path.size
|
|
1238
|
+
if res.get("size") != size:
|
|
1239
|
+
raise ZenodoError(
|
|
1240
|
+
f"File size mismatch for {file.name}: expected {size}, got {res.get('size')} bytes."
|
|
1241
|
+
)
|
|
1242
|
+
online_md5 = _entry_md5(res)
|
|
1243
|
+
if file.md5 != online_md5:
|
|
1244
|
+
raise ZenodoError(
|
|
1245
|
+
f"MD5 checksum mismatch for {file.path}, "
|
|
1246
|
+
f"inventory {file.md5}, online {online_md5}. "
|
|
1247
|
+
"The upload was damaged, or the file changed after the inventory was written."
|
|
1248
|
+
)
|
|
1249
|
+
|
|
1250
|
+
def delete_file(self, rid: str, name: str):
|
|
1251
|
+
"""Delete a file.
|
|
1252
|
+
|
|
1253
|
+
The file must belong to a record in draft mode.
|
|
1254
|
+
"""
|
|
1255
|
+
self.rest.delete(_file_loc(rid, name))
|
|
1256
|
+
|
|
1257
|
+
def get_all_pages(self, loc: str) -> list[dict[str, Any]]:
|
|
1258
|
+
"""Collect the records of a paginated search result.
|
|
1259
|
+
|
|
1260
|
+
Parameters
|
|
1261
|
+
----------
|
|
1262
|
+
loc
|
|
1263
|
+
The address of the search result, appended after the endpoint.
|
|
1264
|
+
|
|
1265
|
+
Returns
|
|
1266
|
+
-------
|
|
1267
|
+
records
|
|
1268
|
+
The records of every page, in the order Zenodo returns them.
|
|
1269
|
+
|
|
1270
|
+
Raises
|
|
1271
|
+
------
|
|
1272
|
+
ZenodoError
|
|
1273
|
+
When Zenodo sends more than `MAX_SEARCH_PAGES` full pages.
|
|
1274
|
+
"""
|
|
1275
|
+
records = []
|
|
1276
|
+
for page in range(1, MAX_SEARCH_PAGES + 1):
|
|
1277
|
+
data = self.rest.get(loc, params={"page": page, "size": SEARCH_PAGE_SIZE})
|
|
1278
|
+
hits = _search_hits(data)
|
|
1279
|
+
records.extend(hits)
|
|
1280
|
+
if len(hits) < SEARCH_PAGE_SIZE:
|
|
1281
|
+
break
|
|
1282
|
+
else:
|
|
1283
|
+
raise ZenodoError(
|
|
1284
|
+
f"Zenodo sent {MAX_SEARCH_PAGES} full pages of results for {loc}, "
|
|
1285
|
+
"which is more than this module collects."
|
|
1286
|
+
)
|
|
1287
|
+
return records
|
|
1288
|
+
|
|
1289
|
+
def get_versions(self, rid: str) -> list[dict[str, Any]]:
|
|
1290
|
+
"""Get all published versions of the dataset to which a record belongs.
|
|
1291
|
+
|
|
1292
|
+
Parameters
|
|
1293
|
+
----------
|
|
1294
|
+
rid
|
|
1295
|
+
The id of any published record of the dataset.
|
|
1296
|
+
|
|
1297
|
+
Returns
|
|
1298
|
+
-------
|
|
1299
|
+
versions
|
|
1300
|
+
One record for every published version, in the order Zenodo returns them.
|
|
1301
|
+
Drafts are not included.
|
|
1302
|
+
"""
|
|
1303
|
+
return self.get_all_pages(f"records/{rid}/versions")
|
|
1304
|
+
|
|
1305
|
+
def create_new_version(self, rid: str) -> dict[str, Any]:
|
|
1306
|
+
"""Create a new version of a published record.
|
|
1307
|
+
|
|
1308
|
+
The result is a draft record.
|
|
1309
|
+
"""
|
|
1310
|
+
return self.rest.post(f"records/{rid}/versions")
|
|
1311
|
+
|
|
1312
|
+
|
|
1313
|
+
NO_TOKEN_WARNING = """\
|
|
1314
|
+
[yellow]The STEPUP_DATA_ZENODO_TOKEN environment variable is not set.
|
|
1315
|
+
Exiting early without interacting with the Zenodo endpoint.
|
|
1316
|
+
Use --dry-run to only validate the config file, without this warning.[/yellow]
|
|
1317
|
+
"""
|
|
1318
|
+
|
|
1319
|
+
EMPTY_TOKEN_WARNING = """\
|
|
1320
|
+
[yellow]The STEPUP_DATA_ZENODO_TOKEN environment variable is empty.
|
|
1321
|
+
Exiting early without interacting with the Zenodo endpoint.
|
|
1322
|
+
Use --dry-run to only validate the config file, without this warning.[/yellow]
|
|
1323
|
+
"""
|
|
1324
|
+
|
|
1325
|
+
OFFLINE_MESSAGE = """\
|
|
1326
|
+
[yellow]The build is offline (STEPUP_BUILD_OFFLINE=1).
|
|
1327
|
+
Exiting early without interacting with the Zenodo endpoint.[/yellow]
|
|
1328
|
+
"""
|
|
1329
|
+
|
|
1330
|
+
ACCESS_DENIED_STATUS_CODES = (401, 403)
|
|
1331
|
+
"""The status codes with which Zenodo refuses a request that the token does not permit."""
|
|
1332
|
+
|
|
1333
|
+
ACCESS_DENIED_HINT = """\
|
|
1334
|
+
Zenodo at {host} denied access. \
|
|
1335
|
+
Check that STEPUP_DATA_ZENODO_TOKEN holds a token created on {host}, \
|
|
1336
|
+
because zenodo.org and sandbox.zenodo.org do not accept each other's tokens, \
|
|
1337
|
+
and that the token has the deposit:write and deposit:actions scopes."""
|
|
1338
|
+
"""Advice appended to an error with one of the `ACCESS_DENIED_STATUS_CODES`.
|
|
1339
|
+
|
|
1340
|
+
As observed on 2026-11-21 on both zenodo.org and sandbox.zenodo.org,
|
|
1341
|
+
Zenodo answers a token it does not know with status 403 and the message "Permission denied.",
|
|
1342
|
+
so a token of the other instance looks like a token without the right scopes.
|
|
1343
|
+
"""
|
|
1344
|
+
|
|
1345
|
+
|
|
1346
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
1347
|
+
"""Main program.
|
|
1348
|
+
|
|
1349
|
+
Returns
|
|
1350
|
+
-------
|
|
1351
|
+
returncode
|
|
1352
|
+
Zero when the synchronization succeeded,
|
|
1353
|
+
one when the user has to correct something or when Zenodo refused a request.
|
|
1354
|
+
The console script wrapper turns this into the exit status of the process.
|
|
1355
|
+
"""
|
|
1356
|
+
args = _parse_args(argv)
|
|
1357
|
+
try:
|
|
1358
|
+
_run(args)
|
|
1359
|
+
except (ZenodoError, RESTError) as exc:
|
|
1360
|
+
print(str(exc), file=sys.stderr)
|
|
1361
|
+
return 1
|
|
1362
|
+
except cattrs.BaseValidationError as exc:
|
|
1363
|
+
# Report what is wrong with each value instead of the nested exception group,
|
|
1364
|
+
# of which most frames sit in the structuring code that cattrs generates.
|
|
1365
|
+
for line in cattrs.transform_error(exc, repr(args.config), _format_error):
|
|
1366
|
+
print(line, file=sys.stderr)
|
|
1367
|
+
return 1
|
|
1368
|
+
return 0
|
|
1369
|
+
|
|
1370
|
+
|
|
1371
|
+
def _run(args: argparse.Namespace):
|
|
1372
|
+
"""Validate the configuration and synchronize the dataset with Zenodo.
|
|
1373
|
+
|
|
1374
|
+
Everything that can be checked locally is checked before the early exits,
|
|
1375
|
+
so that every run reports a configuration that cannot be synchronized,
|
|
1376
|
+
also offline, without a token and with `--dry-run`.
|
|
1377
|
+
The only exception is the MD5 checksums of the files,
|
|
1378
|
+
which are computed right before Zenodo is contacted.
|
|
1379
|
+
"""
|
|
1380
|
+
data = _load_config_data(args.config)
|
|
1381
|
+
_check_outdated_config(data, args.config)
|
|
1382
|
+
_check_endpoint_present(data, args.config)
|
|
1383
|
+
config = _make_converter().structure(data, Config)
|
|
1384
|
+
description = _load_description(args.description)
|
|
1385
|
+
files = _load_files(args.inventory)
|
|
1386
|
+
|
|
1387
|
+
if args.dry_run:
|
|
1388
|
+
CONSOLE.print("[b]The following metadata would be sent to Zenodo:[/b]")
|
|
1389
|
+
CONSOLE.print(JSON.from_data(config.to_zenodo(description, files)))
|
|
1390
|
+
return
|
|
1391
|
+
|
|
1392
|
+
if is_offline():
|
|
1393
|
+
CONSOLE.print(OFFLINE_MESSAGE)
|
|
1394
|
+
return
|
|
1395
|
+
|
|
1396
|
+
# The token is not tracked by StepUp to keep sensitive information out of the workflow graph.
|
|
1397
|
+
token = os.environ.get("STEPUP_DATA_ZENODO_TOKEN")
|
|
1398
|
+
if token is None:
|
|
1399
|
+
CONSOLE.print(NO_TOKEN_WARNING)
|
|
1400
|
+
return
|
|
1401
|
+
if token == "":
|
|
1402
|
+
CONSOLE.print(EMPTY_TOKEN_WARNING)
|
|
1403
|
+
return
|
|
1404
|
+
|
|
1405
|
+
if not args.no_check_md5:
|
|
1406
|
+
_check_local_md5(files, args.inventory)
|
|
1407
|
+
zenodo = ZenodoWrapper(token, config.endpoint, verbose=args.verbose)
|
|
1408
|
+
try:
|
|
1409
|
+
_update_online(zenodo, config, description, files)
|
|
1410
|
+
except RESTError as exc:
|
|
1411
|
+
if exc.status_code not in ACCESS_DENIED_STATUS_CODES:
|
|
1412
|
+
raise
|
|
1413
|
+
hint = ACCESS_DENIED_HINT.format(host=urlparse(config.endpoint).hostname)
|
|
1414
|
+
raise ZenodoError(f"{exc}\n{hint}") from exc
|
|
1415
|
+
|
|
1416
|
+
|
|
1417
|
+
def _load_files(path_inventory: str) -> list[UploadFile]:
|
|
1418
|
+
"""Load the files to upload from the inventory and check that they exist.
|
|
1419
|
+
|
|
1420
|
+
The files are amended as inputs of the current step,
|
|
1421
|
+
so that StepUp knows them also when this step exits early.
|
|
1422
|
+
|
|
1423
|
+
Raises
|
|
1424
|
+
------
|
|
1425
|
+
ZenodoError
|
|
1426
|
+
When the inventory cannot be used, when it lists no files,
|
|
1427
|
+
or when a file it lists does not exist.
|
|
1428
|
+
InputNotFoundError
|
|
1429
|
+
When StepUp has to build a file before it can be uploaded.
|
|
1430
|
+
"""
|
|
1431
|
+
path_inventory = Path(path_inventory)
|
|
1432
|
+
root = path_inventory.parent
|
|
1433
|
+
files = []
|
|
1434
|
+
try:
|
|
1435
|
+
with open_inventory(path_inventory) as reader:
|
|
1436
|
+
algorithm = reader.header.hash_algorithm
|
|
1437
|
+
if algorithm != "md5":
|
|
1438
|
+
found = "no digests" if algorithm is None else f"{algorithm} digests"
|
|
1439
|
+
raise ZenodoError(
|
|
1440
|
+
f"The inventory {path_inventory} has {found}, "
|
|
1441
|
+
"while Zenodo reports MD5 checksums. "
|
|
1442
|
+
"Write it with `sd-make-inventory --hash md5`, which is the default."
|
|
1443
|
+
)
|
|
1444
|
+
for record in reader:
|
|
1445
|
+
if isinstance(record, LinkRecord):
|
|
1446
|
+
raise ZenodoError(
|
|
1447
|
+
f"The inventory {path_inventory} lists the symbolic link {record.path}, "
|
|
1448
|
+
"which cannot be uploaded, because Zenodo has no symbolic links."
|
|
1449
|
+
)
|
|
1450
|
+
files.append(UploadFile((root / record.path).normpath(), record.digest))
|
|
1451
|
+
except ValueError as exc:
|
|
1452
|
+
raise ZenodoError(
|
|
1453
|
+
f"{exc} The inventory is the third argument of `sd-sync-zenodo`, "
|
|
1454
|
+
"after the config file and the description."
|
|
1455
|
+
) from exc
|
|
1456
|
+
if len(files) == 0:
|
|
1457
|
+
raise ZenodoError(
|
|
1458
|
+
f"The inventory {path_inventory} lists no files. "
|
|
1459
|
+
"Zenodo publishes no record without files, "
|
|
1460
|
+
"and it does not offer metadata only records."
|
|
1461
|
+
)
|
|
1462
|
+
_check_zenodo_limits(files, path_inventory)
|
|
1463
|
+
# A missing file is reported below, together with all other missing files.
|
|
1464
|
+
with contextlib.suppress(PathError):
|
|
1465
|
+
amend(inp=[file.path for file in files])
|
|
1466
|
+
missing = [file.path for file in files if not file.path.is_file()]
|
|
1467
|
+
if len(missing) > 0:
|
|
1468
|
+
raise ZenodoError(f"The following files to upload do not exist: {', '.join(missing)}.")
|
|
1469
|
+
return files
|
|
1470
|
+
|
|
1471
|
+
|
|
1472
|
+
MAX_NUM_ZENODO_FILES = 100
|
|
1473
|
+
"""The maximum number of files that Zenodo accepts in a single record."""
|
|
1474
|
+
|
|
1475
|
+
|
|
1476
|
+
def _check_zenodo_limits(files: Sequence[UploadFile], path_inventory: Path):
|
|
1477
|
+
"""Check that Zenodo can hold the files in a single record.
|
|
1478
|
+
|
|
1479
|
+
Parameters
|
|
1480
|
+
----------
|
|
1481
|
+
files
|
|
1482
|
+
The files to upload.
|
|
1483
|
+
path_inventory
|
|
1484
|
+
The inventory that lists the files, used in the messages.
|
|
1485
|
+
|
|
1486
|
+
Raises
|
|
1487
|
+
------
|
|
1488
|
+
ZenodoError
|
|
1489
|
+
When there are too many files or when two files have the same name.
|
|
1490
|
+
"""
|
|
1491
|
+
prefix = f"The inventory {path_inventory} cannot be used."
|
|
1492
|
+
if len(files) > MAX_NUM_ZENODO_FILES:
|
|
1493
|
+
raise ZenodoError(
|
|
1494
|
+
f"{prefix} Zenodo accepts at most {MAX_NUM_ZENODO_FILES} files in one record, "
|
|
1495
|
+
f"got {len(files)}."
|
|
1496
|
+
)
|
|
1497
|
+
seen_paths = {}
|
|
1498
|
+
for file in files:
|
|
1499
|
+
other = seen_paths.get(file.name)
|
|
1500
|
+
if other is not None:
|
|
1501
|
+
raise ZenodoError(
|
|
1502
|
+
f"{prefix} Zenodo does not support directory layouts, "
|
|
1503
|
+
"so files must have different names. "
|
|
1504
|
+
f"The name {file.name} is used by {other} and {file.path}."
|
|
1505
|
+
)
|
|
1506
|
+
seen_paths[file.name] = file.path
|
|
1507
|
+
|
|
1508
|
+
|
|
1509
|
+
def _compute_md5(path: Path) -> str:
|
|
1510
|
+
"""Compute the MD5 checksum of a local file, as 32 lowercase hexadecimal digits."""
|
|
1511
|
+
with open(path, "rb", opener=open_regular_file) as fh:
|
|
1512
|
+
return hashlib.file_digest(fh, "md5").hexdigest()
|
|
1513
|
+
|
|
1514
|
+
|
|
1515
|
+
def _check_local_md5(files: Sequence[UploadFile], path_inventory: str):
|
|
1516
|
+
"""Check that the inventory describes the current contents of the local files.
|
|
1517
|
+
|
|
1518
|
+
Raises
|
|
1519
|
+
------
|
|
1520
|
+
ZenodoError
|
|
1521
|
+
When the MD5 checksum of a file differs from the one in the inventory.
|
|
1522
|
+
"""
|
|
1523
|
+
for file in files:
|
|
1524
|
+
if _compute_md5(file.path) != file.md5:
|
|
1525
|
+
raise ZenodoError(
|
|
1526
|
+
f"The file {file.path} has changed after the inventory {path_inventory} "
|
|
1527
|
+
"was written. Run `stepup build` to bring the inventory up to date, "
|
|
1528
|
+
"or, when you run the sync without StepUp, "
|
|
1529
|
+
"write the inventory again with `sd-make-inventory`."
|
|
1530
|
+
)
|
|
1531
|
+
|
|
1532
|
+
|
|
1533
|
+
def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
|
1534
|
+
"""Parse command-line arguments."""
|
|
1535
|
+
parser = argparse.ArgumentParser(
|
|
1536
|
+
prog="sd-sync-zenodo",
|
|
1537
|
+
description="Synchronize a draft dataset on Zenodo with your local files.",
|
|
1538
|
+
)
|
|
1539
|
+
parser.add_argument(
|
|
1540
|
+
"config",
|
|
1541
|
+
help=f"Configuration file. The format is selected by its suffix: {_format_suffixes()}.",
|
|
1542
|
+
)
|
|
1543
|
+
parser.add_argument(
|
|
1544
|
+
"description",
|
|
1545
|
+
help="A Markdown (.md) or HTML (.html) file describing the dataset. "
|
|
1546
|
+
"Markdown is converted to HTML before it is sent to Zenodo.",
|
|
1547
|
+
)
|
|
1548
|
+
parser.add_argument(
|
|
1549
|
+
"inventory",
|
|
1550
|
+
help="The inventory written by sd-make-inventory, "
|
|
1551
|
+
"which lists the files to upload to Zenodo, with their MD5 checksums. "
|
|
1552
|
+
"The first file is shown in the preview on Zenodo.",
|
|
1553
|
+
)
|
|
1554
|
+
parser.add_argument(
|
|
1555
|
+
"--verbose",
|
|
1556
|
+
"-v",
|
|
1557
|
+
default=False,
|
|
1558
|
+
action="store_true",
|
|
1559
|
+
help="Show details of communication with Zenodo endpoint.",
|
|
1560
|
+
)
|
|
1561
|
+
parser.add_argument(
|
|
1562
|
+
"--dry-run",
|
|
1563
|
+
default=False,
|
|
1564
|
+
action="store_true",
|
|
1565
|
+
help="Validate the configuration, print the metadata that would be sent to Zenodo "
|
|
1566
|
+
"and exit without contacting Zenodo.",
|
|
1567
|
+
)
|
|
1568
|
+
parser.add_argument(
|
|
1569
|
+
"--no-check-md5",
|
|
1570
|
+
default=False,
|
|
1571
|
+
action="store_true",
|
|
1572
|
+
help="Trust the MD5 checksums in the inventory without computing them again. "
|
|
1573
|
+
"Use this when the inventory is known to be up to date, "
|
|
1574
|
+
"e.g. when StepUp builds it.",
|
|
1575
|
+
)
|
|
1576
|
+
return parser.parse_args(argv)
|
|
1577
|
+
|
|
1578
|
+
|
|
1579
|
+
def _load_yaml(path: Path) -> Any:
|
|
1580
|
+
"""Parse a YAML config file."""
|
|
1581
|
+
with open(path, encoding="utf-8") as fh:
|
|
1582
|
+
return yaml.safe_load(fh)
|
|
1583
|
+
|
|
1584
|
+
|
|
1585
|
+
def _load_json(path: Path) -> Any:
|
|
1586
|
+
"""Parse a JSON config file."""
|
|
1587
|
+
with open(path, encoding="utf-8") as fh:
|
|
1588
|
+
return json.load(fh)
|
|
1589
|
+
|
|
1590
|
+
|
|
1591
|
+
def _load_toml(path: Path) -> Any:
|
|
1592
|
+
"""Parse a TOML config file."""
|
|
1593
|
+
with open(path, "rb") as fh:
|
|
1594
|
+
return tomllib.load(fh)
|
|
1595
|
+
|
|
1596
|
+
|
|
1597
|
+
CONFIG_LOADERS = {
|
|
1598
|
+
".yaml": _load_yaml,
|
|
1599
|
+
".yml": _load_yaml,
|
|
1600
|
+
".json": _load_json,
|
|
1601
|
+
".toml": _load_toml,
|
|
1602
|
+
}
|
|
1603
|
+
"""The parser to use for each config file suffix."""
|
|
1604
|
+
|
|
1605
|
+
LEGACY_ZENODO_JSON = ".zenodo.json"
|
|
1606
|
+
"""The metadata file that Zenodo reads when it archives a GitHub release."""
|
|
1607
|
+
|
|
1608
|
+
|
|
1609
|
+
def _format_suffixes() -> str:
|
|
1610
|
+
"""Join the supported config file suffixes into a comma-separated list."""
|
|
1611
|
+
return ", ".join(sorted(CONFIG_LOADERS))
|
|
1612
|
+
|
|
1613
|
+
|
|
1614
|
+
def _load_config_data(path: str | Path) -> dict[str, Any]:
|
|
1615
|
+
"""Load the raw contents of a config file, selecting the parser by file name suffix.
|
|
1616
|
+
|
|
1617
|
+
Parameters
|
|
1618
|
+
----------
|
|
1619
|
+
path
|
|
1620
|
+
The config file to read.
|
|
1621
|
+
|
|
1622
|
+
Returns
|
|
1623
|
+
-------
|
|
1624
|
+
data
|
|
1625
|
+
The mapping parsed from the file, not structured into a `Config` yet.
|
|
1626
|
+
"""
|
|
1627
|
+
path = Path(path)
|
|
1628
|
+
if path.name == LEGACY_ZENODO_JSON:
|
|
1629
|
+
raise ZenodoError(
|
|
1630
|
+
f"{path} is not a sd-sync-zenodo configuration file. "
|
|
1631
|
+
f"A file named {LEGACY_ZENODO_JSON} holds the metadata that Zenodo reads "
|
|
1632
|
+
"when it archives a GitHub release, which follows a different schema. "
|
|
1633
|
+
"It is documented in the GitHub integration section of "
|
|
1634
|
+
"https://developers.zenodo.org/#github"
|
|
1635
|
+
)
|
|
1636
|
+
loader = CONFIG_LOADERS.get(path.suffix.lower())
|
|
1637
|
+
if loader is None:
|
|
1638
|
+
raise ZenodoError(
|
|
1639
|
+
f"Cannot derive the format of the config file {path} from its suffix. "
|
|
1640
|
+
f"The supported suffixes are {_format_suffixes()}."
|
|
1641
|
+
)
|
|
1642
|
+
try:
|
|
1643
|
+
data = loader(path)
|
|
1644
|
+
except (OSError, ValueError, yaml.YAMLError) as exc:
|
|
1645
|
+
raise ZenodoError(f"Cannot read the config file {path}: {exc}") from exc
|
|
1646
|
+
if data is None:
|
|
1647
|
+
raise ZenodoError(f"The config file {path} is empty.")
|
|
1648
|
+
if not isinstance(data, dict):
|
|
1649
|
+
raise ZenodoError(
|
|
1650
|
+
f"The config file {path} must hold a mapping of keys to values at the top level, "
|
|
1651
|
+
f"not a {type(data).__name__}."
|
|
1652
|
+
)
|
|
1653
|
+
return data
|
|
1654
|
+
|
|
1655
|
+
|
|
1656
|
+
REPLACED_CONFIG_KEYS = {
|
|
1657
|
+
"paths": "List the files to upload in an inventory, written by sd-make-inventory.",
|
|
1658
|
+
"path_token": "Set the STEPUP_DATA_ZENODO_TOKEN environment variable instead.",
|
|
1659
|
+
"path_readme": "Pass the description file as the second argument "
|
|
1660
|
+
"of sync_zenodo() or sd-sync-zenodo instead.",
|
|
1661
|
+
"code_repository": "Move it into the 'custom_fields' section.",
|
|
1662
|
+
"metadata.description": "Write the description in a Markdown or HTML file instead, "
|
|
1663
|
+
"and pass it as the second argument of sync_zenodo() or sd-sync-zenodo.",
|
|
1664
|
+
"access.record": "Remove it, because Zenodo does not allow restricted records. "
|
|
1665
|
+
"Use 'files: restricted' in the 'access' section to restrict only the files.",
|
|
1666
|
+
}
|
|
1667
|
+
"""Keys that older config files may still contain, with a hint on how to replace them.
|
|
1668
|
+
|
|
1669
|
+
A dotted key is nested in the sections named by the parts before the last dot.
|
|
1670
|
+
"""
|
|
1671
|
+
|
|
1672
|
+
|
|
1673
|
+
def _check_outdated_config(data: dict[str, Any], config_path: str):
|
|
1674
|
+
"""Raise an informative error when the config file still uses a key that was replaced."""
|
|
1675
|
+
for key, hint in REPLACED_CONFIG_KEYS.items():
|
|
1676
|
+
*sections, name = key.split(".")
|
|
1677
|
+
section = data
|
|
1678
|
+
for section_name in sections:
|
|
1679
|
+
section = section.get(section_name) if isinstance(section, dict) else None
|
|
1680
|
+
if isinstance(section, dict) and name in section:
|
|
1681
|
+
raise ZenodoError(
|
|
1682
|
+
f"The config file {config_path} is outdated. "
|
|
1683
|
+
f"The '{key}' key is no longer used. {hint}"
|
|
1684
|
+
)
|
|
1685
|
+
|
|
1686
|
+
|
|
1687
|
+
def _check_endpoint_present(data: dict[str, Any], config_path: str):
|
|
1688
|
+
"""Raise an informative error when the config file does not name a Zenodo instance."""
|
|
1689
|
+
if "endpoint" not in data:
|
|
1690
|
+
raise ZenodoError(
|
|
1691
|
+
f"The config file {config_path} has no 'endpoint' field. "
|
|
1692
|
+
f"Set it to {PRODUCTION_ENDPOINT} for a dataset to publish, "
|
|
1693
|
+
f"or to {SANDBOX_ENDPOINT} for a trial on the Zenodo sandbox, "
|
|
1694
|
+
"which issues test DOIs and may delete its records at any time. "
|
|
1695
|
+
"The token in STEPUP_DATA_ZENODO_TOKEN must be created on the same instance."
|
|
1696
|
+
)
|
|
1697
|
+
|
|
1698
|
+
|
|
1699
|
+
def _make_converter() -> cattrs.Converter:
|
|
1700
|
+
"""Create the converter that structures the data of a config file into a `Config`."""
|
|
1701
|
+
converter = cattrs.Converter(forbid_extra_keys=True)
|
|
1702
|
+
converter.register_structure_hook(str, _structure_str)
|
|
1703
|
+
converter.register_structure_hook_func(lambda type_: type_ == list[str], _structure_list_str)
|
|
1704
|
+
# The hook factories take the converter as an argument,
|
|
1705
|
+
# which is bound here instead of by cattrs,
|
|
1706
|
+
# because cattrs only passes the converter to a factory as of version 24.1.
|
|
1707
|
+
converter.register_structure_hook_factory(
|
|
1708
|
+
attrs.has, lambda type_: _make_section_hook(type_, converter)
|
|
1709
|
+
)
|
|
1710
|
+
converter.register_structure_hook_factory(
|
|
1711
|
+
_is_list_of_sections, lambda type_: _make_list_of_sections_hook(type_, converter)
|
|
1712
|
+
)
|
|
1713
|
+
return converter
|
|
1714
|
+
|
|
1715
|
+
|
|
1716
|
+
def _make_section_hook(type_: type, converter: cattrs.Converter) -> Callable:
|
|
1717
|
+
"""Create a hook that structures a section of the config file into an attrs class.
|
|
1718
|
+
|
|
1719
|
+
Parameters
|
|
1720
|
+
----------
|
|
1721
|
+
type_
|
|
1722
|
+
The attrs class to structure into.
|
|
1723
|
+
converter
|
|
1724
|
+
The converter for which the hook is made.
|
|
1725
|
+
|
|
1726
|
+
Returns
|
|
1727
|
+
-------
|
|
1728
|
+
hook
|
|
1729
|
+
A cattrs structuring hook rejecting a value that is not a mapping.
|
|
1730
|
+
"""
|
|
1731
|
+
structure_mapping = make_dict_structure_fn(type_, converter)
|
|
1732
|
+
|
|
1733
|
+
def structure(value: Any, type__: type) -> Any:
|
|
1734
|
+
if not isinstance(value, Mapping):
|
|
1735
|
+
raise TypeError(
|
|
1736
|
+
f"Expected a mapping of keys to values, got {type(value).__name__}: {value!r}."
|
|
1737
|
+
)
|
|
1738
|
+
return structure_mapping(value, type__)
|
|
1739
|
+
|
|
1740
|
+
return structure
|
|
1741
|
+
|
|
1742
|
+
|
|
1743
|
+
def _is_list_of_sections(type_: Any) -> bool:
|
|
1744
|
+
"""Tell whether a type annotation describes a list of sections of the config file."""
|
|
1745
|
+
args = get_args(type_)
|
|
1746
|
+
return get_origin(type_) is list and len(args) == 1 and attrs.has(args[0])
|
|
1747
|
+
|
|
1748
|
+
|
|
1749
|
+
def _make_list_of_sections_hook(type_: type, converter: cattrs.Converter) -> Callable:
|
|
1750
|
+
"""Create a hook that structures a list of sections of the config file.
|
|
1751
|
+
|
|
1752
|
+
Parameters
|
|
1753
|
+
----------
|
|
1754
|
+
type_
|
|
1755
|
+
The list type to structure into, whose item type is an attrs class.
|
|
1756
|
+
converter
|
|
1757
|
+
The converter for which the hook is made.
|
|
1758
|
+
|
|
1759
|
+
Returns
|
|
1760
|
+
-------
|
|
1761
|
+
hook
|
|
1762
|
+
A cattrs structuring hook rejecting a value that is not a list.
|
|
1763
|
+
A string is rejected too, even though it is a sequence,
|
|
1764
|
+
because it would otherwise be structured item by item, one error per character.
|
|
1765
|
+
The errors of all items are collected,
|
|
1766
|
+
so that a single run reports every problem in the list.
|
|
1767
|
+
"""
|
|
1768
|
+
(item_type,) = get_args(type_)
|
|
1769
|
+
|
|
1770
|
+
def structure(value: Any, type__: type) -> Any:
|
|
1771
|
+
if isinstance(value, str) or not isinstance(value, Sequence):
|
|
1772
|
+
raise TypeError(f"Expected a list of mappings, got {type(value).__name__}: {value!r}.")
|
|
1773
|
+
items = []
|
|
1774
|
+
excs = []
|
|
1775
|
+
for index, item in enumerate(value):
|
|
1776
|
+
try:
|
|
1777
|
+
items.append(converter.structure(item, item_type))
|
|
1778
|
+
except (cattrs.BaseValidationError, TypeError, ValueError) as exc:
|
|
1779
|
+
# The note tells `cattrs.transform_error` where in the list the error occurred.
|
|
1780
|
+
note = IterableValidationNote(
|
|
1781
|
+
f"Structuring {type__} @ index {index}", index, item_type
|
|
1782
|
+
)
|
|
1783
|
+
exc.__notes__ = [*getattr(exc, "__notes__", []), note]
|
|
1784
|
+
excs.append(exc)
|
|
1785
|
+
if len(excs) > 0:
|
|
1786
|
+
raise IterableValidationError(f"While structuring {type__!r}", excs, type__)
|
|
1787
|
+
return items
|
|
1788
|
+
|
|
1789
|
+
return structure
|
|
1790
|
+
|
|
1791
|
+
|
|
1792
|
+
def _structure_str(value: Any, _type) -> str:
|
|
1793
|
+
"""Structure a string without coercing other types.
|
|
1794
|
+
|
|
1795
|
+
The default cattrs hook stringifies anything,
|
|
1796
|
+
which would silently accept an unquoted YAML value such as `version: 1.0`.
|
|
1797
|
+
"""
|
|
1798
|
+
if not isinstance(value, str):
|
|
1799
|
+
raise TypeError(
|
|
1800
|
+
f"Expected a string, got {type(value).__name__}: {value!r}. "
|
|
1801
|
+
"Enclose the value in quotes to make it a string."
|
|
1802
|
+
)
|
|
1803
|
+
return value
|
|
1804
|
+
|
|
1805
|
+
|
|
1806
|
+
def _structure_list_str(value: Any, _type) -> list[str]:
|
|
1807
|
+
"""Structure a list of strings, accepting a single string as a one element list.
|
|
1808
|
+
|
|
1809
|
+
A string is itself an iterable of strings,
|
|
1810
|
+
so the default cattrs hook would turn `keywords: coffee` into a list of characters.
|
|
1811
|
+
"""
|
|
1812
|
+
if isinstance(value, str):
|
|
1813
|
+
return [value]
|
|
1814
|
+
if isinstance(value, Sequence):
|
|
1815
|
+
return [_structure_str(item, str) for item in value]
|
|
1816
|
+
raise TypeError(
|
|
1817
|
+
f"Expected a string or a list of strings, got {type(value).__name__}: {value!r}."
|
|
1818
|
+
)
|
|
1819
|
+
|
|
1820
|
+
|
|
1821
|
+
def _format_error(exc: BaseException, type_: type | None) -> str:
|
|
1822
|
+
"""Format an error for `cattrs.transform_error`, keeping the message of a failed validation.
|
|
1823
|
+
|
|
1824
|
+
Parameters
|
|
1825
|
+
----------
|
|
1826
|
+
exc
|
|
1827
|
+
The exception raised while structuring one value.
|
|
1828
|
+
type_
|
|
1829
|
+
The type the value was structured into, if known.
|
|
1830
|
+
|
|
1831
|
+
Returns
|
|
1832
|
+
-------
|
|
1833
|
+
message
|
|
1834
|
+
A description of what is wrong with the value.
|
|
1835
|
+
"""
|
|
1836
|
+
if isinstance(exc, ValueError | TypeError) and len(exc.args) > 0:
|
|
1837
|
+
# Only the first argument holds the message.
|
|
1838
|
+
# The validators of attrs pass the attribute, the options and the value as well.
|
|
1839
|
+
return str(exc.args[0])
|
|
1840
|
+
return cattrs.v.format_exception(exc, type_)
|
|
1841
|
+
|
|
1842
|
+
|
|
1843
|
+
MIN_DESCRIPTION_LEN = 3
|
|
1844
|
+
"""The shortest description Zenodo accepts."""
|
|
1845
|
+
|
|
1846
|
+
|
|
1847
|
+
def _load_description(path: str | Path) -> str:
|
|
1848
|
+
"""Load the description from a Markdown or HTML file, and return it as HTML."""
|
|
1849
|
+
path = Path(path)
|
|
1850
|
+
suffix = path.suffix.lower()
|
|
1851
|
+
if suffix not in (".md", ".html"):
|
|
1852
|
+
raise ZenodoError("The description file must be a Markdown (.md) or HTML (.html) file.")
|
|
1853
|
+
if not path.is_file():
|
|
1854
|
+
raise ZenodoError(f"Description file {path} does not exist.")
|
|
1855
|
+
with open(path, encoding="utf-8") as fh:
|
|
1856
|
+
description = fh.read()
|
|
1857
|
+
if suffix == ".md":
|
|
1858
|
+
description = MarkdownIt().render(description)
|
|
1859
|
+
if len(description) < MIN_DESCRIPTION_LEN:
|
|
1860
|
+
raise ZenodoError(
|
|
1861
|
+
f"The description file {path} holds too little text. "
|
|
1862
|
+
f"Zenodo reads a description of at least {MIN_DESCRIPTION_LEN} characters."
|
|
1863
|
+
)
|
|
1864
|
+
return description
|
|
1865
|
+
|
|
1866
|
+
|
|
1867
|
+
def _update_online(
|
|
1868
|
+
zenodo: ZenodoWrapper, config: Config, description: str, files: Sequence[UploadFile]
|
|
1869
|
+
):
|
|
1870
|
+
"""Make the online data set up to date with the local information.
|
|
1871
|
+
|
|
1872
|
+
Parameters
|
|
1873
|
+
----------
|
|
1874
|
+
zenodo
|
|
1875
|
+
The Zenodo wrapper.
|
|
1876
|
+
config
|
|
1877
|
+
The configuration loaded from the config file.
|
|
1878
|
+
description
|
|
1879
|
+
The description of the dataset, in HTML.
|
|
1880
|
+
files
|
|
1881
|
+
The files to upload to Zenodo, as listed in the inventory.
|
|
1882
|
+
"""
|
|
1883
|
+
rid = None
|
|
1884
|
+
if config.path_record_id.exists():
|
|
1885
|
+
rid = config.path_record_id.read_text(encoding="utf-8").strip()
|
|
1886
|
+
if len(rid) == 0:
|
|
1887
|
+
raise ZenodoError(f"The record ID file {config.path_record_id} is empty.")
|
|
1888
|
+
if rid is None:
|
|
1889
|
+
_upload_new_record(zenodo, config, description, files)
|
|
1890
|
+
else:
|
|
1891
|
+
_refresh_existing_record(zenodo, rid, config, description, files)
|
|
1892
|
+
|
|
1893
|
+
|
|
1894
|
+
def _write_record_id(path: Path, rid: str):
|
|
1895
|
+
"""Store the id of the record that the next run has to update.
|
|
1896
|
+
|
|
1897
|
+
The parent directory is created when it does not exist,
|
|
1898
|
+
because the record id file is not an output of the StepUp step
|
|
1899
|
+
and its directory is therefore not prepared for it.
|
|
1900
|
+
|
|
1901
|
+
Raises
|
|
1902
|
+
------
|
|
1903
|
+
ZenodoError
|
|
1904
|
+
When the file cannot be written.
|
|
1905
|
+
The record then exists on Zenodo while nothing local points at it,
|
|
1906
|
+
so the message says which id to record by hand.
|
|
1907
|
+
"""
|
|
1908
|
+
try:
|
|
1909
|
+
# A bare file name has no parent directory to create.
|
|
1910
|
+
if path.parent != "":
|
|
1911
|
+
path.parent.makedirs_p()
|
|
1912
|
+
with open(path, "w", encoding="utf-8", newline="\n") as fh:
|
|
1913
|
+
fh.write(f"{rid}\n")
|
|
1914
|
+
except OSError as exc:
|
|
1915
|
+
raise ZenodoError(
|
|
1916
|
+
f"Cannot write the record ID file {path}: {exc}. "
|
|
1917
|
+
f"Record {rid} exists on Zenodo, so put its id in that file by hand, "
|
|
1918
|
+
"or discard the draft in the web interface of Zenodo."
|
|
1919
|
+
) from exc
|
|
1920
|
+
|
|
1921
|
+
|
|
1922
|
+
def _upload_new_record(
|
|
1923
|
+
zenodo: ZenodoWrapper, config: Config, description: str, files: Sequence[UploadFile]
|
|
1924
|
+
):
|
|
1925
|
+
"""Create a new record on Zenodo and fill it like any other draft.
|
|
1926
|
+
|
|
1927
|
+
The record id is stored before the files are uploaded,
|
|
1928
|
+
so a failed upload leaves a draft that the next run completes,
|
|
1929
|
+
instead of an orphan that has to be discarded by hand.
|
|
1930
|
+
"""
|
|
1931
|
+
record = zenodo.create_new_record(config, description)
|
|
1932
|
+
rid = _record_id(record)
|
|
1933
|
+
_write_record_id(config.path_record_id, rid)
|
|
1934
|
+
CONSOLE.print(f"[b]New record:[/b] {_record_url(zenodo, record)}")
|
|
1935
|
+
_refresh_draft(zenodo, rid, record, config, description, files)
|
|
1936
|
+
|
|
1937
|
+
|
|
1938
|
+
def _refresh_existing_record(
|
|
1939
|
+
zenodo: ZenodoWrapper,
|
|
1940
|
+
rid: str,
|
|
1941
|
+
config: Config,
|
|
1942
|
+
description: str,
|
|
1943
|
+
files: Sequence[UploadFile],
|
|
1944
|
+
):
|
|
1945
|
+
"""Refresh an existing record on Zenodo.
|
|
1946
|
+
|
|
1947
|
+
The metadata is always sent again, without comparing it to what is online,
|
|
1948
|
+
because Zenodo normalizes some values, so a comparison is not worth the effort.
|
|
1949
|
+
As observed on 2026-11-21, it strips the trailing newline of the description,
|
|
1950
|
+
prefixes arXiv identifiers with `arXiv:`,
|
|
1951
|
+
adds the scheme to identifiers sent without one,
|
|
1952
|
+
and fills in the names of ROR funders and the details of awards given by id.
|
|
1953
|
+
"""
|
|
1954
|
+
# When a dataset exists, the actions depend on the current status of the record.
|
|
1955
|
+
record = zenodo.get_record(rid)
|
|
1956
|
+
CONSOLE.print(f"[b]Existing record:[/b] {_record_url(zenodo, record)}")
|
|
1957
|
+
|
|
1958
|
+
if _is_published(record):
|
|
1959
|
+
_check_version_chain(zenodo, record, config)
|
|
1960
|
+
if config.metadata.version == _get_record_version(record):
|
|
1961
|
+
named_files = {file.name: file for file in files}
|
|
1962
|
+
_check_record_md5(record, named_files, config.metadata.version)
|
|
1963
|
+
publication_date = _record_publication_date(record)
|
|
1964
|
+
_republish_metadata(zenodo, rid, config, description, files, publication_date)
|
|
1965
|
+
else:
|
|
1966
|
+
record = _create_new_version(zenodo, rid, config)
|
|
1967
|
+
rid = _record_id(record)
|
|
1968
|
+
_write_record_id(config.path_record_id, rid)
|
|
1969
|
+
_refresh_draft(zenodo, rid, record, config, description, files)
|
|
1970
|
+
else:
|
|
1971
|
+
_refresh_draft(zenodo, rid, record, config, description, files)
|
|
1972
|
+
|
|
1973
|
+
|
|
1974
|
+
def _refresh_draft(
|
|
1975
|
+
zenodo: ZenodoWrapper,
|
|
1976
|
+
rid: str,
|
|
1977
|
+
record: dict[str, Any],
|
|
1978
|
+
config: Config,
|
|
1979
|
+
description: str,
|
|
1980
|
+
files: Sequence[UploadFile],
|
|
1981
|
+
):
|
|
1982
|
+
"""Bring the files and the metadata of a draft record up to date.
|
|
1983
|
+
|
|
1984
|
+
The files are refreshed first,
|
|
1985
|
+
so that the metadata update can select the first file as the default preview.
|
|
1986
|
+
Zenodo drops a default preview whose file is deleted,
|
|
1987
|
+
so a preview left over from an earlier run never blocks the refresh of the files.
|
|
1988
|
+
|
|
1989
|
+
Parameters
|
|
1990
|
+
----------
|
|
1991
|
+
zenodo
|
|
1992
|
+
The Zenodo wrapper.
|
|
1993
|
+
rid
|
|
1994
|
+
The id of the draft record.
|
|
1995
|
+
record
|
|
1996
|
+
The draft record as returned by the Zenodo API.
|
|
1997
|
+
config
|
|
1998
|
+
The configuration loaded from the config file.
|
|
1999
|
+
description
|
|
2000
|
+
The description of the dataset, in HTML.
|
|
2001
|
+
files
|
|
2002
|
+
The files to upload to Zenodo, as listed in the inventory.
|
|
2003
|
+
"""
|
|
2004
|
+
named_files = {file.name: file for file in files}
|
|
2005
|
+
_refresh_files(zenodo, rid, record, named_files, config.metadata.version)
|
|
2006
|
+
CONSOLE.print("Updating metadata of draft record.")
|
|
2007
|
+
_check_draft_errors(zenodo.update_metadata(rid, config, description, files), rid)
|
|
2008
|
+
|
|
2009
|
+
|
|
2010
|
+
def _check_draft_errors(response: dict[str, Any], rid: str):
|
|
2011
|
+
"""Report the problems that Zenodo found in the metadata of a draft.
|
|
2012
|
+
|
|
2013
|
+
Zenodo accepts a metadata update with a schema violation,
|
|
2014
|
+
and lists the problem in the `errors` of the response instead of refusing the request.
|
|
2015
|
+
The offending field is dropped from the stored draft,
|
|
2016
|
+
so the problem only shows up when the draft is published.
|
|
2017
|
+
This was observed on the Zenodo sandbox on 2026-11-21,
|
|
2018
|
+
for example for a title that is too short or a missing publisher.
|
|
2019
|
+
|
|
2020
|
+
Call this only on a response to a metadata update of a draft that has all its files,
|
|
2021
|
+
because Zenodo also lists the missing files of a draft as an error.
|
|
2022
|
+
|
|
2023
|
+
Parameters
|
|
2024
|
+
----------
|
|
2025
|
+
response
|
|
2026
|
+
The response of Zenodo to the metadata update.
|
|
2027
|
+
rid
|
|
2028
|
+
The id of the draft record, used in the message.
|
|
2029
|
+
|
|
2030
|
+
Raises
|
|
2031
|
+
------
|
|
2032
|
+
ZenodoError
|
|
2033
|
+
When the response lists at least one error.
|
|
2034
|
+
The message lists every field with its messages.
|
|
2035
|
+
The draft is kept on Zenodo, so the next run can repair it.
|
|
2036
|
+
"""
|
|
2037
|
+
errors = response.get("errors") if isinstance(response, dict) else None
|
|
2038
|
+
if not errors:
|
|
2039
|
+
return
|
|
2040
|
+
lines = []
|
|
2041
|
+
for error in errors if isinstance(errors, list) else [errors]:
|
|
2042
|
+
if isinstance(error, dict) and "field" in error:
|
|
2043
|
+
messages = error.get("messages")
|
|
2044
|
+
if isinstance(messages, list):
|
|
2045
|
+
messages = " ".join(str(message) for message in messages)
|
|
2046
|
+
lines.append(f"- {error['field']}: {messages}")
|
|
2047
|
+
else:
|
|
2048
|
+
lines.append(f"- {error!r}")
|
|
2049
|
+
raise ZenodoError(
|
|
2050
|
+
f"Zenodo found problems in the metadata of the draft of record {rid}:\n"
|
|
2051
|
+
+ "\n".join(lines)
|
|
2052
|
+
+ "\nThe draft is kept on Zenodo. "
|
|
2053
|
+
"Correct the configuration, and the next run will repair the draft."
|
|
2054
|
+
)
|
|
2055
|
+
|
|
2056
|
+
|
|
2057
|
+
def _check_version_chain(zenodo: ZenodoWrapper, record: dict[str, Any], config: Config):
|
|
2058
|
+
"""Check a published record against the other published versions of the same dataset.
|
|
2059
|
+
|
|
2060
|
+
Zenodo stores the version as free text and never orders versions by it,
|
|
2061
|
+
so the version chain on Zenodo is the only thing that can tell
|
|
2062
|
+
a new version from a stale checkout or a revert.
|
|
2063
|
+
|
|
2064
|
+
Parameters
|
|
2065
|
+
----------
|
|
2066
|
+
zenodo
|
|
2067
|
+
The Zenodo wrapper.
|
|
2068
|
+
record
|
|
2069
|
+
The published record whose id is stored in the local record id file.
|
|
2070
|
+
config
|
|
2071
|
+
The configuration loaded from the config file.
|
|
2072
|
+
|
|
2073
|
+
Raises
|
|
2074
|
+
------
|
|
2075
|
+
ZenodoError
|
|
2076
|
+
When the record is not the latest published version of the dataset,
|
|
2077
|
+
or when the local version is already published as another version.
|
|
2078
|
+
"""
|
|
2079
|
+
rid = _record_id(record)
|
|
2080
|
+
version = config.metadata.version
|
|
2081
|
+
latest = None
|
|
2082
|
+
taken = None
|
|
2083
|
+
for other in zenodo.get_versions(rid):
|
|
2084
|
+
if other.get("versions", {}).get("is_latest", False):
|
|
2085
|
+
latest = other
|
|
2086
|
+
if _record_id(other) != rid and _get_record_version(other) == version:
|
|
2087
|
+
taken = other
|
|
2088
|
+
if latest is None:
|
|
2089
|
+
raise ZenodoError(
|
|
2090
|
+
f"Zenodo did not mark any published version of record {rid} as the latest one. "
|
|
2091
|
+
f"The Accept header of this module, {INVENIORDM_MIMETYPE}, may no longer be honored."
|
|
2092
|
+
)
|
|
2093
|
+
if _record_id(latest) != rid:
|
|
2094
|
+
raise ZenodoError(
|
|
2095
|
+
f"Record {rid} ({_describe_version(record)}) "
|
|
2096
|
+
"is not the latest published version of this dataset. "
|
|
2097
|
+
f"That is record {_record_id(latest)} ({_describe_version(latest)}). "
|
|
2098
|
+
f"Update {config.path_record_id} and the version in the config file, "
|
|
2099
|
+
"e.g. by pulling in the work of your collaborators."
|
|
2100
|
+
)
|
|
2101
|
+
if taken is not None:
|
|
2102
|
+
raise ZenodoError(
|
|
2103
|
+
f"Version {version} is already published as record {_record_id(taken)} of "
|
|
2104
|
+
f"this dataset, while the latest published version has {_describe_version(latest)}. "
|
|
2105
|
+
"Put a version in the config file that was not published before."
|
|
2106
|
+
)
|
|
2107
|
+
|
|
2108
|
+
|
|
2109
|
+
def _entry_md5(entry: dict[str, Any]) -> str:
|
|
2110
|
+
"""Extract the MD5 sum that Zenodo computed for a file, as a hexadecimal string.
|
|
2111
|
+
|
|
2112
|
+
Parameters
|
|
2113
|
+
----------
|
|
2114
|
+
entry
|
|
2115
|
+
The file entry of a record, or the response to the commit of an upload.
|
|
2116
|
+
|
|
2117
|
+
Returns
|
|
2118
|
+
-------
|
|
2119
|
+
md5
|
|
2120
|
+
The hexadecimal digest, without the name of the algorithm.
|
|
2121
|
+
|
|
2122
|
+
Raises
|
|
2123
|
+
------
|
|
2124
|
+
ZenodoError
|
|
2125
|
+
When Zenodo used another algorithm, whose digest cannot be compared to a local MD5 sum.
|
|
2126
|
+
"""
|
|
2127
|
+
checksum = entry.get("checksum")
|
|
2128
|
+
if not (isinstance(checksum, str) and checksum.startswith(MD5_PREFIX)):
|
|
2129
|
+
raise ZenodoError(f"Zenodo returned an unexpected checksum format: {checksum!r}")
|
|
2130
|
+
return checksum[len(MD5_PREFIX) :]
|
|
2131
|
+
|
|
2132
|
+
|
|
2133
|
+
def _search_hits(data: dict[str, Any]) -> list[dict[str, Any]]:
|
|
2134
|
+
"""Extract the records from one page of a search result.
|
|
2135
|
+
|
|
2136
|
+
Parameters
|
|
2137
|
+
----------
|
|
2138
|
+
data
|
|
2139
|
+
A search result as returned by the Zenodo API.
|
|
2140
|
+
|
|
2141
|
+
Returns
|
|
2142
|
+
-------
|
|
2143
|
+
hits
|
|
2144
|
+
The records on the requested page.
|
|
2145
|
+
"""
|
|
2146
|
+
hits = data.get("hits")
|
|
2147
|
+
if not (isinstance(hits, dict) and isinstance(hits.get("hits"), list)):
|
|
2148
|
+
raise ZenodoError(
|
|
2149
|
+
"Zenodo did not describe a search result as an object with a list of hits. "
|
|
2150
|
+
f"The Accept header of this module, {INVENIORDM_MIMETYPE}, may no longer be honored."
|
|
2151
|
+
)
|
|
2152
|
+
return hits["hits"]
|
|
2153
|
+
|
|
2154
|
+
|
|
2155
|
+
def _get_record_version(record: dict[str, Any]) -> str | None:
|
|
2156
|
+
"""Extract the version of a record.
|
|
2157
|
+
|
|
2158
|
+
Zenodo does not require a version,
|
|
2159
|
+
so a record made outside of `sd-sync-zenodo` may well carry none.
|
|
2160
|
+
|
|
2161
|
+
Parameters
|
|
2162
|
+
----------
|
|
2163
|
+
record
|
|
2164
|
+
A record as returned by the Zenodo API.
|
|
2165
|
+
|
|
2166
|
+
Returns
|
|
2167
|
+
-------
|
|
2168
|
+
version
|
|
2169
|
+
The version Zenodo stored, or `None` when the record has none.
|
|
2170
|
+
"""
|
|
2171
|
+
return record.get("metadata", {}).get("version")
|
|
2172
|
+
|
|
2173
|
+
|
|
2174
|
+
def _is_published(record: dict[str, Any]) -> bool:
|
|
2175
|
+
"""Tell whether a record is published, as opposed to a draft that was never published.
|
|
2176
|
+
|
|
2177
|
+
Parameters
|
|
2178
|
+
----------
|
|
2179
|
+
record
|
|
2180
|
+
A record as returned by the Zenodo API.
|
|
2181
|
+
|
|
2182
|
+
Returns
|
|
2183
|
+
-------
|
|
2184
|
+
is_published
|
|
2185
|
+
Whether the record is published.
|
|
2186
|
+
|
|
2187
|
+
Raises
|
|
2188
|
+
------
|
|
2189
|
+
ZenodoError
|
|
2190
|
+
When the record does not say, because acting on a guess would send
|
|
2191
|
+
the requests meant for a draft to a published record, or vice versa.
|
|
2192
|
+
"""
|
|
2193
|
+
is_published = record.get("is_published")
|
|
2194
|
+
if not isinstance(is_published, bool):
|
|
2195
|
+
raise ZenodoError(
|
|
2196
|
+
f"Zenodo did not say whether record {record.get('id')} is published. "
|
|
2197
|
+
f"The Accept header of this module, {INVENIORDM_MIMETYPE}, may no longer be honored."
|
|
2198
|
+
)
|
|
2199
|
+
return is_published
|
|
2200
|
+
|
|
2201
|
+
|
|
2202
|
+
def _record_publication_date(record: dict[str, Any]) -> str | None:
|
|
2203
|
+
"""Extract the publication date of a record.
|
|
2204
|
+
|
|
2205
|
+
Parameters
|
|
2206
|
+
----------
|
|
2207
|
+
record
|
|
2208
|
+
A record as returned by the Zenodo API.
|
|
2209
|
+
|
|
2210
|
+
Returns
|
|
2211
|
+
-------
|
|
2212
|
+
publication_date
|
|
2213
|
+
The publication date Zenodo stored, in ISO format,
|
|
2214
|
+
or `None` when the record has none.
|
|
2215
|
+
"""
|
|
2216
|
+
return record.get("metadata", {}).get("publication_date")
|
|
2217
|
+
|
|
2218
|
+
|
|
2219
|
+
def _record_id(record: dict[str, Any]) -> str:
|
|
2220
|
+
"""Extract the id of a record.
|
|
2221
|
+
|
|
2222
|
+
Parameters
|
|
2223
|
+
----------
|
|
2224
|
+
record
|
|
2225
|
+
A record as returned by the Zenodo API.
|
|
2226
|
+
|
|
2227
|
+
Returns
|
|
2228
|
+
-------
|
|
2229
|
+
rid
|
|
2230
|
+
The id of the record, as the string that identifies it in an address.
|
|
2231
|
+
|
|
2232
|
+
Raises
|
|
2233
|
+
------
|
|
2234
|
+
ZenodoError
|
|
2235
|
+
When the record does not carry an id.
|
|
2236
|
+
"""
|
|
2237
|
+
rid = record.get("id")
|
|
2238
|
+
if rid is None:
|
|
2239
|
+
raise ZenodoError(
|
|
2240
|
+
"Zenodo did not send the id of a record. "
|
|
2241
|
+
f"The Accept header of this module, {INVENIORDM_MIMETYPE}, may no longer be honored."
|
|
2242
|
+
)
|
|
2243
|
+
return str(rid)
|
|
2244
|
+
|
|
2245
|
+
|
|
2246
|
+
def _record_url(zenodo: ZenodoWrapper, record: dict[str, Any]) -> str:
|
|
2247
|
+
"""Build the address of a record to show to the user.
|
|
2248
|
+
|
|
2249
|
+
Parameters
|
|
2250
|
+
----------
|
|
2251
|
+
zenodo
|
|
2252
|
+
The Zenodo wrapper.
|
|
2253
|
+
record
|
|
2254
|
+
A record as returned by the Zenodo API.
|
|
2255
|
+
|
|
2256
|
+
Returns
|
|
2257
|
+
-------
|
|
2258
|
+
url
|
|
2259
|
+
The address of the record on the website of Zenodo,
|
|
2260
|
+
or its address in the API when Zenodo did not send one.
|
|
2261
|
+
"""
|
|
2262
|
+
url = record.get("links", {}).get("self_html")
|
|
2263
|
+
return f"{zenodo.endpoint}/records/{_record_id(record)}" if url is None else url
|
|
2264
|
+
|
|
2265
|
+
|
|
2266
|
+
def _describe_version(record: dict[str, Any]) -> str:
|
|
2267
|
+
"""Describe the version of a record for use in an error message."""
|
|
2268
|
+
version = _get_record_version(record)
|
|
2269
|
+
return "no version" if version is None else f"version {version}"
|
|
2270
|
+
|
|
2271
|
+
|
|
2272
|
+
def _get_record_files(record: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
|
2273
|
+
"""Extract the file entries of a record.
|
|
2274
|
+
|
|
2275
|
+
Parameters
|
|
2276
|
+
----------
|
|
2277
|
+
record
|
|
2278
|
+
A record as returned by the Zenodo API.
|
|
2279
|
+
|
|
2280
|
+
Returns
|
|
2281
|
+
-------
|
|
2282
|
+
entries
|
|
2283
|
+
The file entry of every file in the record, keyed by file name.
|
|
2284
|
+
An entry of a draft record whose content is not uploaded yet carries no checksum.
|
|
2285
|
+
"""
|
|
2286
|
+
files = record.get("files")
|
|
2287
|
+
if not isinstance(files, dict):
|
|
2288
|
+
raise ZenodoError(
|
|
2289
|
+
"Zenodo did not describe the files of a record as an object with entries. "
|
|
2290
|
+
f"It sent a {type(files).__name__} instead. "
|
|
2291
|
+
f"The Accept header of this module, {INVENIORDM_MIMETYPE}, may no longer be honored."
|
|
2292
|
+
)
|
|
2293
|
+
return files.get("entries", {})
|
|
2294
|
+
|
|
2295
|
+
|
|
2296
|
+
@attrs.define(frozen=True)
|
|
2297
|
+
class FileDiff:
|
|
2298
|
+
"""The comparison of the online file entries of a record with the local files.
|
|
2299
|
+
|
|
2300
|
+
Every name occurs in exactly one of the fields, and the names within a field are in the order
|
|
2301
|
+
of the online entries, except for `missing`, which follows the order of the local files.
|
|
2302
|
+
"""
|
|
2303
|
+
|
|
2304
|
+
missing: tuple[str, ...] = attrs.field(converter=tuple)
|
|
2305
|
+
"""Names of local files that do not exist online."""
|
|
2306
|
+
|
|
2307
|
+
extra: tuple[str, ...] = attrs.field(converter=tuple)
|
|
2308
|
+
"""Names of online files that do not exist locally."""
|
|
2309
|
+
|
|
2310
|
+
changed: tuple[str, ...] = attrs.field(converter=tuple)
|
|
2311
|
+
"""Names of files whose online checksum differs from the local MD5 checksum."""
|
|
2312
|
+
|
|
2313
|
+
same: tuple[str, ...] = attrs.field(converter=tuple)
|
|
2314
|
+
"""Names of files whose online checksum equals the local MD5 checksum."""
|
|
2315
|
+
|
|
2316
|
+
incomplete: tuple[str, ...] = attrs.field(converter=tuple)
|
|
2317
|
+
"""Names of local files that Zenodo knows without content, hence without checksum."""
|
|
2318
|
+
|
|
2319
|
+
|
|
2320
|
+
def _diff_files(record: dict[str, Any], files: dict[str, UploadFile]) -> FileDiff:
|
|
2321
|
+
"""Compare the file entries of a record with the local files, without side effects.
|
|
2322
|
+
|
|
2323
|
+
Parameters
|
|
2324
|
+
----------
|
|
2325
|
+
record
|
|
2326
|
+
A record as returned by the Zenodo API.
|
|
2327
|
+
files
|
|
2328
|
+
The files to upload to Zenodo, keyed by file name.
|
|
2329
|
+
|
|
2330
|
+
Returns
|
|
2331
|
+
-------
|
|
2332
|
+
diff
|
|
2333
|
+
The names classified by how the online and local files relate.
|
|
2334
|
+
An online entry without checksum that has a local counterpart is `incomplete`.
|
|
2335
|
+
"""
|
|
2336
|
+
entries = _get_record_files(record)
|
|
2337
|
+
extra, changed, same, incomplete = [], [], [], []
|
|
2338
|
+
for name, entry in entries.items():
|
|
2339
|
+
if name not in files:
|
|
2340
|
+
extra.append(name)
|
|
2341
|
+
elif entry.get("checksum") is None:
|
|
2342
|
+
incomplete.append(name)
|
|
2343
|
+
elif files[name].md5 != _entry_md5(entry):
|
|
2344
|
+
changed.append(name)
|
|
2345
|
+
else:
|
|
2346
|
+
same.append(name)
|
|
2347
|
+
missing = [name for name in files if name not in entries]
|
|
2348
|
+
return FileDiff(missing, extra, changed, same, incomplete)
|
|
2349
|
+
|
|
2350
|
+
|
|
2351
|
+
PUBLISHED_FILE_MISMATCH_HINT = (
|
|
2352
|
+
"The files of a published version cannot be changed. "
|
|
2353
|
+
"Put a version in the config file that was not published before, "
|
|
2354
|
+
"so that the local files are deposited as a new version."
|
|
2355
|
+
)
|
|
2356
|
+
|
|
2357
|
+
|
|
2358
|
+
def _check_record_md5(record: dict[str, Any], files: dict[str, UploadFile], version: str):
|
|
2359
|
+
"""Check that the files of a published record are identical to the local ones.
|
|
2360
|
+
|
|
2361
|
+
Parameters
|
|
2362
|
+
----------
|
|
2363
|
+
record
|
|
2364
|
+
The published record as returned by the Zenodo API.
|
|
2365
|
+
files
|
|
2366
|
+
The files to upload to Zenodo, keyed by file name.
|
|
2367
|
+
version
|
|
2368
|
+
The version of the dataset, used in the messages.
|
|
2369
|
+
|
|
2370
|
+
Raises
|
|
2371
|
+
------
|
|
2372
|
+
ZenodoError
|
|
2373
|
+
When a file exists on only one side, or when two files with the same name differ.
|
|
2374
|
+
"""
|
|
2375
|
+
entries = _get_record_files(record)
|
|
2376
|
+
for name in entries:
|
|
2377
|
+
CONSOLE.print(f"[cyan]Checking MD5:[/cyan] {name} ({version}, published)")
|
|
2378
|
+
diff = _diff_files(record, files)
|
|
2379
|
+
if diff.extra:
|
|
2380
|
+
raise ZenodoError(
|
|
2381
|
+
f"File {diff.extra[0]} exists online but not locally ({version}, published). "
|
|
2382
|
+
f"{PUBLISHED_FILE_MISMATCH_HINT}"
|
|
2383
|
+
)
|
|
2384
|
+
if diff.changed:
|
|
2385
|
+
name = diff.changed[0]
|
|
2386
|
+
raise ZenodoError(
|
|
2387
|
+
f"MD5 checksum mismatch for {files[name].path} ({version}, published), "
|
|
2388
|
+
f"local: {files[name].md5}, online: {_entry_md5(entries[name])}. "
|
|
2389
|
+
f"{PUBLISHED_FILE_MISMATCH_HINT}"
|
|
2390
|
+
)
|
|
2391
|
+
if diff.incomplete:
|
|
2392
|
+
raise ZenodoError(
|
|
2393
|
+
f"File {diff.incomplete[0]} has no checksum online ({version}, published). "
|
|
2394
|
+
f"{PUBLISHED_FILE_MISMATCH_HINT}"
|
|
2395
|
+
)
|
|
2396
|
+
if diff.missing:
|
|
2397
|
+
raise ZenodoError(
|
|
2398
|
+
f"File {diff.missing[0]} exists locally but not online ({version}, published). "
|
|
2399
|
+
f"{PUBLISHED_FILE_MISMATCH_HINT}"
|
|
2400
|
+
)
|
|
2401
|
+
|
|
2402
|
+
|
|
2403
|
+
def _republish_metadata(
|
|
2404
|
+
zenodo: ZenodoWrapper,
|
|
2405
|
+
rid: str,
|
|
2406
|
+
config: Config,
|
|
2407
|
+
description: str,
|
|
2408
|
+
files: Sequence[UploadFile],
|
|
2409
|
+
publication_date: str | None,
|
|
2410
|
+
):
|
|
2411
|
+
"""Put a record in edit mode, update the metadata and publish again.
|
|
2412
|
+
|
|
2413
|
+
The publication date of the record is preserved,
|
|
2414
|
+
because this version was published on that date, not today.
|
|
2415
|
+
"""
|
|
2416
|
+
CONSOLE.print(
|
|
2417
|
+
f"Editing metadata and publishing same version ({config.metadata.version}) again."
|
|
2418
|
+
)
|
|
2419
|
+
zenodo.edit_record(rid)
|
|
2420
|
+
response = zenodo.update_metadata(rid, config, description, files, publication_date)
|
|
2421
|
+
_check_draft_errors(response, rid)
|
|
2422
|
+
zenodo.publish_record(rid)
|
|
2423
|
+
|
|
2424
|
+
|
|
2425
|
+
def _create_new_version(zenodo: ZenodoWrapper, rid: str, config: Config) -> dict[str, Any]:
|
|
2426
|
+
"""Create a new version of the dataset."""
|
|
2427
|
+
draft = zenodo.create_new_version(rid)
|
|
2428
|
+
CONSOLE.print(
|
|
2429
|
+
f"Preparing the draft of a new version ({config.metadata.version}): {draft.get('id')}"
|
|
2430
|
+
)
|
|
2431
|
+
return draft
|
|
2432
|
+
|
|
2433
|
+
|
|
2434
|
+
def _refresh_files(
|
|
2435
|
+
zenodo: ZenodoWrapper,
|
|
2436
|
+
rid: str,
|
|
2437
|
+
record: dict[str, Any],
|
|
2438
|
+
files: dict[str, UploadFile],
|
|
2439
|
+
version: str,
|
|
2440
|
+
):
|
|
2441
|
+
"""Refresh the online files.
|
|
2442
|
+
|
|
2443
|
+
Only files that do not exist online yet or have changed locally are uploaded.
|
|
2444
|
+
Files that are no longer listed locally are removed online.
|
|
2445
|
+
The files to upload are declared together in one request.
|
|
2446
|
+
|
|
2447
|
+
Parameters
|
|
2448
|
+
----------
|
|
2449
|
+
zenodo
|
|
2450
|
+
The Zenodo wrapper.
|
|
2451
|
+
rid
|
|
2452
|
+
The id of the draft record.
|
|
2453
|
+
record
|
|
2454
|
+
The draft record as returned by the Zenodo API.
|
|
2455
|
+
files
|
|
2456
|
+
The files to upload to Zenodo, keyed by file name.
|
|
2457
|
+
version
|
|
2458
|
+
The version of the dataset, used in the messages.
|
|
2459
|
+
"""
|
|
2460
|
+
diff = _diff_files(record, files)
|
|
2461
|
+
for name in diff.extra:
|
|
2462
|
+
CONSOLE.print(f"[red]Deleting:[/red] {name} ({version}, draft)")
|
|
2463
|
+
zenodo.delete_file(rid, name)
|
|
2464
|
+
for name in diff.incomplete:
|
|
2465
|
+
# The file is declared already, so only its content has to be sent.
|
|
2466
|
+
CONSOLE.print(f"[green]Completing:[/green] {files[name].path} ({version}, draft)")
|
|
2467
|
+
zenodo.upload_file(rid, files[name])
|
|
2468
|
+
for name in diff.changed:
|
|
2469
|
+
CONSOLE.print(f"[yellow]Replacing:[/yellow] {files[name].path} ({version}, draft)")
|
|
2470
|
+
zenodo.delete_file(rid, name)
|
|
2471
|
+
for name in diff.same:
|
|
2472
|
+
CONSOLE.print(f"[cyan]Same MD5:[/cyan] {files[name].path} ({version}, draft)")
|
|
2473
|
+
new_files = [files[name] for name in (*diff.changed, *diff.missing)]
|
|
2474
|
+
if len(new_files) > 0:
|
|
2475
|
+
zenodo.start_uploads(rid, new_files)
|
|
2476
|
+
for file in new_files:
|
|
2477
|
+
CONSOLE.print(f"[green]Uploading:[/green] {file.path} ({version}, draft)")
|
|
2478
|
+
zenodo.upload_file(rid, file)
|
|
2479
|
+
|
|
2480
|
+
|
|
2481
|
+
if __name__ == "__main__":
|
|
2482
|
+
sys.exit(main())
|