feat(yocto): recipes an image recipe installs are marked as in the image (declared)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 10m32s

The recipe helper now also reads the image recipes (inherit core-image/image,
or *-image*.bb / an image bbappend that declares installs), local.conf.sample
and distro configurations: IMAGE_INSTALL and CORE_IMAGE_EXTRA_INSTALL with
=, ?=, +=, :append, the old _append and :remove, and IMAGE_FEATURES /
EXTRA_IMAGE_FEATURES. Package groups in the tree are read with their
RDEPENDS/RRECOMMENDS per package, and each recipe with the packages its
PACKAGES names. Still oelint-parser, nothing executed; the recipe inventory
itself is unchanged (checked against Poky's meta: 834 identical recipes).

The agent maps the declared names to recipes (recipe name, PACKAGES,
default -dev/-dbg/... packages), expands package groups one level and maps
IMAGE_FEATURES to OE-Core's FEATURE_PACKAGES groups only where they are in
the tree. Components get SbomEntry.in_image {basis: declared, images}, an
evidence line, a CycloneDX property pruefwerk:component:in_image and the
SPDX package comment. Names not in the tree are listed on the run
(image_install, SkipCode::NotInTree); no component is invented.

The SBOM list sorts in-image components first and filters by in_image; the
dashboard shows an "Im Image (deklariert)" badge and filter whose tooltip
says it is read from the recipes, not resolved by bitbake.

The nightly fixture's image installs a package group (packagegroup-pump ->
pump-web-ui of pump-web); pump-fw stays in no image. Baseline updated; the
nine recipe-lint findings are unchanged. Drops the .pyc committed by #551.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-10-09 19:45:52 +02:00
1 parent 42b25719ec
commit e2e95e636b
24 files changed
+1416 -77

No files matched your search

