Coverage for src/somesy/core/writer.py: 95%
283 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"""Project metadata writer base-class."""
3import logging
4from abc import ABC, abstractmethod
5from collections.abc import Sequence
6from pathlib import Path
7from typing import Any
9import tomlkit
10from tomlkit.items import AoT, Array, InlineTable
12from somesy.core.models import (
13 Entity,
14 Person,
15 ProjectMetadata,
16 find_matching_person,
17 is_blank_person,
18)
20logger = logging.getLogger("somesy")
22# person fields that are role/contribution flags, not part of the person's identity
23_UNMANAGED_PERSON_FIELDS = frozenset(
24 {
25 "author",
26 "publication_author",
27 "maintainer",
28 "contribution",
29 "contribution_types",
30 "contribution_begin",
31 "contribution_end",
32 }
33)
36def toml_array(value: list) -> Array:
37 """Build a multiline tomlkit array, with spaced inline tables."""
38 array = tomlkit.array()
39 array.extend(value)
40 array.multiline(True)
41 # Ensure whitespace after commas in inline tables
42 for item in array:
43 if isinstance(item, InlineTable):
44 # Rebuild the inline table with desired formatting
45 formatted_item = tomlkit.inline_table()
46 for k, v in item.value.items():
47 formatted_item[k] = v
48 formatted_item.trivia.trail = " " # Add space after each comma
49 array[array.index(item)] = formatted_item
50 return array
53def multiline_description(table: Any) -> None:
54 """Store a description containing line breaks as a multiline TOML string."""
55 if "description" in table and "\n" in table["description"]:
56 table["description"] = tomlkit.string(table["description"], multiline=True)
59def format_toml_data(data: Any) -> None:
60 """Prepare a tomlkit document for saving: multiline description, multiline arrays."""
61 multiline_description(data)
63 # Handle arrays with proper formatting (snapshot, since we assign while iterating)
64 for key, value in list(data.items()):
65 if isinstance(value, list) and not isinstance(value, AoT):
66 data[key] = toml_array(value)
67 else:
68 data[key] = value
71class IgnoreKey:
72 """Special marker to be passed for dropping a key from serialization."""
75FieldKeyMapping = dict[str, str | list[str] | IgnoreKey]
76"""Type to be used for the dict passed as `direct_mappings`."""
78DictLike = Any
79"""Dict-like that supports getitem, setitem, delitem, etc.
81NOTE: This should be probably turned into a proper protocol.
82"""
85def license_expression(licenses) -> str:
86 """Convert one or more license identifiers to an SPDX expression."""
87 return " OR ".join(
88 str(license)
89 for license in (licenses if isinstance(licenses, list) else [licenses])
90 )
93class ProjectMetadataWriter(ABC):
94 """Base class for Project Metadata Output Wrapper.
96 All supported output formats are implemented as subclasses.
97 """
99 def __init__(
100 self,
101 path: Path,
102 *,
103 create_if_not_exists: bool | None = False,
104 direct_mappings: FieldKeyMapping | None = None,
105 merge: bool | None = False,
106 pass_validation: bool | None = False,
107 ) -> None:
108 """Initialize the Project Metadata Output Wrapper.
110 Use the `direct_mappings` dict to define
111 format-specific location for certain fields,
112 if no additional processing is needed that
113 requires a customized setter.
115 Args:
116 path: Path to target output file.
117 create_if_not_exists: Create an empty file if not exists. Defaults to False.
118 direct_mappings: Dict with direct mappings of keys between somesy and target
119 merge: Merge the output file with an existing file. Defaults to False.
120 pass_validation: Pass validation for all output files. Defaults to False.
122 """
123 self._data: DictLike = {}
124 self.path = path if isinstance(path, Path) else Path(path)
125 self.create_if_not_exists = create_if_not_exists
126 self.direct_mappings = direct_mappings or {}
127 self.merge = merge
128 self.pass_validation = pass_validation
129 if self.path.is_file():
130 self._load()
131 if not self.pass_validation:
132 self._validate()
133 else:
134 if self.create_if_not_exists:
135 self._init_new_file() # in memory only, written by save()
136 else:
137 raise FileNotFoundError(f"The file {self.path} does not exist.")
139 def _init_new_file(self) -> None:
140 """Initialize the data of a new target file (in memory only).
142 Override to initialize with minimal contents, if needed.
143 Make sure to set `self._data` to match the contents.
144 The file is only created on disk by `save()`.
145 """
146 self._data = {}
148 @abstractmethod
149 def _load(self):
150 """Load the output file and validate it.
152 Implement this method so that it loads the file `self.path`
153 into the `self._data` dict.
155 The file is guaranteed to exist.
156 """
158 @abstractmethod
159 def _validate(self) -> None:
160 """Validate the target file data.
162 Implement this method so that it checks
163 the validity of the metadata (relevant to somesy)
164 in that file and raises exceptions on failure.
165 """
167 @abstractmethod
168 def save(self, path: Path | None) -> None:
169 """Save the output file to the given path.
171 Implement this in a way that will carefully
172 update the target file with new metadata
173 without destroying its other contents or structure.
174 """
176 def _get_property(
177 self,
178 key: str | list[str] | IgnoreKey,
179 *,
180 remove: bool = False,
181 ) -> Any:
182 """Get a property from the data.
184 Override this to e.g. rewrite the retrieved key
185 (e.g. if everything relevant is in some subobject).
187 Args:
188 key: Name of the key or sequence of multiple keys to retrieve the value.
189 remove: If True, will remove the retrieved value and clean up the dict.
191 """
192 if isinstance(key, IgnoreKey):
193 return None
194 key_path = [key] if isinstance(key, str) else key
196 curr: Any = self._data
197 seq = [curr]
198 for k in key_path:
199 curr = curr.get(k)
200 seq.append(curr)
201 if curr is None:
202 return None
204 if remove:
205 seq.pop()
206 del seq[-1][key_path[-1]] # remove leaf value
207 # clean up the tree
208 for path_key, dct in reversed(
209 list(zip(key_path[:-1], seq[:-1], strict=False))
210 ):
211 if not dct.get(path_key):
212 del dct[path_key]
214 return curr
216 def _set_property(self, key: str | list[str] | IgnoreKey, value: Any) -> None:
217 """Set a property in the data.
219 Note if there are lists along the path, they are cleared out.
221 Override this to e.g. rewrite the retrieved key
222 (e.g. if everything relevant is in some subobject).
223 """
224 if isinstance(key, IgnoreKey):
225 return
226 key_path = [key] if isinstance(key, str) else key
228 if not value: # remove value and clean up the sub-dict
229 self._get_property(key_path, remove=True)
230 return
232 # create path on the fly if needed
233 curr = self._data
234 for path_key in key_path[:-1]:
235 if path_key not in curr:
236 curr[path_key] = {}
237 curr = curr[path_key]
239 curr[key_path[-1]] = value
241 # ----
242 # special handling for person metadata
244 def _merge_person_metadata(
245 self,
246 old: Sequence[Person | Entity],
247 new: Sequence[Person | Entity],
248 ) -> list[Person | Entity]:
249 """Update metadata of a list of persons.
251 Will identify people based on orcid, email or full name.
253 If old list has same person listed multiple times,
254 the resulting list will too (we cannot correctly merge for external formats.)
255 """
256 new_people = [] # list for new people (e.g. added authors)
257 # flag, meaning "person was not removed"
258 still_exists = [False for i in range(len(old))]
259 # copies of old person data, to be modified
260 modified_people = [p.model_copy() for p in old]
262 # try to match new people to existing old ones
263 # (inefficient, but author list are not that long usually)
264 for person_meta in new:
265 person_update = person_meta.model_dump()
266 index = find_matching_person(person_meta, modified_people)
267 if index is not None:
268 person = modified_people[index]
270 # not new person (-> will not append new record)
271 # still exists (-> will not be removed from list)
272 still_exists[index] = True
274 # the input is the source of truth for the managed fields:
275 # fields missing in the input are removed from the output person
276 # (unknown extra keys of the output are kept)
277 fields = type(person).model_fields
278 cleared = {
279 k: fields[k].get_default(call_default_factory=True)
280 for k in person.model_dump()
281 if k in fields
282 and k not in person_update
283 and k not in _UNMANAGED_PERSON_FIELDS
284 }
285 updated = person.model_copy(update={**person_update, **cleared})
287 # if there were changes -> update person
288 if updated.model_dump() != person.model_dump():
289 modified_people[index] = updated
291 # show effective update in debug log
292 old_fmt = self._from_person(person)
293 new_fmt = self._from_person(updated)
294 if old_fmt != new_fmt:
295 logger.debug(f"Updating person\n{old_fmt}\nto\n{new_fmt}")
296 else:
297 new_people.append(person_meta)
299 # show added and removed people in debug log
300 removed_people = [old[i] for i in range(len(old)) if not still_exists[i]]
301 for person in removed_people:
302 logger.debug(f"Removing person\n{self._from_person(person)}")
303 for person in new_people:
304 logger.debug(f"Adding person\n{self._from_person(person)}")
306 # return updated list of (still existing) people,
307 # and all new people coming after them.
308 existing_modified = [
309 modified_people[i] for i in range(len(old)) if still_exists[i]
310 ]
311 return existing_modified + new_people
313 def _sync_person_list(
314 self, old: list[Any], new: Sequence[Person | Entity]
315 ) -> list[Any]:
316 """Sync a list of persons with new metadata.
318 Args:
319 old (List[Any]): list of persons in format-specific representation
320 new (List[Person]): list of persons in somesy representation
322 Returns:
323 List[Any]: updated list of persons in format-specific representation
325 """
326 old_people: list[Person | Entity] = self._parse_people(old)
328 # check if people are unique
329 def filter_unique(
330 people: Sequence[Person | Entity],
331 ) -> list[Person | Entity]:
332 """Filter out duplicate people from a list."""
333 if people is None or len(people) == 0:
334 return []
336 unique_people: list[Person | Entity] = []
337 # use same_person method to check if people are unique
338 for person in people:
339 if not any(person.same_person(p) for p in unique_people):
340 unique_people.append(person)
342 return unique_people
344 old_people_unique = filter_unique(old_people)
345 new_people_unique = filter_unique(new)
347 return self._merge_person_metadata(old_people_unique, new_people_unique)
349 def _unparseable_people(self, role: str) -> tuple[Any, list[Any]]:
350 """Return mapped key and raw existing entries of `role` that can't be parsed.
352 Empty list if the target has no list-valued slot for the role.
353 """
354 key = self._get_key(role)
355 raw = self._get_property(key)
356 if not isinstance(raw, list):
357 return key, []
359 def unparseable(entry: Any) -> bool:
360 if entry is None or self._is_blank_person(entry):
361 return False
362 try:
363 return self._to_person(entry) is None
364 except (KeyError, TypeError, ValueError, AttributeError):
365 return True
367 return key, [e for e in raw if unparseable(e)]
369 def _reattach_people(self, key: Any, raw_entries: list[Any]) -> None:
370 """Append raw entries (kept untouched) to the list stored under `key`."""
371 if not raw_entries:
372 return
373 current = self._get_property(key)
374 if isinstance(current, dict): # some formats collapse one-item lists
375 current = [current]
376 if isinstance(current, list):
377 self._set_property(key, current + raw_entries)
379 def _sync_authors(self, metadata: ProjectMetadata) -> None:
380 """Sync output file authors with authors from metadata.
382 This method is existing for the publication_author special case
383 when synchronizing to CITATION.cff.
384 """
385 if self.authors is None or len(self.authors) == 0:
386 self.authors = metadata.authors()
387 else:
388 self.authors = self._sync_person_list(self.authors, metadata.authors())
390 def sync(self, metadata: ProjectMetadata) -> None:
391 """Sync output file with other metadata files."""
392 if metadata.name is not None:
393 self.name = metadata.name
394 if metadata.description is not None:
395 self.description = metadata.description
397 if metadata.version:
398 self.version = metadata.version
400 if metadata.keywords:
401 self.keywords = metadata.keywords
403 # existing entries we cannot parse are kept untouched in the target
404 kept = {r: self._unparseable_people(r) for r in ("authors", "maintainers")}
406 if metadata.authors():
407 self._sync_authors(metadata)
408 self.maintainers = self._sync_person_list(
409 self.maintainers, metadata.maintainers()
410 )
412 for key, raw_entries in kept.values():
413 self._reattach_people(key, raw_entries)
415 if licenses := metadata.license:
416 self.license = license_expression(licenses)
418 # keep existing values in the target file if somesy has none
419 if metadata.homepage:
420 self.homepage = str(metadata.homepage)
421 if metadata.repository:
422 self.repository = str(metadata.repository)
423 if metadata.documentation:
424 self.documentation = str(metadata.documentation)
426 def harvest_metadata(self) -> dict[str, Any]:
427 """Return metadata read from this endpoint in Somesy model terms."""
428 data: dict[str, Any] = {}
429 for field in (
430 "name",
431 "version",
432 "description",
433 "license",
434 "homepage",
435 "repository",
436 "documentation",
437 "keywords",
438 ):
439 try:
440 value = getattr(self, field)
441 except (KeyError, TypeError):
442 continue
443 if value not in (None, [], ""):
444 data[field] = value
446 people: list[Person] = []
447 entities: list[Entity] = []
448 for role in ("authors", "maintainers", "contributors"):
449 for person in self._parse_people(getattr(self, role) or []):
450 updates = (
451 {"author": True, "publication_author": True}
452 if role == "authors"
453 else {}
454 )
455 updates.update({"maintainer": True} if role == "maintainers" else {})
456 person = person.model_copy(update=updates)
457 if isinstance(person, Entity):
458 entities.append(person)
459 else:
460 people.append(person)
462 if people:
463 data["people"] = people
464 if entities:
465 data["entities"] = entities
466 return data
468 @staticmethod
469 @abstractmethod
470 def _from_person(person: Person | Entity) -> Any:
471 """Convert a `Person` or `Entity` object into suitable target format."""
473 @staticmethod
474 @abstractmethod
475 def _to_person(person_obj: Any) -> Person | Entity | None:
476 """Convert an object representing a person into a `Person` or `Entity` object."""
478 @staticmethod
479 def _is_blank_person(person_obj: Any) -> bool:
480 """Return whether an existing person entry is blank, i.e. counts as no person."""
481 return is_blank_person(person_obj)
483 @classmethod
484 def _parse_people(cls, people: list[Any] | None) -> list[Person | Entity]:
485 """Return a list of Persons and Entities parsed from list of format-specific people representations."""
486 # remove None values
487 return [
488 person
489 for p in people or []
490 if p is not None and not cls._is_blank_person(p)
491 if (person := cls._to_person(p)) is not None
492 ]
494 # ----
495 # individual magic getters and setters
497 def _get_key(self, key: str) -> str | list[str] | IgnoreKey:
498 """Get a key itself."""
499 return self.direct_mappings.get(key) or key
501 @property
502 def name(self):
503 """Return the name of the project."""
504 return self._get_property(self._get_key("name"))
506 @name.setter
507 def name(self, name: str) -> None:
508 """Set the name of the project."""
509 self._set_property(self._get_key("name"), name)
511 @property
512 def version(self) -> str | None:
513 """Return the version of the project."""
514 return self._get_property(self._get_key("version"))
516 @version.setter
517 def version(self, version: str | None) -> None:
518 """Set the version of the project."""
519 self._set_property(self._get_key("version"), version)
521 @property
522 def description(self) -> str | None:
523 """Return the description of the project."""
524 return self._get_property(self._get_key("description"))
526 @description.setter
527 def description(self, description: str) -> None:
528 """Set the description of the project."""
529 self._set_property(self._get_key("description"), description)
531 @property
532 def authors(self):
533 """Return the authors of the project."""
534 authors = self._get_property(self._get_key("authors"))
535 if authors is None or len(authors) == 0:
536 return []
538 # only return authors that can be converted to Person
539 authors_validated = [
540 author
541 for author in authors
542 if not self._is_blank_person(author) and self._to_person(author) is not None
543 ]
544 return authors_validated
546 @authors.setter
547 def authors(self, authors: list[Person | Entity]) -> None:
548 """Set the authors of the project."""
549 authors = [self._from_person(c) for c in authors]
550 self._set_property(self._get_key("authors"), authors)
552 @property
553 def maintainers(self):
554 """Return the maintainers of the project."""
555 maintainers = self._get_property(self._get_key("maintainers"))
556 if maintainers is None:
557 return []
559 # only return maintainers that can be converted to Person
560 maintainers_validated = [
561 maintainer
562 for maintainer in maintainers
563 if not self._is_blank_person(maintainer)
564 and self._to_person(maintainer) is not None
565 ]
566 return maintainers_validated
568 @maintainers.setter
569 def maintainers(self, maintainers: list[Person | Entity]) -> None:
570 """Set the maintainers of the project."""
571 maintainers = [self._from_person(c) for c in maintainers]
572 self._set_property(self._get_key("maintainers"), maintainers)
574 @property
575 def contributors(self):
576 """Return the contributors of the project."""
577 return self._get_property(self._get_key("contributors"))
579 @contributors.setter
580 def contributors(self, contributors: list[Person | Entity]) -> None:
581 """Set the contributors of the project."""
582 contributors = [self._from_person(c) for c in contributors]
583 self._set_property(self._get_key("contributors"), contributors)
585 @property
586 def keywords(self) -> list[str] | None:
587 """Return the keywords of the project."""
588 return self._get_property(self._get_key("keywords"))
590 @keywords.setter
591 def keywords(self, keywords: list[str]) -> None:
592 """Set the keywords of the project."""
593 self._set_property(self._get_key("keywords"), keywords)
595 @property
596 def license(self) -> Any:
597 """Return the license of the project."""
598 return self._get_property(self._get_key("license"))
600 @license.setter
601 def license(self, license: Any) -> None:
602 """Set the license of the project."""
603 self._set_property(self._get_key("license"), license)
605 @property
606 def homepage(self) -> str | None:
607 """Return the homepage url of the project."""
608 return self._get_property(self._get_key("homepage"))
610 @homepage.setter
611 def homepage(self, value: str | None) -> None:
612 """Set the homepage url of the project."""
613 self._set_property(self._get_key("homepage"), value)
615 @property
616 def repository(self) -> str | dict | None:
617 """Return the repository url of the project."""
618 return self._get_property(self._get_key("repository"))
620 @repository.setter
621 def repository(self, value: str | dict | None) -> None:
622 """Set the repository url of the project."""
623 self._set_property(self._get_key("repository"), value)
625 @property
626 def documentation(self) -> str | dict | None:
627 """Return the documentation url of the project."""
628 return self._get_property(self._get_key("documentation"))
630 @documentation.setter
631 def documentation(self, value: str | dict | None) -> None:
632 """Set the documentation url of the project."""
633 self._set_property(self._get_key("documentation"), value)