* [PATCH 02/17] cache: Add support for BB_CACHE_EXTRAVARS
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 03/17] runqueue: Add a RecipeCheckEvent Richard Purdie
` (14 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
This allows the metadata to specify that some variables should be cached on a per
recipe basis.
This is useful for example to allow RECIPE_HOSTTOOLS in OE-Core to error up front
in a build if tools are missing rather than the build failing part way through.
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
lib/bb/cache.py | 12 +++++++++++-
1 file changed, 11 insertions(+), 1 deletion(-)
diff --git a/lib/bb/cache.py b/lib/bb/cache.py
index f09716fa719..a1d8bfbd8dd 100644
--- a/lib/bb/cache.py
+++ b/lib/bb/cache.py
@@ -27,7 +27,7 @@ import shutil
logger = logging.getLogger("BitBake.Cache")
-__cache_version__ = "156"
+__cache_version__ = "157"
def getCacheFile(path, filename, mc, data_hash):
mcspec = ''
@@ -131,6 +131,11 @@ class CoreRecipeInfo(RecipeInfoCommon):
self.fakerootnoenv = self.getvar('FAKEROOTNOENV', metadata)
self.extradepsfunc = self.getvar('calculate_extra_depends', metadata)
+ self.extravars = self.listvar('BB_CACHE_EXTRAVARS', metadata)
+ if self.extravars:
+ for var in self.extravars:
+ setattr(self, var, self.getvar(var, metadata))
+
@classmethod
def init_cacheData(cls, cachedata):
# CacheData in Core RecipeInfo Class
@@ -168,6 +173,8 @@ class CoreRecipeInfo(RecipeInfoCommon):
cachedata.fakerootlogs = {}
cachedata.extradepsfunc = {}
+ cachedata.extravars = {}
+
def add_cacheData(self, cachedata, fn):
cachedata.task_deps[fn] = self.task_deps
cachedata.pkg_fn[fn] = self.pn
@@ -237,6 +244,9 @@ class CoreRecipeInfo(RecipeInfoCommon):
cachedata.fakerootlogs[fn] = self.fakerootlogs
cachedata.extradepsfunc[fn] = self.extradepsfunc
+ cachedata.extravars[fn] = {}
+ for var in self.extravars:
+ cachedata.extravars[fn][var] = getattr(self, var)
class SiggenRecipeInfo(RecipeInfoCommon):
__slots__ = ()
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 03/17] runqueue: Add a RecipeCheckEvent
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
2026-11-30 15:28 ` [PATCH 02/17] cache: Add support for BB_CACHE_EXTRAVARS Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 04/17] providers: Drop support for changing preference level based upon layer priority Richard Purdie
` (13 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
This event triggers at the start of a build, once the task graph is known
and provides a list of the recipes which will execure alongside any custom
variable data that was requested to be cached in BB_CACHE_EXTRAVARS.
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
lib/bb/runqueue.py | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/lib/bb/runqueue.py b/lib/bb/runqueue.py
index 501fb92dc49..edb6c7d01ae 100644
--- a/lib/bb/runqueue.py
+++ b/lib/bb/runqueue.py
@@ -1608,6 +1608,8 @@ class RunQueue:
('bb.event.HeartbeatEvent',), data=self.cfgData)
self.dm_event_handler_registered = True
+ bb.event.fire(RecipeCheckEvent(self.rqdata), self.cooker.data)
+
self.rqdata.init_progress_reporter.next_stage()
self.rqexe = RunQueueExecute(self)
@@ -3316,6 +3318,15 @@ class PSIEvent(bb.event.Event):
self.pressure_state = pressure_state
self.pressure_values = pressure_values
+class RecipeCheckEvent(bb.event.Event):
+ def __init__(self, rqdata):
+ super().__init__()
+ recipedata = {}
+ for tid in rqdata.runtaskentries:
+ (mc, fn, taskname, taskfn) = split_tid_mcfn(tid)
+ recipedata[taskfn] = rqdata.dataCaches[mc].extravars[taskfn]
+ self.recipedata = recipedata
+
class runQueuePipe():
"""
Abstraction for a pipe between a worker thread and the server
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 04/17] providers: Drop support for changing preference level based upon layer priority
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
2026-11-30 15:28 ` [PATCH 02/17] cache: Add support for BB_CACHE_EXTRAVARS Richard Purdie
2026-11-30 15:28 ` [PATCH 03/17] runqueue: Add a RecipeCheckEvent Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 05/17] cooker/cache/command/tinfoil: Drop bbfile_priority Richard Purdie
` (12 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
Layer priority overriding preference levels like default preference creates
sigificant confusion. Drop that concept and simplify the code accordingly.
This prepares for bigger layer.conf changes.
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
lib/bb/providers.py | 19 +------------------
1 file changed, 1 insertion(+), 18 deletions(-)
diff --git a/lib/bb/providers.py b/lib/bb/providers.py
index 51f61b6e1d0..9654a42ce00 100644
--- a/lib/bb/providers.py
+++ b/lib/bb/providers.py
@@ -68,24 +68,7 @@ def sortPriorities(pn, dataCache, pkg_pn = None):
if not pkg_pn:
pkg_pn = dataCache.pkg_pn
- files = pkg_pn[pn]
- priorities = {}
- for f in files:
- priority = dataCache.bbfile_priority[f]
- preference = dataCache.pkg_dp[f]
- if priority not in priorities:
- priorities[priority] = {}
- if preference not in priorities[priority]:
- priorities[priority][preference] = []
- priorities[priority][preference].append(f)
- tmp_pn = []
- for pri in sorted(priorities):
- tmp_pref = []
- for pref in sorted(priorities[pri]):
- tmp_pref.extend(priorities[pri][pref])
- tmp_pn = [tmp_pref] + tmp_pn
-
- return tmp_pn
+ return [sorted(pkg_pn[pn], key=dataCache.pkg_dp.__getitem__)]
def versionVariableMatch(cfgData, keyword, pn):
"""
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 05/17] cooker/cache/command/tinfoil: Drop bbfile_priority
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (2 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 04/17] providers: Drop support for changing preference level based upon layer priority Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 06/17] cooker: Change layer.conf handling to new approach Richard Purdie
` (11 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
These are confusing and about to be removed with the layer changes. Prepare the way
for that by removing the cached priority values.
Remove the command and tinfoil APIs that access it.
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
lib/bb/cache.py | 1 -
lib/bb/command.py | 18 +-----------------
lib/bb/cooker.py | 7 -------
lib/bb/tinfoil.py | 10 ----------
4 files changed, 1 insertion(+), 35 deletions(-)
diff --git a/lib/bb/cache.py b/lib/bb/cache.py
index a1d8bfbd8dd..67c3f14ccc1 100644
--- a/lib/bb/cache.py
+++ b/lib/bb/cache.py
@@ -808,7 +808,6 @@ class CacheData(object):
# Indirect Cache variables (set elsewhere)
self.ignored_dependencies = []
self.world_target = set()
- self.bbfile_priority = {}
def add_from_recipeinfo(self, fn, info_array):
for info in info_array:
diff --git a/lib/bb/command.py b/lib/bb/command.py
index f49ebb19d8e..9848b7a6732 100644
--- a/lib/bb/command.py
+++ b/lib/bb/command.py
@@ -406,14 +406,6 @@ class CommandsSync:
return command.cooker.recipecaches[mc].inherits
getRecipeInherits.readonly = True
- def getBbFilePriority(self, command, params):
- try:
- mc = params[0]
- except IndexError:
- mc = ''
- return command.cooker.recipecaches[mc].bbfile_priority
- getBbFilePriority.readonly = True
-
def getDefaultPreference(self, command, params):
try:
mc = params[0]
@@ -437,15 +429,7 @@ class CommandsSync:
mc = params[0]
except IndexError:
mc = ''
-
- # Return list sorted by reverse priority order
- import bb.cache
- def sortkey(x):
- vfn, _ = x
- realfn, _, item_mc = bb.cache.virtualfn2realfn(vfn)
- return -command.cooker.collections[item_mc].calc_bbfile_priority(realfn)[0], vfn
-
- skipdict = OrderedDict(sorted(command.cooker.skiplist_by_mc[mc].items(), key=sortkey))
+ skipdict = OrderedDict(sorted(command.cooker.skiplist_by_mc[mc].items()))
return list(skipdict.items())
getSkippedRecipes.readonly = True
diff --git a/lib/bb/cooker.py b/lib/bb/cooker.py
index 54f87278fde..7fca4ac2f74 100644
--- a/lib/bb/cooker.py
+++ b/lib/bb/cooker.py
@@ -1421,7 +1421,6 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si
# Tweak some variables
item = info_array[0].pn
self.recipecaches[mc].ignored_dependencies = set()
- self.recipecaches[mc].bbfile_priority[fn] = 1
self.configuration.limited_deps = True
# Remove external dependencies
@@ -1702,8 +1701,6 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si
raise bb.BBHandledException()
self.show_appends_with_no_recipes()
self.handlePrefProviders()
- for mc in self.multiconfigs:
- self.recipecaches[mc].bbfile_priority = self.collections[mc].collection_priorities(self.recipecaches[mc].pkg_fn, self.parser.mcfilelist[mc], self.data)
self.state = State.RUNNING
# Send an event listing all stamps reachable after parsing
@@ -1875,10 +1872,6 @@ class CookerCollectFiles(object):
files = (config.getVar( "BBFILES") or "").split()
- # Sort files by priority
- files.sort( key=lambda fileitem: self.calc_bbfile_priority(fileitem)[0] )
- config.setVar("BBFILES_PRIORITIZED", " ".join(files))
-
if not files:
files = self.get_bbfiles()
diff --git a/lib/bb/tinfoil.py b/lib/bb/tinfoil.py
index 4fd2a9af82e..e37cf88ef37 100644
--- a/lib/bb/tinfoil.py
+++ b/lib/bb/tinfoil.py
@@ -12,7 +12,6 @@ import os
import sys
import time
import atexit
-import re
from collections import OrderedDict, defaultdict
from functools import partial, wraps
from contextlib import contextmanager
@@ -300,8 +299,6 @@ class TinfoilCookerAdapter:
attrvalue = self.tinfoil.run_command('getRecipeVersions', self.mc) or {}
elif name == 'inherits':
attrvalue = self.tinfoil.run_command('getRecipeInherits', self.mc) or {}
- elif name == 'bbfile_priority':
- attrvalue = self.tinfoil.run_command('getBbFilePriority', self.mc) or {}
elif name == 'pkg_dp':
attrvalue = self.tinfoil.run_command('getDefaultPreference', self.mc) or {}
elif name == 'fn_provides':
@@ -339,13 +336,6 @@ class TinfoilCookerAdapter:
# Grab these only when they are requested since they aren't always used
if name in self._cache:
return self._cache[name]
- elif name == 'bbfile_config_priorities':
- ret = self.tinfoil.run_command('getLayerPriorities')
- bbfile_config_priorities = []
- for collection, pattern, regex, pri in ret:
- bbfile_config_priorities.append((collection, pattern, re.compile(regex), pri))
-
- attrvalue = bbfile_config_priorities
else:
raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name))
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 06/17] cooker: Change layer.conf handling to new approach
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (3 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 05/17] cooker/cache/command/tinfoil: Drop bbfile_priority Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 16:20 ` [bitbake-devel] " Antonin Godard
2026-11-30 15:28 ` [PATCH 07/17] tests/cooker: Drop obsolete collections test Richard Purdie
` (10 subsequent siblings)
15 siblings, 1 reply; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
This is a fairly radical set of changes to the way layer.conf is handled and how it
works with layers. I tried to split this into more specific changes but bascially
I couldn't make that work in any reasonable way. It is not intended to be backward
compatible even if some bits of syntax are similar.
There were several historical issues:
- layers can contain multiple 'collections'
- priorities could depend on the file, collection and layer which
interacted in ways people couldn't easily picture
- layer.conf became a dumping ground for random variables
- the current internal layer/collection 'names' are suboptimal
This patch therefore:
- Drops the concept of 'collections'
- Drops layer priorities
- Drops file priorities
- Requires LAYERNAME to be set
- Auto constructs BBPATH based on layer dependencies
- AUto constructs BBFILES based on layer dependencies
- Auto constructs BBFILES_DYNAMIC based on a "dynamic-recipes" directory
- Filter layer.conf variables
- Adds support for layer specific variables in layervars.conf
- Sets LAYERDIR_<layername> variables (and includes bitbake)
- No longer supports layers within layers
(multiple layers in a repo is still fine)
More details notes follow (with examples from OE):
"""
layer.conf has radically changed and is now parsed in isolation on top
of bblayers.conf. This means any changes made to variables in that file
don't pass to other files or the global state by default. ":append"
would only add to the value from bblayers. Overrides will not work as
they're not defined at this point.
layer.conf is now expected to set a LAYERNAME.
The layer names are going to change. Some examples:
"core" -> "oe-core"
"openembedded-layer" -> "meta-oe"
"networking-layer" -> meta-oe-networking"
"virtualization-layer" -> "meta-virtualization"
The idea is to have a consistent base prefix for combined repos so that
the repo can be identified from the name (e.g. in a list of
dependencies), and drop unneeded "-layer" suffix, make "core" clearer
from other "core" things. As such, we are expecting layers to move to
new names.
Note that any fragment references also then need to use the new layer
names.
The LAYERDEPENDS and LAYERRECOMMENDS variables remain as before.
LAYER* variables which traditionally had a collection name suffix, e.g.
"_core" now don't need to be suffixed with the layername, but can be.
The concepts of layer priorities, bbfile prorities and collections are
all removed. This means the variables BFILE_COLLECTIONS,
BBFILE_PRIORITY and BBFILE_PATTERN no longer do anything but trigger
warnings.
BBPATH and BBFILES no longer should be set by layer.conf. They are both
now set based upon the information from LAYERDEPENDS. If you depend on
a layer, you have the ability to change it. BBFILES will now just
include .bb and .bbappend files in any recipes* directories.
BBFILES_DYNAMIC is also no longer needed. Instead, bitbake will look
for a "dynamic-recipes" directory and apply any subdirectories
directories there based on layername, adding any files contained to
BBFILES internally dynamically.
Bitbake will set LAYERDIR_<layername> in the global namespace. In
addition, it will also set BITBAKEDIR to point at itself (OE-Core
needs that, hopefully nothing else does and it is really for internal
use to build PATH correctly).
BBLAYERS no longer controls much other that the layers to include.
There are two variables which are exceptions, LAYERSERIES_CORENAMES and
LAYER_PASSTHROUGH_VARS_PREFIXES. These two are only set by the first
layer included that sets them. For the layerseries, this is by
historical precedent, I did this for the latter for now to potentially
cover some weird use cases people may have. I am tempted to remove that
special casing and only allow one layer to set those variables.
There are some variables which can pass from layer.conf into the global
scope. There is a list of variable prefixes which are accepted in
LAYER_PASSTHROUGH_VARS_PREFIXES. These should be lists which work well
with +=.
This list is deliberately restrictive, I've worked with the sample
layers to remove as many of them that I can.
Layers do need some way of setting variables for their own recipes.
This is done with a new layervars.conf, which recipes in a given layer
will always have included (in .bb files but not .bbappend). Note that
layervars.conf is parsed on top of the base configuration, so much later
in parsing than layer.conf.
One pattern we've noticed is layers wanting to warn that the
configuration they provide is not enabled and to provide that config,
usually as a DISTRO_FEATURE. I've changed meta-virtiualization to use
fragments to enable the different configs (which can enable
DISTRO_FEATURES in turn).
That means we can add a LAYER_FRAGEMENTS_RECOMMEND_ANY variable which
is used to warn when fragments aren't selected and the user can
override with LAYER_FRAGEMENTS_OPTED_OUT to hide the warnings if they
really don't want to select any.
Some things are better imeplemented with conf files and a "include_all"
directive in core. I've changed security flags and reproducible builds
to do that, we should be doing this anyway.
Some layers have been setting INHERIT in layer.conf. This is no longer
supported and should be done by configuration files/fragments instead. It
can be done in layervars.conf but will only apply to recipes in that layer
(and not bbapends).
There is a BB_LAYER_FILTER_FUNC variable which takes the name of function
which can make final changes to the datastore at the end of "layer" parsing
before the main parse. If your layer is intended to be shared at all and used
by others outside your own context, you *should not* be using this. It can
only be set once, by the first layer.conf found that sets it.
From an internals perspective, there is now a Layers object stored in
the datastore as "layerdata". This is useful for some areas of the code
to be able to work with layers, such as the fragment code. It is considered
semi-internal API at this point. It does mean anyone iterating datastore
values needs to be careful about non-text return values but we already
have those.
"""
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
.../bitbake-user-manual-metadata.rst | 2 +-
.../bitbake-user-manual-ref-variables.rst | 56 +---
lib/bb/command.py | 9 -
lib/bb/cooker.py | 214 +------------
lib/bb/cookerdata.py | 302 ++++++++++++++----
lib/bb/parse/ast.py | 26 +-
6 files changed, 273 insertions(+), 336 deletions(-)
diff --git a/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst b/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst
index 27711b2c849..3fe4489aebb 100644
--- a/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst
+++ b/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst
@@ -1021,7 +1021,7 @@ variable like this::
OE_FRAGMENTS = "core/domain/somefragment core/someotherfragment anotherlayer/anotherdomain/anotherfragment"
Fragment names listed in this variable must be prefixed by the layer name
-where a fragment file is located, defined by :term:`BBFILE_COLLECTIONS` in ``layer.conf``.
+where a fragment file is located, defined by :term:`LAYERNAME` in ``layer.conf``.
The implementation then expands this list into
:ref:`require <bitbake-user-manual/bitbake-user-manual-metadata:\`\`require\`\` directive>`
diff --git a/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst b/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst
index e258e7afd64..7d3b97bc6ba 100644
--- a/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst
+++ b/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst
@@ -922,48 +922,6 @@ overview of their function and contents.
You must set this variable in the external environment in order
for it to work.
- :term:`BBFILE_COLLECTIONS`
- Lists the names of configured layers. These names are used to find
- the other ``BBFILE_*`` variables. Typically, each layer appends its
- name to this variable in its ``conf/layer.conf`` file.
-
- :term:`BBFILE_PATTERN`
- Variable that expands to match files from
- :term:`BBFILES` in a particular layer. This
- variable is used in the ``conf/layer.conf`` file and must be suffixed
- with the name of the specific layer (e.g.
- ``BBFILE_PATTERN_emenlow``).
-
- :term:`BBFILE_PRIORITY`
- Assigns the priority for recipe files in each layer.
-
- This variable is used in the ``conf/layer.conf`` file and must be
- suffixed with a `_` followed by the name of the specific layer (e.g.
- ``BBFILE_PRIORITY_emenlow``). Colon as separator is not supported.
-
- This variable is useful in situations where the same recipe appears
- in more than one layer. Setting this variable allows you to
- prioritize a layer against other layers that contain the same recipe
- --- effectively letting you control the precedence for the multiple
- layers. The precedence established through this variable stands
- regardless of a recipe's version (:term:`PV` variable).
- For example, a layer that has a recipe with a higher :term:`PV` value but
- for which the :term:`BBFILE_PRIORITY` is set to have a lower precedence
- still has a lower precedence.
-
- A larger value for the :term:`BBFILE_PRIORITY` variable results in a
- higher precedence. For example, the value 6 has a higher precedence
- than the value 5. If not specified, the :term:`BBFILE_PRIORITY` variable
- is set based on layer dependencies (see the :term:`LAYERDEPENDS` variable
- for more information). The default priority, if unspecified for a
- layer with no dependencies, is the lowest defined priority + 1 (or 1
- if no priorities are defined).
-
- .. tip::
-
- You can use the command bitbake-layers show-layers to list all
- configured layers along with their priorities.
-
:term:`BBFILES`
A space-separated list of recipe files BitBake uses to build
software.
@@ -1198,6 +1156,9 @@ overview of their function and contents.
Allows you to use a configuration file to add to the list of
command-line target recipes you want to build.
+ :term:`BITBAKEDIR`
+ BitBake sets this to location where bitbake is being run from.
+
:term:`BITBAKE_UI`
Used to specify the UI module to use when running BitBake. Using this
variable is equivalent to using the ``-u`` command-line option.
@@ -1375,12 +1336,13 @@ overview of their function and contents.
available outside of ``layer.conf`` and references are expanded
immediately when parsing of the file completes.
- :term:`LAYERDIR_RE`
+ :term:`LAYERDIR_<layername>`
+
+ LAYERDIR_<layername> is defined as the path each named layer is located.
+
+ :term:`LAYERNAME`
When used inside the ``layer.conf`` configuration file, this variable
- provides the path of the current layer, escaped for use in a regular
- expression (:term:`BBFILE_PATTERN`). This
- variable is not available outside of ``layer.conf`` and references
- are expanded immediately when parsing of the file completes.
+ provides the name assigned to the current layer.
:term:`LAYERSERIES_COMPAT`
Lists the versions of the OpenEmbedded-Core (OE-Core) for which
diff --git a/lib/bb/command.py b/lib/bb/command.py
index 9848b7a6732..b33e81d3e9a 100644
--- a/lib/bb/command.py
+++ b/lib/bb/command.py
@@ -300,15 +300,6 @@ class CommandsSync:
command.cooker.parseConfiguration()
parseConfiguration.needconfig = False
- def getLayerPriorities(self, command, params):
- command.cooker.parseConfiguration()
- ret = []
- # regex objects cannot be marshalled by xmlrpc
- for collection, pattern, regex, pri in command.cooker.bbfile_config_priorities:
- ret.append((collection, pattern, regex.pattern, pri))
- return ret
- getLayerPriorities.readonly = True
-
def revalidateCaches(self, command, params):
"""Called by UI clients when metadata may have changed"""
command.cooker.revalidateCaches()
diff --git a/lib/bb/cooker.py b/lib/bb/cooker.py
index 7fca4ac2f74..31a78743406 100644
--- a/lib/bb/cooker.py
+++ b/lib/bb/cooker.py
@@ -454,10 +454,9 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si
for mc in self.multiconfigs:
self.recipecaches[mc] = bb.cache.CacheData(self.caches_array)
- self.handleCollections(self.data.getVar("BBFILE_COLLECTIONS"))
self.collections = {}
for mc in self.multiconfigs:
- self.collections[mc] = CookerCollectFiles(self.bbfile_config_priorities, mc)
+ self.collections[mc] = CookerCollectFiles(self.databuilder.layerdata, mc)
self.collections[mc].collect_bbfiles(self.databuilder.mcdata[mc], self.databuilder.mcdata[mc])
self._parsecache_set(False)
@@ -791,7 +790,7 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si
depend_tree["rdepends-pkg"] = {}
depend_tree["rrecs-pkg"] = {}
depend_tree['providermap'] = {}
- depend_tree["layer-priorities"] = self.bbfile_config_priorities
+ depend_tree["layer-priorities"] = None
for mc in taskdata:
for name, fn in list(taskdata[mc].get_providermap().items()):
@@ -1181,129 +1180,6 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si
else:
shell.start( self )
-
- def handleCollections(self, collections):
- """Handle collections"""
- errors = False
- self.bbfile_config_priorities = []
- if collections:
- collection_priorities = {}
- collection_depends = {}
- collection_list = collections.split()
- min_prio = 0
- for c in collection_list:
- bb.debug(1,'Processing %s in collection list' % (c))
-
- # Get collection priority if defined explicitly
- priority = self.data.getVar("BBFILE_PRIORITY_%s" % c)
- if priority:
- try:
- prio = int(priority)
- except ValueError:
- parselog.error("invalid value for BBFILE_PRIORITY_%s: \"%s\"", c, priority)
- errors = True
- if min_prio == 0 or prio < min_prio:
- min_prio = prio
- collection_priorities[c] = prio
- else:
- collection_priorities[c] = None
-
- # Check dependencies and store information for priority calculation
- deps = self.data.getVar("LAYERDEPENDS_%s" % c)
- if deps:
- try:
- depDict = bb.utils.explode_dep_versions2(deps)
- except bb.utils.VersionStringException as vse:
- bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (c, str(vse)))
- for dep, oplist in list(depDict.items()):
- if dep in collection_list:
- for opstr in oplist:
- layerver = self.data.getVar("LAYERVERSION_%s" % dep)
- (op, depver) = opstr.split()
- if layerver:
- try:
- res = bb.utils.vercmp_string_op(layerver, depver, op)
- except bb.utils.VersionStringException as vse:
- bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (c, str(vse)))
- if not res:
- parselog.error("Layer '%s' depends on version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, dep, layerver)
- errors = True
- else:
- parselog.error("Layer '%s' depends on version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, dep)
- errors = True
- else:
- parselog.error("Layer '%s' depends on layer '%s', but this layer is not enabled in your configuration", c, dep)
- errors = True
- collection_depends[c] = list(depDict.keys())
- else:
- collection_depends[c] = []
-
- # Check recommends and store information for priority calculation
- recs = self.data.getVar("LAYERRECOMMENDS_%s" % c)
- if recs:
- try:
- recDict = bb.utils.explode_dep_versions2(recs)
- except bb.utils.VersionStringException as vse:
- bb.fatal('Error parsing LAYERRECOMMENDS_%s: %s' % (c, str(vse)))
- for rec, oplist in list(recDict.items()):
- if rec in collection_list:
- if oplist:
- opstr = oplist[0]
- layerver = self.data.getVar("LAYERVERSION_%s" % rec)
- if layerver:
- (op, recver) = opstr.split()
- try:
- res = bb.utils.vercmp_string_op(layerver, recver, op)
- except bb.utils.VersionStringException as vse:
- bb.fatal('Error parsing LAYERRECOMMENDS_%s: %s' % (c, str(vse)))
- if not res:
- parselog.debug3("Layer '%s' recommends version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, rec, layerver)
- continue
- else:
- parselog.debug3("Layer '%s' recommends version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, rec)
- continue
- parselog.debug3("Layer '%s' recommends layer '%s', so we are adding it", c, rec)
- collection_depends[c].append(rec)
- else:
- parselog.debug3("Layer '%s' recommends layer '%s', but this layer is not enabled in your configuration", c, rec)
-
- # Recursively work out collection priorities based on dependencies
- def calc_layer_priority(collection):
- if not collection_priorities[collection]:
- max_depprio = min_prio
- for dep in collection_depends[collection]:
- calc_layer_priority(dep)
- depprio = collection_priorities[dep]
- if depprio > max_depprio:
- max_depprio = depprio
- max_depprio += 1
- parselog.debug("Calculated priority of layer %s as %d", collection, max_depprio)
- collection_priorities[collection] = max_depprio
-
- # Calculate all layer priorities using calc_layer_priority and store in bbfile_config_priorities
- for c in collection_list:
- calc_layer_priority(c)
- regex = self.data.getVar("BBFILE_PATTERN_%s" % c)
- if regex is None:
- parselog.error("BBFILE_PATTERN_%s not defined" % c)
- errors = True
- continue
- elif regex == "":
- parselog.debug("BBFILE_PATTERN_%s is empty" % c)
- cre = re.compile('^NULL$')
- errors = False
- else:
- try:
- cre = re.compile(regex)
- except re.error:
- parselog.error("BBFILE_PATTERN_%s \"%s\" is not a valid regular expression", c, regex)
- errors = True
- continue
- self.bbfile_config_priorities.append((c, regex, cre, collection_priorities[c]))
- if errors:
- # We've already printed the actual error(s)
- raise CollectionError("Errors during parsing layer configuration")
-
def buildSetVars(self):
"""
Setup any variables needed before starting a build
@@ -1621,7 +1497,7 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si
if flags and "func" in flags and "python" in flags:
expand = False
v = self.data.getVar(k, expand)
- if not k.startswith("__") and not isinstance(v, bb.data_smart.DataSmart):
+ if not k.startswith("__") and not isinstance(v, bb.data_smart.DataSmart) and not isinstance(v, dict):
dump[k] = {
'v' : str(v) ,
'history' : self.data.varhistory.variable(k),
@@ -1819,25 +1695,16 @@ class CookerExit(bb.event.Event):
class CookerCollectFiles(object):
- def __init__(self, priorities, mc=''):
+ def __init__(self, layerdata, mc=''):
self.mc = mc
self.bbappends = []
self.overlayed = None
- # Priorities is a list of tuples, with the second element as the pattern.
- # We need to sort the list with the longest pattern first, and so on to
- # the shortest. This allows nested layers to be properly evaluated.
- self.bbfile_config_priorities = sorted(priorities, key=lambda tup: tup[1], reverse=True)
-
- def calc_bbfile_priority(self, filename):
- for layername, _, regex, pri in self.bbfile_config_priorities:
- if regex.match(filename):
- return pri, regex, layername
- return 0, None, None
+ self.layerdata = layerdata
def get_layername(self, filename):
- for layername, _, regex, _ in self.bbfile_config_priorities:
- if regex.match(filename):
- return layername
+ for layer in self.layerdata:
+ if filename.startswith(self.layerdata[layer].path + "/"):
+ return layer
return None
def get_bbfiles(self):
@@ -1857,7 +1724,8 @@ class CookerCollectFiles(object):
for ignored in ('SCCS', 'CVS', '.svn'):
if ignored in dirs:
dirs.remove(ignored)
- found += [os.path.join(dir, f) for f in files if (f.endswith(('.bb', '.bbappend')))]
+ dirs.sort()
+ found += [os.path.join(dir, f) for f in sorted(files) if (f.endswith(('.bb', '.bbappend')))]
return found
@@ -1992,68 +1860,6 @@ class CookerCollectFiles(object):
filelist.append(filename)
return tuple(filelist)
- def collection_priorities(self, pkgfns, fns, d):
- # Return the priorities of the entries in pkgfns
- # Also check that all the regexes in self.bbfile_config_priorities are used
- # (but to do that we need to ensure skipped recipes aren't counted, nor
- # collections in BBFILE_PATTERN_IGNORE_EMPTY)
-
- priorities = {}
- seen = set()
- matched = set()
-
- matched_regex = set()
- unmatched_regex = set()
- for _, _, regex, _ in self.bbfile_config_priorities:
- unmatched_regex.add(regex)
-
- # Calculate priorities for each file
- for p in pkgfns:
- realfn, cls, mc = bb.cache.virtualfn2realfn(p)
- priorities[p], regex, _ = self.calc_bbfile_priority(realfn)
- if regex in unmatched_regex:
- matched_regex.add(regex)
- unmatched_regex.remove(regex)
- seen.add(realfn)
- if regex:
- matched.add(realfn)
-
- if unmatched_regex:
- # Account for bbappend files
- for b in self.bbappends:
- (bbfile, append) = b
- seen.add(append)
-
- # Account for skipped recipes
- seen.update(fns)
-
- seen.difference_update(matched)
-
- def already_matched(fn):
- for regex in matched_regex:
- if regex.match(fn):
- return True
- return False
-
- for unmatch in unmatched_regex.copy():
- for fn in seen:
- if unmatch.match(fn):
- # If the bbappend or file was already matched by another regex, skip it
- # e.g. for a layer within a layer, the outer regex could match, the inner
- # regex may match nothing and we should warn about that
- if already_matched(fn):
- continue
- unmatched_regex.remove(unmatch)
- break
-
- for collection, pattern, regex, _ in self.bbfile_config_priorities:
- if regex in unmatched_regex:
- if d.getVar('BBFILE_PATTERN_IGNORE_EMPTY_%s' % collection) != '1':
- collectlog.warning("No bb files in %s matched BBFILE_PATTERN_%s '%s'" % (self.mc if self.mc else 'default',
- collection, pattern))
-
- return priorities
-
class ParsingFailure(Exception):
def __init__(self, realexception, recipe):
self.realexception = realexception
diff --git a/lib/bb/cookerdata.py b/lib/bb/cookerdata.py
index 87310af7ce6..3bea91e2387 100644
--- a/lib/bb/cookerdata.py
+++ b/lib/bb/cookerdata.py
@@ -10,11 +10,13 @@
# SPDX-License-Identifier: GPL-2.0-only
#
+import dataclasses
import logging
import os
import re
import sys
import hashlib
+import graphlib
from functools import wraps
import bb.cache
@@ -226,6 +228,22 @@ def findTopdir():
return os.path.abspath(os.getcwd())
+@dataclasses.dataclass(repr=False)
+class Layer:
+ path: str
+ version: str
+ compat: set[str] = dataclasses.field(default_factory=set)
+ depends: dict[dict] = dataclasses.field(default_factory=dict)
+ recommends: dict[dict] = dataclasses.field(default_factory=dict)
+ fragment_recommends_any: set[str] = dataclasses.field(default_factory=set)
+
+ # We need the cache to have a consistent value which sets won't allow so we need
+ # a custom sortable repr.
+ def __repr__(self):
+ return "Layer(path=%r, version=%r, compat=%r, depends=%r, recommends=%r, fragment_recommends_any=%r)" % (
+ self.path, self.version, sorted(self.compat), self.depends,
+ self.recommends, sorted(self.fragment_recommends_any))
+
class CookerDataBuilder(object):
def __init__(self, cookercfg, worker = False):
@@ -280,7 +298,7 @@ class CookerDataBuilder(object):
def parseBaseConfiguration(self, worker=False):
mcdata = {}
try:
- self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
+ self.data, self.layerdata = self.parseConfigurationFiles(self.prefiles, self.postfiles)
servercontext = self.data.getVar("BB_WORKERCONTEXT", False) is None and not worker
bb.fetch.fetcher_init(self.data, servercontext)
@@ -296,7 +314,7 @@ class CookerDataBuilder(object):
raise Exception("Too deep config re-parse loop. Check locations where "
"BB_INVALIDCONF is being set (ConfigParsed event handlers)")
self.data.setVar("BB_INVALIDCONF", False)
- self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
+ self.data, self.layerdata = self.parseConfigurationFiles(self.prefiles, self.postfiles)
reparse_cnt += 1
bb.event.fire(bb.event.ConfigParsed(), self.data)
@@ -307,7 +325,7 @@ class CookerDataBuilder(object):
for config in multiconfig:
if config[0].isdigit():
bb.fatal("Multiconfig name '%s' is invalid as multiconfigs cannot start with a digit" % config)
- parsed_mcdata = self.parseConfigurationFiles(self.prefiles, self.postfiles, config)
+ parsed_mcdata, _ = self.parseConfigurationFiles(self.prefiles, self.postfiles, config)
bb.event.fire(bb.event.ConfigParsed(), parsed_mcdata)
mcdata[config] = parsed_mcdata
if multiconfig:
@@ -369,6 +387,7 @@ class CookerDataBuilder(object):
data = parse_config_file(f, data)
layerconf = self._findLayerConf(data)
+ layerdata = {}
if layerconf:
parselog.debug2("Found bblayers.conf (%s)", layerconf)
# By definition bblayers.conf is in conf/ of TOPDIR.
@@ -402,77 +421,215 @@ class CookerDataBuilder(object):
parselog.critical("Please check BBLAYERS in %s" % (layerconf))
raise bb.BBHandledException()
+ bitbakedir = os.path.realpath(os.path.dirname(__file__) + "/../../")
+ data.setVar("BITBAKEDIR", bitbakedir)
+ data.setVarFlag("BITBAKEDIR", "vardepvalue", "")
+
layerseries = None
- compat_entries = {}
+ layer_safevars = tuple()
+ layer_filterfunc = None
+ errors = []
+ datastores = {}
for layer in layers:
- parselog.debug2("Adding layer %s", layer)
+ parselog.debug2("Adding layer %s" % layer)
if 'HOME' in approved and '~' in layer:
layer = os.path.expanduser(layer)
if layer.endswith('/'):
layer = layer.rstrip('/')
- data.setVar('LAYERDIR', layer)
- data.setVar('LAYERDIR_RE', re.escape(layer))
- data = parse_config_file(os.path.join(layer, "conf", "layer.conf"), data)
- data.expandVarref('LAYERDIR')
- data.expandVarref('LAYERDIR_RE')
-
- # Sadly we can't have nice things.
- # Some layers think they're going to be 'clever' and copy the values from
- # another layer, e.g. using ${LAYERSERIES_COMPAT_core}. The whole point of
- # this mechanism is to make it clear which releases a layer supports and
- # show when a layer master branch is bitrotting and is unmaintained.
- # We therefore avoid people doing this here.
- collections = (data.getVar('BBFILE_COLLECTIONS') or "").split()
- for c in collections:
- compat_entry = data.getVar("LAYERSERIES_COMPAT_%s" % c)
- if compat_entry:
- compat_entries[c] = set(compat_entry.split())
- data.delVar("LAYERSERIES_COMPAT_%s" % c)
- if not layerseries:
- layerseries = set((data.getVar("LAYERSERIES_CORENAMES") or "").split())
- if layerseries:
- data.delVar("LAYERSERIES_CORENAMES")
-
- data.delVar('LAYERDIR_RE')
- data.delVar('LAYERDIR')
- for c in compat_entries:
- data.setVar("LAYERSERIES_COMPAT_%s" % c, " ".join(sorted(compat_entries[c])))
-
- bbfiles_dynamic = (data.getVar('BBFILES_DYNAMIC') or "").split()
- collections = (data.getVar('BBFILE_COLLECTIONS') or "").split()
- invalid = []
- for entry in bbfiles_dynamic:
- parts = entry.split(":", 1)
- if len(parts) != 2:
- invalid.append(entry)
+ layer = os.path.realpath(layer)
+
+ ld = data.createCopy()
+ ld.setVar('LAYERDIR', layer)
+ #ld.setVar('LAYERDIR_RE', re.escape(layer))
+ layerfile = os.path.join(layer, "conf", "layer.conf")
+ ld = parse_config_file(layerfile, ld)
+ bb.parse.mark_dependency(data, layerfile)
+
+ layername = ld.getVar("LAYERNAME")
+ if not layername:
+ errors.append("Layer %s does not set LAYERNAME" % layer)
+ continue
+ if layername in layerdata:
+ errors.append("LAYERNAME %s is used by both %s and %s" % (layername, layer, layerdata[layername].path))
continue
- l, f = parts
- invert = l[0] == "!"
- if invert:
- l = l[1:]
- if (l in collections and not invert) or (l not in collections and invert):
- data.appendVar("BBFILES", " " + f)
- if invalid:
- bb.fatal("BBFILES_DYNAMIC entries must be of the form {!}<collection name>:<filename pattern>, not:\n %s" % "\n ".join(invalid))
-
- collections_tmp = collections[:]
- for c in collections:
- collections_tmp.remove(c)
- if c in collections_tmp:
- bb.fatal("Found duplicated BBFILE_COLLECTIONS '%s', check bblayers.conf or layer.conf to fix it." % c)
-
- compat = set()
- if c in compat_entries:
- compat = compat_entries[c]
- if compat and not layerseries:
- bb.fatal("No core layer found to work with layer '%s'. Missing entry in bblayers.conf?" % c)
- if compat and not (compat & layerseries):
- bb.fatal("Layer %s is not compatible with the core layer which only supports these series: %s (layer is compatible with %s)"
- % (c, " ".join(layerseries), " ".join(compat)))
- elif not compat and not data.getVar("BB_WORKERCONTEXT"):
- bb.warn("Layer %s should set LAYERSERIES_COMPAT_%s in its conf/layer.conf file to list the core layer names it is compatible with." % (c, c))
+ nested = False
+ for pathcheck in layerdata:
+ otherpath = layerdata[pathcheck].path
+ if layer.startswith(otherpath + "/") or otherpath.startswith(layer + "/"):
+ errors.append("Layer path %s (layer %s) conflicts with path %s from layer %s. Layers can't nest." % (layer, layername, otherpath, pathcheck))
+ nested = True
+ if nested:
+ continue
+
+ def getVar(var, layername, ld):
+ value = ld.getVar(var)
+ if not value:
+ value = ld.getVar("%s_%s" % (var, layername))
+ return value
+
+ layerdata[layername] = Layer(
+ path=layer,
+ version=getVar("LAYERVERSION", layername, ld) or "1",
+ compat=set((getVar("LAYERSERIES_COMPAT", layername, ld) or "").split()),
+ depends=bb.utils.explode_dep_versions2(getVar("LAYERDEPENDS", layername, ld) or ""),
+ recommends=bb.utils.explode_dep_versions2(getVar("LAYERRECOMMENDS", layername, ld) or ""),
+ fragment_recommends_any=set((getVar("LAYER_FRAGMENT_RECOMMENDS_ANY", layername, ld) or "").split()),
+ )
+
+ if not layerdata[layername].compat:
+ errors.append("Layer %s should set LAYERSERIES_COMPAT in its conf/layer.conf file to list the core layer names it is compatible with." % (layername))
+
+ if not layerseries:
+ layerseries = set((ld.getVar("LAYERSERIES_CORENAMES") or "").split())
+ if not layer_safevars:
+ layer_safevars = tuple((ld.getVar("LAYER_PASSTHROUGH_VARS_PREFIXES") or "").split())
+ if not layer_filterfunc:
+ layer_filterfunc = ld.getVar("BB_LAYER_FILTER_FUNC")
+ datastores[layer] = ld
+
+ for layername in layerdata:
+ data.setVar("LAYERDIR_%s" % layername, layerdata[layername].path)
+ data.setVarFlag("LAYERDIR_%s" % layername, "vardepvalue", "")
+
+ def copy_layer_history(var, data, ld):
+ base = len(initial.varhistory.variable(var))
+ for entry in ld.varhistory.variable(var)[base:]:
+ if "flag" not in entry:
+ data.varhistory.record(**entry)
+
+ initial = data
+ data = data.createCopy()
+ for layer in sorted(datastores):
+ ld = datastores[layer]
+ for var in ld:
+ if var.startswith(("LAYERNAME", "LAYERDEPENDS", "LAYERRECOMMENDS", "LAYERVERSION", "LAYERSERIES_COMPAT", "LAYERSERIES_CORENAMES", "LAYERDIR", "LAYER_FRAGMENT_RECOMMENDS_ANY", "LAYER_PASSTHROUGH_VARS_PREFIXES")):
+ continue
+ if var.startswith(("BBFILE_COLLECTIONS", "BBFILE_PRIORITY", "BBFILE_PATTERN")):
+ bb.warn("Support for %s was removed and the variable is being ignored but is set by layer %s" % (var, layer))
+ continue
+ if var in ["__depends"]:
+ continue
+ if var in ["BBPATH", "BBFILES", "BBFILES_DYNAMIC"]:
+ if ld.getVar(var) != data.getVar(var):
+ bb.warn("%s now set automatically, the variable is being ignored but is set by layer %s" % (var, layer))
+ bb.warn(str(ld.getVar(var, expand=False)))
+ continue
+ append = None
+ if var in initial:
+ orig = initial.getVar(var, False)
+ new = ld.getVar(var, False)
+ if orig == new:
+ continue
+ if not new.startswith(orig):
+ errors.append("Layer %s is overwriting variable %s, it should only append to it" % (layer, var))
+ continue
+ append = new.removeprefix(orig)
+ if var.startswith(layer_safevars):
+ pass
+ elif var.startswith(("BBLAYERS_LAYERINDEX_NAME", "BB_GLOBAL_PYMODULES")):
+ pass
+ else:
+ bb.warn("Variable %s is set by %s but it will be ignored" % (var, layer))
+ continue
+
+ copy_layer_history(var, data, ld)
+ if append:
+ data.appendVar(var, append)
+ elif var in data:
+ # Assume that if multiple layers set it, it should be space separated.
+ data.appendVar(var, " " + ld.getVar(var, False))
+ else:
+ data.setVar(var, ld.getVar(var, False))
+ if not layerseries:
+ errors.append("No layer sets LAYERSERIES_CORENAMES")
data.setVar("LAYERSERIES_CORENAMES", " ".join(sorted(layerseries)))
+ data.setVar("LAYER_PASSTHROUGH_VARS_PREFIXES", " ".join(layer_safevars))
+
+ layers = set(layerdata)
+ for layer in layerdata:
+ if not (layerdata[layer].compat & layerseries):
+ errors.append("Layer %s is not compatible with the core layer which only supports these series: %s (layer is compatible with %s)"
+ % (layer, " ".join(layerseries), " ".join(layerdata[layer].compat)))
+
+ # Check dependencies
+ if not set(layerdata[layer].depends).issubset(layers):
+ errors.append("Layer %s depends on %s but that layer isn't configured" % (layer, " ".join(set(layerdata[layer].depends) - layers)))
+ continue
+
+ # Check dependency versions
+ for dep in layerdata[layer].depends:
+ for verop in layerdata[layer].depends[dep]:
+ (op, depver) = verop.split()
+ layerver = layerdata[dep].version
+ if not layerver:
+ errors.append("Layer '%s' depends on version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep))
+ continue
+ try:
+ res = bb.utils.vercmp_string_op(layerver, depver, op)
+ except bb.utils.VersionStringException as vse:
+ bb.fatal('Error parsing LAYERDEPENDS for layer %s: %s' % (layer, str(vse)))
+ if not res:
+ errors.append("Layer '%s' depends on version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep, layerver))
+
+ # Check recommends versions
+ for dep in layerdata[layer].recommends:
+ for verop in layerdata[layer].recommends[dep]:
+ if dep not in layerdata:
+ continue
+ (op, depver) = verop.split()
+ layerver = layerdata[dep].version
+ if not layerver:
+ errors.append("Layer '%s' recommends version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep))
+ continue
+ try:
+ res = bb.utils.vercmp_string_op(layerver, depver, op)
+ except bb.utils.VersionStringException as vse:
+ bb.fatal('Error parsing LAYERRECOMMENDS for layer %s: %s' % (layer, str(vse)))
+ if not res:
+ errors.append("Layer '%s' recommends version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep, layerver))
+
+ data.setVar("layerdata", layerdata)
+
+ if errors:
+ for error in errors:
+ bb.error(error)
+ bb.fatal("Layer errors found, parsing stopped")
+
+ # Using the layer dependencies, work out the order layers should be listed
+ # in BBPATH and searched for BBFILES
+ layerorder = graphlib.TopologicalSorter()
+ for layer in sorted(layerdata.keys()):
+ layerorder.add(layer)
+ for dep in layerdata[layer].depends:
+ layerorder.add(layer, dep)
+
+ try:
+ ordering = list(layerorder.static_order())
+ except graphlib.CycleError as exc:
+ bb.fatal("Circular dependencies found from LAYERDEPENDS, can't continue. (%s)" % str(exc))
+
+ # Construct BBPATH
+ data.setVar("BBPATH", ":".join(["${TOPDIR}"] + [layerdata[layer].path for layer in ordering[::-1]]))
+
+ # Construct BBFILES
+ # - any recipes subdirs are added through a glob
+ # - any /dynamic-recipes/<layername>/ are added if the named layer is present
+ bbfiles = []
+ for layer in ordering:
+ recipes = layerdata[layer].path + "/recipes*"
+ bbfiles.append(recipes)
+ dynamic_recipes = layerdata[layer].path + "/dynamic-recipes"
+ if os.path.isdir(dynamic_recipes):
+ for deplayer in os.listdir(dynamic_recipes):
+ if not os.path.isdir(dynamic_recipes + "/" + deplayer):
+ continue
+ if deplayer in layerdata:
+ bbfiles.append(dynamic_recipes + "/" + deplayer)
+ data.setVar("BBFILES", " ".join(bbfiles))
+
+ if layer_filterfunc:
+ bb.utils.better_eval("%s(d)" % layer_filterfunc, {"d": data})
if not data.getVar("BBPATH"):
msg = "The BBPATH variable is not set"
@@ -523,7 +680,7 @@ class CookerDataBuilder(object):
data.setVar('BBINCLUDED',bb.parse.get_file_depends(data))
- return data
+ return data, layerdata
@staticmethod
def _parse_recipe(bb_data, bbfile, appends, mc, layername):
@@ -538,6 +695,19 @@ class CookerDataBuilder(object):
if appends:
bb_data.setVar('__BBAPPEND', " ".join(appends))
+ layerdir = bb_data.getVar("LAYERDIR_%s" % layername)
+ if layerdir:
+ conffile = layerdir + "/conf/layervars.conf"
+ bb.parse.mark_dependency(bb_data, conffile)
+ if os.path.exists(conffile):
+ bb.parse.handle(conffile, bb_data, True, baseconfig=True)
+ # Handle any added INHERITs
+ bbclasses = (bb_data.getVar('INHERIT') or "").split()
+ bb_data.setVar("__bbclasstype", "global")
+ for bbclass in bbclasses:
+ bb_data = _inherit(bbclass, bb_data)
+ bb_data.setVar("__bbclasstype", "recipe")
+
return bb.parse.handle(bbfile, bb_data)
def parseRecipeVariants(self, bbfile, appends, virtonly=False, mc=None, layername=None):
diff --git a/lib/bb/parse/ast.py b/lib/bb/parse/ast.py
index d5d53a7c712..c26632b8b63 100644
--- a/lib/bb/parse/ast.py
+++ b/lib/bb/parse/ast.py
@@ -359,10 +359,11 @@ class AddFragmentsNode(AstNode):
# No need to use mark_dependency since we would only match a fragment
# from a specific layer and there can only be a single layer with a
# given namespace.
- def find_fragment(layers, layerid, full_fragment_name):
- for layerpath in layers.split():
+ def find_fragment(layerdata, layerid, full_fragment_name):
+ if layerid in layerdata:
+ layerpath = layerdata[layerid].path
candidate_fragment_path = os.path.join(layerpath, full_fragment_name)
- if os.path.exists(candidate_fragment_path) and bb.utils.get_file_layer(candidate_fragment_path, data) == layerid:
+ if os.path.exists(candidate_fragment_path):
return candidate_fragment_path
return None
@@ -388,11 +389,17 @@ class AddFragmentsNode(AstNode):
return True
return False
- fragments = data.getVar(self.fragments_variable)
- layers = data.getVar('BBLAYERS')
+ fragments = (data.getVar(self.fragments_variable) or "").split()
flagged_variables = data.getVar(self.flagged_variables_list_variable).split()
builtin_fragments = {f[0]:f[1] for f in [f.split(':') for f in data.getVar(self.builtin_fragments_variable).split()] }
+ layerdata = data.getVar("layerdata", expand=False)
+ optedout = set((data.getVar("LAYER_FRAGMENTS_OPTED_OUT") or "").split())
+ for layer in layerdata:
+ wanted = layerdata[layer].fragment_recommends_any - optedout
+ if wanted and not (wanted & set(fragments)):
+ bb.warn("Layer %s recommends one of the fragments %s to be enabled but none are" % (layer, str(wanted)))
+
if not fragments:
return
@@ -401,7 +408,7 @@ class AddFragmentsNode(AstNode):
builtin_fragments_list = list(
filter(
lambda f: f.startswith(builtin_fragment_key + "/"),
- fragments.split(),
+ fragments,
)
)
if len(builtin_fragments_list) > 1:
@@ -416,12 +423,12 @@ class AddFragmentsNode(AstNode):
)
)
- for f in fragments.split():
+ for f in fragments:
if check_and_set_builtin_fragment(f, data, builtin_fragments):
continue
layerid, fragment_name = f.split('/', 1)
full_fragment_name = data.expand("{}/{}.conf".format(self.fragments_path_prefix, fragment_name))
- fragment_path = find_fragment(layers, layerid, full_fragment_name)
+ fragment_path = find_fragment(layerdata, layerid, full_fragment_name)
if fragment_path:
bb.parse.ConfHandler.include(self.filename, fragment_path, self.lineno, data, "include fragment")
for flagged_var in flagged_variables:
@@ -429,7 +436,8 @@ class AddFragmentsNode(AstNode):
data.setVarFlag(flagged_var, f, val)
data.setVar(flagged_var, None)
else:
- bb.fatal("Could not find fragment {} in enabled layers:\n\t{}".format(f, "\n\t".join(layers.split())))
+ paths = [layerdata[layer].path for layer in layerdata]
+ bb.fatal("Could not find fragment {} in enabled layers:\n\t{}".format(f, "\n\t".join(paths)))
def handleInclude(statements, filename, lineno, m, force):
statements.append(IncludeNode(filename, lineno, m.group(1), force))
^ permalink raw reply related [flat|nested] 18+ messages in thread* Re: [bitbake-devel] [PATCH 06/17] cooker: Change layer.conf handling to new approach
2026-11-30 15:28 ` [PATCH 06/17] cooker: Change layer.conf handling to new approach Richard Purdie
@ 2026-11-30 16:20 ` Antonin Godard
0 siblings, 0 replies; 18+ messages in thread
From: Antonin Godard @ 2026-11-30 16:20 UTC (permalink / raw)
To: richard.purdie, bitbake-devel
Hi,
On Mon Nov 30, 2026 at 4:28 PM CET, Richard Purdie via bitbake-devel wrote:
[...]
> --- a/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst
> +++ b/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst
> @@ -922,48 +922,6 @@ overview of their function and contents.
> You must set this variable in the external environment in order
> for it to work.
>
> - :term:`BBFILE_COLLECTIONS`
> - Lists the names of configured layers. These names are used to find
> - the other ``BBFILE_*`` variables. Typically, each layer appends its
> - name to this variable in its ``conf/layer.conf`` file.
> -
> - :term:`BBFILE_PATTERN`
> - Variable that expands to match files from
> - :term:`BBFILES` in a particular layer. This
> - variable is used in the ``conf/layer.conf`` file and must be suffixed
> - with the name of the specific layer (e.g.
> - ``BBFILE_PATTERN_emenlow``).
> -
> - :term:`BBFILE_PRIORITY`
> - Assigns the priority for recipe files in each layer.
> -
> - This variable is used in the ``conf/layer.conf`` file and must be
> - suffixed with a `_` followed by the name of the specific layer (e.g.
> - ``BBFILE_PRIORITY_emenlow``). Colon as separator is not supported.
> -
> - This variable is useful in situations where the same recipe appears
> - in more than one layer. Setting this variable allows you to
> - prioritize a layer against other layers that contain the same recipe
> - --- effectively letting you control the precedence for the multiple
> - layers. The precedence established through this variable stands
> - regardless of a recipe's version (:term:`PV` variable).
> - For example, a layer that has a recipe with a higher :term:`PV` value but
> - for which the :term:`BBFILE_PRIORITY` is set to have a lower precedence
> - still has a lower precedence.
> -
> - A larger value for the :term:`BBFILE_PRIORITY` variable results in a
> - higher precedence. For example, the value 6 has a higher precedence
> - than the value 5. If not specified, the :term:`BBFILE_PRIORITY` variable
> - is set based on layer dependencies (see the :term:`LAYERDEPENDS` variable
> - for more information). The default priority, if unspecified for a
> - layer with no dependencies, is the lowest defined priority + 1 (or 1
> - if no priorities are defined).
> -
> - .. tip::
> -
> - You can use the command bitbake-layers show-layers to list all
> - configured layers along with their priorities.
> -
> :term:`BBFILES`
> A space-separated list of recipe files BitBake uses to build
> software.
> @@ -1198,6 +1156,9 @@ overview of their function and contents.
> Allows you to use a configuration file to add to the list of
> command-line target recipes you want to build.
>
> + :term:`BITBAKEDIR`
> + BitBake sets this to location where bitbake is being run from.
> +
> :term:`BITBAKE_UI`
> Used to specify the UI module to use when running BitBake. Using this
> variable is equivalent to using the ``-u`` command-line option.
> @@ -1375,12 +1336,13 @@ overview of their function and contents.
> available outside of ``layer.conf`` and references are expanded
> immediately when parsing of the file completes.
>
> - :term:`LAYERDIR_RE`
> + :term:`LAYERDIR_<layername>`
We usually don't have terms with placeholder values. I'd suggest defining it
only as LAYERDIR:
:term:`LAYERDIR`
This variable is automatically defined by :term:`BitBake` when parsing the
layers: when :term:`BitBake` reads the :term:`BBLAYERS` variable, it sets
a new ``LAYERDIR_<layer name>`` variable containing the absolute layer path
for each layer in the list. The ``<layer name>`` value is determined from the
layer's :term:`LAYERNAME`.
Note that I have a follow-up patch for the currently undocumented LAYER*
variables.
[...]
> + if var in initial:
> + orig = initial.getVar(var, False)
> + new = ld.getVar(var, False)
> + if orig == new:
> + continue
> + if not new.startswith(orig):
> + errors.append("Layer %s is overwriting variable %s, it should only append to it" % (layer, var))
> + continue
> + append = new.removeprefix(orig)
> + if var.startswith(layer_safevars):
> + pass
> + elif var.startswith(("BBLAYERS_LAYERINDEX_NAME", "BB_GLOBAL_PYMODULES")):
> + pass
> + else:
> + bb.warn("Variable %s is set by %s but it will be ignored" % (var, layer))
I'd suggest printing a more useful warning message, something along:
bb.warn(f"Variable {var} is set in {layer}/conf/layer.conf and will be ignored. "
"Only variables part of LAYER_PASSTHROUGH_VARS_PREFIXES are allowed "
"to be set from the layer.conf file.")
Antonin
^ permalink raw reply [flat|nested] 18+ messages in thread
* [PATCH 07/17] tests/cooker: Drop obsolete collections test
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (4 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 06/17] cooker: Change layer.conf handling to new approach Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 08/17] default-registry: Update for new layer names Richard Purdie
` (9 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
Since collections are no longer supported, the test no longer makes sense.
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
lib/bb/tests/cooker.py | 59 ------------------------------------------
1 file changed, 59 deletions(-)
diff --git a/lib/bb/tests/cooker.py b/lib/bb/tests/cooker.py
index 923adc156b5..290dfc48394 100644
--- a/lib/bb/tests/cooker.py
+++ b/lib/bb/tests/cooker.py
@@ -306,65 +306,6 @@ with bb.tinfoil.Tinfoil() as tinfoil:
with self._build_dir() as builddir:
self._run_script(builddir, script)
-
-class CookerTest(unittest.TestCase):
- def setUp(self):
- # At least one variable needs to be set
- self.d = bb.data.init()
- topdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testdata/cooker")
- self.d.setVar('TOPDIR', topdir)
-
- def test_CookerCollectFiles_sublayers(self):
- '''Test that a sublayer of an existing layer does not trigger
- No bb files matched ...'''
-
- def append_collection(topdir, path, d):
- collection = path.split('/')[-1]
- pattern = "^" + topdir + "/" + path + "/"
- regex = re.compile(pattern)
- priority = 5
-
- d.setVar('BBFILE_COLLECTIONS', (d.getVar('BBFILE_COLLECTIONS') or "") + " " + collection)
- d.setVar('BBFILE_PATTERN_%s' % (collection), pattern)
- d.setVar('BBFILE_PRIORITY_%s' % (collection), priority)
-
- return (collection, pattern, regex, priority)
-
- topdir = self.d.getVar("TOPDIR")
-
- # Priorities: list of (collection, pattern, regex, priority)
- bbfile_config_priorities = []
- # Order is important for this test, shortest to longest is typical failure case
- bbfile_config_priorities.append( append_collection(topdir, 'first', self.d) )
- bbfile_config_priorities.append( append_collection(topdir, 'second', self.d) )
- bbfile_config_priorities.append( append_collection(topdir, 'second/third', self.d) )
-
- pkgfns = [ topdir + '/first/recipes/sample1_1.0.bb',
- topdir + '/second/recipes/sample2_1.0.bb',
- topdir + '/second/third/recipes/sample3_1.0.bb' ]
-
- class LogHandler(logging.Handler):
- def __init__(self):
- logging.Handler.__init__(self)
- self.logdata = []
-
- def emit(self, record):
- self.logdata.append(record.getMessage())
-
- # Move cooker to use my special logging
- logger = bb.cooker.logger
- log_handler = LogHandler()
- logger.addHandler(log_handler)
- collection = bb.cooker.CookerCollectFiles(bbfile_config_priorities)
- collection.collection_priorities(pkgfns, pkgfns, self.d)
- logger.removeHandler(log_handler)
-
- # Should be empty (no generated messages)
- expected = []
-
- self.assertEqual(log_handler.logdata, expected)
-
-
class BuildFileTest(_BitbakeSubprocessTestCase):
"""Tests for the buildfile ("bitbake -b") mode."""
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 08/17] default-registry: Update for new layer names
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (5 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 07/17] tests/cooker: Drop obsolete collections test Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 09/17] utils: Switch to use layerdata in get_file_layer() Richard Purdie
` (8 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
With the layer changes, various layers are changing names. Update the
fragment references to use the new names.
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
default-registry/configurations/oe-nodistro-master.conf.json | 2 +-
default-registry/configurations/poky-master.conf.json | 4 ++--
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/default-registry/configurations/oe-nodistro-master.conf.json b/default-registry/configurations/oe-nodistro-master.conf.json
index c5d966618d4..cce21be0ad6 100644
--- a/default-registry/configurations/oe-nodistro-master.conf.json
+++ b/default-registry/configurations/oe-nodistro-master.conf.json
@@ -30,7 +30,7 @@
"description": "OpenEmbedded 'nodistro'",
"setup-dir-name": "oe-nodistro-master",
"bb-layers": ["openembedded-core/meta"],
- "oe-fragments": ["core/yocto/monitor-disk-space"],
+ "oe-fragments": ["oe-core/yocto/monitor-disk-space"],
"oe-fragments-one-of": {
"machine": {
"description": "Target machines",
diff --git a/default-registry/configurations/poky-master.conf.json b/default-registry/configurations/poky-master.conf.json
index 452d933a576..2aa901485be 100644
--- a/default-registry/configurations/poky-master.conf.json
+++ b/default-registry/configurations/poky-master.conf.json
@@ -35,7 +35,7 @@
{
"bb-layers": ["openembedded-core/meta","meta-yocto/meta-yocto-bsp","meta-yocto/meta-poky"],
"setup-dir-name": "$distro-master",
- "oe-fragments": ["core/yocto/monitor-disk-space"],
+ "oe-fragments": ["oe-core/yocto/monitor-disk-space"],
"oe-fragments-one-of": {
"machine": {
"description": "Target machines",
@@ -64,7 +64,7 @@
{
"name": "poky-with-sstate",
"description": "Poky - The Yocto Project testing distribution with internet sstate acceleration. Use with caution as it requires a completely robust local network with sufficient bandwidth.",
- "oe-fragments": ["core/yocto/sstate-mirror-cdn"]
+ "oe-fragments": ["oe-core/yocto/sstate-mirror-cdn"]
}
]
}
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 09/17] utils: Switch to use layerdata in get_file_layer()
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (6 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 08/17] default-registry: Update for new layer names Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 10/17] utils: Add bb.utils.have_layer() to simplify metadata layer checks Richard Purdie
` (7 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
After the layer changes, we should use layerdata to obtain layer
information.
Add an indirect function for when layerdata is already present
so IPC can be avoided when using tinfoil. This is used by bblayers
to avoid code duplication.
The code correctly resolves symlinks to the correct layer.
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
lib/bb/utils.py | 79 ++++++++++++++++++++++---------------------------
1 file changed, 35 insertions(+), 44 deletions(-)
diff --git a/lib/bb/utils.py b/lib/bb/utils.py
index 046bf4b8bc6..94e27dcaa52 100644
--- a/lib/bb/utils.py
+++ b/lib/bb/utils.py
@@ -1868,59 +1868,50 @@ def edit_bblayers_conf(bblayers_conf, add, remove, edit_cb=None):
return (notadded, notremoved)
-def get_collection_res(d):
- collections = (d.getVar('BBFILE_COLLECTIONS') or '').split()
- collection_res = {}
- for collection in collections:
- collection_res[collection] = d.getVar('BBFILE_PATTERN_%s' % collection) or ''
- return collection_res
+def get_file_layer_from_layerdata(filename, layerdata):
+ """Determine the layer containing the specified file from a layerdata
+ dictionary, as set in the ``layerdata`` variable. This is useful where
+ the layerdata has already been obtained, avoiding the variable lookup.
+
+ Arguments:
+
+ - ``filename``: the filename to look for.
+ - ``layerdata``: dictionary of layer names to layer information.
+
+ Returns the name of the layer containing the file, or ``None`` if the
+ file isn't within any of the layers.
+ """
+ def find(fn):
+ # Layers can't nest so the first match is the only match
+ for layername, layer in layerdata.items():
+ if fn.startswith(layer.path + "/"):
+ return layername
+ return None
+
+ # The layer paths are canonical. The filename as given usually matches
+ # so only resolve it if it doesn't.
+ layername = find(filename)
+ if layername is None:
+ realfn = os.path.realpath(filename)
+ if realfn != filename:
+ layername = find(realfn)
+ return layername
-def get_file_layer(filename, d, collection_res={}):
- """Determine the collection (or layer name, as defined by a layer's
+def get_file_layer(filename, d):
+ """Determine the layer (as named by ``LAYERNAME`` in the layer's
``layer.conf`` file) containing the specified file.
Arguments:
- ``filename``: the filename to look for.
- ``d``: the data store.
- - ``collection_res``: dictionary with the layer names as keys and file
- patterns to match as defined with the BBFILE_COLLECTIONS and
- BBFILE_PATTERN variables respectively. The return value of
- ``bb.utils.get_collection_res()`` is the default if this variable is
- not specified.
-
- Returns the layer name containing the file. If multiple layers contain the
- file, the last matching layer name from collection_res is returned.
- """
- if not collection_res:
- collection_res = get_collection_res(d)
-
- def path_to_layer(path):
- # Use longest path so we handle nested layers
- matchlen = 0
- match = None
- for collection, regex in collection_res.items():
- if len(regex) > matchlen and re.match(regex, path):
- matchlen = len(regex)
- match = collection
- return match
-
- result = None
- bbfiles = (d.getVar('BBFILES_PRIORITIZED') or '').split()
- bbfilesmatch = False
- for bbfilesentry in bbfiles:
- if fnmatch.fnmatchcase(filename, bbfilesentry):
- bbfilesmatch = True
- result = path_to_layer(bbfilesentry)
- break
-
- if not bbfilesmatch:
- # Probably a bbclass
- result = path_to_layer(filename)
-
- return result
+
+ Returns the name of the layer containing the file, or ``None`` if the
+ file isn't within any configured layer.
+ """
+ return get_file_layer_from_layerdata(filename, d.getVar('layerdata', False) or {})
# Constant taken from http://linux.die.net/include/linux/prctl.h
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 10/17] utils: Add bb.utils.have_layer() to simplify metadata layer checks
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (7 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 09/17] utils: Switch to use layerdata in get_file_layer() Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 11/17] layerindexlib/cooker: Switch to Use layerdata data struture Richard Purdie
` (6 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
Rather than repeat this pattern in many layers, have a simple helper
function in case we ever need to change internals and to make the
code clearer/simpler.
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
lib/bb/utils.py | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/lib/bb/utils.py b/lib/bb/utils.py
index 94e27dcaa52..e4e50072135 100644
--- a/lib/bb/utils.py
+++ b/lib/bb/utils.py
@@ -1913,6 +1913,10 @@ def get_file_layer(filename, d):
"""
return get_file_layer_from_layerdata(filename, d.getVar('layerdata', False) or {})
+def have_layer(layer, d, trueval=True, falseval=False):
+ if layer in d.getVar('layerdata', False):
+ return trueval
+ return falseval
# Constant taken from http://linux.die.net/include/linux/prctl.h
PR_SET_PDEATHSIG = 1
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 11/17] layerindexlib/cooker: Switch to Use layerdata data struture
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (8 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 10/17] utils: Add bb.utils.have_layer() to simplify metadata layer checks Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 12/17] bblayers: Switch to use layerdata and new format layers Richard Purdie
` (5 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
Update to use the new layerdata structure after the layer changes.
Update the test layers to match the new format.
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
lib/layerindexlib/cooker.py | 31 +++++++------------
lib/layerindexlib/tests/cooker.py | 15 ++++++++-
.../tests/testdata/layer1/conf/layer.conf | 13 ++------
.../tests/testdata/layer2/conf/layer.conf | 23 +++++---------
.../tests/testdata/layer3/conf/layer.conf | 18 +++--------
.../tests/testdata/layer4/conf/layer.conf | 23 ++++----------
6 files changed, 47 insertions(+), 76 deletions(-)
diff --git a/lib/layerindexlib/cooker.py b/lib/layerindexlib/cooker.py
index 82d77335f9a..0af92eec51b 100644
--- a/lib/layerindexlib/cooker.py
+++ b/lib/layerindexlib/cooker.py
@@ -93,9 +93,7 @@ class CookerPlugin(layerindexlib.plugin.IndexPlugin):
# It's blank! Nothing to process...
return index
- collections = d.getVar('BBFILE_COLLECTIONS')
- layerconfs = d.varhistory.get_variable_items_files('BBFILE_COLLECTIONS')
- bbfile_collections = {layer: os.path.dirname(os.path.dirname(path)) for layer, path in layerconfs.items()}
+ layerdata = d.getVar('layerdata', False) or {}
(_, bb_branch, _, _) = self._get_bitbake_info()
@@ -104,13 +102,11 @@ class CookerPlugin(layerindexlib.plugin.IndexPlugin):
index.branches[branchId] = layerindexlib.Branch(index, None)
index.branches[branchId].define_data(branchId, branch, bb_branch)
- for entry in collections.split():
- layerpath = entry
- if entry in bbfile_collections:
- layerpath = bbfile_collections[entry]
+ for entry, layer in layerdata.items():
+ layerpath = layer.path
layername = d.getVar('BBLAYERS_LAYERINDEX_NAME_%s' % entry) or os.path.basename(layerpath)
- layerversion = d.getVar('LAYERVERSION_%s' % entry) or ""
+ layerversion = layer.version or ""
layerurl = self._handle_git_remote(layerpath)
layersubdir = ""
@@ -164,6 +160,7 @@ class CookerPlugin(layerindexlib.plugin.IndexPlugin):
raise layerindexlib.plugin.LayerIndexPluginUrlError(self.type, url)
d = self.layerindex.data
+ layerdata = d.getVar('layerdata', False) or {}
params = self.layerindex._parse_params(up.params)
@@ -199,12 +196,7 @@ class CookerPlugin(layerindexlib.plugin.IndexPlugin):
branchName = index.layerBranches[layerBranchId].branch.name
collection = index.layerBranches[layerBranchId].collection
- def add_dependency(layerDependencyId, index, deps, required):
- try:
- depDict = bb.utils.explode_dep_versions2(deps)
- except bb.utils.VersionStringException as vse:
- bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (collection, str(vse)))
-
+ def add_dependency(layerDependencyId, index, depDict, required):
for dep, oplist in list(depDict.items()):
# We need to search ourselves, so use the _ version...
depLayerBranch = index.find_collection(dep, branches=[branchName])
@@ -225,13 +217,12 @@ class CookerPlugin(layerindexlib.plugin.IndexPlugin):
return layerDependencyId
- deps = d.getVar("LAYERDEPENDS_%s" % collection)
- if deps:
- layerDependencyId = add_dependency(layerDependencyId, index, deps, True)
+ layer = layerdata.get(collection)
+ if layer and layer.depends:
+ layerDependencyId = add_dependency(layerDependencyId, index, layer.depends, True)
- deps = d.getVar("LAYERRECOMMENDS_%s" % collection)
- if deps:
- layerDependencyId = add_dependency(layerDependencyId, index, deps, False)
+ if layer and layer.recommends:
+ layerDependencyId = add_dependency(layerDependencyId, index, layer.recommends, False)
# Need to load recipes here (requires cooker access)
recipeId = 0
diff --git a/lib/layerindexlib/tests/cooker.py b/lib/layerindexlib/tests/cooker.py
index 5ddf89aa211..04c5483783e 100644
--- a/lib/layerindexlib/tests/cooker.py
+++ b/lib/layerindexlib/tests/cooker.py
@@ -5,6 +5,7 @@
import os
import bb
+import bb.cookerdata
import layerindexlib
from layerindexlib.tests.common import LayersTest
@@ -26,8 +27,20 @@ class LayerIndexCookerTest(LayersTest):
self.d.setVar('BBPATH', new_bbpath)
self.d = bb.parse.handle("%s/conf/bblayers.conf" % new_bbpath, self.d, True)
+ layerdata = {}
for layer in self.d.getVar('BBLAYERS').split():
- self.d = bb.parse.handle("%s/conf/layer.conf" % layer, self.d, True)
+ ld = bb.parse.handle("%s/conf/layer.conf" % layer, self.d.createCopy(), True)
+ layername = ld.getVar('LAYERNAME')
+ layerdata[layername] = bb.cookerdata.Layer(
+ path=layer,
+ version=ld.getVar('LAYERVERSION') or "1",
+ depends=bb.utils.explode_dep_versions2(ld.getVar('LAYERDEPENDS') or ""),
+ recommends=bb.utils.explode_dep_versions2(ld.getVar('LAYERRECOMMENDS') or ""),
+ )
+ indexname = ld.getVar('BBLAYERS_LAYERINDEX_NAME_%s' % layername)
+ if indexname:
+ self.d.setVar('BBLAYERS_LAYERINDEX_NAME_%s' % layername, indexname)
+ self.d.setVar('layerdata', layerdata)
self.layerindex = layerindexlib.LayerIndex(self.d)
self.layerindex.load_layerindex('cooker://', load=['layerDependencies'])
diff --git a/lib/layerindexlib/tests/testdata/layer1/conf/layer.conf b/lib/layerindexlib/tests/testdata/layer1/conf/layer.conf
index 966d5319596..dbabd91e6c5 100644
--- a/lib/layerindexlib/tests/testdata/layer1/conf/layer.conf
+++ b/lib/layerindexlib/tests/testdata/layer1/conf/layer.conf
@@ -1,17 +1,10 @@
-# We have a conf and classes directory, add to BBPATH
-BBPATH .= ":${LAYERDIR}"
-# We have recipes-* directories, add to BBFILES
-BBFILES += "${LAYERDIR}/recipes-*/*/*.bb"
-
-BBFILE_COLLECTIONS += "core"
-BBFILE_PATTERN_core = "^${LAYERDIR}/"
-BBFILE_PRIORITY_core = "5"
+LAYERNAME = "core"
LAYERSERIES_CORENAMES = "sumo"
# This should only be incremented on significant changes that will
# cause compatibility issues with other layers
-LAYERVERSION_core = "11"
-LAYERSERIES_COMPAT_core = "sumo"
+LAYERVERSION = "11"
+LAYERSERIES_COMPAT = "sumo"
BBLAYERS_LAYERINDEX_NAME_core = "openembedded-core"
diff --git a/lib/layerindexlib/tests/testdata/layer2/conf/layer.conf b/lib/layerindexlib/tests/testdata/layer2/conf/layer.conf
index 7569d1c2172..cea7d19d950 100644
--- a/lib/layerindexlib/tests/testdata/layer2/conf/layer.conf
+++ b/lib/layerindexlib/tests/testdata/layer2/conf/layer.conf
@@ -1,20 +1,13 @@
-# We have a conf and classes directory, add to BBPATH
-BBPATH .= ":${LAYERDIR}"
-
-# We have a packages directory, add to BBFILES
-BBFILES += "${LAYERDIR}/recipes-*/*/*.bb \
- ${LAYERDIR}/recipes-*/*/*.bbappend"
-
-BBFILE_COLLECTIONS += "networking-layer"
-BBFILE_PATTERN_networking-layer := "^${LAYERDIR}/"
-BBFILE_PRIORITY_networking-layer = "5"
+LAYERNAME = "networking-layer"
# This should only be incremented on significant changes that will
# cause compatibility issues with other layers
-LAYERVERSION_networking-layer = "1"
+LAYERVERSION = "1"
+
+LAYERDEPENDS = "core"
+LAYERDEPENDS += "openembedded-layer"
+LAYERDEPENDS += "meta-python"
-LAYERDEPENDS_networking-layer = "core"
-LAYERDEPENDS_networking-layer += "openembedded-layer"
-LAYERDEPENDS_networking-layer += "meta-python"
+LAYERSERIES_COMPAT = "sumo"
-LAYERSERIES_COMPAT_networking-layer = "sumo"
+BBLAYERS_LAYERINDEX_NAME_networking-layer = "networking-layer"
diff --git a/lib/layerindexlib/tests/testdata/layer3/conf/layer.conf b/lib/layerindexlib/tests/testdata/layer3/conf/layer.conf
index 7089071faf6..af089a7ca11 100644
--- a/lib/layerindexlib/tests/testdata/layer3/conf/layer.conf
+++ b/lib/layerindexlib/tests/testdata/layer3/conf/layer.conf
@@ -1,19 +1,11 @@
-# We might have a conf and classes directory, append to BBPATH
-BBPATH .= ":${LAYERDIR}"
-
-# We have recipes directories, add to BBFILES
-BBFILES += "${LAYERDIR}/recipes*/*/*.bb ${LAYERDIR}/recipes*/*/*.bbappend"
-
-BBFILE_COLLECTIONS += "meta-python"
-BBFILE_PATTERN_meta-python := "^${LAYERDIR}/"
-BBFILE_PRIORITY_meta-python = "7"
+LAYERNAME = "meta-python"
# This should only be incremented on significant changes that will
# cause compatibility issues with other layers
-LAYERVERSION_meta-python = "1"
+LAYERVERSION = "1"
-LAYERDEPENDS_meta-python = "core openembedded-layer"
+LAYERDEPENDS = "core openembedded-layer"
-LAYERSERIES_COMPAT_meta-python = "sumo"
+LAYERSERIES_COMPAT = "sumo"
-LICENSE_PATH += "${LAYERDIR}/licenses"
+BBLAYERS_LAYERINDEX_NAME_meta-python = "meta-python"
diff --git a/lib/layerindexlib/tests/testdata/layer4/conf/layer.conf b/lib/layerindexlib/tests/testdata/layer4/conf/layer.conf
index 6649ee02081..974ebac002f 100644
--- a/lib/layerindexlib/tests/testdata/layer4/conf/layer.conf
+++ b/lib/layerindexlib/tests/testdata/layer4/conf/layer.conf
@@ -1,22 +1,11 @@
-# We have a conf and classes directory, append to BBPATH
-BBPATH .= ":${LAYERDIR}"
-
-# We have a recipes directory, add to BBFILES
-BBFILES += "${LAYERDIR}/recipes-*/*/*.bb ${LAYERDIR}/recipes-*/*/*.bbappend"
-
-BBFILE_COLLECTIONS += "openembedded-layer"
-BBFILE_PATTERN_openembedded-layer := "^${LAYERDIR}/"
-
-# Define the priority for recipes (.bb files) from this layer,
-# choosing carefully how this layer interacts with all of the
-# other layers.
-
-BBFILE_PRIORITY_openembedded-layer = "6"
+LAYERNAME = "openembedded-layer"
# This should only be incremented on significant changes that will
# cause compatibility issues with other layers
-LAYERVERSION_openembedded-layer = "1"
+LAYERVERSION = "1"
+
+LAYERDEPENDS = "core"
-LAYERDEPENDS_openembedded-layer = "core"
+LAYERSERIES_COMPAT = "sumo"
-LAYERSERIES_COMPAT_openembedded-layer = "sumo"
+BBLAYERS_LAYERINDEX_NAME_openembedded-layer = "openembedded-layer"
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 12/17] bblayers: Switch to use layerdata and new format layers
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (9 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 11/17] layerindexlib/cooker: Switch to Use layerdata data struture Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 13/17] tests/runqueue: Add a test for RecipeCheckEvent/BB_CACHE_EXTRAVARS Richard Purdie
` (4 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
Switch to use the new layerdata structure after the layer changes.
The output does change as layers no longer have priorities.
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
lib/bblayers/action.py | 65 +++++++++++-------------------------------
lib/bblayers/common.py | 20 +++++++++++--
lib/bblayers/query.py | 41 +++++++-------------------
3 files changed, 44 insertions(+), 82 deletions(-)
diff --git a/lib/bblayers/action.py b/lib/bblayers/action.py
index a14f19948e1..7ee326946fa 100644
--- a/lib/bblayers/action.py
+++ b/lib/bblayers/action.py
@@ -4,7 +4,6 @@
# SPDX-License-Identifier: GPL-2.0-only
#
-import fnmatch
import logging
import os
import shutil
@@ -103,16 +102,17 @@ cleanup may still be necessary afterwards, in particular:
* where non-recipe files (such as patches) are overwritten (the flatten
command will show a warning for these)
* where anything beyond the normal layer setup has been added to
- layer.conf (only the lowest priority number layer's layer.conf is used)
+ layer.conf (only the first layer's layer.conf is used, so the
+ flattened layer takes that layer's LAYERNAME and LAYERDEPENDS)
* overridden/appended items from bbappends will need to be tidied up
* when the flattened layers do not have the same directory structure (the
flatten command should show a warning when this will cause a problem)
Warning: if you flatten several layers where another layer is intended to
-be used "inbetween" them (in layer priority order) such that recipes /
-bbappends in the layers interact, and then attempt to use the new output
-layer together with that other layer, you may no longer get the same
-build results (as the layer priority order has effectively changed).
+be used "inbetween" them such that recipes / bbappends in the layers
+interact, and then attempt to use the new output layer together with that
+other layer, you may no longer get the same build results (as the layer
+ordering has effectively changed).
"""
if len(args.layer) == 1:
logger.error('If you specify layers to flatten you must specify at least two')
@@ -212,53 +212,20 @@ build results (as the layer priority order has effectively changed).
bb.utils.copyfile(appendname, fdest)
first_append = fdest
- # Get the regex for the first layer in our list (which is where the conf/layer.conf file will
- # have come from)
- first_regex = None
- layerdir = layers[0]
- for layername, pattern, regex, _ in self.tinfoil.cooker.bbfile_config_priorities:
- if regex.match(os.path.join(layerdir, 'test')):
- first_regex = regex
- break
-
- if first_regex:
- # Find the BBFILES entries that match (which will have come from this conf/layer.conf file)
- bbfiles = str(self.tinfoil.config_data.getVar('BBFILES')).split()
- bbfiles_layer = []
- for item in bbfiles:
- if first_regex.match(item):
- newpath = os.path.join(outputdir, item[len(layerdir)+1:])
- bbfiles_layer.append(newpath)
-
- if bbfiles_layer:
- # Check that all important layer files match BBFILES
- for root, dirs, files in os.walk(outputdir):
- for f1 in files:
- ext = os.path.splitext(f1)[1]
- if ext in ['.bb', '.bbappend']:
- f1full = os.sep.join([root, f1])
- entry_found = False
- for item in bbfiles_layer:
- if fnmatch.fnmatch(f1full, item):
- entry_found = True
- break
- if not entry_found:
- logger.warning("File %s does not match the flattened layer's BBFILES setting, you may need to edit conf/layer.conf or move the file elsewhere" % f1full)
+ # Bitbake only looks for recipes and bbappends within a layer's recipes*
+ # directories (and dynamic-recipes/<layername>/), check the flattened
+ # layer's files will still be found
+ for root, dirs, files in os.walk(outputdir):
+ for f1 in files:
+ if f1.endswith(('.bb', '.bbappend')):
+ f1full = os.path.join(root, f1)
+ topdir = os.path.relpath(f1full, outputdir).split(os.sep)[0]
+ if not (topdir.startswith('recipes') or topdir == 'dynamic-recipes'):
+ logger.warning("File %s is not within a recipes* directory of the flattened layer so will not be found, you may need to move it" % f1full)
self.tinfoil.modified_files()
- def get_file_layer(self, filename):
- layerdir = self.get_file_layerdir(filename)
- if layerdir:
- return self.get_layer_name(layerdir)
- else:
- return '?'
-
- def get_file_layerdir(self, filename):
- layer = bb.utils.get_file_layer(filename, self.tinfoil.config_data)
- return self.bbfile_collections.get(layer, None)
-
def apply_append(self, appendname, recipename):
with open(appendname, 'r') as appendfile:
with open(recipename, 'a') as recipefile:
diff --git a/lib/bblayers/common.py b/lib/bblayers/common.py
index f7b9cee3717..6a97476aa2a 100644
--- a/lib/bblayers/common.py
+++ b/lib/bblayers/common.py
@@ -8,6 +8,8 @@ import argparse
import logging
import os
+import bb.utils
+
logger = logging.getLogger('bitbake-layers')
@@ -15,12 +17,12 @@ class LayerPlugin():
def __init__(self):
self.tinfoil = None
self.bblayers = []
+ self.layerdata = {}
def tinfoil_init(self, tinfoil):
self.tinfoil = tinfoil
self.bblayers = (self.tinfoil.config_data.getVar('BBLAYERS') or "").split()
- layerconfs = self.tinfoil.config_data.varhistory.get_variable_items_files('BBFILE_COLLECTIONS')
- self.bbfile_collections = {layer: os.path.dirname(os.path.dirname(path)) for layer, path in layerconfs.items()}
+ self.layerdata = self.tinfoil.config_data.getVar('layerdata', False) or {}
@staticmethod
def add_command(subparsers, cmdname, function, parserecipes=True, *args, **kwargs):
@@ -37,3 +39,17 @@ class LayerPlugin():
def get_layer_name(self, layerdir):
return os.path.basename(layerdir.rstrip(os.sep))
+
+ def get_file_layerdir(self, filename):
+ """Return the directory of the configured layer containing filename, or None"""
+ layername = bb.utils.get_file_layer_from_layerdata(filename, self.layerdata)
+ if layername:
+ return self.layerdata[layername].path
+ return None
+
+ def get_file_layer(self, filename):
+ layerdir = self.get_file_layerdir(filename)
+ if layerdir:
+ return self.get_layer_name(layerdir)
+ else:
+ return '?'
diff --git a/lib/bblayers/query.py b/lib/bblayers/query.py
index 7b8d1afd719..385e965e9ca 100644
--- a/lib/bblayers/query.py
+++ b/lib/bblayers/query.py
@@ -25,16 +25,14 @@ def plugin_init(plugins):
class QueryPlugin(LayerPlugin):
def __init__(self):
super(QueryPlugin, self).__init__()
- self.collection_res = {}
def do_show_layers(self, args):
"""show current configured layers."""
- logger.plain("%s %s %s" % ("layer".ljust(20), "path".ljust(70), "priority"))
- logger.plain('=' * 104)
- for layer, _, regex, pri in self.tinfoil.cooker.bbfile_config_priorities:
- layerdir = self.bbfile_collections.get(layer, None)
- layername = layer
- logger.plain("%s %s %s" % (layername.ljust(20), layerdir.ljust(70), pri))
+ logger.plain("%s %s %s %s" % ("layer".ljust(20), "path".ljust(70), "version".ljust(7), "depends"))
+ logger.plain('=' * 113)
+ for layername, layer in self.layerdata.items():
+ depends = bb.utils.join_deps(layer.depends, commasep=False)
+ logger.plain("%s %s %s %s" % (layername.ljust(20), layer.path.ljust(70), str(layer.version).ljust(7), depends))
def version_str(self, pe, pv, pr = None):
verstr = "%s" % pv
@@ -65,12 +63,9 @@ are overlayed will also be listed, with a " (skipped)" suffix.
classes[classfile].append(classdir)
# Locating classes and other files is a bit more complicated than recipes -
- # layer priority is not a factor; instead BitBake uses the first matching
- # file in BBPATH, which is manipulated directly by each layer's
- # conf/layer.conf in turn, thus the order of layers in bblayers.conf is a
- # factor - however, each layer.conf is free to either prepend or append to
- # BBPATH (or indeed do crazy stuff with it). Thus the order in BBPATH might
- # not be exactly the order present in bblayers.conf either.
+ # BitBake uses the first matching file in BBPATH, which is constructed
+ # from the layer dependencies (layers come before the layers they depend
+ # upon) so the order may not match the order present in bblayers.conf.
bbpath = str(self.tinfoil.config_data.getVar('BBPATH'))
overlayed_class_found = False
for (classfile, classdirs) in classes.items():
@@ -255,22 +250,6 @@ skipped recipes will also be listed, with a " (skipped)" suffix.
return items_listed
- def get_file_layer(self, filename):
- layerdir = self.get_file_layerdir(filename)
- if layerdir:
- return self.get_layer_name(layerdir)
- else:
- return '?'
-
- def get_collection_res(self):
- if not self.collection_res:
- self.collection_res = bb.utils.get_collection_res(self.tinfoil.config_data)
- return self.collection_res
-
- def get_file_layerdir(self, filename):
- layer = bb.utils.get_file_layer(filename, self.tinfoil.config_data, self.get_collection_res())
- return self.bbfile_collections.get(layer, None)
-
def remove_layer_prefix(self, f):
"""Remove the layer_dir prefix, e.g., f = /path/to/layer_dir/foo/blah, the
return value will be: layer_dir/foo/blah"""
@@ -527,12 +506,12 @@ NOTE: .bbappend files can impact the dependencies.
self.add_command(sp, 'show-layers', self.do_show_layers, parserecipes=False)
parser_show_overlayed = self.add_command(sp, 'show-overlayed', self.do_show_overlayed)
- parser_show_overlayed.add_argument('-f', '--filenames', help='instead of the default formatting, list filenames of higher priority recipes with the ones they overlay indented underneath', action='store_true')
+ parser_show_overlayed.add_argument('-f', '--filenames', help='instead of the default formatting, list filenames of preferred recipes with the ones they overlay indented underneath', action='store_true')
parser_show_overlayed.add_argument('-s', '--same-version', help='only list overlayed recipes where the version is the same', action='store_true')
parser_show_overlayed.add_argument('--mc', help='use specified multiconfig', default='')
parser_show_recipes = self.add_command(sp, 'show-recipes', self.do_show_recipes)
- parser_show_recipes.add_argument('-f', '--filenames', help='instead of the default formatting, list filenames of higher priority recipes with the ones they overlay indented underneath', action='store_true')
+ parser_show_recipes.add_argument('-f', '--filenames', help='instead of the default formatting, list filenames of preferred recipes with the ones they overlay indented underneath', action='store_true')
parser_show_recipes.add_argument('-r', '--recipes-only', help='instead of the default formatting, list recipes only', action='store_true')
parser_show_recipes.add_argument('-m', '--multiple', help='only list where multiple recipes (in the same layer or different layers) exist for the same recipe name', action='store_true')
parser_show_recipes.add_argument('-i', '--inherits', help='only list recipes that inherit the named class(es) - separate multiple classes using , (without spaces)', metavar='CLASS', default='')
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 13/17] tests/runqueue: Add a test for RecipeCheckEvent/BB_CACHE_EXTRAVARS
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (10 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 12/17] bblayers: Switch to use layerdata and new format layers Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 14/17] tests: Add tests for wildcard version comparisions Richard Purdie
` (3 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
Add a test for the new BB_CACHE_EXTRAVARS code and the associated
event. Check the event is triggered and data is passed through to
the event as expected.
Initial code was from Claude, heavily editted.
AI-Generated: Uses Claude (Opus 5.5)
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
.../classes/recipecheckevent.bbclass | 16 +++++
lib/bb/tests/runqueue.py | 63 +++++++++++++++++--
2 files changed, 74 insertions(+), 5 deletions(-)
create mode 100644 lib/bb/tests/runqueue-tests/classes/recipecheckevent.bbclass
diff --git a/lib/bb/tests/runqueue-tests/classes/recipecheckevent.bbclass b/lib/bb/tests/runqueue-tests/classes/recipecheckevent.bbclass
new file mode 100644
index 00000000000..ec12724e712
--- /dev/null
+++ b/lib/bb/tests/runqueue-tests/classes/recipecheckevent.bbclass
@@ -0,0 +1,16 @@
+#
+# Test helper for BB_CACHE_EXTRAVARS: records the per-recipe values passed to
+# event handlers through bb.runqueue.RecipeCheckEvent as JSON in
+# ${TOPDIR}/extravars.json, keyed by recipe file basename.
+#
+
+addhandler extravars_test_handler
+extravars_test_handler[eventmask] = "bb.runqueue.RecipeCheckEvent"
+python extravars_test_handler() {
+ import json
+ result = {}
+ for fn, values in e.recipedata.items():
+ result[os.path.basename(fn)] = values
+ with open(e.data.expand("${TOPDIR}/extravars.json"), "w") as f:
+ json.dump(result, f, sort_keys=True)
+}
diff --git a/lib/bb/tests/runqueue.py b/lib/bb/tests/runqueue.py
index d8c49f8c0c0..9b4287aaf96 100644
--- a/lib/bb/tests/runqueue.py
+++ b/lib/bb/tests/runqueue.py
@@ -12,13 +12,14 @@ import tempfile
import subprocess
import sys
import time
+import json
#
# TODO:
# Add tests on task ordering (X happens before Y after Z)
#
-class RunQueueTests(unittest.TestCase):
+class RunQueueBase(unittest.TestCase):
alltasks = ['package', 'fetch', 'unpack', 'patch', 'prepare_recipe_sysroot', 'configure',
'compile', 'install', 'packagedata', 'package_qa', 'package_write_rpm', 'package_write_ipk',
@@ -53,6 +54,13 @@ class RunQueueTests(unittest.TestCase):
os.remove(tasklog)
return tasks
+ def shutdown(self, tempdir):
+ # Wait for the hashserve socket to disappear else we'll see races with the tempdir cleanup
+ while (os.path.exists(tempdir + "/hashserve.sock") or os.path.exists(tempdir + "cache/hashserv.db-wal") or os.path.exists(tempdir + "/bitbake.lock")):
+ time.sleep(0.5)
+
+class RunQueueTests(RunQueueBase):
+
def test_no_setscenevalid(self):
with tempfile.TemporaryDirectory(prefix="runqueuetest") as tempdir:
cmd = ["bitbake", "a1"]
@@ -427,8 +435,53 @@ class RunQueueTests(unittest.TestCase):
self.shutdown(tempdir)
- def shutdown(self, tempdir):
- # Wait for the hashserve socket to disappear else we'll see races with the tempdir cleanup
- while (os.path.exists(tempdir + "/hashserve.sock") or os.path.exists(tempdir + "cache/hashserv.db-wal") or os.path.exists(tempdir + "/bitbake.lock")):
- time.sleep(0.5)
+# Test BB_CACHE_EXTRAVARS and RecipeCheckEvent
+class cacheExtraVarsTests(RunQueueBase):
+
+ def trigger_recipecheckevent(self, tempdir, conf, targets):
+ # Helper to write the config, run bitbake and trigger RecipeCheckEvent
+ # returning json data of the event
+ postconf = os.path.join(tempdir, "extravars.conf")
+ with open(postconf, "w") as f:
+ f.write('INHERIT += "recipecheckevent"\n' + conf)
+ result = os.path.join(tempdir, "extravars.json")
+ if os.path.exists(result):
+ os.remove(result)
+ try:
+ output = self.run_bitbakecmd(["bitbake", "-R", postconf] + targets, tempdir, cleanup=True)
+ self.assertTrue(os.path.exists(result), "RecipeCheckEvent handler did not run")
+ with open(result) as f:
+ return json.load(f)
+ finally:
+ if os.path.exists(result):
+ os.remove(result)
+
+ def test_cache_extravars(self):
+ # Check variables listed in BB_CACHE_EXTRAVARS are stored in the recipe
+ # cache and passed to RecipeCheckEvent.
+
+ conf = 'OVERRIDES = "pn-${PN}"\n' \
+ 'BB_CACHE_EXTRAVARS = "EXTRAVAR_A EXTRAVAR_B EXTRAVAR_UNSET"\n' \
+ 'EXTRAVAR_A = "default"\n' \
+ 'EXTRAVAR_A:pn-a1 = "a1-value"\n' \
+ 'EXTRAVAR_B = "${PN}-b"\n' \
+ 'EXTRAVAR_UNLISTED = "should-not-appear"\n'
+ expected = {
+ "a1.bb": {"EXTRAVAR_A": "a1-value", "EXTRAVAR_B": "a1-b", "EXTRAVAR_UNSET": ""},
+ "b1.bb": {"EXTRAVAR_A": "default", "EXTRAVAR_B": "b1-b", "EXTRAVAR_UNSET": ""},
+ }
+ with tempfile.TemporaryDirectory(prefix="runqueuetest") as tempdir:
+ # b1 depends on a1, so both expected
+ data = self.trigger_recipecheckevent(tempdir, conf, ["b1"])
+ self.assertEqual(data, expected)
+
+ self.shutdown(tempdir)
+
+ def test_cache_extravars_unset(self):
+ # Without BB_CACHE_EXTRAVARS the event still fires, with no values
+ with tempfile.TemporaryDirectory(prefix="runqueuetest") as tempdir:
+ data = self.trigger_recipecheckevent(tempdir, "", ["a1"])
+ self.assertEqual(data, {"a1.bb": {}})
+
+ self.shutdown(tempdir)
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 14/17] tests: Add tests for wildcard version comparisions
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (11 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 13/17] tests/runqueue: Add a test for RecipeCheckEvent/BB_CACHE_EXTRAVARS Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 15/17] tests/layers: Add tests after layer changes Richard Purdie
` (2 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
Given the recent bug identified, add some tests for the
provider version wildcard handling.
AI-Generated: Uses Claude (Opus 5.5)
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
bin/bitbake-selftest | 1 +
lib/bb/tests/providers.py | 147 ++++++++++++++++++++++++++++++++++++++
2 files changed, 148 insertions(+)
mode change 100755 => 100644 bin/bitbake-selftest
create mode 100644 lib/bb/tests/providers.py
diff --git a/bin/bitbake-selftest b/bin/bitbake-selftest
old mode 100755
new mode 100644
index e5a68ba1db5..48820b6716b
--- a/bin/bitbake-selftest
+++ b/bin/bitbake-selftest
@@ -34,6 +34,7 @@ tests = ["bb.tests.codeparser",
"bb.tests.fetch",
"bb.tests.fetch_import",
"bb.tests.parse",
+ "bb.tests.providers",
"bb.tests.runqueue",
"bb.tests.server",
"bb.tests.setup",
diff --git a/lib/bb/tests/providers.py b/lib/bb/tests/providers.py
new file mode 100644
index 00000000000..614ee6aa4eb
--- /dev/null
+++ b/lib/bb/tests/providers.py
@@ -0,0 +1,147 @@
+#
+# BitBake Tests for the provider selection code (providers.py)
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import itertools
+import logging
+import unittest
+
+import bb
+import bb.data
+import bb.providers
+
+
+class FakeDataCache:
+ """
+ Minimal stand-in for the parsed recipe cache, holding only the fields
+ that bb.providers reads.
+ """
+ def __init__(self):
+ self.pkg_pn = {}
+ self.pkg_fn = {}
+ self.pkg_pepvpr = {}
+ self.pkg_dp = {}
+ self.preferred = {}
+
+ def add(self, pn, pv, pe=None, pr="r0", dp=0, fn=None):
+ if fn is None:
+ fn = "/layer/recipes/%s/%s_%s.bb" % (pn, pn, pv)
+ self.pkg_pn.setdefault(pn, []).append(fn)
+ self.pkg_fn[fn] = pn
+ self.pkg_pepvpr[fn] = (pe, pv, pr)
+ self.pkg_dp[fn] = dp
+ return fn
+
+
+class PreferredVersionWildcardTest(unittest.TestCase):
+ """
+ Regression tests for PREFERRED_VERSION/REQUIRED_VERSION values ending in
+ '%' which match more than one available version. The highest matching
+ version must be selected, independently of the order the recipes were
+ found in, rather than whichever matching file happened to come first.
+ """
+
+ def setUp(self):
+ self.d = bb.data.init()
+ # Silence the expected "not available" warnings in negative tests
+ self.logger = logging.getLogger("BitBake.Provider")
+ self.oldlevel = self.logger.level
+ self.logger.setLevel(logging.CRITICAL)
+
+ def tearDown(self):
+ self.logger.setLevel(self.oldlevel)
+
+ def make_cache(self, versions, pn="foo"):
+ cache = FakeDataCache()
+ files = {}
+ for pv in versions:
+ files[pv] = cache.add(pn, pv)
+ return cache, files
+
+ def best(self, cache, pn="foo"):
+ # Returns (latest, latest_f, preferred_ver, preferred_file, required)
+ return bb.providers.findBestProvider(pn, self.d, cache)
+
+ def test_wildcard_selects_highest_match(self):
+ self.d.setVar("PREFERRED_VERSION_foo", "1.%")
+ cache, files = self.make_cache(["1.0", "1.2", "2.0"])
+ _, _, pref_ver, pref_file, required = self.best(cache)
+ self.assertEqual(pref_file, files["1.2"])
+ self.assertEqual(pref_ver, (None, "1.2", "r0"))
+ self.assertFalse(required)
+
+ def test_wildcard_uses_version_ordering(self):
+ # 1.10 > 1.9 > 1.2 by version comparison, but not by string comparison
+ self.d.setVar("PREFERRED_VERSION_foo", "1.%")
+ cache, files = self.make_cache(["1.2", "1.10", "1.9", "2.0"])
+ _, _, _, pref_file, _ = self.best(cache)
+ self.assertEqual(pref_file, files["1.10"])
+
+ def test_wildcard_independent_of_recipe_order(self):
+ self.d.setVar("PREFERRED_VERSION_foo", "1.%")
+ versions = ["1.0", "1.1", "1.3", "2.0"]
+ for order in itertools.permutations(versions):
+ with self.subTest(order=order):
+ cache, files = self.make_cache(order)
+ _, _, pref_ver, pref_file, _ = self.best(cache)
+ self.assertEqual(pref_file, files["1.3"])
+ self.assertEqual(pref_ver, (None, "1.3", "r0"))
+
+ def test_wildcard_pn_override(self):
+ self.d.setVar("PREFERRED_VERSION:pn-foo", "1.%")
+ cache, files = self.make_cache(["1.0", "1.5", "2.0"])
+ _, _, _, pref_file, _ = self.best(cache)
+ self.assertEqual(pref_file, files["1.5"])
+
+ def test_wildcard_longer_prefix(self):
+ # "1.2%" matches 1.2 and 1.2.x (and also 1.20), the highest wins
+ self.d.setVar("PREFERRED_VERSION_foo", "1.2%")
+ cache, files = self.make_cache(["1.2", "1.2.3", "1.2.10", "1.3"])
+ _, _, _, pref_file, _ = self.best(cache)
+ self.assertEqual(pref_file, files["1.2.10"])
+
+ def test_wildcard_single_match(self):
+ self.d.setVar("PREFERRED_VERSION_foo", "1.%")
+ cache, files = self.make_cache(["1.4", "2.0", "3.0"])
+ _, _, _, pref_file, _ = self.best(cache)
+ self.assertEqual(pref_file, files["1.4"])
+
+ def test_exact_version_unaffected(self):
+ self.d.setVar("PREFERRED_VERSION_foo", "1.2")
+ cache, files = self.make_cache(["1.0", "1.2", "1.3", "2.0"])
+ _, _, _, pref_file, _ = self.best(cache)
+ self.assertEqual(pref_file, files["1.2"])
+
+ def test_wildcard_no_match_falls_back_to_latest(self):
+ self.d.setVar("PREFERRED_VERSION_foo", "3.%")
+ cache, files = self.make_cache(["1.0", "1.2", "2.0"])
+ latest, latest_f, pref_ver, pref_file, required = self.best(cache)
+ self.assertEqual(latest_f, files["2.0"])
+ self.assertEqual(pref_file, files["2.0"])
+ self.assertFalse(required)
+
+ def test_required_wildcard_selects_highest_match(self):
+ self.d.setVar("REQUIRED_VERSION_foo", "1.%")
+ cache, files = self.make_cache(["1.0", "1.7", "2.0"])
+ _, _, pref_ver, pref_file, required = self.best(cache)
+ self.assertEqual(pref_file, files["1.7"])
+ self.assertEqual(pref_ver, (None, "1.7", "r0"))
+ self.assertTrue(required)
+
+ def test_required_wildcard_no_match(self):
+ self.d.setVar("REQUIRED_VERSION_foo", "3.%")
+ cache, files = self.make_cache(["1.0", "2.0"])
+ _, _, pref_ver, pref_file, required = self.best(cache)
+ self.assertIsNone(pref_file)
+ self.assertIsNone(pref_ver)
+ self.assertTrue(required)
+
+ def test_filterproviders_wildcard(self):
+ # The same selection must be made through filterProviders(), which is
+ # the path taken when resolving a build dependency
+ self.d.setVar("PREFERRED_VERSION_foo", "1.%")
+ cache, files = self.make_cache(["1.0", "1.2", "1.10", "2.0"])
+ eligible, _ = bb.providers.filterProviders(list(files.values()), "foo", self.d, cache)
+ self.assertEqual(eligible[0], files["1.10"])
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 15/17] tests/layers: Add tests after layer changes
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (12 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 14/17] tests: Add tests for wildcard version comparisions Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 16/17] ast/cookerdata: Allow addfragments to be called more than once Richard Purdie
2026-11-30 15:28 ` [PATCH 17/17] tests/layers: Add fragments tests Richard Purdie
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
Add tests for the new style layers covering:
- the per layer information recorded from layer.conf through to the
new layerdata object in the datastore
- error reporting for:
- missing or duplicate LAYERNAME
- nested layers,
- incompatible series
- missing dependencies
- version mismatches
- circular dependencies
- BBPATH and BBFILES being built in dependency order regardless of
BBLAYERS order
- warnings for the removed BBFILE_COLLECTIONS/PRIORITY/PATTERN variables
and for layers setting BBFILES
- variables a layer can set, append to or not overwrite, including
values set by more than one layer
- bb.utils.get_file_layer() and bb.utils.have_layer()
- conf/layervars.conf applying only to recipes in its own layer
- DEFAULT_PREFERENCE set via layervars.conf changing which version of
a recipe is built
AI-Generated: Uses Claude (Opus 5.5)
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
bin/bitbake-selftest | 1 +
lib/bb/tests/layers.py | 472 +++++++++++++++++++++++++++++++++++++++++
2 files changed, 473 insertions(+)
mode change 100644 => 100755 bin/bitbake-selftest
create mode 100644 lib/bb/tests/layers.py
diff --git a/bin/bitbake-selftest b/bin/bitbake-selftest
old mode 100644
new mode 100755
index 48820b6716b..45f0fa71827
--- a/bin/bitbake-selftest
+++ b/bin/bitbake-selftest
@@ -33,6 +33,7 @@ tests = ["bb.tests.codeparser",
"bb.tests.event",
"bb.tests.fetch",
"bb.tests.fetch_import",
+ "bb.tests.layers",
"bb.tests.parse",
"bb.tests.providers",
"bb.tests.runqueue",
diff --git a/lib/bb/tests/layers.py b/lib/bb/tests/layers.py
new file mode 100644
index 00000000000..70767b50b6d
--- /dev/null
+++ b/lib/bb/tests/layers.py
@@ -0,0 +1,472 @@
+#
+# BitBake Tests for layer configuration handling (cookerdata.py)
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import logging
+import os
+import subprocess
+import tempfile
+import time
+import types
+import unittest
+
+import bb
+import bb.cookerdata
+import bb.siggen
+import bb.utils
+
+
+class _LayerBuilder(bb.cookerdata.CookerDataBuilder):
+ def __init__(self, topdir):
+ cfg = types.SimpleNamespace(prefile=[], postfile=[], tracking=False,
+ skip_fragments=True, env={})
+ super().__init__(cfg)
+ self.topdir = topdir
+
+ def _findLayerConf(self, data):
+ return os.path.join(self.topdir, "conf", "bblayers.conf")
+
+
+class LayerTestBase(unittest.TestCase):
+ CORE_CONF = """\
+LAYERNAME = "core"
+LAYERSERIES_CORENAMES = "series1 series2"
+LAYERSERIES_COMPAT = "series1"
+LAYERVERSION = "5"
+LAYER_PASSTHROUGH_VARS_PREFIXES = "PASSVAR"
+"""
+
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory(prefix="bblayertest")
+ self.topdir = os.path.realpath(self._tmp.name)
+ self.layers = []
+ self.bblayers_extra = ""
+ self.add_layer("core", self.CORE_CONF)
+ # bitbake.conf and base.bbclass are found through the BBPATH that is
+ # constructed from the layers
+ self.write("core/conf/bitbake.conf", 'CACHE = "${TOPDIR}/cache"\n')
+ self.write("core/classes/base.bbclass", "")
+
+ def tearDown(self):
+ self._tmp.cleanup()
+
+ def write(self, relpath, content):
+ path = os.path.join(self.topdir, relpath)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w") as f:
+ f.write(content)
+ return path
+
+ def path(self, name):
+ return os.path.join(self.topdir, name)
+
+ def add_layer(self, dirname, conf, listed=True):
+ self.write(os.path.join(dirname, "conf", "layer.conf"), conf)
+ if listed:
+ self.layers.append(self.path(dirname))
+ return self.path(dirname)
+
+ def simple_layer(self, name, extra="", dirname=None):
+ conf = 'LAYERNAME = "%s"\nLAYERSERIES_COMPAT = "series1"\n%s' % (name, extra)
+ return self.add_layer(dirname or name, conf)
+
+ def parse(self):
+ self.write("conf/bblayers.conf",
+ 'BBLAYERS = "%s"\n%s' % (" ".join(self.layers), self.bblayers_extra))
+ builder = _LayerBuilder(self.topdir)
+ return builder.parseConfigurationFiles([], [])
+
+ def parse_fails(self, *expected):
+ """Parse expecting failure; check each expected string is logged."""
+ with self.assertLogs("BitBake", level="ERROR") as logs:
+ with self.assertRaises(bb.BBHandledException):
+ self.parse()
+ output = "\n".join(logs.output)
+ for e in expected:
+ self.assertIn(e, output)
+ return output
+
+
+class LayerDataTest(LayerTestBase):
+
+ def test_basic_layerdata(self):
+ a = self.simple_layer("a", 'LAYERDEPENDS = "core"\nLAYERVERSION = "3"\n')
+ d, layerdata = self.parse()
+ self.assertEqual(set(layerdata), {"core", "a"})
+ self.assertEqual(layerdata["a"].path, a)
+ self.assertEqual(layerdata["a"].version, "3")
+ self.assertEqual(layerdata["a"].compat, {"series1"})
+ self.assertEqual(list(layerdata["a"].depends), ["core"])
+ self.assertEqual(layerdata["core"].version, "5")
+ self.assertEqual(d.getVar("LAYERDIR_a"), a)
+ self.assertEqual(d.getVar("LAYERDIR_core"), self.path("core"))
+ self.assertEqual(d.getVar("LAYERSERIES_CORENAMES"), "series1 series2")
+ self.assertEqual(set(d.getVar("layerdata", False)), set(layerdata))
+
+ def test_default_version(self):
+ self.simple_layer("a")
+ _, layerdata = self.parse()
+ self.assertEqual(layerdata["a"].version, "1")
+
+ def test_suffixed_variables(self):
+ # The old <VAR>_<layername> forms are still accepted
+ self.add_layer("a", 'LAYERNAME = "a"\nLAYERSERIES_COMPAT_a = "series1"\n'
+ 'LAYERDEPENDS_a = "core"\nLAYERVERSION_a = "7"\n')
+ _, layerdata = self.parse()
+ self.assertEqual(layerdata["a"].compat, {"series1"})
+ self.assertEqual(list(layerdata["a"].depends), ["core"])
+ self.assertEqual(layerdata["a"].version, "7")
+
+ def test_trailing_slash_and_symlink(self):
+ self.simple_layer("a")
+ os.symlink(self.path("a"), self.path("a-link"))
+ self.layers[-1] = self.path("a-link") + "/"
+ _, layerdata = self.parse()
+ self.assertEqual(layerdata["a"].path, self.path("a"))
+
+ def test_layerdata_repr_stable(self):
+ # repr() feeds the cache hash so must not depend on set ordering
+ self.simple_layer("a", 'LAYERSERIES_COMPAT = "s3 s1 s2"\n')
+ self.simple_layer("b", 'LAYERSERIES_COMPAT = "s2 s1 s3"\n')
+ self.CORE_CONF = self.CORE_CONF.replace("series1 series2", "s1")
+ self.write("core/conf/layer.conf", self.CORE_CONF.replace('COMPAT = "series1"', 'COMPAT = "s1"'))
+ _, layerdata = self.parse()
+ self.assertIn("compat=['s1', 's2', 's3']", repr(layerdata["a"]))
+ self.assertEqual(repr(layerdata["a"]).replace(self.path("a"), "X"),
+ repr(layerdata["b"]).replace(self.path("b"), "X"))
+
+
+class LayerErrorTest(LayerTestBase):
+
+ def test_missing_layername(self):
+ self.add_layer("a", 'LAYERSERIES_COMPAT = "series1"\n')
+ self.parse_fails("does not set LAYERNAME")
+
+ def test_duplicate_layername(self):
+ self.simple_layer("a")
+ self.simple_layer("a", dirname="a2")
+ self.parse_fails("LAYERNAME a is used by both")
+
+ def test_nested_layers(self):
+ self.simple_layer("a")
+ self.simple_layer("inner", dirname="a/inner")
+ self.parse_fails("Layers can't nest")
+
+ def test_sibling_prefix_is_not_nesting(self):
+ # /x/a and /x/ab share a string prefix but are not nested
+ self.simple_layer("a")
+ self.simple_layer("ab")
+ _, layerdata = self.parse()
+ self.assertEqual(set(layerdata), {"core", "a", "ab"})
+
+ def test_missing_compat(self):
+ self.add_layer("a", 'LAYERNAME = "a"\n')
+ self.parse_fails("Layer a should set LAYERSERIES_COMPAT")
+
+ def test_incompatible_series(self):
+ self.add_layer("a", 'LAYERNAME = "a"\nLAYERSERIES_COMPAT = "oldseries"\n')
+ self.parse_fails("Layer a is not compatible with the core layer")
+
+ def test_compat_any_supported_series(self):
+ self.add_layer("a", 'LAYERNAME = "a"\nLAYERSERIES_COMPAT = "oldseries series2"\n')
+ _, layerdata = self.parse()
+ self.assertIn("a", layerdata)
+
+ def test_no_corenames(self):
+ self.write("core/conf/layer.conf",
+ 'LAYERNAME = "core"\nLAYERSERIES_COMPAT = "series1"\n')
+ self.parse_fails("No layer sets LAYERSERIES_CORENAMES")
+
+ def test_missing_dependency(self):
+ self.simple_layer("a", 'LAYERDEPENDS = "core missing"\n')
+ self.parse_fails("Layer a depends on missing but that layer isn't configured")
+
+ def test_dependency_version_ok(self):
+ self.simple_layer("a", 'LAYERDEPENDS = "core (>= 5)"\n')
+ _, layerdata = self.parse()
+ self.assertEqual(layerdata["a"].depends, {"core": [">= 5"]})
+
+ def test_dependency_version_mismatch(self):
+ self.simple_layer("a", 'LAYERDEPENDS = "core (>= 6)"\n')
+ self.parse_fails("Layer 'a' depends on version >= 6 of layer 'core', but version 5")
+
+ def test_recommends_absent_layer_ok(self):
+ self.simple_layer("a", 'LAYERRECOMMENDS = "missing (>= 1)"\n')
+ _, layerdata = self.parse()
+ self.assertIn("missing", layerdata["a"].recommends)
+
+ def test_recommends_version_mismatch(self):
+ self.simple_layer("a", 'LAYERRECOMMENDS = "core (< 5)"\n')
+ self.parse_fails("Layer 'a' recommends version < 5 of layer 'core', but version 5")
+
+ def test_circular_dependency(self):
+ self.simple_layer("a", 'LAYERDEPENDS = "b"\n')
+ self.simple_layer("b", 'LAYERDEPENDS = "a"\n')
+ self.parse_fails("Circular dependencies found from LAYERDEPENDS")
+
+ def test_all_errors_reported(self):
+ # Errors are collected and reported together rather than one per run
+ self.add_layer("a", 'LAYERSERIES_COMPAT = "series1"\n')
+ self.simple_layer("b", 'LAYERDEPENDS = "missing"\n')
+ self.parse_fails("does not set LAYERNAME", "Layer b depends on missing")
+
+
+class LayerOrderingTest(LayerTestBase):
+
+ def test_bbpath_and_bbfiles_follow_dependencies(self):
+ # Listed in bblayers.conf in an order unrelated to the dependencies
+ self.simple_layer("top", 'LAYERDEPENDS = "mid"\n')
+ self.simple_layer("mid", 'LAYERDEPENDS = "core"\n')
+ d, _ = self.parse()
+ core, mid, top = self.path("core"), self.path("mid"), self.path("top")
+ # Layers which depend on others come first in BBPATH so they can override
+ self.assertEqual(d.getVar("BBPATH"), ":".join([self.topdir, top, mid, core]))
+ self.assertEqual(d.getVar("BBFILES").split(),
+ [core + "/recipes*", mid + "/recipes*", top + "/recipes*"])
+
+ def test_ordering_independent_of_bblayers_order(self):
+ self.simple_layer("a", 'LAYERDEPENDS = "core"\n')
+ self.simple_layer("b", 'LAYERDEPENDS = "core"\n')
+ d1, _ = self.parse()
+ self.layers.reverse()
+ d2, _ = self.parse()
+ self.assertEqual(d1.getVar("BBPATH"), d2.getVar("BBPATH"))
+ self.assertEqual(d1.getVar("BBFILES"), d2.getVar("BBFILES"))
+
+ def test_dynamic_recipes(self):
+ a = self.simple_layer("a")
+ self.simple_layer("b")
+ os.makedirs(os.path.join(a, "dynamic-recipes", "b"))
+ os.makedirs(os.path.join(a, "dynamic-recipes", "notpresent"))
+ self.write("a/dynamic-recipes/README", "not a directory\n")
+ d, _ = self.parse()
+ bbfiles = d.getVar("BBFILES").split()
+ self.assertIn(a + "/dynamic-recipes/b", bbfiles)
+ self.assertNotIn(a + "/dynamic-recipes/notpresent", bbfiles)
+ self.assertNotIn(a + "/dynamic-recipes/README", bbfiles)
+
+ def test_layer_bbfiles_ignored(self):
+ self.simple_layer("a", 'BBFILES += "${LAYERDIR}/other/*.bb"\n')
+ with self.assertLogs("BitBake", level="WARNING") as logs:
+ d, _ = self.parse()
+ self.assertNotIn("other", d.getVar("BBFILES"))
+ self.assertTrue(any("BBFILES now set automatically" in l for l in logs.output))
+
+ def test_removed_collection_variables_warn(self):
+ self.simple_layer("a", 'BBFILE_COLLECTIONS += "a"\nBBFILE_PRIORITY_a = "6"\n'
+ 'BBFILE_PATTERN_a = "^${LAYERDIR}/"\n')
+ with self.assertLogs("BitBake", level="WARNING") as logs:
+ d, _ = self.parse()
+ output = "\n".join(logs.output)
+ for var in ("BBFILE_COLLECTIONS", "BBFILE_PRIORITY_a", "BBFILE_PATTERN_a"):
+ self.assertIn("Support for %s was removed" % var, output)
+ self.assertIsNone(d.getVar(var))
+
+
+class LayerVariableTest(LayerTestBase):
+
+ def test_non_passthrough_variable_ignored(self):
+ self.simple_layer("a", 'SOMEVAR = "x"\n')
+ with self.assertLogs("BitBake", level="WARNING") as logs:
+ d, _ = self.parse()
+ self.assertIsNone(d.getVar("SOMEVAR"))
+ self.assertTrue(any("Variable SOMEVAR is set by" in l for l in logs.output))
+
+ def test_passthrough_variable_set(self):
+ self.simple_layer("a", 'PASSVAR_A = "x"\n')
+ d, _ = self.parse()
+ self.assertEqual(d.getVar("PASSVAR_A"), "x")
+
+ def test_passthrough_variable_from_two_layers(self):
+ # Neither value is in the base configuration, so they're space separated
+ self.simple_layer("a", 'PASSVAR_A = "x"\n')
+ self.simple_layer("b", 'PASSVAR_A = "y"\n')
+ d, _ = self.parse()
+ self.assertEqual(d.getVar("PASSVAR_A").split(), ["x", "y"])
+
+ def test_passthrough_variable_append(self):
+ self.bblayers_extra = 'PASSVAR_A = "base"\n'
+ self.simple_layer("a", 'PASSVAR_A:append = " fromlayer"\n')
+ d, _ = self.parse()
+ self.assertEqual(d.getVar("PASSVAR_A"), "base fromlayer")
+
+ def test_passthrough_variable_overwrite_error(self):
+ self.bblayers_extra = 'PASSVAR_A = "base"\n'
+ self.simple_layer("a", 'PASSVAR_A = "replaced"\n')
+ self.parse_fails("Layer %s is overwriting variable PASSVAR_A" % self.path("a"))
+
+ def test_unchanged_base_variable_ok(self):
+ self.bblayers_extra = 'SOMEVAR = "base"\n'
+ self.simple_layer("a")
+ d, _ = self.parse()
+ self.assertEqual(d.getVar("SOMEVAR"), "base")
+
+ def test_layer_internal_variables_not_exported(self):
+ self.simple_layer("a")
+ d, _ = self.parse()
+ for var in ("LAYERNAME", "LAYERDIR", "LAYERSERIES_COMPAT", "LAYERVERSION"):
+ self.assertIsNone(d.getVar(var), var)
+
+
+class LayerUtilsTest(LayerTestBase):
+
+ def test_get_file_layer(self):
+ a = self.simple_layer("a")
+ self.simple_layer("ab")
+ d, _ = self.parse()
+ self.assertEqual(bb.utils.get_file_layer(a + "/recipes/foo.bb", d), "a")
+ self.assertEqual(bb.utils.get_file_layer(self.path("ab") + "/classes/x.bbclass", d), "ab")
+ self.assertEqual(bb.utils.get_file_layer(self.path("core") + "/conf/bitbake.conf", d), "core")
+ self.assertIsNone(bb.utils.get_file_layer(self.topdir + "/elsewhere/foo.bb", d))
+ # The layer directory itself isn't a file within the layer
+ self.assertIsNone(bb.utils.get_file_layer(a, d))
+
+ def test_get_file_layer_symlink(self):
+ a = self.simple_layer("a")
+ os.symlink(a, self.path("link"))
+ d, _ = self.parse()
+ self.assertEqual(bb.utils.get_file_layer(self.path("link") + "/recipes/foo.bb", d), "a")
+
+ def test_have_layer(self):
+ self.simple_layer("a")
+ d, _ = self.parse()
+ self.assertTrue(bb.utils.have_layer("a", d))
+ self.assertFalse(bb.utils.have_layer("missing", d))
+ self.assertEqual(bb.utils.have_layer("a", d, "yes", "no"), "yes")
+ self.assertEqual(bb.utils.have_layer("missing", d, "yes", "no"), "no")
+
+
+class LayerVarsConfTest(LayerTestBase):
+
+ def test_layervars_scoped_to_layer(self):
+ # conf/layervars.conf applies only to recipes from its own layer
+ self.simple_layer("a")
+ self.write("a/conf/layervars.conf", 'FROM_LAYERVARS = "a"\n')
+ a_recipe = self.write("a/recipes/foo/foo_1.0.bb", "")
+ core_recipe = self.write("core/recipes/bar/bar_1.0.bb", "")
+ d, _ = self.parse()
+ bb.parse.siggen = bb.siggen.init(d)
+ da = bb.cookerdata.CookerDataBuilder._parse_recipe(bb.data.createCopy(d), a_recipe, [], "", "a")
+ dc = bb.cookerdata.CookerDataBuilder._parse_recipe(bb.data.createCopy(d), core_recipe, [], "", "core")
+ self.assertEqual(da[""].getVar("FROM_LAYERVARS"), "a")
+ self.assertIsNone(dc[""].getVar("FROM_LAYERVARS"))
+
+
+class LayerVarsDefaultPreferenceTest(LayerTestBase):
+ """
+ End-to-end check that DEFAULT_PREFERENCE set in a layer's
+ conf/layervars.conf changes which version of a recipe provided by several
+ layers bitbake selects to build, and only for that layer's recipes.
+ """
+
+ bitbake = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "bin", "bitbake"))
+
+ BITBAKE_CONF = """\
+CACHE = "${TOPDIR}/cache"
+PN = "${@bb.parse.vars_from_file(d.getVar('FILE', False),d)[0]}"
+PV = "${@bb.parse.vars_from_file(d.getVar('FILE', False),d)[1] or '1.0'}"
+PR = "r0"
+PF = "${PN}-${PV}-${PR}"
+PROVIDES = "${PN}"
+TMPDIR = "${TOPDIR}/tmp"
+STAMP = "${TMPDIR}/stamps/${PF}"
+T = "${TMPDIR}/work/${PF}/temp"
+B = "${TMPDIR}/work/${PF}"
+BB_NUMBER_THREADS = "1"
+"""
+
+ BASE_CLASS = """\
+python do_build() {
+ with open(d.expand("${TOPDIR}/built.log"), "a") as f:
+ f.write(d.expand("${PN} ${PV}\\n"))
+}
+addtask build
+do_build[dirs] = "${B}"
+do_build[nostamp] = "1"
+do_build[deptask] = "do_build"
+"""
+
+ def setUp(self):
+ super().setUp()
+ self.write("core/conf/bitbake.conf", self.BITBAKE_CONF)
+ self.write("core/classes/base.bbclass", self.BASE_CLASS)
+ self.simple_layer("a", 'LAYERDEPENDS = "core"\n')
+ self.simple_layer("b", 'LAYERDEPENDS = "core"\n')
+ # foo: highest version in a, b has an older one
+ self.write("core/recipes/foo/foo_1.0.bb", "")
+ self.write("a/recipes/foo/foo_2.0.bb", "")
+ self.write("b/recipes/foo/foo_1.5.bb", "")
+ # qux: only in core and a, so b's layervars.conf must not affect it
+ self.write("core/recipes/qux/qux_1.0.bb", "")
+ self.write("a/recipes/qux/qux_2.0.bb", "")
+ # bar depends on foo, checks dependency resolution picks the same foo
+ self.write("core/recipes/bar/bar_1.0.bb", 'DEPENDS = "foo"\n')
+
+ def tearDown(self):
+ # Wait for the bitbake server to release the build directory
+ deadline = time.monotonic() + 30
+ while os.path.exists(os.path.join(self.topdir, "bitbake.lock")) and time.monotonic() < deadline:
+ time.sleep(0.5)
+ super().tearDown()
+
+ def build(self, *targets):
+ self.write("conf/bblayers.conf",
+ 'BBLAYERS = "%s"\n%s' % (" ".join(self.layers), self.bblayers_extra))
+ log = os.path.join(self.topdir, "built.log")
+ if os.path.exists(log):
+ os.remove(log)
+ env = os.environ.copy()
+ env.pop("BBPATH", None)
+ proc = subprocess.run([self.bitbake] + list(targets), cwd=self.topdir, env=env,
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+ universal_newlines=True)
+ if proc.returncode:
+ self.fail("bitbake %s failed:\n%s" % (" ".join(targets), proc.stdout))
+ with open(log) as f:
+ return dict(line.split() for line in f)
+
+ def test_no_layervars_selects_highest(self):
+ self.assertEqual(self.build("foo", "qux"), {"foo": "2.0", "qux": "2.0"})
+
+ def test_layervars_default_preference(self):
+ self.write("b/conf/layervars.conf", 'DEFAULT_PREFERENCE = "1"\n')
+ built = self.build("foo", "qux")
+ # b's older foo now wins over a's newer one...
+ self.assertEqual(built["foo"], "1.5")
+ # ...but recipes from other layers are unaffected
+ self.assertEqual(built["qux"], "2.0")
+
+ def test_layervars_default_preference_dependency(self):
+ # The same version is chosen when foo is pulled in through DEPENDS
+ self.write("b/conf/layervars.conf", 'DEFAULT_PREFERENCE = "1"\n')
+ self.assertEqual(self.build("bar"), {"foo": "1.5", "bar": "1.0"})
+
+ def test_layervars_negative_default_preference(self):
+ # A negative preference in a deprioritises its versions instead
+ self.write("a/conf/layervars.conf", 'DEFAULT_PREFERENCE = "-1"\n')
+ self.assertEqual(self.build("foo", "qux"), {"foo": "1.5", "qux": "1.0"})
+
+ def test_preferred_version_overrides_layervars(self):
+ self.write("b/conf/layervars.conf", 'DEFAULT_PREFERENCE = "1"\n')
+ self.bblayers_extra = 'PREFERRED_VERSION_foo = "2.0"\n'
+ self.assertEqual(self.build("foo")["foo"], "2.0")
+
+ def test_layervars_change_invalidates_cache(self):
+ # layervars.conf is a parse dependency of the layer's recipes, so
+ # adding, changing or removing it must not leave stale cached results
+ self.assertEqual(self.build("foo")["foo"], "2.0")
+ conf = self.write("b/conf/layervars.conf", 'DEFAULT_PREFERENCE = "1"\n')
+ self.assertEqual(self.build("foo")["foo"], "1.5")
+ # Ensure the mtime changes even on filesystems with coarse timestamps
+ st = os.stat(conf)
+ self.write("b/conf/layervars.conf", 'DEFAULT_PREFERENCE = "0"\n')
+ os.utime(conf, (st.st_atime + 2, st.st_mtime + 2))
+ self.assertEqual(self.build("foo")["foo"], "2.0")
+ os.remove(conf)
+ self.write("b/conf/layervars.conf", 'DEFAULT_PREFERENCE = "1"\n')
+ os.utime(conf, (st.st_atime + 4, st.st_mtime + 4))
+ self.assertEqual(self.build("foo")["foo"], "1.5")
+ os.remove(conf)
+ self.assertEqual(self.build("foo")["foo"], "2.0")
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 16/17] ast/cookerdata: Allow addfragments to be called more than once
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (13 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 15/17] tests/layers: Add tests after layer changes Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
2026-11-30 15:28 ` [PATCH 17/17] tests/layers: Add fragments tests Richard Purdie
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
Since it was implemented, one probably that has been tricky is that distros can't
enable fragments since the distro itself can be selected by a fragment.
Work around this by allowing the addfragments call to be called more than once.
Fragments are only applied the first time they are seen.
This means the recommends checks have to happen after bitbake.conf is parsed.
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
.../bitbake-user-manual-metadata.rst | 3 +++
lib/bb/cookerdata.py | 18 ++++++++++++++++++
lib/bb/parse/ast.py | 10 +++++-----
3 files changed, 26 insertions(+), 5 deletions(-)
diff --git a/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst b/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst
index 3fe4489aebb..b52b5de03d8 100644
--- a/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst
+++ b/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst
@@ -1052,6 +1052,9 @@ bitbake will treat that as direct value assignment in its configuration::
SOMEVARIABLE = "somevalue"
+``addfragments`` can be called more than once with the same arguments.
+Fragments that have already been applied are not applied again.
+
Locating Include Files
----------------------
diff --git a/lib/bb/cookerdata.py b/lib/bb/cookerdata.py
index 3bea91e2387..7d769682450 100644
--- a/lib/bb/cookerdata.py
+++ b/lib/bb/cookerdata.py
@@ -228,6 +228,22 @@ def findTopdir():
return os.path.abspath(os.getcwd())
+
+def check_fragment_recommendations(d):
+ """
+ Warn about recommended fragments which aren't enabled or opted out.
+ """
+ enabled = d.getVar("_BB_FRAGMENTS_ENABLED")
+ if enabled is None:
+ return
+ enabled = set(enabled.split())
+ layerdata = d.getVar("layerdata", expand=False) or {}
+ optedout = set((d.getVar("LAYER_FRAGMENTS_OPTED_OUT") or "").split())
+ for layer in layerdata:
+ wanted = layerdata[layer].fragment_recommends_any - optedout
+ if wanted and not (wanted & enabled):
+ bb.warn("Layer %s recommends one of the fragments %s to be enabled but none are" % (layer, str(wanted)))
+
@dataclasses.dataclass(repr=False)
class Layer:
path: str
@@ -663,6 +679,8 @@ class CookerDataBuilder(object):
for p in postfiles:
data = parse_config_file(p, data)
+ check_fragment_recommendations(data)
+
# Handle any INHERITs and inherit the base class
bbclasses = ["base"] + (data.getVar('INHERIT') or "").split()
for bbclass in bbclasses:
diff --git a/lib/bb/parse/ast.py b/lib/bb/parse/ast.py
index c26632b8b63..ffba5d5b960 100644
--- a/lib/bb/parse/ast.py
+++ b/lib/bb/parse/ast.py
@@ -394,11 +394,11 @@ class AddFragmentsNode(AstNode):
builtin_fragments = {f[0]:f[1] for f in [f.split(':') for f in data.getVar(self.builtin_fragments_variable).split()] }
layerdata = data.getVar("layerdata", expand=False)
- optedout = set((data.getVar("LAYER_FRAGMENTS_OPTED_OUT") or "").split())
- for layer in layerdata:
- wanted = layerdata[layer].fragment_recommends_any - optedout
- if wanted and not (wanted & set(fragments)):
- bb.warn("Layer %s recommends one of the fragments %s to be enabled but none are" % (layer, str(wanted)))
+
+ # addfragments can be called more than once, only apply fragments once
+ enabled = (data.getVar("_BB_FRAGMENTS_ENABLED") or "").split()
+ fragments = [f for f in fragments if f not in enabled]
+ data.setVar("_BB_FRAGMENTS_ENABLED", " ".join(enabled + fragments))
if not fragments:
return
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 17/17] tests/layers: Add fragments tests
2026-11-30 15:28 [PATCH 01/17] uihelper: Fix exception when TaskStarted event handler breaks Richard Purdie
` (14 preceding siblings ...)
2026-11-30 15:28 ` [PATCH 16/17] ast/cookerdata: Allow addfragments to be called more than once Richard Purdie
@ 2026-11-30 15:28 ` Richard Purdie
15 siblings, 0 replies; 18+ messages in thread
From: Richard Purdie @ 2026-11-30 15:28 UTC (permalink / raw)
To: bitbake-devel
Add some tests to ensure the addfragment behaviour we want is tested.
AI-Generated: Uses Claude (Opus 5.5)
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
---
lib/bb/tests/layers.py | 81 ++++++++++++++++++++++++++++++++++++++++--
1 file changed, 78 insertions(+), 3 deletions(-)
diff --git a/lib/bb/tests/layers.py b/lib/bb/tests/layers.py
index 70767b50b6d..c55066fe109 100644
--- a/lib/bb/tests/layers.py
+++ b/lib/bb/tests/layers.py
@@ -19,9 +19,9 @@ import bb.utils
class _LayerBuilder(bb.cookerdata.CookerDataBuilder):
- def __init__(self, topdir):
+ def __init__(self, topdir, skip_fragments=True):
cfg = types.SimpleNamespace(prefile=[], postfile=[], tracking=False,
- skip_fragments=True, env={})
+ skip_fragments=skip_fragments, env={})
super().__init__(cfg)
self.topdir = topdir
@@ -30,6 +30,8 @@ class _LayerBuilder(bb.cookerdata.CookerDataBuilder):
class LayerTestBase(unittest.TestCase):
+ skip_fragments = True
+
CORE_CONF = """\
LAYERNAME = "core"
LAYERSERIES_CORENAMES = "series1 series2"
@@ -75,7 +77,7 @@ LAYER_PASSTHROUGH_VARS_PREFIXES = "PASSVAR"
def parse(self):
self.write("conf/bblayers.conf",
'BBLAYERS = "%s"\n%s' % (" ".join(self.layers), self.bblayers_extra))
- builder = _LayerBuilder(self.topdir)
+ builder = _LayerBuilder(self.topdir, self.skip_fragments)
return builder.parseConfigurationFiles([], [])
def parse_fails(self, *expected):
@@ -354,6 +356,79 @@ class LayerVarsConfTest(LayerTestBase):
self.assertIsNone(dc[""].getVar("FROM_LAYERVARS"))
+class FragmentsTest(LayerTestBase):
+ skip_fragments = False
+
+ # Mirrors the way OE-Core uses addfragments: it is called once before the
+ # distro configuration (which a builtin fragment can select) and again
+ # afterwards so the distro can enable fragments too
+ BITBAKE_CONF = """\
+CACHE = "${TOPDIR}/cache"
+FRAGS_METADATA_VARS = "FRAG_SUMMARY"
+FRAGS_BUILTIN = "distro:DISTRO"
+addfragments conf/fragments FRAGMENTS FRAGS_METADATA_VARS FRAGS_BUILTIN
+include conf/distro/${DISTRO}.conf
+addfragments conf/fragments FRAGMENTS FRAGS_METADATA_VARS FRAGS_BUILTIN
+"""
+
+ def setUp(self):
+ super().setUp()
+ self.write("core/conf/bitbake.conf", self.BITBAKE_CONF)
+ self.write("core/conf/fragments/a.conf",
+ 'FRAG_SUMMARY = "Fragment a"\nFRAG_A = "set"\nCOUNT += "a"\n')
+ self.write("core/conf/fragments/b.conf",
+ 'FRAG_SUMMARY = "Fragment b"\nFRAG_B = "set"\nCOUNT += "b"\n')
+ self.write("core/conf/distro/mydistro.conf",
+ 'DISTRO_SET = "1"\nFRAGMENTS += "core/a"\n')
+
+ def test_distro_fragment_applied(self):
+ self.bblayers_extra = 'DISTRO = "mydistro"\n'
+ d, _ = self.parse()
+ self.assertEqual(d.getVar("DISTRO_SET"), "1")
+ self.assertEqual(d.getVar("FRAG_A"), "set")
+ self.assertEqual(d.getVarFlag("FRAG_SUMMARY", "core/a"), "Fragment a")
+ self.assertIsNone(d.getVar("FRAG_SUMMARY"))
+
+ def test_fragments_applied_once(self):
+ # distro/mydistro and core/b are seen by both addfragments calls, and
+ # core/a is enabled by both the user and the distro
+ self.bblayers_extra = 'FRAGMENTS = "distro/mydistro core/b core/a"\n'
+ d, _ = self.parse()
+ self.assertEqual(d.getVar("DISTRO"), "mydistro")
+ self.assertEqual(d.getVar("DISTRO_SET"), "1")
+ self.assertEqual(d.getVar("COUNT").split(), ["b", "a"])
+
+ def test_missing_distro_fragment_fatal(self):
+ self.write("core/conf/distro/mydistro.conf", 'FRAGMENTS += "core/missing"\n')
+ self.bblayers_extra = 'DISTRO = "mydistro"\n'
+ with self.assertLogs("BitBake", level="ERROR") as logs:
+ with self.assertRaises(bb.BBHandledException):
+ self.parse()
+ self.assertIn("core/missing", "\n".join(logs.output))
+
+ def test_recommendation_satisfied_by_distro_fragment(self):
+ self.simple_layer("other", 'LAYER_FRAGMENT_RECOMMENDS_ANY = "core/a"\n')
+ self.bblayers_extra = 'DISTRO = "mydistro"\n'
+ with self.assertNoLogs("BitBake", level="WARNING"):
+ self.parse()
+
+ def test_recommendation_warned_once(self):
+ self.simple_layer("other", 'LAYER_FRAGMENT_RECOMMENDS_ANY = "core/b"\n')
+ self.bblayers_extra = 'DISTRO = "mydistro"\n'
+ with self.assertLogs("BitBake", level="WARNING") as logs:
+ self.parse()
+ warnings = [l for l in logs.output if "recommends one of the fragments" in l]
+ self.assertEqual(len(warnings), 1, logs.output)
+
+ def test_recommendation_not_checked_when_skipping_fragments(self):
+ self.skip_fragments = True
+ self.simple_layer("other", 'LAYER_FRAGMENT_RECOMMENDS_ANY = "core/b"\n')
+ self.bblayers_extra = 'DISTRO = "mydistro"\n'
+ with self.assertNoLogs("BitBake", level="WARNING"):
+ d, _ = self.parse()
+ self.assertIsNone(d.getVar("FRAG_A"))
+
+
class LayerVarsDefaultPreferenceTest(LayerTestBase):
"""
End-to-end check that DEFAULT_PREFERENCE set in a layer's
^ permalink raw reply related [flat|nested] 18+ messages in thread