Coverage for src/somesy/pyproject/writer.py: 98%
295 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"""Pyproject writers for PEP 621 `[project]` metadata and Poetry."""
3import logging
4import re
5from pathlib import Path
6from typing import Any
8import tomlkit
9import wrapt
10from rich.pretty import pretty_repr
11from tomlkit import load
12from tomlkit.items import Table
14from somesy.core.core import atomic_write
15from somesy.core.log import VERBOSE
16from somesy.core.models import Entity, Person, ProjectMetadata, parse_name_email
17from somesy.core.writer import (
18 IgnoreKey,
19 ProjectMetadataWriter,
20 license_expression,
21 multiline_description,
22 toml_array,
23)
25from .models import Pep621Config, PoetryConfig
27logger = logging.getLogger("somesy")
29SUMMARY_MAX_LENGTH = 512
30"""Longest package summary (`description`) that PyPI accepts on upload."""
32SUMMARY_LINE_BREAK = re.compile(r"[\r\n]")
33"""Line breaks are not allowed in a package summary (core metadata `Summary`)."""
36def normalize_url_key(name: str) -> str:
37 """Return a `[project.urls]` key in a form that can be compared.
39 PEP 621 does not standardize these key names, so the same URL appears as
40 "Bug Tracker", "bug-tracker" or "bugtracker" depending on the template the
41 project started from.
42 """
43 return re.sub(r"[\s_-]+", "", name).lower()
46class PyprojectCommon(ProjectMetadataWriter):
47 """Poetry config file handler parsed from pyproject.toml."""
49 def __init__(
50 self,
51 path: Path,
52 *,
53 section: list[str],
54 model_cls,
55 direct_mappings=None,
56 pass_validation: bool | None = False,
57 ):
58 """Poetry config file handler parsed from pyproject.toml.
60 See [somesy.core.writer.ProjectMetadataWriter.__init__][].
61 """
62 self._model_cls = model_cls
63 self._section = section
64 self._created_tables: list[Table] = []
65 super().__init__(
66 path,
67 create_if_not_exists=False,
68 direct_mappings=direct_mappings or {},
69 pass_validation=pass_validation,
70 )
72 def _get_key(self, key: str) -> str | list[str] | IgnoreKey:
73 """Get a key itself, resolving url keys to their spelling in the file."""
74 mapped = super()._get_key(key)
75 if isinstance(mapped, list) and mapped[:1] == ["urls"]:
76 return ["urls", self._url_key(mapped[-1])]
77 return mapped
79 def _url_key(self, name: str, *, warn: bool = False) -> str:
80 """Return the spelling of the `[project.urls]` key `name` to read or write.
82 The common project templates capitalize the keys ("Homepage",
83 "Bug Tracker"). An existing entry is used whatever its spelling; if
84 several spellings of the same key exist, the first one is used. A key
85 somesy adds follows the predominant capitalization of the table.
86 """
87 keys = list(self._get_property(["urls"]) or {})
88 matches = [k for k in keys if normalize_url_key(k) == normalize_url_key(name)]
89 if matches:
90 if warn and len(matches) > 1:
91 logger.warning(
92 "Found several spellings of the url '%s' (%s), updating '%s'.",
93 name,
94 ", ".join(f"'{k}'" for k in matches),
95 matches[0],
96 )
97 return matches[0]
98 capitalized = sum(key[:1].isupper() for key in keys)
99 if capitalized > len(keys) - capitalized:
100 return name.capitalize()
101 return name
103 def _is_dynamic(self, field: str, value: Any) -> bool:
104 """Return whether `field` is dynamic, warning if somesy has a value for it."""
105 if field not in self._dynamic_fields:
106 return False
107 if value:
108 logger.warning(
109 f"Field '{field}' is listed as dynamic — skipping sync from somesy."
110 )
111 return True
113 @property
114 def _dynamic_fields(self) -> list[str]:
115 """Return the list of fields marked as dynamic in pyproject.toml."""
116 return self._get_property(["dynamic"]) or []
118 @property
119 def version(self) -> str | None:
120 """Return the version of the project."""
121 return self._get_property(self._get_key("version"))
123 @version.setter
124 def version(self, version: str | None) -> None:
125 """Set version, skipping if listed as dynamic."""
126 if self._is_dynamic("version", version):
127 return
128 self._set_property(self._get_key("version"), version)
130 def _keeps_license(self, current: Any) -> bool:
131 """Tell if the license must be left alone (`file` table or `license-files`)."""
132 return (isinstance(current, dict) and "file" in current) or bool(
133 self._get_property(["license-files"])
134 )
136 @property
137 def license(self) -> str | None:
138 """Return the license of the project as an SPDX expression.
140 PEP 639 replaced the `license = { text = ... }` table with a plain
141 expression, but files predating it are still valid and must be read.
142 A `{ file = ... }` table names a license file instead of an
143 identifier, so there is no expression to report.
144 """
145 license = self._get_property(["license"])
146 if isinstance(license, dict):
147 return license.get("text")
148 return license
150 @license.setter
151 def license(self, license: str | None) -> None:
152 """Set the license of the project.
154 A `license = { file = ... }` table or `license-files` in the file are
155 left untouched, somesy only manages the SPDX expression. A
156 `license = { text = ... }` table is replaced by the expression.
157 """
158 if self._is_dynamic("license", license):
159 return
160 current = self._get_property(["license"])
161 if self._keeps_license(current):
162 if license:
163 logger.warning(
164 "The license of the pyproject file was kept, it is given as a "
165 "table or with 'license-files' and somesy does not update it."
166 )
167 return
168 self._set_property(["license"], license)
170 def _person_entries(self, people: list[Person | Entity]) -> list[Any]:
171 """Convert people to the representation used in the file."""
172 return [self._from_person(person) for person in people]
174 @property
175 def authors(self):
176 """Return the authors of the project."""
177 return super().authors
179 @authors.setter
180 def authors(self, authors: list[Person | Entity]) -> None:
181 """Set authors, skipping if listed as dynamic."""
182 if not self._is_dynamic("authors", authors):
183 self._set_property(self._get_key("authors"), self._person_entries(authors))
185 @property
186 def maintainers(self):
187 """Return the maintainers of the project."""
188 return super().maintainers
190 @maintainers.setter
191 def maintainers(self, maintainers: list[Person | Entity]) -> None:
192 """Set maintainers, skipping if listed as dynamic."""
193 if not self._is_dynamic("maintainers", maintainers):
194 self._set_property(
195 self._get_key("maintainers"), self._person_entries(maintainers)
196 )
198 @property
199 def keywords(self) -> list[str] | None:
200 """Return the keywords of the project."""
201 return super().keywords
203 @keywords.setter
204 def keywords(self, keywords: list[str]) -> None:
205 """Set keywords, skipping if listed as dynamic."""
206 if not self._is_dynamic("keywords", keywords):
207 self._set_property(self._get_key("keywords"), keywords)
209 def _set_url(self, field: str, value: str | None) -> None:
210 """Set a project url, skipping if `urls` is listed as dynamic."""
211 if self._is_dynamic("urls", value):
212 return
213 key = self._get_key(field)
214 if isinstance(key, list):
215 self._url_key(key[-1], warn=True)
216 self._set_property(key, value)
218 @property
219 def homepage(self) -> str | None:
220 """Return the homepage url of the project."""
221 return super().homepage
223 @homepage.setter
224 def homepage(self, value: str | None) -> None:
225 """Set the homepage url of the project."""
226 self._set_url("homepage", value)
228 @property
229 def repository(self) -> str | dict | None:
230 """Return the repository url of the project."""
231 return super().repository
233 @repository.setter
234 def repository(self, value: str | dict | None) -> None:
235 """Set the repository url of the project."""
236 self._set_url("repository", value) # type: ignore[arg-type]
238 @property
239 def documentation(self) -> str | dict | None:
240 """Return the documentation url of the project."""
241 return super().documentation
243 @documentation.setter
244 def documentation(self, value: str | dict | None) -> None:
245 """Set the documentation url of the project."""
246 self._set_url("documentation", value) # type: ignore[arg-type]
248 @property
249 def description(self) -> str | None:
250 """Return the description of the project."""
251 return self._get_property(self._get_key("description"))
253 @description.setter
254 def description(self, description: str) -> None:
255 """Set description, skipping if listed as dynamic."""
256 if self._is_dynamic("description", description):
257 return
258 if description and (
259 len(description) > SUMMARY_MAX_LENGTH
260 or SUMMARY_LINE_BREAK.search(description)
261 ):
262 logger.warning(
263 "Field 'description' becomes the package summary, which must be a "
264 "single line of at most %d characters to be uploaded to PyPI. "
265 "Put a longer text in the 'abstract' field instead.",
266 SUMMARY_MAX_LENGTH,
267 )
268 self._set_property(self._get_key("description"), description)
270 def _load(self) -> None:
271 """Load pyproject.toml file."""
272 with open(self.path, encoding="utf-8") as f:
273 self._data = tomlkit.load(f)
275 def _validate(self) -> None:
276 """Validate poetry config using pydantic class.
278 In order to preserve toml comments and structure, tomlkit library is used.
279 Pydantic class only used for validation.
280 """
281 if self.pass_validation:
282 return
283 config = dict(self._get_property([]))
284 logger.debug(
285 f"Validating config using {self._model_cls.__name__}: {pretty_repr(config)}"
286 )
287 self._model_cls(**config)
289 def save(self, path: Path | None = None) -> None:
290 """Save the pyproject file."""
291 path = path or self.path
293 atomic_write(path, tomlkit.dumps(self._data))
295 def _get_property(
296 self, key: str | list[str] | IgnoreKey, *, remove: bool = False, **kwargs
297 ) -> Any:
298 """Get a property from the pyproject.toml file."""
299 if isinstance(key, IgnoreKey):
300 return None
301 key_path = [key] if isinstance(key, str) else key
302 full_path = self._section + key_path
303 return super()._get_property(full_path, remove=remove, **kwargs)
305 def _set_property(self, key: str | list[str] | IgnoreKey, value: Any) -> None:
306 """Set a property in the pyproject.toml file."""
307 if isinstance(key, IgnoreKey):
308 return
309 key_path = [key] if isinstance(key, str) else key
311 if not value: # remove value and clean up the sub-dict
312 self._get_property(key_path, remove=True)
313 return
315 # get the tomlkit object of the section
316 dat = self._get_property([])
318 # dig down, create missing nested objects on the fly
319 curr = dat
320 for path_key in key_path[:-1]:
321 if path_key not in curr:
322 table = tomlkit.table()
323 curr.add(path_key, table)
324 self._created_tables.append(table)
325 curr = curr[path_key]
327 # Handle arrays with proper formatting
328 if isinstance(value, list):
329 array = toml_array(value)
330 curr[key_path[-1]] = array
331 else:
332 curr[key_path[-1]] = value
334 if any(curr is table for table in self._created_tables):
335 for field in curr:
336 curr.item(field).trivia.trail = "\n"
337 curr.item(list(curr)[-1]).trivia.trail = "\n\n"
340class Poetry(PyprojectCommon):
341 """Poetry config file handler parsed from pyproject.toml."""
343 def __init__(
344 self,
345 path: Path,
346 pass_validation: bool | None = False,
347 version: int | None = 1,
348 ):
349 """Poetry config file handler parsed from pyproject.toml.
351 See [somesy.core.writer.ProjectMetadataWriter.__init__][].
352 """
353 version = version or 1
354 self._poetry_version = version
355 v2_mappings = {
356 "homepage": ["urls", "homepage"],
357 "repository": ["urls", "repository"],
358 "documentation": ["urls", "documentation"],
359 }
360 if version == 1:
361 super().__init__(
362 path,
363 section=["tool", "poetry"],
364 model_cls=PoetryConfig,
365 pass_validation=pass_validation,
366 )
367 else:
368 super().__init__(
369 path,
370 section=["project"],
371 model_cls=PoetryConfig,
372 pass_validation=pass_validation,
373 direct_mappings=v2_mappings,
374 )
376 @staticmethod
377 def _from_person(person: Person | Entity, poetry_version: int = 1):
378 """Convert project metadata person object to poetry string for person format "full name <email>."""
379 if poetry_version == 1:
380 return person.to_name_email_string()
381 else:
382 return _pep621_person(person)
384 @staticmethod
385 def _to_person(
386 person_obj: str | dict[str, str],
387 ) -> Person | Entity | None:
388 """Convert from free string to person or entity object."""
389 if isinstance(person_obj, dict):
390 temp = str(person_obj["name"])
391 if "email" in person_obj:
392 temp = f"{temp} <{person_obj['email']}>"
393 person_obj = temp
394 return parse_name_email(person_obj)
396 def _person_entries(self, people: list[Person | Entity]) -> list[Any]:
397 """Convert people to the person format of the Poetry version."""
398 return [self._from_person(person, self._poetry_version) for person in people]
400 def sync(self, metadata: ProjectMetadata) -> None:
401 """Sync metadata with pyproject.toml file."""
402 super().sync(metadata)
404 # For Poetry v2, convert authors and maintainers from array of tables to inline tables
405 if self._poetry_version == 2:
406 multiline_description(self._data["project"])
407 # Move urls section to the end if it exists
408 if "urls" in self._data["project"]:
409 urls = self._data["project"].pop("urls")
410 self._data["project"]["urls"] = urls
411 self._sync_legacy_metadata(metadata)
413 def _sync_legacy_metadata(self, metadata: ProjectMetadata) -> None:
414 """Update the deprecated metadata keys that exist in `[tool.poetry]`.
416 Poetry 2.x still accepts them, so they must not go stale next to
417 `[project]`. Keys that are absent are never added.
418 """
419 legacy = self._data.get("tool", {}).get("poetry")
420 if legacy is None:
421 return
422 dynamic = self._dynamic_fields
424 def update(key: str, value: Any, field: str | None = None) -> None:
425 if not value or key not in legacy or (field or key) in dynamic:
426 return
427 if isinstance(value, list):
428 if list(legacy[key]) != value:
429 legacy[key] = toml_array(value)
430 elif legacy[key] != value:
431 legacy[key] = value
433 update("name", metadata.name)
434 update("version", metadata.version)
435 update("description", metadata.description)
437 if metadata.license and not self._keeps_license(
438 self._get_property(["license"])
439 ):
440 update("license", license_expression(metadata.license))
442 update("keywords", list(metadata.keywords or []))
444 for role, new in (
445 ("authors", metadata.authors()),
446 ("maintainers", metadata.maintainers()),
447 ):
448 if role not in legacy or role in dynamic:
449 continue
450 if role == "authors" and not new:
451 continue
452 people = self._sync_person_list(list(legacy[role]), new)
453 update(role, [p.to_name_email_string() for p in people])
454 if not people:
455 del legacy[role]
457 urls = {
458 "homepage": metadata.homepage,
459 "repository": metadata.repository,
460 "documentation": metadata.documentation,
461 }
462 for key, url in urls.items():
463 if url:
464 update(key, str(url), "urls")
465 if "urls" in legacy and "urls" not in dynamic:
466 for old_key in legacy["urls"]:
467 url = urls.get(normalize_url_key(old_key))
468 if url and legacy["urls"][old_key] != str(url):
469 legacy["urls"][old_key] = str(url)
472class Pep621(PyprojectCommon):
473 """Handler for PEP 621 `[project]` metadata in pyproject.toml.
475 This covers every backend that stores its metadata in the standard
476 `[project]` table, i.e. uv, hatchling, flit, PDM, setuptools and
477 Poetry 2.x. Only Poetry 1.x needs its own handler, see [somesy.pyproject.writer.Poetry][].
478 """
480 def __init__(self, path: Path, pass_validation: bool | None = False):
481 """PEP 621 `[project]` config file handler parsed from pyproject.toml.
483 See [somesy.core.writer.ProjectMetadataWriter.__init__][].
484 """
485 section = ["project"]
486 mappings = {
487 "homepage": ["urls", "homepage"],
488 "repository": ["urls", "repository"],
489 "documentation": ["urls", "documentation"],
490 }
491 super().__init__(
492 path,
493 section=section,
494 direct_mappings=mappings,
495 model_cls=Pep621Config,
496 pass_validation=pass_validation,
497 )
499 @staticmethod
500 def _from_person(person: Person | Entity):
501 """Convert project metadata person object to a PEP 621 person table."""
502 return _pep621_person(person)
504 @staticmethod
505 def _to_person(person_obj: str | dict) -> Entity | Person | None:
506 """Parse a PEP 621 person entry to a Person/Entity."""
507 # NOTE: for our purposes, does not matter what are given or family names,
508 # we only compare on full_name anyway.
509 if isinstance(person_obj, dict):
510 temp = str(person_obj["name"])
511 if "email" in person_obj:
512 temp = f"{temp} <{person_obj['email']}>"
513 person_obj = temp
515 return parse_name_email(person_obj)
517 def sync(self, metadata: ProjectMetadata) -> None:
518 """Sync metadata with pyproject.toml file and fix license field."""
519 super().sync(metadata)
522def _pep621_person(person: Person | Entity) -> dict[str, str]:
523 """Convert a person/entity to a PEP 621 person table."""
524 response = {"name": person.full_name}
525 if person.email:
526 response["email"] = person.email
527 return response
530def _builds_with_poetry(data: Any) -> bool:
531 """Return whether the project declares a Poetry build backend.
533 Only used to tell a Poetry 2.x project apart from a project of another
534 backend that kept a `[tool.poetry]` section for its dependencies, for
535 example while migrating away from Poetry. Without a build backend we
536 cannot tell, and assume Poetry as before.
537 """
538 backend = data.get("build-system", {}).get("build-backend")
539 return not backend or "poetry" in str(backend)
542# ----
545class Pyproject(wrapt.ObjectProxy):
546 """Class for syncing pyproject file with other metadata files."""
548 __wrapped__: Pep621 | Poetry
550 def __init__(self, path: Path, pass_validation: bool | None = False):
551 """Pyproject wrapper class. Wraps either PEP 621 `[project]` or Poetry metadata.
553 The handler is picked based on the metadata tables present in the file,
554 not on the configured build backend.
556 Args:
557 path (Path): Path to pyproject.toml file.
558 pass_validation (bool, optional): Whether to pass validation. Defaults to False.
560 Raises:
561 FileNotFoundError: Raised when pyproject.toml file is not found.
562 ValueError: Neither project nor tool.poetry object is found in pyproject.toml file.
564 """
565 data = None
566 if not path.is_file():
567 raise FileNotFoundError(f"pyproject file {path} not found")
569 with open(path, "r", encoding="utf-8") as f:
570 data = load(f)
572 # inspect file to pick suitable project metadata writer
573 is_poetry = "tool" in data and "poetry" in data["tool"]
574 has_project = "project" in data
576 if is_poetry and has_project and not _builds_with_poetry(data):
577 # another backend builds the project, so it reads the metadata from
578 # [project] and what remains in [tool.poetry] is only configuration
579 logger.log(
580 VERBOSE,
581 "Ignoring the tool.poetry section, the project is not built with Poetry",
582 )
583 is_poetry = False
585 if is_poetry:
586 if has_project:
587 logger.log(
588 VERBOSE,
589 "Found Poetry 2.x metadata with project section in pyproject.toml",
590 )
591 else:
592 logger.log(VERBOSE, "Found Poetry 1.x metadata in pyproject.toml")
593 self.__wrapped__ = Poetry(
594 path, pass_validation=pass_validation, version=2 if has_project else 1
595 )
596 elif has_project and not is_poetry:
597 # brackets are escaped, the log handler renders rich markup
598 logger.log(VERBOSE, "Found PEP 621 \\[project] metadata in pyproject.toml")
599 self.__wrapped__ = Pep621(path, pass_validation=pass_validation)
600 else:
601 msg = (
602 "The pyproject.toml file is ambiguous. Ensure it has either a PEP 621 "
603 "[project] section (uv, hatchling, flit, PDM, setuptools, Poetry 2.x) "
604 "or a [tool.poetry] section (Poetry 1.x)."
605 )
606 raise ValueError(msg)
608 super().__init__(self.__wrapped__)