+308 -25
View File
@@ -7,11 +7,17 @@ oelint-parser (BSD-2-Clause), which reads BitBake syntax and never executes the
recipes' Python or shell code.
Each recipe is parsed with its own bbappends. Layer overrides between layers,
PACKAGECONFIG, the distro and machine configuration and what an image installs
are not resolved: this is an inventory of the recipes in the tree, not the
image's SBOM.
PACKAGECONFIG, the distro and machine configuration are not resolved: this is
an inventory of the recipes in the tree, not the image's SBOM.
Output: {"recipes": [...], "errors": [{"file", "error"}]}, sorted by file.
What the image recipes, local.conf.sample and the distro configurations
declare an image installs (IMAGE_INSTALL, CORE_IMAGE_EXTRA_INSTALL,
IMAGE_FEATURES) is read as written, with the package groups' RDEPENDS and
RRECOMMENDS, so that the agent can mark the recipes an image names. Every
override's assignment counts; nothing is resolved the way BitBake would.
Output: {"recipes", "images", "packagegroups", "configs": [...],
"errors": [{"file", "error"}]}, each sorted by file.
"""
import glob
@@ -33,6 +39,15 @@ SKIPPED_DIRS = {".git", ".hg", ".svn", "build", "tmp", "sstate-cache", "download
# How much of a patch is read for its CVE: tags; the header comes first.
PATCH_HEADER_BYTES = 64 * 1024
# The variables saying what an image installs, and its features.
INSTALL_VARIABLES = ("IMAGE_INSTALL", "CORE_IMAGE_EXTRA_INSTALL")
FEATURE_VARIABLES = ("IMAGE_FEATURES", "EXTRA_IMAGE_FEATURES")
# The operations an override suffix can name (`:append`, old `_append`).
OPERATIONS = ("append", "prepend", "remove")
VERSION_CONSTRAINT = re.compile(r"\([^()]*\)")
CVE_ID = re.compile(r"CVE-\d{4}-\d{4,}")
CVE_TAG = re.compile(r"^CVE:\s*(.*)$", re.MULTILINE)
@@ -59,11 +74,23 @@ def confine(tree: str) -> None:
setattr(cls_stash, "__oe_utils_read_file_regex__", regex.compile(r"(?!)"))
def walk(tree: str) -> tuple[list[str], list[str], list[str]]:
"""The layer roots (directories with conf/layer.conf), recipes and appends."""
def is_config(root: str, name: str) -> bool:
"""Whether `name` in directory `root` is a configuration that can declare
what images install: a local.conf.sample or a distro configuration."""
if name == "local.conf.sample":
return True
return name.endswith(".conf") and os.path.basename(root) == "distro" and (
os.path.basename(os.path.dirname(root)) == "conf"
)
def walk(tree: str) -> tuple[list[str], list[str], list[str], list[str]]:
"""The layer roots (directories with conf/layer.conf), recipes, appends
and the configurations that can declare what images install."""
layers: list[str] = []
recipes: list[str] = []
appends: list[str] = []
configs: list[str] = []
for root, dirs, files in os.walk(tree):
dirs[:] = sorted(d for d in dirs if d not in SKIPPED_DIRS)
if os.path.basename(root) == "conf" and "layer.conf" in files:
@@ -76,7 +103,9 @@ def walk(tree: str) -> tuple[list[str], list[str], list[str]]:
recipes.append(path)
elif name.endswith(".bbappend"):
appends.append(path)
return sorted(layers), sorted(recipes), sorted(appends)
elif is_config(root, name):
configs.append(path)
return sorted(layers), sorted(recipes), sorted(appends), sorted(configs)
def appends_for(recipe: str, appends: list[str]) -> list[str]:
@@ -91,6 +120,22 @@ def appends_for(recipe: str, appends: list[str]) -> list[str]:
return matching
def file_stem(path: str) -> str:
"""The recipe name part of a .bb or .bbappend file name: before the
version (`busybox_1.35.0.bb`), without an append's `%` wildcard."""
name = os.path.basename(path)
for suffix in (".bbappend", ".bb"):
if name.endswith(suffix):
name = name[: -len(suffix)]
break
return name.split("_", 1)[0].replace("%", "")
def is_image_name(path: str) -> bool:
"""Whether the file is named like an image recipe (`*-image*.bb`)."""
return "-image" in file_stem(path)
def is_build_host_recipe(name: str) -> bool:
"""Whether the recipe only builds a tool for the build host or SDK."""
return name.endswith(("-native", "-cross", "-crosssdk")) or name.startswith("nativesdk-")
@@ -176,6 +221,134 @@ def flags(stash: Stash, recipe: str, name: str) -> dict[str, str]:
return found
def assignment_parts(
item: Variable, name: str, scoped: bool
) -> tuple[list[str], str | None, list[str]] | None:
"""What an assignment to `name` is: the words before its operation (a
package such as `${PN}-utils`, or an override such as `qemux86`), the
operation (`append`, `prepend`, `remove` or None) and the overrides after
it. None for an assignment of another variable.
oelint-parser splits `IMAGE_INSTALL_append` (the syntax before Kirkstone)
into the variable and `append` only in a file without any `:` override;
otherwise it keeps the whole name, which is split here. Another variable
with a longer name (`IMAGE_FEATURES_REPLACES_…`) is not an assignment of
`name`: in the old syntax only an operation may follow the name directly,
or, for a per-package variable (RDEPENDS), the package."""
if item.VarName == name:
subs = list(item.SubItems)
elif item.VarName.startswith(name + "_"):
subs = item.VarName[len(name) + 1 :].split("_") + list(item.SubItems)
if not scoped and subs[0] not in OPERATIONS:
return None
else:
return None
operation = next((s for s in subs if s in OPERATIONS), None)
if operation is None:
return subs, None, []
at = subs.index(operation)
return subs[:at], operation, subs[at + 1 :]
def without_inline_python(text: str) -> str:
"""`text` without its inline Python (`${@bb.utils.contains(...)}`): what
it would add depends on the configuration, which is not resolved."""
kept = []
at = 0
while (start := text.find("${@", at)) != -1:
kept.append(text[at:start])
depth = 0
end = start + 1
while end < len(text):
if text[end] == "{":
depth += 1
elif text[end] == "}":
depth -= 1
if depth == 0:
break
end += 1
at = end + 1
kept.append(text[at:])
return " ".join(kept)
def fold(stash: Stash, path: str, items: list[Variable], name: str, scoped: bool) -> list[str]:
"""The words `items` (assignments of `name`) give together: `=`, `?=`,
`+=` in order, then every `:append`/`:prepend` and every override's
assignment added, then `:remove` taken away. With `scoped`, the first word
before the operation is the package and the rest are overrides."""
base: list[str] | None = None
added: list[str] = []
removed: set[str] = set()
for item in sorted(items, key=lambda i: i.Line):
parts = assignment_parts(item, name, scoped)
if parts is None:
continue
before, operation, after = parts
overrides = before[1:] if scoped else before
text = without_inline_python(stash.ExpandTerm(path, raw(stash, item)))
# A version constraint (`foo (>= 1.2)`) is not a package.
found = Item.safe_linesplit(VERSION_CONSTRAINT.sub(" ", text))
if operation == "remove" and not overrides and not after:
removed.update(found)
elif operation is not None or overrides:
# An override (a machine, a distro) is not resolved: it counts.
if operation != "remove":
added.extend(found)
else:
op = item.VarOp.strip()
if op in ("=", ":="):
base = found
elif op in ("?=", "??="):
base = found if base is None else base
else:
base = (base or []) + found
words_found = [w for w in (base or []) + added if w not in removed]
return list(dict.fromkeys(words_found))
def variables(stash: Stash, path: str) -> list[Variable]:
"""Every variable assignment in `path`, its includes and appends."""
return stash.GetItemsFor(filename=path, classifier=Variable.CLASSIFIER)
def declared(stash: Stash, path: str, names: tuple[str, ...]) -> list[str]:
"""The words the variables `names` declare in `path`, in order, once."""
items = variables(stash, path)
found = [w for name in names for w in fold(stash, path, items, name, scoped=False)]
return list(dict.fromkeys(found))
def per_package(stash: Stash, path: str, names: tuple[str, ...]) -> dict[str, list[str]]:
"""The words the per-package variables `names` (RDEPENDS:${PN}-x) give
each package of `path`, keyed by the package name as expanded."""
items = variables(stash, path)
keyed: dict[str, list[Variable]] = {}
for name in names:
for item in items:
parts = assignment_parts(item, name, scoped=True)
if parts is None or not parts[0]:
continue
package = stash.ExpandTerm(path, parts[0][0]).strip()
keyed.setdefault(package, [])
if item not in keyed[package]:
keyed[package].append(item)
found: dict[str, list[str]] = {}
for package, group in sorted(keyed.items()):
words_found = [w for name in names for w in fold(stash, path, group, name, scoped=True)]
if words_found:
found[package] = list(dict.fromkeys(words_found))
return found
def image_declarations(stash: Stash, path: str) -> dict[str, list[str]]:
"""What `path` declares an image installs, and its features."""
return {
"install": declared(stash, path, INSTALL_VARIABLES),
"features": declared(stash, path, FEATURE_VARIABLES),
}
def status_entry(cve: str, value: str) -> dict[str, str]:
"""A CVE_STATUS value `reason: detail` as its parts."""
reason, _, detail = value.partition(":")
@@ -243,26 +416,94 @@ def sources(origins: list[str], tree: str, src_uri: list[str]) -> tuple[str | No
return upstream, patches
def read_recipe(recipe: str, appends: list[str], layers: list[str], tree: str) -> dict | None:
"""One recipe as JSON, or None for an image, a package group or a
build-host tool, which are not components of the product."""
stash = Stash(quiet=True, layer_paths=layers)
for path in [recipe, *appends]:
def parsed(paths: list[str], layers: list[str], negative: bool = False) -> Stash:
"""A stash of `paths` (a recipe and its appends, or a configuration).
oelint-parser emulates `bb.utils.contains` by taking its true branch, or
with `negative` its false one; it never runs the Python."""
stash = Stash(quiet=True, layer_paths=layers, negative_inline=negative)
for path in paths:
stash.AddFile(path)
stash.Finalize()
if stash.IsImage(recipe) or stash.IsPackageGroup(recipe):
return None
return stash
def static_words(found: list[str]) -> list[str]:
"""The words that are names as written, not a variable left unexpanded."""
return [w for w in found if "${" not in w and "@" not in w]
def common(positive, negative):
"""What two readings agree on: the words of a list in both (in the first
one's order), a dictionary key by key, any other value as first read."""
if isinstance(positive, list):
kept = set(negative) if isinstance(negative, list) else set()
return [w for w in positive if w in kept]
if isinstance(positive, dict):
other = negative if isinstance(negative, dict) else {}
return {key: common(value, other.get(key)) for key, value in positive.items()}
return positive
def unconditional(paths: list[str], layers: list[str], read) -> dict:
"""`read(stash)` of `paths` with what both branches of every inline
condition give: an install only when `DISTRO_FEATURES` contains `x11`
is not declared for the image as such."""
return common(read(parsed(paths, layers)), read(parsed(paths, layers, negative=True)))
def read_image(stash: Stash, recipe: str, appends: list[str], tree: str) -> dict:
"""An image recipe (or a bbappend of one not in the tree): its name and
what it declares it installs."""
return {
"file": os.path.relpath(recipe, tree),
"appends": [os.path.relpath(a, tree) for a in appends],
"pn": file_stem(recipe),
**image_declarations(stash, recipe),
}
def read_packagegroup(stash: Stash, recipe: str, tree: str) -> dict:
"""A package group: the packages it makes and what each one pulls in
(RDEPENDS, and RRECOMMENDS, which are installed unless excluded)."""
pn = stash.GuessRecipeName(recipe)
return {
"file": os.path.relpath(recipe, tree),
"pn": pn,
"packages": static_words(declared(stash, recipe, ("PACKAGES",))) or [pn],
"rdepends": per_package(stash, recipe, ("RDEPENDS", "RRECOMMENDS")),
}
def read_recipe(
recipe: str, appends: list[str], layers: list[str], tree: str
) -> tuple[str, dict] | None:
"""One recipe as JSON with its kind: `recipe` for a component of the
product, `image` or `packagegroup`; None for a build-host tool."""
paths = [recipe, *appends]
stash = parsed(paths, layers)
if stash.IsPackageGroup(recipe):
return "packagegroup", unconditional(
paths, layers, lambda s: read_packagegroup(s, recipe, tree)
)
if stash.IsImage(recipe) or is_image_name(recipe):
image = unconditional(paths, layers, lambda s: read_image(s, recipe, appends, tree))
# Named like an image (`*-image*.bb`) without inheriting an image
# class: an image only if it declares what to install
# (`xcb-util-image` is a library).
if stash.IsImage(recipe) or image["install"] or image["features"]:
return "image", image
pn = stash.GuessRecipeName(recipe)
if is_build_host_recipe(pn):
return None
pv = value(stash, recipe, "PV") or stash.GuessRecipeVersion(recipe)
origins = [recipe, *appends]
upstream, patches = sources(origins, tree, words(stash, recipe, "SRC_URI"))
return {
return "recipe", {
"file": os.path.relpath(recipe, tree),
"appends": [os.path.relpath(a, tree) for a in appends],
"pn": pn,
"bpn": stash.GuessBaseRecipeName(recipe),
"packages": static_words(declared(stash, recipe, ("PACKAGES",))),
"pv": pv,
"srcrev": value(stash, recipe, "SRCREV") or None,
"src_uri": upstream,
@@ -274,21 +515,63 @@ def read_recipe(recipe: str, appends: list[str], layers: list[str], tree: str) -
}
def orphan_image_appends(recipe_files: list[str], appends: list[str]) -> list[str]:
"""The bbappends of images whose recipe is not in the tree
(`core-image-minimal.bbappend` extending Poky's image)."""
return [
append
for append in appends
if is_image_name(append)
and not any(append in appends_for(recipe, [append]) for recipe in recipe_files)
]
def declaring_image(append: str, layers: list[str], tree: str) -> tuple[str, dict] | None:
"""The bbappend of an image not in the tree, if it declares anything."""
image = unconditional([append], layers, lambda s: read_image(s, append, [], tree))
return ("image", image) if image["install"] or image["features"] else None
def read_config(config: str, layers: list[str], tree: str) -> tuple[str, dict] | None:
"""What a local.conf.sample or distro configuration declares every image
installs; None when it declares nothing."""
declarations = unconditional([config], layers, lambda s: image_declarations(s, config))
if not declarations["install"] and not declarations["features"]:
return None
return "config", {"file": os.path.relpath(config, tree), **declarations}
def main(tree: str) -> int:
tree = os.path.realpath(tree)
confine(tree)
layers, recipe_files, appends = walk(tree)
recipes = []
layers, recipe_files, appends, configs = walk(tree)
layers = layers or [tree]
read: dict[str, list[dict]] = {"recipe": [], "image": [], "packagegroup": [], "config": []}
errors = []
for recipe in recipe_files:
def attempt(path: str, reader) -> None:
try:
read = read_recipe(recipe, appends_for(recipe, appends), layers or [tree], tree)
except Exception as error: # noqa: BLE001 - one unreadable recipe must not stop the rest
errors.append({"file": os.path.relpath(recipe, tree), "error": type(error).__name__})
continue
if read is not None:
recipes.append(read)
json.dump({"recipes": recipes, "errors": errors}, sys.stdout, sort_keys=True)
result = reader()
except Exception as error: # noqa: BLE001 - one unreadable file must not stop the rest
errors.append({"file": os.path.relpath(path, tree), "error": type(error).__name__})
return
if result is not None:
read[result[0]].append(result[1])
for recipe in recipe_files:
attempt(recipe, lambda: read_recipe(recipe, appends_for(recipe, appends), layers, tree))
for append in orphan_image_appends(recipe_files, appends):
attempt(append, lambda: declaring_image(append, layers, tree))
for config in configs:
attempt(config, lambda: read_config(config, layers, tree))
output = {
"recipes": read["recipe"],
"images": sorted(read["image"], key=lambda i: i["file"]),
"packagegroups": read["packagegroup"],
"configs": read["config"],
"errors": errors,
}
json.dump(output, sys.stdout, sort_keys=True)
return 0