"""The packages rpm has on a dnf or yum host: the query and its parse.""" from __future__ import annotations from typing import NotRequired from napalm_device_types.models import PackageDict #: One line per package, the version as ``[epoch:]version-release`` the way dpkg #: writes it: the epoch only where the package has one. Oracle's and Red Hat's #: fixes name it (``1:6.2.0-13.el9``), and without it an epoch-1 fix reads as newer #: than every installed build (NetOrk/netork#2394). The source rpm before the #: summary, which stays last and keeps whatever it contains. RPM_QUERY_COMMAND = ( "rpm -qa --queryformat " "'%{NAME}\\t%|EPOCH?{%{EPOCH}:}:{}|%{VERSION}-%{RELEASE}\\t%{SIZE}\\t%{SOURCERPM}" "\\t%{SUMMARY}\\n'" " 2>/dev/null" ) class RpmPackageDict(PackageDict): """An rpm package with the name of the source rpm it was built from. ``perf``, ``python3-perf`` and ``bpftool`` come from ``kernel``, and Red Hat lists them in every kernel CVE; their source is what tells them apart from user space (NetOrk/netork#2394). Deliberately not dpkg's ``source_package``: netOrk reads that as the name a distribution files its verdicts under, which holds for Debian and not for Oracle or Red Hat, whose records name the binary. Absent where rpm names none (``gpg-pubkey``). """ source_rpm: NotRequired[str] def source_rpm_name(sourcerpm: str) -> str | None: """``kernel-5.14.0-687.66.1.el9_8.src.rpm`` → ``kernel``; ``None`` for ``(none)``.""" stem = sourcerpm.strip() for suffix in (".src.rpm", ".nosrc.rpm"): if stem.endswith(suffix): stem = stem.removesuffix(suffix) break else: return None name, *version_release = stem.rsplit("-", 2) return name if len(version_release) == 2 and name else None def parse_rpm_query(out: str, source: str) -> list[PackageDict]: """The packages in ``RPM_QUERY_COMMAND``'s output, each marked as *source*'s.""" packages: list[PackageDict] = [] for line in out.splitlines(): parts = line.split("\t", 4) if len(parts) < 2: continue size = parts[2].strip() if len(parts) > 2 else "" package: RpmPackageDict = { "name": parts[0].strip(), "version": parts[1].strip(), "installed": True, "description": parts[4].strip() if len(parts) > 4 else "", "size": int(size) if size.isdigit() else 0, "source": source, } built_from = source_rpm_name(parts[3]) if len(parts) > 3 else None if built_from: package["source_rpm"] = built_from packages.append(package) return packages