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