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