Skip to content

pyproject

Pyproject module.

Pep621

Bases: PyprojectCommon

Handler for PEP 621 [project] metadata in pyproject.toml.

This covers every backend that stores its metadata in the standard [project] table, i.e. uv, hatchling, flit, PDM, setuptools and Poetry 2.x. Only Poetry 1.x needs its own handler, see somesy.pyproject.writer.Poetry.

Source code in src/somesy/pyproject/writer.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
class Pep621(PyprojectCommon):
    """Handler for PEP 621 `[project]` metadata in pyproject.toml.

    This covers every backend that stores its metadata in the standard
    `[project]` table, i.e. uv, hatchling, flit, PDM, setuptools and
    Poetry 2.x. Only Poetry 1.x needs its own handler, see [somesy.pyproject.writer.Poetry][].
    """

    def __init__(self, path: Path, pass_validation: bool | None = False):
        """PEP 621 `[project]` config file handler parsed from pyproject.toml.

        See [somesy.core.writer.ProjectMetadataWriter.__init__][].
        """
        section = ["project"]
        mappings = {
            "homepage": ["urls", "homepage"],
            "repository": ["urls", "repository"],
            "documentation": ["urls", "documentation"],
        }
        super().__init__(
            path,
            section=section,
            direct_mappings=mappings,
            model_cls=Pep621Config,
            pass_validation=pass_validation,
        )

    @staticmethod
    def _from_person(person: Person | Entity):
        """Convert project metadata person object to a PEP 621 person table."""
        return _pep621_person(person)

    @staticmethod
    def _to_person(person_obj: str | dict) -> Entity | Person | None:
        """Parse a PEP 621 person entry to a Person/Entity."""
        # NOTE: for our purposes, does not matter what are given or family names,
        # we only compare on full_name anyway.
        if isinstance(person_obj, dict):
            temp = str(person_obj["name"])
            if "email" in person_obj:
                temp = f"{temp} <{person_obj['email']}>"
            person_obj = temp

        return parse_name_email(person_obj)

    def sync(self, metadata: ProjectMetadata) -> None:
        """Sync metadata with pyproject.toml file and fix license field."""
        super().sync(metadata)

__init__

__init__(path: Path, pass_validation: bool | None = False)

PEP 621 [project] config file handler parsed from pyproject.toml.

See somesy.core.writer.ProjectMetadataWriter.init.

Source code in src/somesy/pyproject/writer.py
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def __init__(self, path: Path, pass_validation: bool | None = False):
    """PEP 621 `[project]` config file handler parsed from pyproject.toml.

    See [somesy.core.writer.ProjectMetadataWriter.__init__][].
    """
    section = ["project"]
    mappings = {
        "homepage": ["urls", "homepage"],
        "repository": ["urls", "repository"],
        "documentation": ["urls", "documentation"],
    }
    super().__init__(
        path,
        section=section,
        direct_mappings=mappings,
        model_cls=Pep621Config,
        pass_validation=pass_validation,
    )

sync

sync(metadata: ProjectMetadata) -> None

Sync metadata with pyproject.toml file and fix license field.

Source code in src/somesy/pyproject/writer.py
517
518
519
def sync(self, metadata: ProjectMetadata) -> None:
    """Sync metadata with pyproject.toml file and fix license field."""
    super().sync(metadata)

Poetry

Bases: PyprojectCommon

Poetry config file handler parsed from pyproject.toml.

