Skip to content

Commit 74f4153

Browse files
committed
Implemented writing SBOM to a file.
1 parent 0a5903c commit 74f4153

File tree

3 files changed

+16
-9
lines changed

3 files changed

+16
-9
lines changed

cyclonedx/output/__init__.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
# SPDX-License-Identifier: Apache-2.0
1616

1717
import importlib
18+
import os
1819
from abc import ABC, abstractmethod
1920
from enum import Enum
2021

@@ -52,9 +53,21 @@ def set_bom(self, bom: Bom):
5253
def output_as_string(self) -> str:
5354
pass
5455

55-
@abstractmethod
56-
def output_to_file(self, filename: str):
57-
pass
56+
def output_to_file(self, filename: str, allow_overwrite: bool = False):
57+
# Check directory writable
58+
output_filename = os.path.realpath(filename)
59+
output_directory = os.path.dirname(output_filename)
60+
61+
if not os.access(output_directory, os.W_OK):
62+
raise PermissionError
63+
64+
if os.path.exists(output_filename) and not allow_overwrite:
65+
raise FileExistsError
66+
67+
with open(output_filename, mode='w') as f_out:
68+
f_out.write(self.output_as_string())
69+
70+
f_out.close()
5871

5972

6073
def get_instance(bom: Bom = None, output_format: OutputFormat = OutputFormat.XML,

cyclonedx/output/json.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,6 @@ class Json(BaseOutput, BaseSchemaVersion):
2626
def output_as_string(self) -> str:
2727
return json.dumps(self._get_json())
2828

29-
def output_to_file(self, filename: str):
30-
raise NotImplementedError
31-
3229
def _get_json(self) -> dict:
3330
components = list(map(self._get_component_as_dict, self.get_bom().get_components()))
3431

cyclonedx/output/xml.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,6 @@ def output_as_string(self) -> str:
3939

4040
return Xml.XML_VERSION_DECLARATION + ElementTree.tostring(bom, 'unicode')
4141

42-
def output_to_file(self, filename: str):
43-
raise NotImplementedError
44-
4542
def _component_supports_bom_ref_attribute(self) -> bool:
4643
return True
4744

0 commit comments

Comments
 (0)