Skip to content

Commit

Permalink
Determine cyclonedx major version without importlib
Browse files Browse the repository at this point in the history
  • Loading branch information
hedtke committed Aug 24, 2023
1 parent 4002763 commit 96fb5a7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
12 changes: 7 additions & 5 deletions extensions/commands/recipe/cmd_create_sbom.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from importlib.metadata import version
import os.path
import sys
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Set, Tuple, Union, Dict
Expand All @@ -12,10 +11,6 @@
from cyclonedx.model.bom import Bom


def cyclonedx_major_version_is_4() -> int:
return version('cyclonedx-python-lib')[0] == '4'


def format_text(output: Dict[str, Any]) -> None:
serialized = output['formatters'][output['sbom_format']](output['bom']).output_as_string()
cli_out_write(serialized)
Expand Down Expand Up @@ -50,6 +45,13 @@ def create_sbom(conan_api: ConanAPI, parser, *args) -> Dict[str, Any]:
def package_type_to_component_type(pt: str) -> ComponentType:
return ComponentType.APPLICATION if pt == "application" else ComponentType.LIBRARY

def cyclonedx_major_version_is_4() -> bool:
try:
LicenseChoice(license=LicenseFactory().make_from_string("MIT"))
return True
except TypeError: # argument in version 3 is named license_
return False

def licenses(ls: Optional[Union[Tuple[str, ...], Set[str], List[str], str]]) -> Optional[Iterable[LicenseChoice]]:
"""
see https://cyclonedx.org/docs/1.4/json/#components_items_licenses
Expand Down
14 changes: 9 additions & 5 deletions tests/test_create_sbom.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import importlib.metadata
import json
import xml.dom.minidom
import os
Expand All @@ -13,10 +12,6 @@
REQ_DEP = "m4"


def cyclonedx_major_version_is_4() -> int:
return importlib.metadata.version('cyclonedx-python-lib')[0] == '4'


@pytest.fixture(autouse=True)
def conan_test():
old_env = dict(os.environ)
Expand Down Expand Up @@ -48,6 +43,15 @@ def _test_generated_sbom_json(sbom, test_metadata_name, spec_version):


def _test_generated_sbom_xml(sbom, test_metadata_name, spec_version):
def cyclonedx_major_version_is_4() -> bool:
try:
from cyclonedx.factory.license import LicenseFactory
from cyclonedx.model import LicenseChoice
LicenseChoice(license=LicenseFactory().make_from_string("MIT"))
return True
except TypeError: # argument in version 3 is named license_
return False

def with_ns(key: str) -> str:
ns = "ns0:" if cyclonedx_major_version_is_4() else ""
return ns + key
Expand Down

0 comments on commit 96fb5a7

Please sign in to comment.