Source code in src/somesy/pyproject/writer.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
class Poetry(PyprojectCommon):
    """Poetry config file handler parsed from pyproject.toml."""

    def __init__(
        self,
        path: Path,
        pass_validation: bool | None = False,
        version: int | None = 1,
    ):
        """Poetry config file handler parsed from pyproject.toml.

        See [somesy.core.writer.ProjectMetadataWriter.__init__][].
        """
        version = version or 1
        self._poetry_version = version
        v2_mappings = {
            "homepage": ["urls", "homepage"],
            "repository": ["urls", "repository"],
            "documentation": ["urls", "documentation"],
        }
        if version == 1:
            super().__init__(
                path,
                section=["tool", "poetry"],
                model_cls=PoetryConfig,
                pass_validation=pass_validation,
            )
        else:
            super().__init__(
                path,
                section=["project"],
                model_cls=PoetryConfig,
                pass_validation=pass_validation,
                direct_mappings=v2_mappings,
            )

    @staticmethod
    def _from_person(person: Person | Entity, poetry_version: int = 1):
        """Convert project metadata person object to poetry string for person format "full name <email>."""
        if poetry_version == 1:
            return person.to_name_email_string()
        else:
            return _pep621_person(person)

    @staticmethod
    def _to_person(
        person_obj: str | dict[str, str],
    ) -> Person | Entity | None:
        """Convert from free string to person or entity object."""
        if isinstance(person_obj, dict):
            temp = str(person_obj["name"])
            if "email" in person_obj:
                temp = f"{temp} <{person_obj['email']}>"
            person_obj = temp
        return parse_name_email(person_obj)

    def _person_entries(self, people: list[Person | Entity]) -> list[Any]:
        """Convert people to the person format of the Poetry version."""
        return [self._from_person(person, self._poetry_version) for person in people]

    def sync(self, metadata: ProjectMetadata) -> None:
        """Sync metadata with pyproject.toml file."""
        super().sync(metadata)

        # For Poetry v2, convert authors and maintainers from array of tables to inline tables
        if self._poetry_version == 2:
            multiline_description(self._data["project"])
            # Move urls section to the end if it exists
            if "urls" in self._data["project"]:
                urls = self._data["project"].pop("urls")
                self._data["project"]["urls"] = urls
            self._sync_legacy_metadata(metadata)

    def _sync_legacy_metadata(self, metadata: ProjectMetadata) -> None:
        """Update the deprecated metadata keys that exist in `[tool.poetry]`.

        Poetry 2.x still accepts them, so they must not go stale next to
        `[project]`. Keys that are absent are never added.
        """
        legacy = self._data.get("tool", {}).get("poetry")
        if legacy is None:
            return
        dynamic = self._dynamic_fields

        def update(key: str, value: Any, field: str | None = None) -> None:
            if not value or key not in legacy or (field or key) in dynamic:
                return
            if isinstance(value, list):
                if list(legacy[key]) != value:
                    legacy[key] = toml_array(value)
            elif legacy[key] != value:
                legacy[key] = value

        update("name", metadata.name)
        update("version", metadata.version)
        update("description", metadata.description)

        if metadata.license and not self._keeps_license(
            self._get_property(["license"])
        ):
            update("license", license_expression(metadata.license))

        update("keywords", list(metadata.keywords or []))

        for role, new in (
            ("authors", metadata.authors()),
            ("maintainers", metadata.maintainers()),
        ):
            if role not in legacy or role in dynamic:
                continue
            if role == "authors" and not new:
                continue
            people = self._sync_person_list(list(legacy[role]), new)
            update(role, [p.to_name_email_string() for p in people])
            if not people:
                del legacy[role]

        urls = {
            "homepage": metadata.homepage,
            "repository": metadata.repository,
            "documentation": metadata.documentation,
        }
        for key, url in urls.items():
            if url:
                update(key, str(url), "urls")
        if "urls" in legacy and "urls" not in dynamic:
            for old_key in legacy["urls"]:
                url = urls.get(normalize_url_key(old_key))
                if url and legacy["urls"][old_key] != str(url):
                    legacy["urls"][old_key] = str(url)

__init__

__init__(
    path: Path,
    pass_validation: bool | None = False,
    version: int | None = 1,
)

Poetry config file handler parsed from pyproject.toml.

See somesy.core.writer.ProjectMetadataWriter.init.

Source code in src/somesy/pyproject/writer.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def __init__(
    self,
    path: Path,
    pass_validation: bool | None = False,
    version: int | None = 1,
):
    """Poetry config file handler parsed from pyproject.toml.

    See [somesy.core.writer.ProjectMetadataWriter.__init__][].
    """
    version = version or 1
    self._poetry_version = version
    v2_mappings = {
        "homepage": ["urls", "homepage"],
        "repository": ["urls", "repository"],
        "documentation": ["urls", "documentation"],
    }
    if version == 1:
        super().__init__(
            path,
            section=["tool", "poetry"],
            model_cls=PoetryConfig,
            pass_validation=pass_validation,
        )
    else:
        super().__init__(
            path,
            section=["project"],
            model_cls=PoetryConfig,
            pass_validation=pass_validation,
            direct_mappings=v2_mappings,
        )

sync

sync(metadata: ProjectMetadata) -> None

Sync metadata with pyproject.toml file.

Source code in src/somesy/pyproject/writer.py
400
401
402
403
404
405
406
407
408
409
410
411
def sync(self, metadata: ProjectMetadata) -> None:
    """Sync metadata with pyproject.toml file."""
    super().sync(metadata)

    # For Poetry v2, convert authors and maintainers from array of tables to inline tables
    if self._poetry_version == 2:
        multiline_description(self._data["project"])
        # Move urls section to the end if it exists
        if "urls" in self._data["project"]:
            urls = self._data["project"].pop("urls")
            self._data["project"]["urls"] = urls
        self._sync_legacy_metadata(metadata)

Pyproject

Bases: ObjectProxy

Class for syncing pyproject file with other metadata files.

