Coverage for src/somesy/package_json/writer.py: 94%

129 statements  

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

1"""package.json parser and saver.""" 

2 

3import json 

4import logging 

5from collections import OrderedDict 

6from pathlib import Path 

7from typing import Any 

8 

9from rich.pretty import pretty_repr 

10 

11from somesy.core.core import write_json 

12from somesy.core.models import Entity, Person, ProjectMetadata, is_blank_person 

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

14from somesy.package_json.models import PackageAuthor, PackageJsonConfig 

15 

16logger = logging.getLogger("somesy") 

17 

18 

19class PackageJSON(ProjectMetadataWriter): 

20 """package.json parser and saver.""" 

21 

22 def __init__( 

23 self, 

24 path: Path, 

25 pass_validation: bool | None = False, 

26 ): 

27 """package.json parser. 

28 

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

30 """ 

31 mappings: FieldKeyMapping = { 

32 "authors": ["author"], 

33 "documentation": IgnoreKey(), 

34 } 

35 super().__init__( 

36 path, 

37 create_if_not_exists=False, 

38 direct_mappings=mappings, 

39 pass_validation=pass_validation, 

40 ) 

41 

42 @property 

43 def authors(self): 

44 """Return the only author of the package.json file as list.""" 

45 # check if the author has the correct format 

46 author = self._get_property(self._get_key("authors")) 

47 if author is None or is_blank_person(author): 

48 return [] 

49 if isinstance(author, str): 

50 author = PackageJsonConfig.convert_author(author) 

51 return [author] 

52 

53 @authors.setter 

54 def authors(self, authors: list[Entity | Person]) -> None: 

55 """Set the authors of the project.""" 

56 authors_dict = self._from_person(authors[0]) 

57 self._set_property(self._get_key("authors"), authors_dict) 

58 

59 @property 

60 def maintainers(self): 

61 """Return the maintainers of the package.json file.""" 

62 # check if the maintainer has the correct format 

63 maintainers = self._get_property(self._get_key("maintainers")) 

64 # return empty list if maintainers is None 

65 if maintainers is None: 

66 return [] 

67 

68 maintainers_valid = [] 

69 

70 for maintainer in maintainers: 

71 if is_blank_person(maintainer): 

72 continue 

73 if isinstance(maintainer, str): 

74 maintainer = PackageJsonConfig.convert_author(maintainer) 

75 if maintainer is None: 

76 continue 

77 maintainers_valid.append(maintainer) 

78 return maintainers_valid 

79 

80 @maintainers.setter 

81 def maintainers(self, maintainers: list[Entity | Person]) -> None: 

82 """Set the maintainers of the project.""" 

83 maintainers_dict = [self._from_person(m) for m in maintainers] 

84 self._set_property(self._get_key("maintainers"), maintainers_dict) 

85 

86 @property 

87 def contributors(self): 

88 """Return the contributors of the package.json file.""" 

89 # check if the contributor has the correct format 

90 contributors = self._get_property(self._get_key("contributors")) 

91 # return empty list if contributors is None 

92 if contributors is None: 

93 return [] 

94 

95 contributors_valid = [] 

96 

97 for contributor in contributors: 

98 if is_blank_person(contributor): 

99 continue 

100 if isinstance(contributor, str): 

101 contributor = PackageJsonConfig.convert_author(contributor) 

102 if contributor is None: 

103 continue 

104 contributors_valid.append(contributor) 

105 return contributors_valid 

106 

107 @contributors.setter 

108 def contributors(self, contributors: list[Entity | Person]) -> None: 

109 """Set the contributors of the project.""" 

110 contributors_dict = [self._from_person(c) for c in contributors] 

111 self._set_property(self._get_key("contributors"), contributors_dict) 

112 

113 def _load(self) -> None: 

114 """Load package.json file.""" 

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

116 self._data = json.load(f, object_pairs_hook=OrderedDict) 

117 

118 def _validate(self) -> None: 

119 """Validate package.json content using pydantic class.""" 

120 if self.pass_validation: 

121 return 

122 config = dict(self._get_property([])) 

123 logger.debug( 

124 f"Validating config using {PackageJsonConfig.__name__}: {pretty_repr(config)}" 

125 ) 

126 PackageJsonConfig(**config) 

127 

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

129 """Save the package.json file.""" 

130 path = path or self.path 

131 logger.debug(f"Saving package.json to {path}") 

132 

133 write_json(self._data, path) 

134 

135 @staticmethod 

136 def _from_person(person: Entity | Person) -> dict: 

137 """Convert project metadata person/entity object to package.json dict for person format.""" 

138 response = {} 

139 if isinstance(person, Person): 

140 response["name"] = person.full_name 

141 if person.orcid: 

142 response["url"] = str(person.orcid) 

143 else: 

144 response["name"] = person.name 

145 if person.website: 

146 response["url"] = str(person.website) 

147 

148 if person.email: 

149 response["email"] = person.email 

150 

151 return response 

152 

153 @staticmethod 

154 def _to_person( 

155 person_obj: str | dict[str, Any] | PackageAuthor, 

156 ) -> Entity | Person: 

157 """Convert package.json dict or str for person format to project metadata person object.""" 

158 if isinstance(person_obj, str): 

159 # parse from package.json format 

160 person_obj = PackageJsonConfig.convert_author(person_obj) 

161 

162 if isinstance(person_obj, PackageAuthor): 

163 person_obj = person_obj.model_dump(exclude_none=True) 

164 

165 person_dict: dict[str, Any] = person_obj # type: ignore 

166 

167 if "name" in person_dict and " " in person_dict["name"]: 

168 names = [s.strip() for s in person_dict["name"].split()] 

169 person_obj = { 

170 "given-names": " ".join(names[:-1]), 

171 "family-names": names[-1], 

172 } 

173 if "email" in person_dict: 

174 person_obj["email"] = person_dict["email"].strip() 

175 if "url" in person_dict and "orcid.org" in person_dict["url"]: 

176 person_obj["orcid"] = person_dict["url"].strip() 

177 return Person(**person_obj) 

178 else: 

179 entity_obj = {"name": person_dict["name"]} 

180 if "email" in person_dict: 

181 entity_obj["email"] = person_dict["email"].strip() 

182 if "url" in person_dict: 

183 entity_obj["website"] = person_dict["url"].strip() 

184 return Entity(**entity_obj) 

185 

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

187 """Sync package.json with project metadata. 

188 

189 Use existing sync function from ProjectMetadataWriter but update repository and contributors. 

190 """ 

191 super().sync(metadata) 

192 

193 # package.json has a single author slot, further authors become contributors 

194 written = [self._to_person(a) for a in self.authors] 

195 further_authors = [ 

196 a for a in metadata.authors() if not any(a.same_person(w) for w in written) 

197 ] 

198 self.contributors = self._sync_person_list( 

199 self.contributors, [*further_authors, *metadata.contributors()] 

200 ) 

201 

202 @property 

203 def repository(self) -> str | dict | None: 

204 """Return the repository url of the project.""" 

205 if repo := super().repository: 

206 if isinstance(repo, str): 

207 return repo 

208 else: 

209 return repo.get("url") 

210 else: 

211 return None 

212 

213 @repository.setter 

214 def repository(self, value: str | dict | None) -> None: 

215 """Set the repository url of the project.""" 

216 if value is None: 

217 self._set_property(self._get_key("repository"), None) 

218 else: 

219 self._set_property( 

220 self._get_key("repository"), {"type": "git", "url": value} 

221 )