Skip to content

Commit 2a2b2dd

Browse files
authored
refactor(DX): rename get_instance() (#469)
- deprecate function `output.get_instance()` - add function `outout.make_outputter()` - rename function `validation.get_instance()` -> `validation.make_schemabased_validator()` - rename function `validation.schema.get_instance()` -> `validation.make_schemabased_validator()` --------- Signed-off-by: Jan Kowalleck <[email protected]>
1 parent 65e79cf commit 2a2b2dd

File tree

10 files changed

+86
-184
lines changed

10 files changed

+86
-184
lines changed

cyclonedx/output/__init__.py

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
"""
2121

2222
import os
23+
import warnings
2324
from abc import ABC, abstractmethod
2425
from typing import TYPE_CHECKING, Any, Iterable, Literal, Mapping, Optional, Type, Union, overload
2526

@@ -41,11 +42,6 @@ def __init__(self, bom: 'Bom', **kwargs: int) -> None:
4142
self._bom = bom
4243
self._generated: bool = False
4344

44-
def _chained_components(self, container: Union['Bom', 'Component']) -> Iterable['Component']:
45-
for component in container.components:
46-
yield component
47-
yield from self._chained_components(component)
48-
4945
@property
5046
@abstractmethod
5147
def schema_version(self) -> SchemaVersion:
@@ -95,40 +91,37 @@ def output_to_file(self, filename: str, allow_overwrite: bool = False, *,
9591

9692

9793
@overload
98-
def get_instance(bom: 'Bom', output_format: Literal[OutputFormat.JSON],
99-
schema_version: SchemaVersion = ...) -> 'JsonOutputter':
94+
def make_outputter(bom: 'Bom', output_format: Literal[OutputFormat.JSON],
95+
schema_version: SchemaVersion) -> 'JsonOutputter':
10096
...
10197

10298

10399
@overload
104-
def get_instance(bom: 'Bom', output_format: Literal[OutputFormat.XML] = ...,
105-
schema_version: SchemaVersion = ...) -> 'XmlOutputter':
100+
def make_outputter(bom: 'Bom', output_format: Literal[OutputFormat.XML],
101+
schema_version: SchemaVersion) -> 'XmlOutputter':
106102
...
107103

108104

109105
@overload
110-
def get_instance(bom: 'Bom', output_format: OutputFormat = ...,
111-
schema_version: SchemaVersion = ...
112-
) -> Union['XmlOutputter', 'JsonOutputter']:
106+
def make_outputter(bom: 'Bom', output_format: OutputFormat,
107+
schema_version: SchemaVersion) -> Union['XmlOutputter', 'JsonOutputter']:
113108
...
114109

115110

116-
def get_instance(bom: 'Bom', output_format: OutputFormat = OutputFormat.XML,
117-
schema_version: SchemaVersion = LATEST_SUPPORTED_SCHEMA_VERSION) -> BaseOutput:
111+
def make_outputter(bom: 'Bom', output_format: OutputFormat, schema_version: SchemaVersion) -> BaseOutput:
118112
"""
119113
Helper method to quickly get the correct output class/formatter.
120114
121115
Pass in your BOM and optionally an output format and schema version (defaults to XML and latest schema version).
122116
123117
124-
Raises error when no instance could be built.
118+
Raises error when no instance could be made.
125119
126120
:param bom: Bom
127121
:param output_format: OutputFormat
128122
:param schema_version: SchemaVersion
129123
:return: BaseOutput
130124
"""
131-
# all exceptions are undocumented, as they are pure functional, and should be prevented by correct typing...
132125
if TYPE_CHECKING: # pragma: no cover
133126
BY_SCHEMA_VERSION: Mapping[SchemaVersion, Type[BaseOutput]]
134127
if OutputFormat.JSON is output_format:
@@ -142,3 +135,13 @@ def get_instance(bom: 'Bom', output_format: OutputFormat = OutputFormat.XML,
142135
if klass is None:
143136
raise ValueError(f'Unknown {output_format.name}/schema_version: {schema_version!r}')
144137
return klass(bom)
138+
139+
140+
def get_instance(bom: 'Bom', output_format: OutputFormat = OutputFormat.XML,
141+
schema_version: SchemaVersion = LATEST_SUPPORTED_SCHEMA_VERSION) -> BaseOutput:
142+
"""DEPRECATED. use :func:`make_outputter` instead!"""
143+
warnings.warn(
144+
'function `get_instance()` is deprecated, use `make_outputter()` instead.',
145+
DeprecationWarning
146+
)
147+
return make_outputter(bom, output_format, schema_version)

cyclonedx/validation/__init__.py

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,14 @@
1515

1616

1717
from abc import ABC, abstractmethod
18-
from typing import TYPE_CHECKING, Any, Optional, Protocol
18+
from typing import TYPE_CHECKING, Any, Literal, Optional, Protocol, Union, overload
1919

2020
from ..schema import OutputFormat
2121

2222
if TYPE_CHECKING: # pragma: no cover
2323
from ..schema import SchemaVersion
24+
from .json import JsonValidator
25+
from .xml import XmlValidator
2426

2527

2628
class ValidationError:
@@ -41,8 +43,8 @@ def __str__(self) -> str:
4143
return str(self.data)
4244

4345

44-
class SchemaBasedValidator(Protocol):
45-
"""Schema based Validator protocol"""
46+
class SchemabasedValidator(Protocol):
47+
"""Schema-based Validator protocol"""
4648

4749
def validate_str(self, data: str) -> Optional[ValidationError]:
4850
"""Validate a string
@@ -55,8 +57,8 @@ def validate_str(self, data: str) -> Optional[ValidationError]:
5557
...
5658

5759

58-
class BaseSchemaBasedValidator(ABC, SchemaBasedValidator):
59-
"""Base Schema based Validator"""
60+
class BaseSchemabasedValidator(ABC, SchemabasedValidator):
61+
"""Base Schema-based Validator"""
6062

6163
def __init__(self, schema_version: 'SchemaVersion') -> None:
6264
self.__schema_version = schema_version
@@ -79,3 +81,39 @@ def output_format(self) -> OutputFormat:
7981
def _schema_file(self) -> Optional[str]:
8082
"""get the schema file according to schema version."""
8183
...
84+
85+
86+
@overload
87+
def make_schemabased_validator(output_format: Literal[OutputFormat.JSON], schema_version: 'SchemaVersion'
88+
) -> 'JsonValidator':
89+
...
90+
91+
92+
@overload
93+
def make_schemabased_validator(output_format: Literal[OutputFormat.XML], schema_version: 'SchemaVersion'
94+
) -> 'XmlValidator':
95+
...
96+
97+
98+
@overload
99+
def make_schemabased_validator(output_format: OutputFormat, schema_version: 'SchemaVersion'
100+
) -> Union['JsonValidator', 'XmlValidator']:
101+
...
102+
103+
104+
def make_schemabased_validator(output_format: OutputFormat, schema_version: 'SchemaVersion'
105+
) -> 'BaseSchemabasedValidator':
106+
"""get the default Schema-based Validator for a certain :class:``OutputFormat``.
107+
108+
Raises error when no instance could be made.
109+
"""
110+
if TYPE_CHECKING: # pragma: no cover
111+
from typing import Type
112+
Validator: Type[BaseSchemabasedValidator]
113+
if OutputFormat.JSON is output_format:
114+
from .json import JsonValidator as Validator
115+
elif OutputFormat.XML is output_format:
116+
from .xml import XmlValidator as Validator
117+
else:
118+
raise ValueError(f'Unexpected output_format: {output_format!r}')
119+
return Validator(schema_version)

cyclonedx/validation/json.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727

2828
from ..exception import MissingOptionalDependencyException
2929
from ..schema._res import BOM_JSON as _S_BOM, BOM_JSON_STRICT as _S_BOM_STRICT, JSF as _S_JSF, SPDX_JSON as _S_SPDX
30-
from . import BaseSchemaBasedValidator, SchemaBasedValidator, ValidationError
30+
from . import BaseSchemabasedValidator, SchemabasedValidator, ValidationError
3131

3232
_missing_deps_error: Optional[Tuple[MissingOptionalDependencyException, ImportError]] = None
3333
try:
@@ -45,7 +45,7 @@
4545
), err
4646

