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