24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414 | class CodeMeta(ProjectMetadataWriter):
"""Codemeta.json parser and saver."""
def __init__(
self,
path: Path,
merge: bool | None = False,
pass_validation: bool | None = False,
enrich_sources: dict[str, Path | list[Path] | None] | None = None,
enrich_root: Path | None = None,
enrich_project_root: Path | None = None,
):
"""Codemeta.json parser.
If `enrich_sources` is given, `sync` also fills optional fields from
these project files (see [somesy.codemeta.enrich.enrich][]), relative
to `enrich_root` (default: the directory of the file) and
`enrich_project_root` (default: `enrich_root`).
See [somesy.core.writer.ProjectMetadataWriter.__init__][].
"""
self.merge = merge
self._enrich_sources = enrich_sources
self._enrich_root = enrich_root or Path(path).parent
self._enrich_project_root = enrich_project_root or self._enrich_root
self._default_context = V3_CONTEXT
mappings: FieldKeyMapping = {
"repository": ["codeRepository"],
"homepage": ["softwareHelp"],
"documentation": ["buildInstructions"],
"keywords": ["keywords"],
"authors": ["author"],
"maintainers": ["maintainer"],
"contributors": ["contributor"],
}
super().__init__(
path,
create_if_not_exists=True,
direct_mappings=mappings,
merge=merge,
pass_validation=pass_validation,
)
@property
def authors(self):
"""Return the authors of the codemeta.json file."""
return self._get_property(self._get_key("authors")) or []
@authors.setter
def authors(self, authors: list[Person | Entity]) -> None:
"""Set the authors of the project."""
authors_dict = self._people_with_roles(authors)
self._set_property(self._get_key("authors"), authors_dict)
@property
def maintainers(self):
"""Return the maintainers of the codemeta.json file."""
return self._get_property(self._get_key("maintainers"))
@maintainers.setter
def maintainers(self, maintainers: list[Person | Entity]) -> None:
"""Set the maintainers of the project."""
maintainers_dict = [self._from_person(m) for m in maintainers]
self._set_property(self._get_key("maintainers"), maintainers_dict)
@property
def contributors(self):
"""Return the contributors of the codemeta.json file."""
return self._get_property(self._get_key("contributors"))
@contributors.setter
def contributors(self, contributors: list[Person | Entity]) -> None:
"""Set the contributors of the project."""
contributors_dict = self._people_with_roles(contributors)
self._set_property(self._get_key("contributors"), contributors_dict)
def _load(self) -> None:
"""Load codemeta.json file."""
with self.path.open(encoding="utf-8") as f:
self._data = json.load(f, object_pairs_hook=OrderedDict)
def _upgrade_to_v3(self) -> None:
"""Normalize an existing CodeMeta file before v3.1 validation."""
context = self._data.get("@context", [])
context = context if isinstance(context, list) else [context]
context = [item for item in context if item != V2_CONTEXT]
if V3_CONTEXT not in context:
context.insert(0, V3_CONTEXT)
self._data["@context"] = context
for old, new in (
("contIntegration", "continuousIntegration"),
("embargoDate", "embargoEndDate"),
):
if old in self._data and new in self._data:
logger.warning(
f"Both '{old}' and '{new}' found in codemeta.json, "
f"dropping '{old}' in favor of '{new}'."
)
elif old in self._data:
self._data[new] = self._data[old]
self._data.pop(old, None)
def _read_file(self) -> dict[str, Any] | None:
"""Return the content of the file on disk, or None if it cannot be read."""
try:
return json.loads(self.path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
def _set_git_dependent_values(
self, previous: dict[str, Any] | None, git_version: bool
) -> None:
"""Set `dateModified`, and keep values that only depend on the Git state.
A new commit or tag alone must not change the file, otherwise a sync
on the committed file (e.g. a pre-commit hook in CI) would modify it.
So if nothing else changed, the previous `dateModified` and a `version`
taken from a Git tag are kept. Otherwise `dateModified` is set to today
(UTC) and the version from the latest tag is used.
A `dateCreated` that Git cannot provide (shallow history) is kept from
the previous file, also when not merging.
"""
if previous and "dateCreated" in previous:
self._data.setdefault("dateCreated", previous["dateCreated"])
keys = ["dateModified"] + (["version"] if git_version else [])
def without_keys(data: dict[str, Any]) -> dict[str, Any]:
data = json.loads(json.dumps(data, default=str))
return {k: v for k, v in data.items() if k not in keys}
if previous is not None and without_keys(self._data) == without_keys(previous):
for key in keys:
if key in previous:
self._data[key] = previous[key]
else:
self._data.pop(key, None)
else:
self._data["dateModified"] = datetime.now(timezone.utc).date().isoformat()
def _validate(self) -> None:
"""Validate codemeta.json content using pydantic class."""
if self.pass_validation:
return
if not self.merge:
return
self._upgrade_to_v3()
invalid_fields = validate_codemeta(self._data)
if invalid_fields:
raise ValueError(
f"Invalid fields in codemeta.json: {invalid_fields}. Cannot merge with invalid fields."
)
def _init_new_file(self) -> None:
"""Initialize new codemeta.json data (in memory) with bare minimum generic data."""
self._data = OrderedDict(self._new_data())
def _new_data(self) -> dict[str, Any]:
"""Return the bare minimum generic CodeMeta data."""
return {
"@context": self._default_context,
"@type": "SoftwareSourceCode",
"author": [],
}
def save(self, path: Path | None = None) -> None:
"""Save the codemeta.json file."""
path = path or self.path
logger.debug(f"Saving codemeta.json to {path}")
# copy the _data
data = self._data.copy()
# set license
if "license" in data:
licenses = data["license"]
licenses = licenses if isinstance(licenses, list) else [licenses]
data["license"] = [
license
if license.startswith("https://spdx.org/licenses/")
else f"https://spdx.org/licenses/{license}"
for license in licenses
]
write_json(data, path)
@staticmethod
def _from_person(person: Person | Entity) -> dict:
"""Convert project metadata person object to codemeta.json dict for person format."""
if isinstance(person, Person):
person_dict = {
"@type": "Person",
}
if person.given_names:
person_dict["givenName"] = person.given_names
if person.family_names:
person_dict["familyName"] = person.family_names
if person.email:
person_dict["email"] = person.email
if person.orcid:
person_dict["@id"] = str(person.orcid)
person_dict["identifier"] = str(person.orcid)
if person.address:
person_dict["address"] = person.address
if person.affiliation:
person_dict["affiliation"] = person.affiliation
return person_dict
else:
entity_dict = {"@type": "Organization", "name": person.name}
if person.address:
entity_dict["address"] = person.address
if person.email:
entity_dict["email"] = person.email
if person.date_start:
entity_dict["startDate"] = person.date_start.isoformat()
if person.date_end:
entity_dict["endDate"] = person.date_end.isoformat()
if person.website:
entity_dict["@id"] = str(person.website)
entity_dict["identifier"] = str(person.website)
if person.rorid:
entity_dict["@id"] = str(person.rorid)
entity_dict["identifier"] = str(person.rorid)
return entity_dict
@staticmethod
def _role_identifier(person: Person | Entity, person_dict: dict) -> str:
"""Return an identifier that can link a CodeMeta role to its person."""
if identifier := person_dict.get("@id"):
return identifier
identity = person.email or person.full_name
return f"urn:uuid:{uuid.uuid5(uuid.NAMESPACE_URL, f'{type(person).__name__}:{identity}')}"
@staticmethod
def _has_contribution_metadata(person: Person | Entity) -> bool:
"""Return whether a person has metadata representable by a CodeMeta role."""
return any(
(
person.contribution,
person.contribution_types,
person.contribution_begin,
person.contribution_end,
)
)
def _people_with_roles(self, people: Sequence[Person | Entity]) -> list[dict]:
"""Serialize people and their granular contribution roles."""
result = []
for person in people:
person_dict = self._from_person(person)
if not self._has_contribution_metadata(person):
result.append(person_dict)
continue
identifier = self._role_identifier(person, person_dict)
person_dict["@id"] = identifier
result.append(person_dict)
role_names: list[str | None] = []
if person.contribution:
role_names.append(person.contribution)
role_names.extend(
contribution_type.value
for contribution_type in person.contribution_types or []
)
if not role_names:
role_names.append(None)
for role_name in role_names:
role = {"@type": "Role", "schema:author": identifier}
if role_name:
role["roleName"] = role_name
if person.contribution_begin:
role["startDate"] = person.contribution_begin.isoformat()
if person.contribution_end:
role["endDate"] = person.contribution_end.isoformat()
result.append(role)
return result
@staticmethod
def _to_person(person_obj) -> Person | Entity | None:
"""Convert codemeta.json dict or str for person/entity format to project metadata person object."""
if person_obj.get("@type") == "Role":
return None
if "name" in person_obj:
entity_obj = {"name": person_obj["name"]}
return Entity(**entity_obj)
else:
person_data = {}
if "givenName" in person_obj:
person_data["given_names"] = person_obj["givenName"].strip()
if "familyName" in person_obj:
person_data["family_names"] = person_obj["familyName"].strip()
if "email" in person_obj:
person_data["email"] = person_obj["email"].strip()
if "orcid.org/" in person_obj.get("@id", ""):
person_data["orcid"] = person_obj["@id"].strip()
if "address" in person_obj:
person_data["address"] = person_obj["address"].strip()
return Person(**person_data)
def _sync_person_list(
self, old: list[Any], new: Sequence[Person | Entity]
) -> list[Any]:
"""Override the _sync_person_list function from ProjectMetadataWriter.
This method wont care about existing persons in codemeta.json file.
Args:
old (List[Any]): existing persons in codemeta.json file, in this case ignored in the output. However, it is necessary to make the function compatible with the parent class.
new (List[Person]): new persons to add to codemeta.json file
Returns:
List[Any]: list of new persons to add to codemeta.json file
"""
return list(new)
def sync(self, metadata: ProjectMetadata) -> None:
"""Sync codemeta.json with project metadata.
Use existing sync function from ProjectMetadataWriter but update repository and contributors.
"""
previous = self._read_file()
stale: dict[str, Any] = {}
key_order: list[str] = []
if not self.merge:
self._data = self._new_data()
else:
self._upgrade_to_v3()
self._data["@type"] = "SoftwareSourceCode"
# Fields somesy produces (from metadata or enrichment) are refreshed:
# set aside old values, those still absent after syncing are kept.
key_order = list(self._data)
stale = {
key: self._data.pop(key) for key in ENRICHED_KEYS if key in self._data
}
if metadata.authors():
self._data["author"] = []
self._data["maintainer"] = []
self._data["contributor"] = []
super().sync(metadata)
if metadata.doi:
self._data["identifier"] = f"https://doi.org/{metadata.doi}"
elif "identifier" in self._data:
identifiers = self._data["identifier"]
identifiers = (
identifiers if isinstance(identifiers, list) else [identifiers]
)
kept = [
i
for i in identifiers
if not (isinstance(i, str) and i.startswith("https://doi.org/"))
]
if kept:
self._data["identifier"] = kept if len(kept) > 1 else kept[0]
else:
del self._data["identifier"]
if licenses := metadata.license:
self.license = [
f"https://spdx.org/licenses/{license.value}"
for license in (licenses if isinstance(licenses, list) else [licenses])
]
self.contributors = metadata.contributors()
if "softwareHelp" in self._data:
self._data["url"] = self._data["softwareHelp"]
if self._enrich_sources is not None:
enrich_codemeta(
self._data,
self._enrich_sources,
self._enrich_root,
self._enrich_project_root,
)
# keep old values of fields nothing refreshed
for key, value in stale.items():
self._data.setdefault(key, value)
if self._enrich_sources is not None:
self._set_git_dependent_values(previous, git_version=not metadata.version)
if self.merge and key_order:
# in their original place
order = {key: i for i, key in enumerate(key_order)}
self._data = OrderedDict(
sorted(self._data.items(), key=lambda kv: order.get(kv[0], len(order)))
)
|