Andrew Geissler | 5199d83 | 2021-09-24 16:47:35 -0500 | [diff] [blame] | 1 | # |
Patrick Williams | 92b42cb | 2022-09-03 06:53:57 -0500 | [diff] [blame] | 2 | # Copyright OpenEmbedded Contributors |
| 3 | # |
Andrew Geissler | 5199d83 | 2021-09-24 16:47:35 -0500 | [diff] [blame] | 4 | # SPDX-License-Identifier: GPL-2.0-only |
| 5 | # |
| 6 | |
| 7 | import collections |
| 8 | |
| 9 | DepRecipe = collections.namedtuple("DepRecipe", ("doc", "doc_sha1", "recipe")) |
| 10 | DepSource = collections.namedtuple("DepSource", ("doc", "doc_sha1", "recipe", "file")) |
| 11 | |
| 12 | |
| 13 | def get_recipe_spdxid(d): |
| 14 | return "SPDXRef-%s-%s" % ("Recipe", d.getVar("PN")) |
| 15 | |
| 16 | |
| 17 | def get_package_spdxid(pkg): |
| 18 | return "SPDXRef-Package-%s" % pkg |
| 19 | |
| 20 | |
| 21 | def get_source_file_spdxid(d, idx): |
| 22 | return "SPDXRef-SourceFile-%s-%d" % (d.getVar("PN"), idx) |
| 23 | |
| 24 | |
| 25 | def get_packaged_file_spdxid(pkg, idx): |
| 26 | return "SPDXRef-PackagedFile-%s-%d" % (pkg, idx) |
| 27 | |
| 28 | |
| 29 | def get_image_spdxid(img): |
| 30 | return "SPDXRef-Image-%s" % img |
| 31 | |
| 32 | |
Andrew Geissler | 7e0e3c0 | 2022-02-25 20:34:39 +0000 | [diff] [blame] | 33 | def get_sdk_spdxid(sdk): |
| 34 | return "SPDXRef-SDK-%s" % sdk |
| 35 | |
| 36 | |
Andrew Geissler | 615f2f1 | 2022-07-15 14:00:58 -0500 | [diff] [blame] | 37 | def write_doc(d, spdx_doc, subdir, spdx_deploy=None, indent=None): |
Andrew Geissler | 5199d83 | 2021-09-24 16:47:35 -0500 | [diff] [blame] | 38 | from pathlib import Path |
| 39 | |
| 40 | if spdx_deploy is None: |
| 41 | spdx_deploy = Path(d.getVar("SPDXDEPLOY")) |
| 42 | |
| 43 | dest = spdx_deploy / subdir / (spdx_doc.name + ".spdx.json") |
| 44 | dest.parent.mkdir(exist_ok=True, parents=True) |
| 45 | with dest.open("wb") as f: |
Andrew Geissler | 615f2f1 | 2022-07-15 14:00:58 -0500 | [diff] [blame] | 46 | doc_sha1 = spdx_doc.to_json(f, sort_keys=True, indent=indent) |
Andrew Geissler | 5199d83 | 2021-09-24 16:47:35 -0500 | [diff] [blame] | 47 | |
| 48 | l = spdx_deploy / "by-namespace" / spdx_doc.documentNamespace.replace("/", "_") |
| 49 | l.parent.mkdir(exist_ok=True, parents=True) |
| 50 | l.symlink_to(os.path.relpath(dest, l.parent)) |
| 51 | |
| 52 | return doc_sha1 |
| 53 | |
| 54 | |
| 55 | def read_doc(fn): |
| 56 | import hashlib |
| 57 | import oe.spdx |
| 58 | import io |
| 59 | import contextlib |
| 60 | |
| 61 | @contextlib.contextmanager |
| 62 | def get_file(): |
| 63 | if isinstance(fn, io.IOBase): |
| 64 | yield fn |
| 65 | else: |
| 66 | with fn.open("rb") as f: |
| 67 | yield f |
| 68 | |
| 69 | with get_file() as f: |
| 70 | sha1 = hashlib.sha1() |
| 71 | while True: |
| 72 | chunk = f.read(4096) |
| 73 | if not chunk: |
| 74 | break |
| 75 | sha1.update(chunk) |
| 76 | |
| 77 | f.seek(0) |
| 78 | doc = oe.spdx.SPDXDocument.from_json(f) |
| 79 | |
| 80 | return (doc, sha1.hexdigest()) |