Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions cyclonedx_py/_internal/utils/poetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

if TYPE_CHECKING:
from cyclonedx.model.component import ComponentType
from cyclonedx.model.license import License


def poetry2extrefs(poetry: dict[str, Any]) -> Generator['ExternalReference', None, None]:
Expand All @@ -62,6 +63,17 @@ def poetry2extrefs(poetry: dict[str, Any]) -> Generator['ExternalReference', Non
pass


def poetry2licenses(poetry: dict[str, Any], lfac: 'LicenseFactory') -> Generator['License', None, None]:
lack = LicenseAcknowledgement.DECLARED
if 'classifiers' in poetry:
yield from classifiers2licenses(poetry['classifiers'], lfac, lack)
if 'license' in poetry:
# per spec(https://python-poetry.org/docs/pyproject#license):
# the `license` is intended to be the name of a license, not the license text itself.
yield lfac.make_from_string(poetry['license'],
license_acknowledgement=lack)


def poetry2component(poetry: dict[str, Any], *, ctype: 'ComponentType') -> 'Component':
component = Component(
type=ctype,
Expand All @@ -72,15 +84,7 @@ def poetry2component(poetry: dict[str, Any], *, ctype: 'ComponentType') -> 'Comp
# TODO add more properties according to spec
)
# region licenses
lfac = LicenseFactory()
lack = LicenseAcknowledgement.DECLARED
if 'classifiers' in poetry:
component.licenses.update(classifiers2licenses(poetry['classifiers'], lfac, lack))
if 'license' in poetry:
# per spec(https://python-poetry.org/docs/pyproject#license):
# the `license` is intended to be the name of a license, not the license text itself.
component.licenses.add(lfac.make_from_string(poetry['license'],
license_acknowledgement=lack))
component.licenses.update(poetry2licenses(poetry, LicenseFactory()))
licenses_fixup(component)
# endregion licenses
return component
Expand All @@ -97,7 +101,9 @@ def poetry2dependencies(poetry: dict[str, Any]) -> Generator['Requirement', None
)
):
req = Requirement(name)
if isinstance(spec, dict) and 'extras' in spec:
req.extras = set(spec['extras'])
specs = spec if isinstance(spec, list) else (spec,)
req.extras = set(chain.from_iterable(
s.get('extras', ()) for s in specs if isinstance(s, dict)
))
# add other optional properties as soon as they were needed
yield req
50 changes: 38 additions & 12 deletions cyclonedx_py/_internal/utils/pyproject.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
project2licenses as pep621_project2licenses,
)
from .pep639 import project2licenses as pep639_project2licenses
from .poetry import poetry2component, poetry2dependencies
from .poetry import poetry2component, poetry2dependencies, poetry2extrefs, poetry2licenses
from .toml import toml_loads

if TYPE_CHECKING: # pragma: no cover
Expand All @@ -41,29 +41,57 @@
from packaging.requirements import Requirement


def _merge_poetry_into_component(component: 'Component',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wrong scope.
tis is poetry-specific, so it belongs into the poetry implementation.

project: dict[str, Any],
poetry: dict[str, Any],
lfac: 'LicenseFactory',
has_pep639_licenses: bool) -> None:
if component.version is None:
component.version = poetry.get('version')
if component.description is None:
component.description = poetry.get('description')

existing_extrefs = {(er.type, er.url) for er in component.external_references}
for er in poetry2extrefs(poetry):
if (er.type, er.url) not in existing_extrefs:
component.external_references.add(er)
existing_extrefs.add((er.type, er.url))

if not has_pep639_licenses:
fallback_keys = ('license', 'classifiers')
poetry_fallback = {k: poetry[k] for k in fallback_keys if k not in project and k in poetry}
component.licenses.update(poetry2licenses(poetry_fallback, lfac))


