Coverage for src/somesy/pom_xml/writer.py: 96%
186 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"""Writer adapter for pom.xml files."""
3import logging
4import xml.etree.ElementTree as ET
5from pathlib import Path
6from typing import Any
8from somesy.core.models import Entity, Person, is_blank_person
9from somesy.core.types import ContributionTypeEnum
10from somesy.core.writer import FieldKeyMapping, IgnoreKey, ProjectMetadataWriter
12from . import POM_PREF, POM_ROOT_ATRS, POM_URL
13from .xmlproxy import XMLProxy
15XSI_URL = "http://www.w3.org/2001/XMLSchema-instance"
17logger = logging.getLogger("somesy")
19_ENTITY_MARK = "__somesy_entity__"
20"""Private record key flagging that a POM person is a known organisation."""
23class POM(ProjectMetadataWriter):
24 """Java Maven pom.xml parser and saver."""
26 # TODO: write a wrapper for ElementTree that behaves like a dict
27 # TODO: set up correct field name mappings
29 def __init__(
30 self,
31 path: Path,
32 create_if_not_exists: bool = True,
33 pass_validation: bool | None = False,
34 ):
35 """Java Maven pom.xml parser.
37 See [somesy.core.writer.ProjectMetadataWriter.__init__][].
38 """
39 mappings: FieldKeyMapping = {
40 # "year": ["inceptionYear"], # not supported by somesy + does not really change
41 # "project_slug": ["artifactId"], # not supported by somesy for sync
42 "license": ["licenses", "license"],
43 "homepage": ["url"],
44 "repository": ["scm"],
45 "documentation": ["distributionManagement", "site"],
46 "authors": ["developers", "developer"],
47 "contributors": ["contributors", "contributor"],
48 }
49 self._entity_names: set[str] = set()
50 super().__init__(
51 path,
52 create_if_not_exists=create_if_not_exists,
53 direct_mappings=mappings,
54 pass_validation=pass_validation,
55 )
57 def _init_new_file(self):
58 """Initialize new pom.xml file."""
59 ET.register_namespace("", POM_URL)
60 ET.register_namespace("xsi", XSI_URL)
61 root = ET.Element(
62 POM_PREF + "project",
63 {"{" + XSI_URL + "}schemaLocation": POM_ROOT_ATRS["xsi:schemaLocation"]},
64 )
65 pom = XMLProxy(root, default_namespace=POM_URL)
66 pom["properties"] = {"info.versionScheme": "semver-spec"}
67 self._data = pom
69 def _load(self):
70 """Load the POM file."""
71 ET.register_namespace("", POM_URL) # register POM as default xml namespace
72 self._data = XMLProxy.parse(self.path, default_namespace=POM_URL)
74 def _validate(self) -> None:
75 """Validate the POM file."""
76 logger.info("Cannot validate POM file, skipping validation.")
78 def save(self, path: Path | None = None) -> None:
79 """Save the POM DOM to a file."""
80 ET.register_namespace("", POM_URL)
81 self._data.write(path or self.path, default_namespace=None)
83 def _get_property(
84 self,
85 key: str | list[str] | IgnoreKey,
86 *,
87 remove: bool = False,
88 ) -> Any | None:
89 """Get (a) property by key."""
90 if isinstance(key, IgnoreKey):
91 return None
92 elem = super()._get_property(key, remove=remove)
93 if elem is not None:
94 if isinstance(elem, list):
95 return [e.to_jsonlike() for e in elem]
96 else:
97 return elem.to_jsonlike()
98 return None
100 @staticmethod
101 def _from_person(person: Entity | Person):
102 """Convert person object to dict for POM XML person format."""
103 ret: dict[str, Any] = {}
104 if isinstance(person, Person):
105 person_id = person.to_name_email_string()
106 if person.orcid:
107 person_id = str(person.orcid)
108 ret["url"] = str(person.orcid)
109 else:
110 person_id = person.to_name_email_string()
111 if person.website:
112 person_id = str(person.website)
113 ret["url"] = str(person.website)
114 ret["id"] = person_id
115 ret["name"] = person.full_name
116 if person.email:
117 ret["email"] = person.email
118 if person.contribution_types:
119 ret["roles"] = {"role": [c.value for c in person.contribution_types]}
120 return ret
122 @staticmethod
123 def _parse_roles(person_obj: dict) -> list[ContributionTypeEnum] | None:
124 """Return the POM roles that are valid contribution types (roles are free text in POM)."""
125 roles = (person_obj.get("roles") or {}).get("role")
126 if not roles:
127 return None
128 if not isinstance(roles, list):
129 roles = [roles]
130 known = {c.value for c in ContributionTypeEnum}
131 valid = [ContributionTypeEnum(r) for r in roles if r in known]
132 if len(valid) < len(roles):
133 logger.debug(f"Ignoring POM roles that are not contribution types: {roles}")
134 return valid or None
136 def _records_keeping_roles(
137 self, people: list[Entity | Person], existing: list[dict]
138 ) -> list[dict[str, Any]]:
139 """Convert people to POM records, keeping free-text roles of matching existing entries."""
140 known = {c.value for c in ContributionTypeEnum}
141 old_people = [(self._to_person(e), e) for e in self._mark_entities(existing)]
142 records = []
143 for person in people:
144 record = self._from_person(person)
145 for old_person, old in old_people:
146 if old_person is None or not old_person.same_person(person):
147 continue
148 old_roles = (old.get("roles") or {}).get("role") or []
149 if not isinstance(old_roles, list):
150 old_roles = [old_roles]
151 roles = record.get("roles", {}).get("role", [])
152 roles += [r for r in dict.fromkeys(old_roles) if r not in known]
153 if roles:
154 record["roles"] = {"role": roles}
155 break
156 records.append(record)
157 return records
159 def _mark_entities(self, people: list[dict]) -> list[dict]:
160 """Mark records named like a known organisation, so they are parsed as Entity."""
161 return [
162 {**p, _ENTITY_MARK: True}
163 if isinstance(p, dict) and p.get("name") in self._entity_names
164 else p
165 for p in people
166 ]
168 def _sync_person_list(self, old: list[Any], new) -> list[Any]:
169 """Sync people, matching existing records against known organisations first."""
170 return super()._sync_person_list(self._mark_entities(old), new)
172 @staticmethod
173 def _to_person(person_obj: dict) -> Entity | Person | None:
174 """Parse POM XML person to a somesy Person.
176 POM has no person/entity distinction. During sync, names of organisations
177 known from the input metadata are parsed as Entity. Otherwise this is a
178 heuristic: a name containing a space is a Person (last word is the
179 family name), anything else is an Entity.
180 """
181 if is_blank_person(person_obj):
182 return None
183 if "name" not in person_obj:
184 logger.warning(f"POM person without name, omitting: {person_obj}")
185 return None
186 if " " in person_obj["name"] and not person_obj.get(_ENTITY_MARK):
187 names = person_obj["name"].split()
188 gnames = " ".join(names[:-1])
189 fname = names[-1]
190 email = person_obj.get("email")
191 url = person_obj.get("url")
192 maybe_orcid = url if url and "orcid.org" in url else None
193 contr = POM._parse_roles(person_obj)
195 return Person(
196 given_names=gnames,
197 family_names=fname,
198 email=email,
199 orcid=maybe_orcid,
200 contribution_types=contr,
201 )
202 else:
203 name = person_obj["name"]
204 email = person_obj.get("email")
205 url = person_obj.get("url")
206 contr = POM._parse_roles(person_obj)
208 return Entity(
209 name=name,
210 email=email,
211 website=url,
212 contribution_types=contr,
213 )
215 # no search keywords supported in POM
216 @property
217 def keywords(self) -> list[str] | None:
218 """Return the keywords of the project."""
220 @keywords.setter
221 def keywords(self, keywords: list[str]) -> None:
222 """Set the keywords of the project."""
224 # authors must be a list
225 @property
226 def authors(self):
227 """Return the authors of the project."""
228 authors = self._get_property(self._get_key("authors"))
229 if authors is None:
230 return []
231 return authors if isinstance(authors, list) else [authors]
233 @authors.setter
234 def authors(self, authors: list[Entity | Person]) -> None:
235 """Set the authors of the project."""
236 author_records = self._records_keeping_roles(authors, self.authors)
237 self._set_property(self._get_key("authors"), author_records)
239 # contributors must be a list
240 @property
241 def contributors(self):
242 """Return the contributors of the project."""
243 contr = self._get_property(self._get_key("contributors"))
244 if contr is None:
245 return []
246 return contr if isinstance(contr, list) else [contr]
248 @contributors.setter
249 def contributors(self, contributors: list[Entity | Person]) -> None:
250 """Set the contributors of the project."""
251 contr = self._records_keeping_roles(contributors, self.contributors)
252 self._set_property(self._get_key("contributors"), contr)
254 # no maintainers supported im POM, only developers and contributors
255 @property
256 def maintainers(self):
257 """Return the maintainers of the project."""
258 return []
260 @maintainers.setter
261 def maintainers(self, maintainers: list[Person | Entity]) -> None:
262 """Set the maintainers of the project."""
264 @property
265 def license(self) -> str | list[str] | None:
266 """Return the license of the project."""
267 licenses = self._get_property(self._get_key("license"))
268 if licenses is None:
269 return None
270 licenses = licenses if isinstance(licenses, list) else [licenses]
271 names = [license["name"] for license in licenses]
272 return names[0] if len(names) == 1 else names
274 @license.setter
275 def license(self, license: str | list[str] | None) -> None:
276 """Set the license of the project."""
277 licenses = license if isinstance(license, list) else [license]
278 self._set_property(
279 self._get_key("license"),
280 [{"name": license, "distribution": "repo"} for license in licenses],
281 )
283 @property
284 def repository(self) -> str | dict | None:
285 """Return the repository url of the project."""
286 repo = super().repository
287 if isinstance(repo, str):
288 return repo
289 return repo.get("url") if repo is not None else None
291 @repository.setter
292 def repository(self, value: str | dict | None) -> None:
293 """Set the repository url of the project."""
294 if value is None:
295 return
296 # only touch <scm><url>, keep e.g. <connection> intact
297 self._set_property(["scm", "url"], value)
299 @property
300 def documentation(self) -> str | dict | None:
301 """Return the documentation url of the project."""
302 docs = super().documentation
303 if isinstance(docs, str):
304 return docs
305 return docs.get("url") if docs is not None else None
307 @documentation.setter
308 def documentation(self, value: str | dict | None) -> None:
309 """Set the documentation url of the project."""
310 if value is None:
311 return
312 self._set_property(
313 self._get_key("documentation"), {"name": "documentation site", "url": value}
314 )
316 def sync(self, metadata) -> None:
317 """Sync codemeta.json with project metadata.
319 Use existing sync function from ProjectMetadataWriter but update repository and contributors.
320 """
321 self._entity_names = {e.name for e in metadata.entities}
322 super().sync(metadata)
323 if licenses := metadata.license:
324 self.license = (
325 [license.value for license in licenses]
326 if isinstance(licenses, list)
327 else licenses.value
328 )
329 self.contributors = self._sync_person_list(
330 self.contributors, metadata.contributors()
331 )