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

1"""Project metadata writer base-class.""" 

2 

3import logging 

4from abc import ABC, abstractmethod 

5from collections.abc import Sequence 

6from pathlib import Path 

7from typing import Any 

8 

9import tomlkit 

10from tomlkit.items import AoT, Array, InlineTable 

11 

12from somesy.core.models import ( 

13 Entity, 

14 Person, 

15 ProjectMetadata, 

16 find_matching_person, 

17 is_blank_person, 

18) 

19 

20logger = logging.getLogger("somesy") 

21 

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) 

34 

35 

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 

51 

52 

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) 

57 

58 

59def format_toml_data(data: Any) -> None: 

60 """Prepare a tomlkit document for saving: multiline description, multiline arrays.""" 

61 multiline_description(data) 

62 

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 

69 

70 

71class IgnoreKey: 

72 """Special marker to be passed for dropping a key from serialization.""" 

73 

74 

75FieldKeyMapping = dict[str, str | list[str] | IgnoreKey] 

76"""Type to be used for the dict passed as `direct_mappings`.""" 

77 

78DictLike = Any 

79"""Dict-like that supports getitem, setitem, delitem, etc. 

80 

81NOTE: This should be probably turned into a proper protocol. 

82""" 

83 

84 

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 ) 

91 

92 

93class ProjectMetadataWriter(ABC): 

94 """Base class for Project Metadata Output Wrapper. 

95 

96 All supported output formats are implemented as subclasses. 

97 """ 

98 

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. 

109 

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. 

114 

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. 

121 

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.") 

138 

139 def _init_new_file(self) -> None: 

140 """Initialize the data of a new target file (in memory only). 

141 

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 = {} 

147 

148 @abstractmethod 

149 def _load(self): 

150 """Load the output file and validate it. 

151 

152 Implement this method so that it loads the file `self.path` 

153 into the `self._data` dict. 

154 

155 The file is guaranteed to exist. 

156 """ 

157 

158 @abstractmethod 

159 def _validate(self) -> None: 

160 """Validate the target file data. 

161 

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 """ 

166 

167 @abstractmethod 

168 def save(self, path: Path | None) -> None: 

169 """Save the output file to the given path. 

170 

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 """ 

175 

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. 

183 

184 Override this to e.g. rewrite the retrieved key 

185 (e.g. if everything relevant is in some subobject). 

186 

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. 

190 

191 """ 

192 if isinstance(key, IgnoreKey): 

193 return None 

194 key_path = [key] if isinstance(key, str) else key 

195 

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 

203 

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] 

213 

214 return curr 

215 

216 def _set_property(self, key: str | list[str] | IgnoreKey, value: Any) -> None: 

217 """Set a property in the data. 

218 

219 Note if there are lists along the path, they are cleared out. 

220 

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 

227 

228 if not value: # remove value and clean up the sub-dict 

229 self._get_property(key_path, remove=True) 

230 return 

231 

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] 

238 

239 curr[key_path[-1]] = value 

240 

241 # ---- 

242 # special handling for person metadata 

243 

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. 

250 

251 Will identify people based on orcid, email or full name. 

252 

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] 

261 

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] 

269 

270 # not new person (-> will not append new record) 

271 # still exists (-> will not be removed from list) 

272 still_exists[index] = True 

273 

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}) 

286 

287 # if there were changes -> update person 

288 if updated.model_dump() != person.model_dump(): 

289 modified_people[index] = updated 

290 

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) 

298 

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)}") 

305 

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 

312 

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. 

317 

318 Args: 

319 old (List[Any]): list of persons in format-specific representation 

320 new (List[Person]): list of persons in somesy representation 

321 

322 Returns: 

323 List[Any]: updated list of persons in format-specific representation 

324 

325 """ 

326 old_people: list[Person | Entity] = self._parse_people(old) 

327 

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 [] 

335 

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) 

341 

342 return unique_people 

343 

344 old_people_unique = filter_unique(old_people) 

345 new_people_unique = filter_unique(new) 

346 

347 return self._merge_person_metadata(old_people_unique, new_people_unique) 

348 

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. 

351 

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, [] 

358 

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 

366 

367 return key, [e for e in raw if unparseable(e)] 

368 

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) 

378 

379 def _sync_authors(self, metadata: ProjectMetadata) -> None: 

380 """Sync output file authors with authors from metadata. 

381 

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()) 

389 

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 

396 

397 if metadata.version: 

398 self.version = metadata.version 

399 

400 if metadata.keywords: 

401 self.keywords = metadata.keywords 

402 

403 # existing entries we cannot parse are kept untouched in the target 

404 kept = {r: self._unparseable_people(r) for r in ("authors", "maintainers")} 

405 

406 if metadata.authors(): 

407 self._sync_authors(metadata) 

408 self.maintainers = self._sync_person_list( 

409 self.maintainers, metadata.maintainers() 

410 ) 

411 

412 for key, raw_entries in kept.values(): 

413 self._reattach_people(key, raw_entries) 

414 

415 if licenses := metadata.license: 

416 self.license = license_expression(licenses) 

417 

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) 

425 

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 

445 

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) 

461 

462 if people: 

463 data["people"] = people 

464 if entities: 

465 data["entities"] = entities 

466 return data 

467 

468 @staticmethod 

469 @abstractmethod 

470 def _from_person(person: Person | Entity) -> Any: 

471 """Convert a `Person` or `Entity` object into suitable target format.""" 

472 

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.""" 

477 

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) 

482 

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 ] 

493 

494 # ---- 

495 # individual magic getters and setters 

496 

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 

500 

501 @property 

502 def name(self): 

503 """Return the name of the project.""" 

504 return self._get_property(self._get_key("name")) 

505 

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) 

510 

511 @property 

512 def version(self) -> str | None: 

513 """Return the version of the project.""" 

514 return self._get_property(self._get_key("version")) 

515 

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) 

520 

521 @property 

522 def description(self) -> str | None: 

523 """Return the description of the project.""" 

524 return self._get_property(self._get_key("description")) 

525 

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) 

530 

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 [] 

537 

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 

545 

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) 

551 

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 [] 

558 

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 

567 

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) 

573 

574 @property 

575 def contributors(self): 

576 """Return the contributors of the project.""" 

577 return self._get_property(self._get_key("contributors")) 

578 

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) 

584 

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")) 

589 

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) 

594 

595 @property 

596 def license(self) -> Any: 

597 """Return the license of the project.""" 

598 return self._get_property(self._get_key("license")) 

599 

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) 

604 

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")) 

609 

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) 

614 

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")) 

619 

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) 

624 

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")) 

629 

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)