sbom.py

clew/wiki/sbom.py

The SBOM page: the repository's own SBOM rendered, beside its files' licences (#70, P5.8).

read_sbom

tuple[tuple[str, str], list[Component]] clew.wiki.sbom.read_sbom(Path path)

Read one SBOM file, SPDX 2.3 or CycloneDX JSON, by its content.

clew/wiki/sbom.py:49

Source · 16 lines
def read_sbom(path: Path) -> tuple[tuple[str, str], list[Component]]:
    """FORMAT BY CONTENT, not by file name: `spdxVersion` is SPDX, `bomFormat: CycloneDX` is
    CycloneDX; anything else raises ValueError naming the file, so a wrong file is a build fault
    the page reports, never a silently empty table.

    @brief Read an SBOM.
    @return Package and components.
    """
    doc = json.loads(Path(path).read_text(encoding="utf-8"))
    if str(doc.get("spdxVersion", "")).startswith("SPDX-"):
        return _spdx(doc)
    if doc.get("bomFormat") == "CycloneDX":
        return _cyclonedx(doc)
    raise ValueError(f"{path} is neither SPDX JSON nor CycloneDX JSON")

Activity · 6 steps
lines 57–57doc = json.loads(Path(path).read_text(encoding="utf-8"))lines 58–58◇ if str(doc.get("spdxVersion", "")).startswith("SPDX-")lines 59–59return _spdx(doc)lines 60–60◇ if doc.get("bomFormat") == "CycloneDX"lines 61–61return _cyclonedx(doc)lines 62–62raise ValueError(f"{path} is neither SPDX JSON nor CycloneDX JSON")

Requirements

REQ-DDB-WIKI-051

sbom_html

str clew.wiki.sbom.sbom_html(list sboms, tuple[str,...] accepted, dict file_licences, int unlicensed)

The SBOM page's HTML.

clew/wiki/sbom.py:184

Source · 25 lines
def sbom_html(sboms: list, accepted: tuple[str, ...], file_licences: dict, unlicensed: int) -> str:
    """@brief SBOMs, then the files' licences. @return HTML."""
    parts = [_policy(accepted)]
    if not sboms:
        parts.append(
            '<p class="none">No SBOM was found: none is declared under <code>wiki.sbom.files</code> '
            "and none is at the repository root (<code>sbom.spdx.json</code>, "
            "<code>bom.cdx.json</code>). The wiki renders an SBOM; it never makes one.</p>"
        )
    for rel, (name, licence), comps in sboms:
        ## E-25: a column empty in every row is not drawn.
        cols = [c for c in _COLUMNS if any(getattr(comp, c) for comp in comps)]
        rows = "".join(_row(c, accepted, cols) for c in comps)
        heads = "".join(f"<th>{_HEADS.get(c, c)}</th>" for c in cols)
        parts.append(
            f'<section class="sbom"><h2><code>{escape(rel)}</code></h2>'
            f"<p>Package <strong>{escape(name)}</strong>, licence <code>{escape(licence)}</code>; "
            f"{len(comps)} components.</p>"
            '<div class="table-wrap"><table class="clew sbom"><thead><tr><th>component</th>'
            f"{heads}</tr></thead><tbody>{rows}</tbody></table></div></section>"
        )
    parts.append(_files(file_licences, unlicensed))
    return "".join(parts)

Activity · 10 steps
lines 186–186parts = [_policy(accepted)]lines 187–187◇ if not sbomslines 188–192parts.append( '<p class="none">No SBOM was found: none is declared under <code>wiki.sbom.files</code> ' "and none is at the repository root (<code>sbom.spdx.json</code>, " "<code>bom.cdx.json</code>). The wiki renders an SBOM; it never makes one.</p>" )lines 193–193◇ for rel, (name, licence), comps in sbomslines 195–195cols = [c for c in _COLUMNS if any(getattr(comp, c) for comp in comps)]lines 196–196rows = "".join(_row(c, accepted, cols) for c in comps)lines 197–197heads = "".join(f"<th>{_HEADS.get(c, c)}</th>" for c in cols)lines 198–204parts.append( f'<section class="sbom"><h2><code>{escape(rel)}</code></h2>' f"<p>Package <strong>{escape(name)}</strong>, licence <code>{escape(licence)}</code>; " f"{len(comps)} components.</p>" '<div class="table-wrap"><table class="clew sbom"><thead><tr><th>component</th>' f"{heads}</tr></thead><tbody>{rows}</tbody></table></div></section>" )lines 205–205parts.append(_files(file_licences, unlicensed))lines 206–206return "".join(parts)

Requirements

REQ-DDB-WIKI-051

sbom_page

str clew.wiki.sbom.sbom_page(Path repo_root, Path db, config, Path source)

Write the SBOM page from the repository's SBOMs and the index's file licences.

clew/wiki/sbom.py:300

Show on the map →

Called by _build_site

Calls _file_licences, _toml_accepted, read_sbom, sbom_html

Source · 35 lines
def sbom_page(repo_root: Path, db: Path, config, source: Path) -> str:  # noqa: ANN001
    """AN SBOM THAT WILL NOT READ IS SAID, by file and reason, not dropped: the page lists it under
    the table rather than failing the whole site.

    @brief Write sbom.md.
    @return Page name.
    """
    root = Path(repo_root)
    sboms, refused = [], []
    for path in sorted({p for g in config.sbom_files for p in root.glob(g) if p.is_file()}):
        rel = path.relative_to(root).as_posix()
        try:
            sboms.append((rel, *read_sbom(path)))
        except (OSError, ValueError) as exc:
            refused.append(f"<li><code>{escape(rel)}</code>: {escape(str(exc))}</li>")
    accepted = config.sbom_accepted or _toml_accepted(root / "docs" / "sbom.toml")
    counts, unlicensed = _file_licences(db)
    html = sbom_html(sboms, accepted, counts, unlicensed)
    if refused:
        html += f'<p class="bad">Not read:</p><ul>{"".join(refused)}</ul>'
    lines = [
        "# SBOM",
        "",
        "The software bill of materials this repository carries, rendered as it is (the wiki never "
        "writes one), and the licence each of its own files declares.",
        "",
        "```{raw} html",
        html,
        "```",
        "",
    ]
    (Path(source) / "sbom.md").write_text("\n".join(lines), encoding="utf-8")
    return "sbom"

Activity · 16 steps
lines 307–307root = Path(repo_root)lines 308–308sboms, refused = [], []lines 309–309◇ for path in sorted({p for g in config.sbom_files for p in root.glob(g) if p.is_file()})lines 310–310rel = path.relative_to(root).as_posix()lines 311–311trylines 312–312sboms.append((rel, *read_sbom(path)))lines 313–313except (OSError, ValueError) as exclines 314–314refused.append(f"<li><code>{escape(rel)}</code>: {escape(str(exc))}</li>")lines 315–315accepted = config.sbom_accepted or _toml_accepted(root / "docs" / "sbom.toml")lines 316–316counts, unlicensed = _file_licences(db)lines 317–317html = sbom_html(sboms, accepted, counts, unlicensed)lines 318–318◇ if refusedlines 319–319html += f'<p class="bad">Not read:</p><ul>{"".join(refused)}</ul>'lines 320–330lines = [ "# SBOM", "", "The software bill of materials this repository carries, rendered as it is (the wiki never " "writes one), and the licence each of its own files declares.", "", "```{raw} html", html, "```", "", ]lines 331–331(Path(source) / "sbom.md").write_text("\n".join(lines), encoding="utf-8")lines 332–332return "sbom"

Requirements

REQ-DDB-WIKI-051