Coverage for src/somesy/cff/writer.py: 100%

86 statements  

« prev     ^ index     » next       coverage.py v7.16.0, created at 2026-11-09 13:08 +0000

1"""Citation File Format (CFF) parser and saver.""" 

2 

3import json 

4import logging 

5from copy import deepcopy 

6from io import StringIO 

7from pathlib import Path 

8 

9from cffconvert import Citation 

10from ruamel.yaml import YAML 

11from ruamel.yaml.scalarstring import LiteralScalarString 

12 

13from somesy.core.core import atomic_write 

14from somesy.core.models import Entity, Person, ProjectMetadata 

15from somesy.core.writer import FieldKeyMapping, IgnoreKey, ProjectMetadataWriter 

16 

17logger = logging.getLogger("somesy") 

18 

19 

20def _drop_rorid(data) -> None: 

21 """Remove `rorid` from entities; earlier somesy versions wrote this non-CFF key.""" 

22 for key in ("authors", "contact"): 

23 for entry in data.get(key) or []: 

24 if isinstance(entry, dict) and "name" in entry: 

25 entry.pop("rorid", None) 

26 

27 

28class CFF(ProjectMetadataWriter): 

29 """Citation File Format (CFF) parser and saver.""" 

30 

31 def __init__( 

32 self, 

33 path: Path, 

34 create_if_not_exists: bool = True, 

35 pass_validation: bool = False, 

36 ): 

37 """Citation File Format (CFF) parser. 

38 

39 See [somesy.core.writer.ProjectMetadataWriter.__init__][]. 

40 """ 

41 self._yaml = YAML() 

42 self._yaml.preserve_quotes = True 

43 self._yaml.indent(mapping=2, sequence=4, offset=2) 

44 self._yaml.width = 120 

45 

46 mappings: FieldKeyMapping = { 

47 "name": ["title"], 

48 "description": ["abstract"], 

49 "homepage": ["url"], 

50 "repository": ["repository-code"], 

51 "documentation": IgnoreKey(), 

52 "maintainers": ["contact"], 

53 } 

54 super().__init__( 

55 path, 

56 create_if_not_exists=create_if_not_exists, 

57 direct_mappings=mappings, 

58 pass_validation=pass_validation, 

59 ) 

60 

61 def _init_new_file(self): 

62 """Initialize new CFF file.""" 

63 self._was_empty = True # nothing to validate yet 

64 self._data = { 

65 "cff-version": "1.2.0", 

66 "message": "If you use this software, please cite it using these metadata.", 

67 "type": "software", 

68 } 

69 

70 def _load(self): 

71 """Load the CFF file.""" 

72 with open(self.path, encoding="utf-8") as f: 

73 self._data = self._yaml.load(f) 

74 self._was_empty = not self._data 

75 if self._was_empty: # empty or comment-only file, treat like a new one 

76 self._init_new_file() 

77 

78 def _validate(self) -> None: 

79 """Validate the CFF file.""" 

80 if self.pass_validation or self._was_empty: 

81 return 

82 try: 

83 # validate the loaded data without a stray `rorid` (repaired on sync) 

84 data = deepcopy(self._data) 

85 _drop_rorid(data) 

86 stream = StringIO() 

87 self._yaml.dump(data, stream) 

88 Citation(stream.getvalue(), src=self.path).validate() 

89 except ValueError as e: 

90 raise ValueError(f"CITATION.cff file is not valid!\n{e}") from e 

91 

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

93 """Save the CFF object to a file.""" 

94 path = path or self.path 

95 

96 # if description have new line characters, it should be saved as multiline string 

97 abstract = self._data.get("abstract") 

98 if isinstance(abstract, str) and "\n" in abstract: 

99 self._data["abstract"] = LiteralScalarString(abstract) 

100 

101 stream = StringIO() 

102 self._yaml.dump(self._data, stream) 

103 atomic_write(path, stream.getvalue()) 

104 

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

106 """Ensure that publication authors are added all into author list.""" 

107 self.authors = self._sync_person_list( 

108 self.authors, metadata.publication_authors() 

109 ) 

110 

111 def sync(self, metadata: ProjectMetadata) -> None: 

112 """Sync CFF metadata.""" 

113 _drop_rorid(self._data) 

114 super().sync(metadata) 

115 # CFF 1.2.0 allows a list of SPDX ids 

116 if isinstance(metadata.license, list) and len(metadata.license) > 1: 

117 self.license = [license.value for license in metadata.license] 

118 # an abstract can be longer than a package summary, so prefer it here 

119 if metadata.abstract: 

120 self.description = metadata.abstract 

121 if metadata.doi: 

122 self._data["doi"] = metadata.doi 

123 

124 @staticmethod 

125 def _from_person(person: Person | Entity): 

126 """Convert project metadata person or entity object to cff dict for person format.""" 

127 json_str = person.model_dump_json( 

128 exclude={ 

129 "contribution", 

130 "contribution_types", 

131 "contribution_begin", 

132 "contribution_end", 

133 "author", 

134 "publication_author", 

135 "maintainer", 

136 }, 

137 by_alias=True, # e.g. family_names -> family-names, etc. 

138 ) 

139 ret = json.loads(json_str) 

140 ret.pop("rorid", None) # not a CFF field 

141 return ret 

142 

143 @staticmethod 

144 def _is_blank_person(person_obj) -> bool: 

145 """Incomplete CFF people are kept with a warning, never treated as blank.""" 

146 return False 

147 

148 @staticmethod 

149 def _to_person(person_obj) -> Person | Entity | None: 

150 """Parse CFF Person to a somesy Person or entity. 

151 

152 Entries lacking a required field are skipped with a warning. 

153 """ 

154 # if the object has key name, it is an entity 

155 if "name" in person_obj: 

156 model: type[Person | Entity] = Entity 

157 else: 

158 model = Person 

159 model._aliases() 

160 required = { 

161 f.alias or k for k, f in model.model_fields.items() if f.is_required() 

162 } 

163 if missing := required - set(person_obj.keys()): 

164 logger.warning( 

165 f"Skipping incomplete CITATION.cff person/entity {dict(person_obj)}, " 

166 f"missing: {', '.join(sorted(missing))}" 

167 ) 

168 return None 

169 ret = model.make_partial(person_obj) 

170 

171 # construct (partial) Person while preserving key order from YAML 

172 ret.set_key_order(list(person_obj.keys())) 

173 return ret