Repository navigation
Expand file tree
/
Copy path_spdx.py
More file actions
76 lines (62 loc) · 2.59 KB
/
Copy path_spdx.py
File metadata and controls
76 lines (62 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""The spdx subcommand: render a CycloneDX SBOM as SPDX 2.3."""
from __future__ import annotations
__lazy_modules__ = [
"python_sbom",
"python_sbom._formats._json",
"python_sbom._formats._spdx",
"python_sbom._validate._limits",
]
from typing import TYPE_CHECKING, Protocol
from python_sbom import SbomError
from python_sbom._formats._json import ( # simplint: ignore[private-import-path] # avoid root export
dumps,
is_document,
load_json,
)
from python_sbom._formats._spdx import render_spdx # simplint: ignore[private-import-path] # avoid root export
from python_sbom._validate._limits import ( # simplint: ignore[private-import-path] # avoid root export
MAX_COMPONENTS,
byte_limit,
)
if TYPE_CHECKING:
from pathlib import Path
from python_sbom._model._types import Document # simplint: ignore[private-import-path] # avoid root export
class _Options(Protocol):
source: Path
target: Path
def run(options: _Options) -> bool:
document = _read(options.source)
try:
rendered = dumps(render_spdx(document))
# ValueError: a timestamp fromisoformat rejects; AttributeError: a tools value that is neither an array nor an
# object; RecursionError: nesting json.dumps, a few frames deeper than json.loads, gives up on
except (AttributeError, KeyError, TypeError, ValueError, RecursionError) as error:
# the CLI renders without the schema check, which needs the validate extra
msg = f"{options.source} is not a CycloneDX document python-sbom can render: {error!r}"
raise SbomError(msg) from error
# bytes, so the line endings are the same on every operating system
options.target.write_bytes(rendered)
return True
def _read(source: Path) -> Document:
# the size validate accepts at its default component cap, so the parser never holds more than validate lets it
limit = byte_limit(MAX_COMPONENTS)
try:
with source.open("rb") as handle:
raw = handle.read(limit + 1)
except OSError as error:
raise SbomError(str(error)) from error
if len(raw) > limit:
msg = f"{source} is over {limit} bytes, the size limit of an SBOM python-sbom reads"
raise SbomError(msg)
try:
loaded = load_json(raw)
except SbomError as error:
msg = f"{source} {error}"
raise SbomError(msg) from error
if not is_document(loaded):
msg = f"{source} is not a CycloneDX document python-sbom can render"
raise SbomError(msg)
return loaded
__all__ = [
"run", # simplint: ignore[unused-export] # the parser names it for pkgutil.resolve_name
]