|
| 1 | +import json |
| 2 | +import csv |
| 3 | +import sys |
| 4 | +# from pathlib import Path |
| 5 | +from tabulate import tabulate |
| 6 | + |
| 7 | +input_file = sys.argv[1] if len(sys.argv) > 1 else "sbom.json" |
| 8 | +output_file = sys.argv[2] if len(sys.argv) > 2 else "sbom.csv" |
| 9 | + |
| 10 | +with open(input_file, "r", encoding="utf-8") as f: |
| 11 | + sbom = json.load(f) |
| 12 | + |
| 13 | +packages = sbom.get("packages", []) |
| 14 | + |
| 15 | +columns = [ |
| 16 | + "name", |
| 17 | + "versionInfo", |
| 18 | + "type", |
| 19 | + "supplier", |
| 20 | + "downloadLocation", |
| 21 | + "licenseConcluded", |
| 22 | + "licenseDeclared", |
| 23 | + "externalRefs" |
| 24 | +] |
| 25 | + |
| 26 | + |
| 27 | +def get_type(pkg): |
| 28 | + spdxid = pkg.get("SPDXID", "") |
| 29 | + if "-" in spdxid: |
| 30 | + parts = spdxid.split("-") |
| 31 | + if len(parts) > 2: |
| 32 | + return parts[2] |
| 33 | + refs = pkg.get("externalRefs", []) |
| 34 | + for ref in refs: |
| 35 | + if ref.get("referenceType") == "purl": |
| 36 | + return ref.get("referenceLocator", "").split("/")[0] |
| 37 | + return "" |
| 38 | + |
| 39 | + |
| 40 | +def get_external_refs(pkg): |
| 41 | + refs = pkg.get("externalRefs", []) |
| 42 | + return ";".join([ref.get("referenceLocator", "") for ref in refs]) |
| 43 | + |
| 44 | + |
| 45 | +with open(output_file, "w", newline="", encoding="utf-8") as csvfile: |
| 46 | + writer = csv.DictWriter(csvfile, fieldnames=columns) |
| 47 | + writer.writeheader() |
| 48 | + for pkg in packages: |
| 49 | + row = { |
| 50 | + "name": pkg.get("name", ""), |
| 51 | + "versionInfo": pkg.get("versionInfo", ""), |
| 52 | + "type": get_type(pkg), |
| 53 | + "supplier": pkg.get("supplier", ""), |
| 54 | + "downloadLocation": pkg.get("downloadLocation", ""), |
| 55 | + "licenseConcluded": pkg.get("licenseConcluded", ""), |
| 56 | + "licenseDeclared": pkg.get("licenseDeclared", ""), |
| 57 | + "externalRefs": get_external_refs(pkg) |
| 58 | + } |
| 59 | + writer.writerow(row) |
| 60 | + |
| 61 | +print(f"CSV export complete: {output_file}") |
| 62 | + |
| 63 | + |
| 64 | +with open("sbom_table.txt", "w", encoding="utf-8") as f: |
| 65 | + table = [] |
| 66 | + for pkg in packages: |
| 67 | + row = [ |
| 68 | + pkg.get("name", ""), |
| 69 | + pkg.get("versionInfo", ""), |
| 70 | + get_type(pkg), |
| 71 | + pkg.get("supplier", ""), |
| 72 | + pkg.get("downloadLocation", ""), |
| 73 | + pkg.get("licenseConcluded", ""), |
| 74 | + pkg.get("licenseDeclared", ""), |
| 75 | + get_external_refs(pkg) |
| 76 | + ] |
| 77 | + table.append(row) |
| 78 | + f.write(tabulate(table, columns, tablefmt="grid")) |
0 commit comments