4747

48-
class _BaseJsonValidator(BaseSchemaBasedValidator, ABC):
48+
class _BaseJsonValidator(BaseSchemabasedValidator, ABC):
4949
@property
5050
def output_format(self) -> Literal[OutputFormat.JSON]:
5151
return OutputFormat.JSON
@@ -98,15 +98,15 @@ def __make_validator_registry() -> Registry[Any]:
9898
])
9999

100100

101-
class JsonValidator(_BaseJsonValidator, BaseSchemaBasedValidator, SchemaBasedValidator):
101+
class JsonValidator(_BaseJsonValidator, BaseSchemabasedValidator, SchemabasedValidator):
102102
"""Validator for CycloneDX documents in JSON format."""
103103

104104
@property
105105
def _schema_file(self) -> Optional[str]:
106106
return _S_BOM.get(self.schema_version)
107107

108108

109-
class JsonStrictValidator(_BaseJsonValidator, BaseSchemaBasedValidator, SchemaBasedValidator):
109+
class JsonStrictValidator(_BaseJsonValidator, BaseSchemabasedValidator, SchemabasedValidator):
110110
"""Strict validator for CycloneDX documents in JSON format.
111111
112112
In contrast to :class:`~JsonValidator`,

cyclonedx/validation/schema.py

Lines changed: 0 additions & 61 deletions
This file was deleted.

cyclonedx/validation/xml.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from ..exception import MissingOptionalDependencyException
2323
from ..schema import OutputFormat
2424
from ..schema._res import BOM_XML as _S_BOM
25-
from . import BaseSchemaBasedValidator, SchemaBasedValidator, ValidationError
25+
from . import BaseSchemabasedValidator, SchemabasedValidator, ValidationError
2626

2727
if TYPE_CHECKING: # pragma: no cover
2828
from ..schema import SchemaVersion
@@ -37,7 +37,7 @@
3737
), err
3838

3939

40-
class _BaseXmlValidator(BaseSchemaBasedValidator, ABC):
40+
class _BaseXmlValidator(BaseSchemabasedValidator, ABC):
4141

4242
@property
4343
def output_format(self) -> Literal[OutputFormat.XML]:
@@ -86,7 +86,7 @@ def _validator(self) -> 'XMLSchema':
8686
return self.__validator
8787

8888

89-
class XmlValidator(_BaseXmlValidator, BaseSchemaBasedValidator, SchemaBasedValidator):
89+
class XmlValidator(_BaseXmlValidator, BaseSchemabasedValidator, SchemabasedValidator):
9090
"""Validator for CycloneDX documents in XML format."""
9191

9292
@property

examples/complex.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@
2424
from cyclonedx.model import OrganizationalEntity, XsUri
2525
from cyclonedx.model.bom import Bom
2626
from cyclonedx.model.component import Component, ComponentType
27-
from cyclonedx.output import get_instance as get_outputter
27+
from cyclonedx.output import make_outputter, LATEST_SUPPORTED_SCHEMA_VERSION
2828
from cyclonedx.output.json import JsonV1Dot4
2929
from cyclonedx.schema import SchemaVersion, OutputFormat
3030
from cyclonedx.validation.json import JsonStrictValidator
31-
from cyclonedx.validation.schema import get_instance as get_validator
31+
from cyclonedx.validation import make_schemabased_validator
3232

3333
from typing import TYPE_CHECKING
3434

@@ -99,10 +99,11 @@
9999
# region XML
100100
"""demo with implicit instructions for SchemaVersion, outputter and validator. TypeCheckers will catch errors."""
101101

102-
my_xml_outputter: 'XmlOutputter' = get_outputter(bom, OutputFormat.XML)
102+
my_xml_outputter: 'XmlOutputter' = make_outputter(bom, OutputFormat.XML, LATEST_SUPPORTED_SCHEMA_VERSION)
103103
serialized_xml = my_xml_outputter.output_as_string(indent=2)
104104
print(serialized_xml)
105-
my_xml_validator: 'XmlValidator' = get_validator(my_xml_outputter.output_format, my_xml_outputter.schema_version)
105+
my_xml_validator: 'XmlValidator' = make_schemabased_validator(
106+
my_xml_outputter.output_format, my_xml_outputter.schema_version)
106107
try:
107108
validation_errors = my_xml_validator.validate_str(serialized_xml)
108109
if validation_errors:

tests/test_e2e_environment.py

Lines changed: 0 additions & 79 deletions
This file was deleted.

0 commit comments

Comments
 (0)