Source code in src/somesy/pyproject/writer.py
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
class Pyproject(wrapt.ObjectProxy):
    """Class for syncing pyproject file with other metadata files."""

    __wrapped__: Pep621 | Poetry

    def __init__(self, path: Path, pass_validation: bool | None = False):
        """Pyproject wrapper class. Wraps either PEP 621 `[project]` or Poetry metadata.

        The handler is picked based on the metadata tables present in the file,
        not on the configured build backend.

        Args:
            path (Path): Path to pyproject.toml file.
            pass_validation (bool, optional): Whether to pass validation. Defaults to False.

        Raises:
            FileNotFoundError: Raised when pyproject.toml file is not found.
            ValueError: Neither project nor tool.poetry object is found in pyproject.toml file.

        """
        data = None
        if not path.is_file():
            raise FileNotFoundError(f"pyproject file {path} not found")

        with open(path, "r", encoding="utf-8") as f:
            data = load(f)

        # inspect file to pick suitable project metadata writer
        is_poetry = "tool" in data and "poetry" in data["tool"]
        has_project = "project" in data

        if is_poetry and has_project and not _builds_with_poetry(data):
            # another backend builds the project, so it reads the metadata from
            # [project] and what remains in [tool.poetry] is only configuration
            logger.log(
                VERBOSE,
                "Ignoring the tool.poetry section, the project is not built with Poetry",
            )
            is_poetry = False

        if is_poetry:
            if has_project:
                logger.log(
                    VERBOSE,
                    "Found Poetry 2.x metadata with project section in pyproject.toml",
                )
            else:
                logger.log(VERBOSE, "Found Poetry 1.x metadata in pyproject.toml")
            self.__wrapped__ = Poetry(
                path, pass_validation=pass_validation, version=2 if has_project else 1
            )
        elif has_project and not is_poetry:
            # brackets are escaped, the log handler renders rich markup
            logger.log(VERBOSE, "Found PEP 621 \\[project] metadata in pyproject.toml")
            self.__wrapped__ = Pep621(path, pass_validation=pass_validation)
        else:
            msg = (
                "The pyproject.toml file is ambiguous. Ensure it has either a PEP 621 "
                "[project] section (uv, hatchling, flit, PDM, setuptools, Poetry 2.x) "
                "or a [tool.poetry] section (Poetry 1.x)."
            )
            raise ValueError(msg)

        super().__init__(self.__wrapped__)

__init__

__init__(path: Path, pass_validation: bool | None = False)

Pyproject wrapper class. Wraps either PEP 621 [project] or Poetry metadata.

The handler is picked based on the metadata tables present in the file, not on the configured build backend.

Parameters:

Name Type Description Default
path Path

Path to pyproject.toml file.

required
pass_validation bool

Whether to pass validation. Defaults to False.

False

Raises:

Type Description
FileNotFoundError

Raised when pyproject.toml file is not found.

ValueError

Neither project nor tool.poetry object is found in pyproject.toml file.

Source code in src/somesy/pyproject/writer.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
def __init__(self, path: Path, pass_validation: bool | None = False):
    """Pyproject wrapper class. Wraps either PEP 621 `[project]` or Poetry metadata.

    The handler is picked based on the metadata tables present in the file,
    not on the configured build backend.

    Args:
        path (Path): Path to pyproject.toml file.
        pass_validation (bool, optional): Whether to pass validation. Defaults to False.

    Raises:
        FileNotFoundError: Raised when pyproject.toml file is not found.
        ValueError: Neither project nor tool.poetry object is found in pyproject.toml file.

    """
    data = None
    if not path.is_file():
        raise FileNotFoundError(f"pyproject file {path} not found")

    with open(path, "r", encoding="utf-8") as f:
        data = load(f)

    # inspect file to pick suitable project metadata writer
    is_poetry = "tool" in data and "poetry" in data["tool"]
    has_project = "project" in data

    if is_poetry and has_project and not _builds_with_poetry(data):
        # another backend builds the project, so it reads the metadata from
        # [project] and what remains in [tool.poetry] is only configuration
        logger.log(
            VERBOSE,
            "Ignoring the tool.poetry section, the project is not built with Poetry",
        )
        is_poetry = False

    if is_poetry:
        if has_project:
            logger.log(
                VERBOSE,
                "Found Poetry 2.x metadata with project section in pyproject.toml",
            )
        else:
            logger.log(VERBOSE, "Found Poetry 1.x metadata in pyproject.toml")
        self.__wrapped__ = Poetry(
            path, pass_validation=pass_validation, version=2 if has_project else 1
        )
    elif has_project and not is_poetry:
        # brackets are escaped, the log handler renders rich markup
        logger.log(VERBOSE, "Found PEP 621 \\[project] metadata in pyproject.toml")
        self.__wrapped__ = Pep621(path, pass_validation=pass_validation)
    else:
        msg = (
            "The pyproject.toml file is ambiguous. Ensure it has either a PEP 621 "
            "[project] section (uv, hatchling, flit, PDM, setuptools, Poetry 2.x) "
            "or a [tool.poetry] section (Poetry 1.x)."
        )
        raise ValueError(msg)

    super().__init__(self.__wrapped__)