def pyproject2component(data: dict[str, Any], *,
ctype: 'ComponentType',
fpath: str,
gather_license_texts: bool,
logger: 'Logger'
) -> 'Component':
tool = data.get('tool', {})
if poetry := tool.get('poetry'):
return poetry2component(poetry, ctype=ctype)
if project := data.get('project'):
project: dict[str, Any] = data.get('project', {})
poetry: dict[str, Any] = data.get('tool', {}).get('poetry', {})
if project:
if 'name' not in project and 'name' in poetry:
project = {**project, 'name': poetry['name']}
component = pep621_project2component(project, ctype=ctype)
# region licenses
lfac = LicenseFactory()
component.licenses.update(pep639_project2licenses(project, lfac, gather_license_texts,
fpath=fpath, logger=logger))
if len(component.licenses) == 0:
has_pep639_licenses = len(component.licenses) > 0
if not has_pep639_licenses:
# According to PEP 639 spec, if licenses are declared in the "new" style,
# all other license declarations MUST be ignored.
# https://peps.python.org/pep-0639/#converting-legacy-metadata
component.licenses.update(pep621_project2licenses(project, lfac, gather_license_texts, fpath=fpath))
if poetry:
_merge_poetry_into_component(component, project, poetry, lfac, has_pep639_licenses)
licenses_fixup(component)
# endregion licenses
return component
if poetry:
return poetry2component(poetry, ctype=ctype)
raise ValueError('Unable to build component from pyproject: pyproject.toml is not PEP 621-compliant')


Expand All @@ -90,9 +118,7 @@ def pyproject_file2component(pyproject_file: str, *,


def pyproject2dependencies(data: dict[str, Any]) -> Iterator['Requirement']:
tool = data.get('tool', {})
if 'poetry' in tool:
return poetry2dependencies(tool['poetry'])
if 'project' in data:
return pep621_project2dependencies(data['project'])
return iter(())
if project := data.get('project'):
yield from pep621_project2dependencies(project)
if poetry := data.get('tool', {}).get('poetry'):
yield from poetry2dependencies(poetry)
40 changes: 40 additions & 0 deletions tests/integration/test_cli_requirements.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
import random
from collections.abc import Generator
from glob import glob
from json import loads as json_loads
from os.path import basename, join, splitext
from tempfile import TemporaryDirectory
from typing import Any
from unittest import TestCase

Expand Down Expand Up @@ -134,6 +136,44 @@ def test_with_index_auth(self, infile: str, sv: SchemaVersion, of: OutputFormat)
self.assertEqual(0, res, err)
self.assertEqualSnapshot(out, 'index_auth', infile, sv, of)

def test_with_hybrid_poetry_v2_pyproject(self) -> None:
pyproject_toml = """\
[project]
name = "hybrid-poetry-v2-app"
dynamic = ["version"]
description = "Hybrid Poetry v2 manifest"
license = "Apache-2.0"

[tool.poetry]
version = "1.4.0"
repository = "https://github.com/example/hybrid-poetry-v2-app"

[tool.poetry.group.dev.dependencies]
ddt = "^1.7.2"
"""
with TemporaryDirectory() as tmpdir:
pyp = join(tmpdir, 'pyproject.toml')
req = join(tmpdir, 'requirements.txt')
with open(pyp, 'w', encoding='utf8') as f:
f.write(pyproject_toml)
with open(req, 'w', encoding='utf8') as f:
f.write('toml==0.10.2\n')
res, out, err = run_cli(
'requirements',
'-vvv',
'--sv', '1.6',
'--of', OutputFormat.JSON.name,
'--output-reproducible',
'--pyproject', pyp,
'-o=-',
req)
self.assertEqual(0, res, err)
bom = json_loads(out)
root = bom['metadata']['component']
self.assertEqual('hybrid-poetry-v2-app', root['name'])
self.assertEqual('1.4.0', root['version'])
self.assertEqual([{'license': {'acknowledgement': 'declared', 'id': 'Apache-2.0'}}], root['licenses'])

def assertEqualSnapshot(self, actual: str, # noqa:N802
purpose: str,
reqfile: str,
Expand Down
Loading