Coverage for src/somesy/core/models.py: 95%
393 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"""Core models for the somesy package."""
3from __future__ import annotations
5import functools
6import json
7import logging
8import re
9from collections.abc import Sequence
10from datetime import date
11from pathlib import Path
12from typing import Annotated, Any
14from pydantic import (
15 BaseModel,
16 Field,
17 PrivateAttr,
18 field_validator,
19 model_validator,
20)
21from rich.pretty import pretty_repr
23from .core import get_input_content
24from .log import SomesyLogLevel
25from .types import ContributionTypeEnum, Country, HttpUrlStr, LicenseEnum
27logger = logging.getLogger("somesy")
29# --------
30# Somesy configuration model
33class SomesyBaseModel(BaseModel):
34 """Customized pydantic BaseModel for somesy.
36 Apart from some general tweaks for better defaults,
37 adds a private `_key_order` field, which is used to track the
38 preferred order for serialization (usually coming from some existing input).
40 It can be set on an instance using the set_key_order method,
41 and is preserved by `copy()`.
43 NOTE: The custom order is intended for leaf models (no further nested models),
44 custom order will not work correctly across nesting layers.
45 """
47 model_config = {
48 "extra": "forbid",
49 "validate_assignment": True,
50 "populate_by_name": True,
51 "str_strip_whitespace": True,
52 "str_min_length": 1,
53 }
55 # ----
56 # Key order magic
58 _key_order: list[str] = PrivateAttr([])
59 """List of field names (NOT aliases!) in the order they should be written in."""
61 @classmethod
62 @functools.lru_cache # compute once per class
63 def _aliases(cls) -> dict[str, str]:
64 """Map back from alias field names to internal field names."""
65 return {v.alias or k: k for k, v in cls.model_fields.items()}
67 @classmethod
68 def make_partial(cls, dct):
69 """Construct unvalidated partial model from dict.
71 Handles aliases correctly, unlike `construct`.
72 """
73 un_alias = cls._aliases()
74 return cls.model_construct(**{un_alias.get(k) or k: v for k, v in dct.items()})
76 def set_key_order(self, keys: list[str]):
77 """Setter for custom key order used in serialization."""
78 un_alias = self._aliases()
79 # make sure we use the _actual_ field names
80 self._key_order = [un_alias.get(k) or k for k in keys]
82 def model_copy(self, *args, **kwargs):
83 """Patched copy method (to preserve custom key order)."""
84 ret = super().model_copy(*args, **kwargs)
85 ret.set_key_order(list(self._key_order))
86 return ret
88 @staticmethod
89 def _patch_kwargs_defaults(kwargs):
90 """Set some default arguments if they are not set by kwargs."""
91 for key in ["exclude_defaults", "exclude_none"]:
92 if kwargs.get(key, None) is None:
93 kwargs[key] = True
95 def _reorder_dict(self, dct):
96 """Return dict with patched key order (according to `self._key_order`).
98 Keys in `dct` not listed in `self._key_order` come after all others.
100 Used to patch up `model_dump()` and `model_dump_json()`.
101 """
102 key_order = self._key_order or []
103 existing = set(key_order).intersection(set(dct.keys()))
104 key_order = [k for k in key_order if k in existing]
105 key_order += [k for k in dct if k not in existing]
106 return {k: dct[k] for k in key_order}
108 def model_dump(self, *args, **kwargs):
109 """Patched dict method (to preserve custom key order)."""
110 self._patch_kwargs_defaults(kwargs)
111 by_alias = kwargs.pop("by_alias", False)
113 dct = super().model_dump(*args, **kwargs, by_alias=False)
114 ret = self._reorder_dict(dct)
116 if by_alias:
117 ret = {type(self).model_fields[k].alias or k: v for k, v in ret.items()}
118 return ret
120 def model_dump_json(self, *args, **kwargs):
121 """Patched json method (to preserve custom key order)."""
122 self._patch_kwargs_defaults(kwargs)
123 by_alias = kwargs.pop("by_alias", False)
125 # loop back json through dict to apply custom key order
126 dct = json.loads(super().model_dump_json(*args, **kwargs, by_alias=False))
127 ret = self._reorder_dict(dct)
129 if by_alias:
130 ret = {type(self).model_fields[k].alias or k: v for k, v in ret.items()}
131 return json.dumps(ret, ensure_ascii=False)
134_SOMESY_TARGETS = [
135 "cff",
136 "pyproject",
137 "package_json",
138 "codemeta",
139 "julia",
140 "fortran",
141 "pom_xml",
142 "mkdocs",
143 "rust",
144]
147class SomesyConfig(SomesyBaseModel):
148 """Pydantic model for somesy tool configuration.
150 Note that all fields match CLI options, and CLI options will override the
151 values declared in a somesy input file (such as `somesy.toml`).
152 """
154 @model_validator(mode="before")
155 @classmethod
156 def at_least_one_target(cls, values):
157 """Check that at least one output file is enabled."""
158 if all(values.get(f"no_sync_{x}") for x in _SOMESY_TARGETS):
159 msg = "No sync target enabled, nothing to do. Probably this is a mistake?"
160 raise ValueError(msg)
162 return values
164 # cli flags
165 show_info: Annotated[
166 bool,
167 Field(
168 description="Show basic information messages on run (-v flag).",
169 ),
170 ] = False
171 verbose: Annotated[
172 bool, Field(description="Show verbose messages on run (-vv flag).")
173 ] = False
174 debug: Annotated[
175 bool, Field(description="Show debug messages on run (-vvv flag).")
176 ] = False
178 input_file: Annotated[
179 Path | None, Field(description="Project metadata input file path.")
180 ] = Path("somesy.toml")
182 no_sync_pyproject: Annotated[
183 bool, Field(description="Do not sync with pyproject.toml.")
184 ] = False
185 pyproject_file: Annotated[
186 Path | list[Path], Field(description="pyproject.toml file path.")
187 ] = Path("pyproject.toml")
189 no_sync_package_json: Annotated[
190 bool, Field(description="Do not sync with package.json.")
191 ] = False
192 package_json_file: Annotated[
193 Path | list[Path], Field(description="package.json file path.")
194 ] = Path("package.json")
196 no_sync_julia: Annotated[
197 bool, Field(description="Do not sync with Project.toml.")
198 ] = False
199 julia_file: Annotated[
200 Path | list[Path], Field(description="Project.toml file path.")
201 ] = Path("Project.toml")
203 no_sync_fortran: Annotated[
204 bool, Field(description="Do not sync with fpm.toml.")
205 ] = False
206 fortran_file: Annotated[
207 Path | list[Path], Field(description="fpm.toml file path.")
208 ] = Path("fpm.toml")
210 no_sync_pom_xml: Annotated[bool, Field(description="Do not sync with pom.xml.")] = (
211 False
212 )
213 pom_xml_file: Annotated[
214 Path | list[Path], Field(description="pom.xml file path.")
215 ] = Path("pom.xml")
217 no_sync_mkdocs: Annotated[
218 bool, Field(description="Do not sync with mkdocs.yml.")
219 ] = False
220 mkdocs_file: Annotated[
221 Path | list[Path], Field(description="mkdocs.yml file path.")
222 ] = Path("mkdocs.yml")
224 no_sync_rust: Annotated[bool, Field(description="Do not sync with Cargo.toml.")] = (
225 False
226 )
227 rust_file: Annotated[
228 Path | list[Path], Field(description="Cargo.toml file path.")
229 ] = Path("Cargo.toml")
231 no_sync_cff: Annotated[bool, Field(description="Do not sync with CFF.")] = False
232 cff_file: Annotated[Path | list[Path], Field(description="CFF file path.")] = Path(
233 "CITATION.cff"
234 )
236 no_sync_codemeta: Annotated[
237 bool, Field(description="Do not sync with codemeta.json.")
238 ] = False
239 codemeta_file: Annotated[
240 Path | list[Path], Field(description="codemeta.json file path.")
241 ] = Path("codemeta.json")
242 merge_codemeta: Annotated[
243 bool,
244 Field(
245 description="Merge codemeta.json with with an existing codemeta.json file."
246 ),
247 ] = False
249 # property to pass validation for all inputs/outputs
250 pass_validation: Annotated[
251 bool | None,
252 Field(description="Allow incomplete input and pass output validation."),
253 ] = False
255 # packages (sub-folders) for monorepos with their own somesy config
256 packages: Annotated[
257 Path | list[Path] | None,
258 Field(
259 description="Packages (sub-folders) for monorepos with their own somesy config."
260 ),
261 ] = None
263 def log_level(self) -> SomesyLogLevel:
264 """Return log level derived from this configuration."""
265 return SomesyLogLevel.from_flags(
266 info=self.show_info, verbose=self.verbose, debug=self.debug
267 )
269 def update_log_level(self, log_level: SomesyLogLevel):
270 """Update config flags according to passed log level."""
271 self.show_info = log_level == SomesyLogLevel.INFO
272 self.verbose = log_level == SomesyLogLevel.VERBOSE
273 self.debug = log_level == SomesyLogLevel.DEBUG
275 _cli_overrides: dict[str, Any] = PrivateAttr(default_factory=dict)
276 """Options explicitly set on this config (CLI), set on the combined config."""
278 def get_input(self) -> SomesyInput:
279 """Based on the somesy config, load the complete somesy input."""
280 # only explicitly set fields override the config file
281 explicit = self.model_dump(
282 exclude_unset=True, exclude_defaults=False, exclude_none=False
283 )
284 # get metadata+config from specified input file; the strictness of the
285 # project model follows an explicitly passed pass_validation
286 somesy_input = SomesyInput.from_input_file(
287 self.input_file or Path("somesy.toml"),
288 pass_validation=explicit.get("pass_validation"),
289 )
290 # update input with merged config settings (cli overrides config file)
291 dct: dict[str, Any] = {}
292 dct.update(
293 (somesy_input.config or SomesyConfig()).model_dump(
294 exclude_unset=True, exclude_defaults=False, exclude_none=False
295 )
296 )
297 dct.update(explicit)
298 somesy_input.config = SomesyConfig(**dct)
299 somesy_input.config._cli_overrides = explicit
300 return somesy_input
302 def resolve_paths(self, base_dir: Path) -> None:
303 """Resolve all paths in the config relative to the given base directory.
305 Args:
306 base_dir: The base directory to resolve paths against.
308 """
310 def resolve_path(
311 paths: Path | list[Path] | None,
312 ) -> Path | list[Path] | None:
313 if paths is None:
314 return None
315 if isinstance(paths, list):
316 return [base_dir / p for p in paths]
317 return base_dir / paths
319 # Resolve all file paths
320 resolved_input = resolve_path(self.input_file)
321 self.input_file = resolved_input if isinstance(resolved_input, Path) else None
322 for field in (
323 "pyproject_file",
324 "package_json_file",
325 "julia_file",
326 "fortran_file",
327 "pom_xml_file",
328 "mkdocs_file",
329 "rust_file",
330 "cff_file",
331 "codemeta_file",
332 "packages",
333 ):
334 resolved = resolve_path(getattr(self, field))
335 if resolved is not None:
336 setattr(self, field, resolved)
339# --------
340# Project metadata model (modified from CITATION.cff)
343class ContributorBaseModel(SomesyBaseModel):
344 """Base model for Person and Entity models.
346 This schema is based on CITATION.cff 1.2, modified and extended for the needs of somesy.
347 """
349 email: Annotated[
350 str | None,
351 Field(
352 pattern=r"^[\S]+@[\S]+\.[\S]{2,}$",
353 description="The person's email address.",
354 ),
355 ] = None
357 alias: Annotated[str | None, Field(description="The contributor's alias.")] = None
358 address: Annotated[str | None, Field(description="The contributor's address.")] = (
359 None
360 )
361 city: Annotated[str | None, Field(description="The entity's city.")] = None
362 country: Annotated[Country | None, Field(description="The entity's country.")] = (
363 None
364 )
365 fax: Annotated[str | None, Field(description="The person's fax number.")] = None
366 post_code: Annotated[
367 str | None, Field(alias="post-code", description="The entity's post-code.")
368 ] = None
369 region: Annotated[str | None, Field(description="The entity's region.")] = None
370 tel: Annotated[str | None, Field(description="The entity's phone number.")] = None
372 # ----
373 # somesy-specific extensions
374 author: Annotated[
375 bool,
376 Field(
377 description="Indicates whether the entity is an author of the project (i.e. significant contributor)."
378 ),
379 ] = False
380 publication_author: Annotated[
381 bool | None,
382 Field(
383 description="Indicates whether the entity is to be listed as an author in academic citations."
384 ),
385 ] = None
386 maintainer: Annotated[
387 bool,
388 Field(
389 description="Indicates whether the entity is a maintainer of the project (i.e. for contact)."
390 ),
391 ] = False
393 # NOTE: CFF 1.3 (once done) might provide ways for refined contributor description. That should be implemented here.
394 contribution: Annotated[
395 str | None,
396 Field(description="Summary of how the entity contributed to the project."),
397 ] = None
398 contribution_types: Annotated[
399 list[ContributionTypeEnum] | None,
400 Field(
401 description="Relevant types of contributions (see https://allcontributors.org/docs/de/emoji-key).",
402 min_length=1,
403 ),
404 ] = None
405 contribution_begin: Annotated[
406 date | None, Field(description="Beginning date of the contribution.")
407 ] = None
408 contribution_end: Annotated[
409 date | None, Field(description="Ending date of the contribution.")
410 ] = None
412 @model_validator(mode="before")
413 @classmethod
414 def author_implies_publication(cls, values):
415 """Ensure consistency of author and publication_author."""
416 if values.get("author"):
417 # NOTE: explicitly check for False (different case from None = missing!)
418 if values.get("publication_author") is False:
419 msg = "Combining author=true and publication_author=false is invalid!"
420 raise ValueError(msg)
421 values["publication_author"] = True
422 return values
424 # helper methods
425 @property
426 def full_name(self) -> str:
427 """Return the name of the contributor."""
428 raise NotImplementedError
430 def to_name_email_string(self) -> str:
431 """Convert project metadata person object to poetry string for person format `full name <x@y.z>`."""
432 if self.email:
433 return f"{self.full_name} <{self.email}>"
434 else:
435 return self.full_name
437 @classmethod
438 def from_name_email_string(cls, person: str) -> ContributorBaseModel:
439 """Return the type of class based on an name/e-mail string like `full name <x@y.z>`.
441 If the name is `A B C`, then `A B` will be the given names and `C` will be the family name.
442 A single-word name is not a valid person name and raises a `ValidationError`.
443 """
444 raise NotImplementedError
447class Entity(ContributorBaseModel):
448 """Metadata about an entity in the context of a software project ownership.
450 An entity, i.e., an institution, team, research group, company, conference, etc., as opposed to a single natural person.
451 This schema is based on CITATION.cff 1.2, modified and extended for the needs of somesy.
452 """
454 # NOTE: we rely on the defined aliases for direct CITATION.cff interoperability.
456 date_end: Annotated[
457 date | None,
458 Field(
459 alias="date-end",
460 description="The entity's ending date, e.g., when the entity is a conference.",
461 ),
462 ] = None
463 date_start: Annotated[
464 date | None,
465 Field(
466 alias="date-start",
467 description="The entity's starting date, e.g., when the entity is a conference.",
468 ),
469 ] = None
470 location: Annotated[
471 str | None,
472 Field(
473 description="The entity's location, e.g., when the entity is a conference."
474 ),
475 ] = None
476 name: Annotated[str, Field(description="The entity's name.")]
477 website: Annotated[
478 HttpUrlStr | None, Field(description="The entity's website.")
479 ] = None
480 rorid: Annotated[
481 HttpUrlStr | None,
482 Field(
483 description="The entity's ROR ID url **(not required, but highly suggested)**."
484 ),
485 ] = None
487 # helper methods
488 @property
489 def full_name(self) -> str:
490 """Use same property as Person for code integration."""
491 return self.name
493 @classmethod
494 def from_name_email_string(cls, person: str) -> Entity:
495 """Return an `Entity` based on an name/e-mail string like `name <x@y.z>`."""
496 m = re.match(r"\s*([^<]+)<([^>]+)>", person)
497 if m is None:
498 return Entity(name=person)
500 name, mail = (
501 m.group(1).strip(),
502 m.group(2).strip(),
503 )
504 return Entity(name=name, email=mail)
506 def same_person(self, other: Person | Entity) -> bool:
507 """Return whether two Entity metadata records are about the same real person.
509 Uses heuristic match based on email and name (whichever are provided).
510 """
511 if not isinstance(other, Entity):
512 return False
513 if (
514 self.rorid is not None
515 and other.rorid is not None
516 and self.rorid == other.rorid
517 ):
518 return True
519 if self.rorid is not None and other.rorid is not None:
520 # distinct identifiers: different organizations, even with equal names
521 return False
522 if (
523 self.website is not None
524 and other.website is not None
525 and self.website == other.website
526 ):
527 return True
528 if self.website is not None and other.website is not None:
529 return False
530 if (
531 self.email is not None
532 and other.email is not None
533 and self.email == other.email
534 ):
535 return True
536 return self.name == other.name
538 def model_dump_json(self, *args, **kwargs):
539 """Patched json method (to preserve custom key order).
541 If no website is set, the rorid is used as website and removed.
542 If a website is set, the rorid is kept alongside it.
543 """
544 ret = super().model_dump_json(*args, **kwargs)
545 # convert ret to dict
546 ret = json.loads(ret)
547 if self.rorid is not None and "website" not in ret:
548 ret["website"] = str(self.rorid)
549 ret.pop("rorid", None)
550 # convert ret back to json string
551 return json.dumps(ret, ensure_ascii=False)
554class Person(ContributorBaseModel):
555 """Metadata about a person in the context of a software project.
557 This schema is based on CITATION.cff 1.2, modified and extended for the needs of somesy.
558 """
560 # NOTE: we rely on the defined aliases for direct CITATION.cff interoperability.
562 orcid: Annotated[
563 HttpUrlStr | None,
564 Field(
565 description="The person's ORCID url **(not required, but highly suggested)**."
566 ),
567 ] = None
568 family_names: Annotated[
569 str, Field(alias="family-names", description="The person's family names.")
570 ]
571 given_names: Annotated[
572 str, Field(alias="given-names", description="The person's given names.")
573 ]
574 name_particle: Annotated[
575 str | None,
576 Field(
577 alias="name-particle",
578 description="The person's name particle, e.g., a nobiliary particle or a preposition meaning 'of' or 'from'"
579 " (for example 'von' in 'Alexander von Humboldt').",
580 examples=["von"],
581 ),
582 ] = None
583 name_suffix: Annotated[
584 str | None,
585 Field(
586 alias="name-suffix",
587 description="The person's name-suffix, e.g. 'Jr.' for Sammy Davis Jr. or 'III' for Frank Edwin Wright III.",
588 examples=["Jr.", "III"],
589 ),
590 ] = None
591 affiliation: Annotated[
592 str | None, Field(description="The person's affiliation.")
593 ] = None
595 # helper methods
597 @field_validator("orcid", mode="before")
598 @classmethod
599 def orcid_from_string(cls, orcid: Any) -> Any:
600 """Convert orcid id string to HttpUrlStr."""
601 # orcid regex without https://orcid.org/ prefix
602 orcid_regex = r"^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{3}[0-9X]$"
603 if (
604 orcid is not None
605 and isinstance(orcid, str)
606 and re.match(orcid_regex, orcid)
607 ):
608 return f"https://orcid.org/{orcid}"
609 return orcid
611 @property
612 def full_name(self) -> str:
613 """Return the full name of the person."""
614 names = []
616 if self.given_names:
617 names.append(self.given_names)
619 if self.name_particle:
620 names.append(self.name_particle)
622 if self.family_names:
623 names.append(self.family_names)
625 if self.name_suffix:
626 names.append(self.name_suffix)
628 return " ".join(names) if names else ""
630 @classmethod
631 def from_name_email_string(cls, person: str) -> Person:
632 """Return a `Person` based on an name/e-mail string like `full name <x@y.z>`.
634 If the name is `A B C`, then `A B` will be the given names and `C` will be the family name.
635 A single-word name is not a valid person name and raises a `ValidationError`.
636 """
637 m = re.match(r"\s*([^<]+)<([^>]+)>", person)
638 if m is None:
639 names = [s.strip() for s in person.split()]
640 return Person.model_validate(
641 {
642 "given-names": " ".join(names[:-1]),
643 "family-names": names[-1],
644 }
645 )
646 names, mail = (
647 [s.strip() for s in m.group(1).split()],
648 m.group(2).strip(),
649 )
650 # NOTE: for our purposes, does not matter what are given or family names,
651 # we only compare on full_name anyway.
652 return Person.model_validate(
653 {
654 "given-names": " ".join(names[:-1]),
655 "family-names": names[-1],
656 "email": mail,
657 }
658 )
660 def same_person(self, other) -> bool:
661 """Return whether two Person metadata records are about the same real person.
663 Uses heuristic match based on orcid, email and name (whichever are provided).
664 """
665 if not isinstance(other, Person):
666 return False
667 if self.orcid is not None and other.orcid is not None:
668 # having orcids is the best case, a real identifier
669 # NOTE: converting to str from pydantic-internal Url object for == !
670 return str(self.orcid) == str(other.orcid)
672 # otherwise, try to match according to mail/name
673 # sourcery skip: merge-nested-ifs
674 if (
675 self.email is not None
676 and other.email is not None
677 and self.email == other.email
678 ):
679 # an email address belongs to exactly one person
680 # => same email -> same person
681 return True
682 # otherwise, need to check name
683 # (a person often has multiple email addresses)
685 # no orcids, no/distinct email address
686 # -> decide based on full_name (which is always present)
687 return self.full_name == other.full_name
690def is_blank_person(person_obj: Any) -> bool:
691 """Return whether an existing person entry is empty (e.g. `""`, `{}`, `{"name": ""}`).
693 Such entries are the normal state of freshly generated files (e.g. `npm init`)
694 and count as "no person".
695 """
696 if isinstance(person_obj, BaseModel):
697 person_obj = person_obj.model_dump()
698 if isinstance(person_obj, str):
699 return not person_obj.strip()
700 if isinstance(person_obj, dict):
701 return all(v is None or is_blank_person(v) for v in person_obj.values())
702 return False
705def parse_name_email(person_obj: str) -> Person | Entity | None:
706 """Parse a "Name <email>" string to a Person, falling back to an Entity."""
707 if is_blank_person(person_obj):
708 return None
709 try:
710 return Person.from_name_email_string(person_obj)
711 except (ValueError, AttributeError):
712 logger.info(f"Cannot convert {person_obj} to Person object, trying Entity.")
714 try:
715 return Entity.from_name_email_string(person_obj)
716 except (ValueError, AttributeError):
717 logger.warning(f"Cannot convert {person_obj} to Entity.")
718 return None
721def _same_identifier(a, b) -> bool:
722 """Return whether two records share an identifier (orcid or rorid)."""
723 for attr in ("orcid", "rorid"):
724 x, y = getattr(a, attr, None), getattr(b, attr, None)
725 if x is not None and y is not None and str(x) == str(y):
726 return True
727 return False
730def _distinct_identifiers(a, b) -> bool:
731 """Return whether two records have different identifiers (orcid or rorid)."""
732 for attr in ("orcid", "rorid"):
733 x, y = getattr(a, attr, None), getattr(b, attr, None)
734 if x is not None and y is not None and str(x) != str(y):
735 return True
736 return False
739def find_matching_person(
740 person: Person | Entity, candidates: Sequence[Person | Entity]
741) -> int | None:
742 """Return the index of the candidate that is the same person, or None.
744 If several candidates match, a warning naming them is logged and the
745 candidate with the same ORCID/ROR ID is used (else the first match).
746 """
747 matches = [i for i, c in enumerate(candidates) if c.same_person(person)]
748 if not matches:
749 return None
750 if len(matches) == 1:
751 return matches[0]
752 names = ", ".join(
753 f"'{candidates[i].full_name}' (position {i + 1})" for i in matches
754 )
755 chosen = next(
756 (i for i in matches if _same_identifier(candidates[i], person)), matches[0]
757 )
758 logger.warning(
759 f"'{person.full_name}' matches several people: {names}. "
760 f"Using the one at position {chosen + 1}."
761 )
762 return chosen
765def _ensure_distinct(items: list, kind: str) -> list:
766 """Raise a ValueError if the same person/entity is listed twice.
768 A pair is not reported if one of its members is ambiguous, i.e. also matches
769 two entries with different ORCIDs/ROR IDs (e.g. two ORCIDs and one without).
770 """
771 n = len(items)
772 same = [
773 [i != j and items[i].same_person(items[j]) for j in range(n)] for i in range(n)
774 ]
776 def ambiguous(i: int) -> bool:
777 nb = [k for k in range(n) if same[i][k]]
778 return any(_distinct_identifiers(items[a], items[b]) for a in nb for b in nb)
780 for i in range(n):
781 for j in range(i + 1, n):
782 if same[i][j] and not ambiguous(i) and not ambiguous(j):
783 a = pretty_repr(json.loads(items[i].model_dump_json()))
784 b = pretty_repr(json.loads(items[j].model_dump_json()))
785 msg = f"Same {kind} is listed twice:\n{a}\n{b}"
786 raise ValueError(msg)
787 return items
790class ProjectMetadata(SomesyBaseModel):
791 """Pydantic model for Project Metadata Input."""
793 model_config = {"extra": "ignore"}
795 @field_validator("people")
796 @classmethod
797 def ensure_distinct_people(cls, people):
798 """Make sure that no person is listed twice in the same list."""
799 return _ensure_distinct(people, "person")
801 @field_validator("entities")
802 @classmethod
803 def ensure_distinct_entities(cls, entities):
804 """Make sure that no entity is listed twice in the same list."""
805 return _ensure_distinct(entities, "entity")
807 @model_validator(mode="after")
808 def at_least_one_author(self) -> ProjectMetadata:
809 """Make sure there is at least one author."""
810 if not self.people and not self.entities:
811 raise ValueError(
812 "There have to be at least a person or an organization in the input"
813 )
814 if not any(p.author for p in self.people) and not any(
815 e.author for e in self.entities
816 ):
817 raise ValueError("At least one person must be an author of this project.")
818 return self
820 name: Annotated[str, Field(description="Project name.")]
821 description: Annotated[str, Field(description="Project description.")]
822 abstract: Annotated[
823 str | None,
824 Field(
825 description="Project abstract for CITATION.cff (defaults to description)."
826 ),
827 ] = None
828 version: Annotated[str | None, Field(description="Project version.")] = None
829 doi: Annotated[str | None, Field(description="Project DOI.")] = None
830 license: Annotated[
831 LicenseEnum | list[LicenseEnum],
832 Field(description="SPDX License string(s)."),
833 ]
835 @field_validator("doi", mode="before")
836 @classmethod
837 def normalize_doi(cls, doi: Any) -> str | None:
838 """Normalize DOI URLs to the DOI value accepted by CITATION.cff."""
839 if doi is None:
840 return None
841 if isinstance(doi, str):
842 doi = re.sub(
843 r"^https?://(?:dx\.)?doi\.org/", "", doi.strip(), flags=re.IGNORECASE
844 )
845 if re.fullmatch(r"10\.\d{4,9}/[-._;()/:A-Z0-9]+", doi, flags=re.IGNORECASE):
846 return doi
847 raise ValueError("DOI must be a DOI or a doi.org URL.")
849 @field_validator("license")
850 @classmethod
851 def validate_license_list(cls, license):
852 """Require at least one license when licenses are provided as a list."""
853 if isinstance(license, list) and not license:
854 raise ValueError("At least one license must be provided.")
855 return license
857 homepage: Annotated[
858 HttpUrlStr | None, Field(description="URL of the project homepage.")
859 ] = None
860 repository: Annotated[
861 HttpUrlStr | None,
862 Field(description="URL of the project source code repository."),
863 ] = None
864 documentation: Annotated[
865 HttpUrlStr | None, Field(description="URL of the project documentation.")
866 ] = None
868 keywords: Annotated[
869 list[str] | None,
870 Field(min_length=1, description="Keywords that describe the project."),
871 ] = None
873 people: list[Person] = Field(
874 default_factory=list,
875 description="Project authors, maintainers and contributors.",
876 )
878 entities: list[Entity] = Field(
879 default_factory=list,
880 description="Project authors, maintainers and contributors as entities (organizations).",
881 )
883 def authors(self) -> list[Person | Entity]:
884 """Return people and entities explicitly marked as authors."""
885 authors: list[Person | Entity] = [p for p in self.people if p.author]
886 authors.extend([e for e in self.entities if e.author])
887 return authors
889 def publication_authors(self) -> list[Person | Entity]:
890 """Return people marked as publication authors.
892 This always includes people marked as authors.
893 """
894 # return an empty list if no publication authors are specified
895 if not any(p.publication_author for p in self.people) and not any(
896 p.publication_author for p in self.entities
897 ):
898 return []
899 publication_authors: list[Person | Entity] = [
900 p for p in self.people if p.publication_author
901 ]
902 publication_authors.extend([e for e in self.entities if e.publication_author])
903 return publication_authors
905 def maintainers(self) -> list[Person | Entity]:
906 """Return people and entities marked as maintainers."""
907 maintainers: list[Person | Entity] = [p for p in self.people if p.maintainer]
908 maintainers.extend([e for e in self.entities if e.maintainer])
909 return maintainers
911 def contributors(self) -> list[Person | Entity]:
912 """Return only people and entities not marked as authors."""
913 contributors: list[Person | Entity] = [p for p in self.people if not p.author]
914 contributors.extend([e for e in self.entities if not e.author])
915 return contributors
918class PartialProjectMetadata(ProjectMetadata):
919 """Validated project metadata that may omit normally required values."""
921 name: str | None = None # type: ignore[assignment]
922 description: str | None = None # type: ignore[assignment]
923 license: LicenseEnum | list[LicenseEnum] | None = None # type: ignore[assignment]
925 @model_validator(mode="after")
926 def at_least_one_author(self) -> PartialProjectMetadata:
927 """Allow an author to be omitted while retaining all field validation."""
928 return self
931class SomesyInput(SomesyBaseModel):
932 """The complete somesy input file (`somesy.toml`) or section (`pyproject.toml`)."""
934 _origin: Path | None = PrivateAttr(default=None)
936 project: Annotated[
937 ProjectMetadata | PartialProjectMetadata,
938 Field(description="Project metadata to be used and synchronized."),
939 ]
940 config: Annotated[
941 SomesyConfig,
942 Field(
943 description="somesy tool configuration (matches CLI flags).",
944 default_factory=lambda: SomesyConfig(),
945 ),
946 ]
948 # if config.input_file is set, use it as origin
949 @model_validator(mode="after")
950 def set_origin(self):
951 """Set the origin of the input file."""
952 if isinstance(self.project, PartialProjectMetadata) and not bool(
953 self.config.pass_validation
954 ):
955 ProjectMetadata.model_validate(self.project.model_dump())
956 if self.config and self.config.input_file:
957 self._origin = self.config.input_file
958 return self
960 def is_somesy_file(self) -> bool:
961 """Return whether this somesy input is from a somesy config file.
963 That means, returns False if it is from pyproject.toml or package.json.
964 """
965 return self.is_somesy_file_path(self._origin or Path("."))
967 @classmethod
968 def is_somesy_file_path(cls, path: Path) -> bool:
969 """Return whether the path looks like a somesy config file.
971 That means, returns False if it is e.g. pyproject.toml or package.json.
972 """
973 return str(path).endswith("somesy.toml")
975 @classmethod
976 def from_input_file(
977 cls,
978 path: Path,
979 *,
980 allow_incomplete: bool = False,
981 pass_validation: bool | None = None,
982 ) -> SomesyInput:
983 """Load somesy input from given file.
985 If `pass_validation` is given, it overrides the value from the file
986 (and decides whether the project is validated strictly).
987 """
988 content = get_input_content(path)
989 config = SomesyConfig(**content.get("config", {}))
990 if allow_incomplete:
991 config.pass_validation = True
992 if pass_validation is not None:
993 config.pass_validation = pass_validation
994 project_model = (
995 PartialProjectMetadata if config.pass_validation else ProjectMetadata
996 )
997 ret = cls.model_validate(
998 {
999 **content,
1000 "project": project_model(**content["project"]),
1001 "config": config,
1002 }
1003 )
1004 ret._origin = path
1005 return ret