Skip to contentSkip to conversation

cache: Drop unused function

PATCH In review Richard Purdie 2 participants 8 messages Aug 12, 2024 – Aug 13, 2024

lore
Share & tools
lore
#0 lore raw

PATCH 1/4 cache: Drop unused function

I can't spot any users of this function and it is poking at variables inside cooker that could and are about to change so drop it.

---
 lib/bb/cache.py | 19 -------------------
 1 file changed, 19 deletions(-)
lib/bb/cache.py +0 -19
index 4a96f5b313..c48feb7138 100644
@@ -779,25 +779,6 @@ class MulticonfigCache(Mapping):
         for k in self.__caches:
             yield k
 
-def init(cooker):
-    """
-    The Objective: Cache the minimum amount of data possible yet get to the
-    stage of building packages (i.e. tryBuild) without reparsing any .bb files.
-
-    To do this, we intercept getVar calls and only cache the variables we see
-    being accessed. We rely on the cache getVar calls being made for all
-    variables bitbake might need to use to reach this stage. For each cached
-    file we need to track:
-
-    * Its mtime
-    * The mtimes of all its dependencies
-    * Whether it caused a parse.SkipRecipe exception
-
-    Files causing parsing errors are evicted from the cache.
-
-    """
-    return Cache(cooker.configuration.data, cooker.configuration.data_hash)
-
 
 class CacheData(object):
     """
#1 lore raw

PATCH 2/4 cookerdata: Separate out data_hash and hook to tinfoil

Within tinfoil, the user can write to the configuration data but it won't cause the data_hash checksum to be re-written, meaning cached parsing data can be reused when it would now be incorrect.

Abstract out the data_hash code and add it to the invalidateCaches command, called by tinfoil.modified_files() meaning that tinfoil can instruct bitbake to update the caches and re-parse if necessary.

Also move the data_hash entirely into databuilder and drop the copy in cooker as obsolete and not needed.

---
 lib/bb/cooker.py     | 10 +++++++---
 lib/bb/cookerdata.py | 13 +++++++++----
 2 files changed, 16 insertions(+), 7 deletions(-)
lib/bb/cooker.py +7 -3
index 6754f986bf..31fee2bead 100644
@@ -281,7 +281,6 @@ class BBCooker:
         self.databuilder = bb.cookerdata.CookerDataBuilder(self.configuration, False)
         self.databuilder.parseBaseConfiguration()
         self.data = self.databuilder.data
-        self.data_hash = self.databuilder.data_hash
         self.extraconfigdata = {}
 
         eventlog = self.data.getVar("BB_DEFAULT_EVENTLOG")
@@ -370,6 +369,11 @@ class BBCooker:
         if not clean:
             bb.parse.BBHandler.cached_statements = {}
 
+        # If writes were made to any of the data stores, we need to recalcuate the data
+        # store cache
+        if hasattr(self, "databuilder"):
+            self.databuilder.calc_datastore_hashes()
+
     def parseConfiguration(self):
         self.updateCacheSync()
 
@@ -1338,7 +1342,7 @@ class BBCooker:
         self.buildSetVars()
         self.reset_mtime_caches()
 
-        bb_caches = bb.cache.MulticonfigCache(self.databuilder, self.data_hash, self.caches_array)
+        bb_caches = bb.cache.MulticonfigCache(self.databuilder, self.databuilder.data_hash, self.caches_array)
 
         layername = self.collections[mc].calc_bbfile_priority(fn)[2]
         infos = bb_caches[mc].parse(fn, self.collections[mc].get_file_appends(fn), layername)
@@ -2112,7 +2116,7 @@ class CookerParser(object):
         self.mcfilelist = mcfilelist
         self.cooker = cooker
         self.cfgdata = cooker.data
-        self.cfghash = cooker.data_hash
+        self.cfghash = cooker.databuilder.data_hash
         self.cfgbuilder = cooker.databuilder
 
         # Accounting statistics
lib/bb/cookerdata.py +9 -4
index 0649e40995..3ad5cf3dd0 100644
@@ -254,9 +254,16 @@ class CookerDataBuilder(object):
         self.data = self.basedata
         self.mcdata = {}
 
+    def calc_datastore_hashes(self):
+        data_hash = hashlib.sha256()
+        data_hash.update(self.data.get_hash().encode('utf-8'))
+        multiconfig = (self.data.getVar("BBMULTICONFIG") or "").split()
+        for config in multiconfig:
+            data_hash.update(self.mcdata[config].get_hash().encode('utf-8'))
+        self.data_hash = data_hash.hexdigest()
+
     def parseBaseConfiguration(self, worker=False):
         mcdata = {}
-        data_hash = hashlib.sha256()
         try:
             self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
 
@@ -279,7 +286,6 @@ class CookerDataBuilder(object):
                 bb.event.fire(bb.event.ConfigParsed(), self.data)
 
             bb.parse.init_parser(self.data)
-            data_hash.update(self.data.get_hash().encode('utf-8'))
             mcdata[''] = self.data
 
             multiconfig = (self.data.getVar("BBMULTICONFIG") or "").split()
@@ -289,11 +295,9 @@ class CookerDataBuilder(object):
                 parsed_mcdata = self.parseConfigurationFiles(self.prefiles, self.postfiles, config)
                 bb.event.fire(bb.event.ConfigParsed(), parsed_mcdata)
                 mcdata[config] = parsed_mcdata
-                data_hash.update(parsed_mcdata.get_hash().encode('utf-8'))
             if multiconfig:
                 bb.event.fire(bb.event.MultiConfigParsed(mcdata), self.data)
 
-            self.data_hash = data_hash.hexdigest()
         except bb.data_smart.ExpansionError as e:
             logger.error(str(e))
             raise bb.BBHandledException()
@@ -328,6 +332,7 @@ class CookerDataBuilder(object):
         for mc in mcdata:
             self.mcdata[mc] = bb.data.createCopy(mcdata[mc])
         self.data = self.mcdata['']
+        self.calc_datastore_hashes()
 
     def reset(self):
         # We may not have run parseBaseConfiguration() yet
#2 lore raw

RE: [bitbake-devel] [PATCH 2/4] cookerdata: Separate out data_hash and hook to tinfoil

Quoted 36 lines

-----Original Message-----
From: [email protected] <[email protected]> On Behalf Of Richard Purdie
Sent: den 12 augusti 2024 17:54
To: [email protected]
Subject: [bitbake-devel] [PATCH 2/4] cookerdata: Separate out data_hash and hook to tinfoil

Within tinfoil, the user can write to the configuration data but it won't cause the data_hash checksum to be re-written, meaning cached parsing data can be reused when it would now be incorrect.

Abstract out the data_hash code and add it to the invalidateCaches command, called by tinfoil.modified_files() meaning that tinfoil can instruct bitbake to update the caches and re-parse if necessary.

Also move the data_hash entirely into databuilder and drop the copy in cooker as obsolete and not needed.

---
 lib/bb/cooker.py     | 10 +++++++---
 lib/bb/cookerdata.py | 13 +++++++++----
 2 files changed, 16 insertions(+), 7 deletions(-)
lib/bb/cooker.py +0 -1
index 6754f986bf..31fee2bead 100644
@@ -281,7 +281,6 @@ class BBCooker:
         self.databuilder = bb.cookerdata.CookerDataBuilder(self.configuration, False)
         self.databuilder.parseBaseConfiguration()
         self.data = self.databuilder.data
-        self.data_hash = self.databuilder.data_hash
         self.extraconfigdata = {}
 
         eventlog = self.data.getVar("BB_DEFAULT_EVENTLOG")

lib/bb/cooker.py class BBCooker: · line 372

Quoted 4 lines
lib/bb/cooker.py +1 -0
@@ -370,6 +369,11 @@ class BBCooker:
         if not clean:
             bb.parse.BBHandler.cached_statements = {}
 
+        # If writes were made to any of the data stores, we need to recalcuate the data

Typo: recalcuate -> recalculate

Quoted 68 lines
lib/bb/cooker.py +6 -2
+        # store cache
+        if hasattr(self, "databuilder"):
+            self.databuilder.calc_datastore_hashes()
+
     def parseConfiguration(self):
         self.updateCacheSync()
 
@@ -1338,7 +1342,7 @@ class BBCooker:
         self.buildSetVars()
         self.reset_mtime_caches()
 
-        bb_caches = bb.cache.MulticonfigCache(self.databuilder, self.data_hash, self.caches_array)
+        bb_caches = bb.cache.MulticonfigCache(self.databuilder, self.databuilder.data_hash, self.caches_array)
 
         layername = self.collections[mc].calc_bbfile_priority(fn)[2]
         infos = bb_caches[mc].parse(fn, self.collections[mc].get_file_appends(fn), layername)
@@ -2112,7 +2116,7 @@ class CookerParser(object):
         self.mcfilelist = mcfilelist
         self.cooker = cooker
         self.cfgdata = cooker.data
-        self.cfghash = cooker.data_hash
+        self.cfghash = cooker.databuilder.data_hash
         self.cfgbuilder = cooker.databuilder
 
         # Accounting statistics
lib/bb/cookerdata.py +8 -4
index 0649e40995..3ad5cf3dd0 100644
@@ -254,9 +254,16 @@ class CookerDataBuilder(object):
         self.data = self.basedata
         self.mcdata = {}
 
+    def calc_datastore_hashes(self):
+        data_hash = hashlib.sha256()
+        data_hash.update(self.data.get_hash().encode('utf-8'))
+        multiconfig = (self.data.getVar("BBMULTICONFIG") or "").split()
+        for config in multiconfig:
+            data_hash.update(self.mcdata[config].get_hash().encode('utf-8'))
+        self.data_hash = data_hash.hexdigest()
+
     def parseBaseConfiguration(self, worker=False):
         mcdata = {}
-        data_hash = hashlib.sha256()
         try:
             self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
 
@@ -279,7 +286,6 @@ class CookerDataBuilder(object):
                 bb.event.fire(bb.event.ConfigParsed(), self.data)
 
             bb.parse.init_parser(self.data)
-            data_hash.update(self.data.get_hash().encode('utf-8'))
             mcdata[''] = self.data
 
             multiconfig = (self.data.getVar("BBMULTICONFIG") or "").split()
@@ -289,11 +295,9 @@ class CookerDataBuilder(object):
                 parsed_mcdata = self.parseConfigurationFiles(self.prefiles, self.postfiles, config)
                 bb.event.fire(bb.event.ConfigParsed(), parsed_mcdata)
                 mcdata[config] = parsed_mcdata
-                data_hash.update(parsed_mcdata.get_hash().encode('utf-8'))
             if multiconfig:
                 bb.event.fire(bb.event.MultiConfigParsed(mcdata), self.data)
 
-            self.data_hash = data_hash.hexdigest()
         except bb.data_smart.ExpansionError as e:
             logger.error(str(e))
             raise bb.BBHandledException()

lib/bb/cookerdata.py class CookerDataBuilder(object): · line 338

Quoted 7 lines
lib/bb/cookerdata.py +1 -0
@@ -328,6 +332,7 @@ class CookerDataBuilder(object):
         for mc in mcdata:
             self.mcdata[mc] = bb.data.createCopy(mcdata[mc])
         self.data = self.mcdata['']
+        self.calc_datastore_hashes()
 
     def reset(self):
         # We may not have run parseBaseConfiguration() yet

//Peter

#3 lore raw

PATCH 3/4 BBHandler/ast: Improve addtask handling

In reply to Richard Purdie

The recent addtask improvement to handle comments complicated the regex significantly and there are already a number of corner cases in that code which aren't handled well.

Instead of trying to complicate the regex further, switch to code logic instead. This means the following cases are now handled:

* addtask with multiple task names
* addtask with multiple before constraints
* addtask with multiple after constraints

The testcase is updated to match the improvements.

---
 lib/bb/parse/ast.py                | 26 +++++++-------------
 lib/bb/parse/parse_py/BBHandler.py | 38 +++++++++++++++++-------------
 lib/bb/tests/parse.py              | 15 ++++--------
 3 files changed, 35 insertions(+), 44 deletions(-)
lib/bb/parse/ast.py +9 -17
index 7581d003fd..001ba8d289 100644
@@ -240,14 +240,16 @@ class ExportFuncsNode(AstNode):
                 data.setVar(func, sentinel + "    " + calledfunc + "\n", parsing=True)
 
 class AddTaskNode(AstNode):
-    def __init__(self, filename, lineno, func, before, after):
+    def __init__(self, filename, lineno, tasks, before, after):
         AstNode.__init__(self, filename, lineno)
-        self.func = func
+        self.tasks = tasks
         self.before = before
         self.after = after
 
     def eval(self, data):
-        bb.build.addtask(self.func, self.before, self.after, data)
+        tasks = self.tasks.split()
+        for task in tasks:
+            bb.build.addtask(task, self.before, self.after, data)
 
 class DelTaskNode(AstNode):
     def __init__(self, filename, lineno, tasks):
@@ -348,21 +350,11 @@ def handlePythonMethod(statements, filename, lineno, funcname, modulename, body)
 def handleExportFuncs(statements, filename, lineno, m, classname):
     statements.append(ExportFuncsNode(filename, lineno, m.group(1), classname))
 
-def handleAddTask(statements, filename, lineno, m):
-    func = m.group("func")
-    before = m.group("before")
-    after = m.group("after")
-    if func is None:
-        return
-
-    statements.append(AddTaskNode(filename, lineno, func, before, after))
-
-def handleDelTask(statements, filename, lineno, m):
-    func = m.group(1)
-    if func is None:
-        return
+def handleAddTask(statements, filename, lineno, tasks, before, after):
+    statements.append(AddTaskNode(filename, lineno, tasks, before, after))
 
-    statements.append(DelTaskNode(filename, lineno, func))
+def handleDelTask(statements, filename, lineno, tasks):
+    statements.append(DelTaskNode(filename, lineno, tasks))
 
 def handleBBHandlers(statements, filename, lineno, m):
     statements.append(BBHandlerNode(filename, lineno, m.group(1)))
lib/bb/parse/parse_py/BBHandler.py +22 -16
index c1653faeee..87c03e9238 100644
@@ -23,7 +23,7 @@ __func_start_regexp__    = re.compile(r"(((?P<py>python(?=(\s|\()))|(?P<fr>faker
 __inherit_regexp__       = re.compile(r"inherit\s+(.+)" )
 __inherit_def_regexp__   = re.compile(r"inherit_defer\s+(.+)" )
 __export_func_regexp__   = re.compile(r"EXPORT_FUNCTIONS\s+(.+)" )
-__addtask_regexp__       = re.compile(r"addtask\s+(?P<func>\w+)\s*((before\s*(?P<before>(([^#\n]*(?=after))|([^#\n]*))))|(after\s*(?P<after>(([^#\n]*(?=before))|([^#\n]*)))))*(?P<comment>#.*|.*?)")
+__addtask_regexp__       = re.compile(r"addtask\s+([^#\n]+)(?P<comment>#.*|.*?)")
 __deltask_regexp__       = re.compile(r"deltask\s+([^#\n]+)(?P<comment>#.*|.*?)")
 __addhandler_regexp__    = re.compile(r"addhandler\s+(.+)" )
 __def_regexp__           = re.compile(r"def\s+(\w+).*:" )
@@ -239,29 +239,35 @@ def feeder(lineno, s, fn, root, statements, eof=False):
 
     m = __addtask_regexp__.match(s)
     if m:
-        if len(m.group().split()) == 2:
-            # Check and warn for "addtask task1 task2"
-            m2 = re.match(r"addtask\s+(?P<func>\w+)(?P<ignores>.*)", s)
-            if m2 and m2.group('ignores'):
-                logger.warning('addtask ignored: "%s"' % m2.group('ignores'))
-
-        # Check and warn for "addtask task1 before task2 before task3", the
-        # similar to "after"
-        taskexpression = s.split()
-        for word in ('before', 'after'):
-            if taskexpression.count(word) > 1:
-                logger.warning("addtask contained multiple '%s' keywords, only one is supported" % word)
+        after = ""
+        before = ""
+        tasks = m.group(1).split(" before ")[0].split(" after ")[0]
+
+        for exp in m.group(1).split(" before "):
+            exp2 = exp.split(" after ")
+            if len(exp2) > 1:
+                after = after + " ".join(exp2[1:])
+
+        for exp in m.group(1).split(" after "):
+            exp2 = exp.split(" before ")
+            if len(exp2) > 1:
+                before = before + " ".join(exp2[1:])
 
-        # Check and warn for having task with exprssion as part of task name
+        # Check and warn for having task with a keyword as part of task name
+        taskexpression = s.split()
         for te in taskexpression:
             if any( ( "%s_" % keyword ) in te for keyword in bb.data_smart.__setvar_keyword__ ):
                 raise ParseError("Task name '%s' contains a keyword which is not recommended/supported.\nPlease rename the task not to include the keyword.\n%s" % (te, ("\n".join(map(str, bb.data_smart.__setvar_keyword__)))), fn)
-        ast.handleAddTask(statements, fn, lineno, m)
+
+        if tasks is not None:
+            ast.handleAddTask(statements, fn, lineno, tasks, before, after)
         return
 
     m = __deltask_regexp__.match(s)
     if m:
-        ast.handleDelTask(statements, fn, lineno, m)
+        task = m.group(1)
+        if task is not None:
+            ast.handleDelTask(statements, fn, lineno, task)
         return
 
     m = __addhandler_regexp__.match(s)
lib/bb/tests/parse.py +4 -11
index d076fcc208..97df2c4590 100644
@@ -177,7 +177,7 @@ python () {
 
     addtask_deltask = """
 addtask do_patch after do_foo after do_unpack before do_configure before do_compile
-addtask do_fetch do_patch
+addtask do_fetch2 do_patch2
 
 addtask do_myplaintask
 addtask do_myplaintask2
@@ -194,18 +194,11 @@ deltask do_fetch ${MYVAR} ${EMPTYVAR}
 deltask ${EMPTYVAR}
 """
     def test_parse_addtask_deltask(self):
-        import sys
 
-        with self.assertLogs() as logs:
-            f = self.parsehelper(self.addtask_deltask)
-            d = bb.parse.handle(f.name, self.d)['']
+        f = self.parsehelper(self.addtask_deltask)
+        d = bb.parse.handle(f.name, self.d)['']
 
-        output = "".join(logs.output)
-        self.assertTrue("addtask contained multiple 'before' keywords" in output)
-        self.assertTrue("addtask contained multiple 'after' keywords" in output)
-        self.assertTrue('addtask ignored: " do_patch"' in output)
-        self.assertEqual(['do_myplaintask', 'do_mytask', 'do_mytask2'], d.getVar("__BBTASKS"))
-        #self.assertTrue('dependent task do_foo for do_patch does not exist' in output)
+        self.assertEqual(['do_fetch2', 'do_patch2', 'do_myplaintask', 'do_mytask', 'do_mytask2'], d.getVar("__BBTASKS"))
 
     broken_multiline_comment = """
 # First line of comment \\
#4 lore raw

RE: [bitbake-devel] [PATCH 3/4] BBHandler/ast: Improve addtask handling

Quoted 107 lines

-----Original Message-----
From: [email protected] <[email protected]> On Behalf Of Richard Purdie
Sent: den 12 augusti 2024 17:54
To: [email protected]
Subject: [bitbake-devel] [PATCH 3/4] BBHandler/ast: Improve addtask handling

The recent addtask improvement to handle comments complicated the regex significantly and there are already a number of corner cases in that code which aren't handled well.

Instead of trying to complicate the regex further, switch to code logic instead. This means the following cases are now handled:

* addtask with multiple task names
* addtask with multiple before constraints
* addtask with multiple after constraints

The testcase is updated to match the improvements.

---
 lib/bb/parse/ast.py                | 26 +++++++-------------
 lib/bb/parse/parse_py/BBHandler.py | 38 +++++++++++++++++-------------
 lib/bb/tests/parse.py              | 15 ++++--------
 3 files changed, 35 insertions(+), 44 deletions(-)
lib/bb/parse/ast.py +9 -17
index 7581d003fd..001ba8d289 100644
@@ -240,14 +240,16 @@ class ExportFuncsNode(AstNode):
                 data.setVar(func, sentinel + "    " + calledfunc + "\n", parsing=True)
 
 class AddTaskNode(AstNode):
-    def __init__(self, filename, lineno, func, before, after):
+    def __init__(self, filename, lineno, tasks, before, after):
         AstNode.__init__(self, filename, lineno)
-        self.func = func
+        self.tasks = tasks
         self.before = before
         self.after = after
 
     def eval(self, data):
-        bb.build.addtask(self.func, self.before, self.after, data)
+        tasks = self.tasks.split()
+        for task in tasks:
+            bb.build.addtask(task, self.before, self.after, data)
 
 class DelTaskNode(AstNode):
     def __init__(self, filename, lineno, tasks):
@@ -348,21 +350,11 @@ def handlePythonMethod(statements, filename, lineno, funcname, modulename, body)
 def handleExportFuncs(statements, filename, lineno, m, classname):
     statements.append(ExportFuncsNode(filename, lineno, m.group(1), classname))
 
-def handleAddTask(statements, filename, lineno, m):
-    func = m.group("func")
-    before = m.group("before")
-    after = m.group("after")
-    if func is None:
-        return
-
-    statements.append(AddTaskNode(filename, lineno, func, before, after))
-
-def handleDelTask(statements, filename, lineno, m):
-    func = m.group(1)
-    if func is None:
-        return
+def handleAddTask(statements, filename, lineno, tasks, before, after):
+    statements.append(AddTaskNode(filename, lineno, tasks, before, after))
 
-    statements.append(DelTaskNode(filename, lineno, func))
+def handleDelTask(statements, filename, lineno, tasks):
+    statements.append(DelTaskNode(filename, lineno, tasks))
 
 def handleBBHandlers(statements, filename, lineno, m):
     statements.append(BBHandlerNode(filename, lineno, m.group(1)))
lib/bb/parse/parse_py/BBHandler.py +4 -13
index c1653faeee..87c03e9238 100644
@@ -23,7 +23,7 @@ __func_start_regexp__    = re.compile(r"(((?P<py>python(?=(\s|\()))|(?P<fr>faker
 __inherit_regexp__       = re.compile(r"inherit\s+(.+)" )
 __inherit_def_regexp__   = re.compile(r"inherit_defer\s+(.+)" )
 __export_func_regexp__   = re.compile(r"EXPORT_FUNCTIONS\s+(.+)" )
-__addtask_regexp__       = re.compile(r"addtask\s+(?P<func>\w+)\s*((before\s*(?P<before>(([^#\n]*(?=after))|([^#\n]*))))|(after\s*(?P<after>(([^#\n]*(?=before))|([^#\n]*)))))*(?P<comment>#.*|.*?)")
+__addtask_regexp__       = re.compile(r"addtask\s+([^#\n]+)(?P<comment>#.*|.*?)")
 __deltask_regexp__       = re.compile(r"deltask\s+([^#\n]+)(?P<comment>#.*|.*?)")
 __addhandler_regexp__    = re.compile(r"addhandler\s+(.+)" )
 __def_regexp__           = re.compile(r"def\s+(\w+).*:" )
@@ -239,29 +239,35 @@ def feeder(lineno, s, fn, root, statements, eof=False):
 
     m = __addtask_regexp__.match(s)
     if m:
-        if len(m.group().split()) == 2:
-            # Check and warn for "addtask task1 task2"
-            m2 = re.match(r"addtask\s+(?P<func>\w+)(?P<ignores>.*)", s)
-            if m2 and m2.group('ignores'):
-                logger.warning('addtask ignored: "%s"' % m2.group('ignores'))
-
-        # Check and warn for "addtask task1 before task2 before task3", the
-        # similar to "after"
-        taskexpression = s.split()
-        for word in ('before', 'after'):
-            if taskexpression.count(word) > 1:
-                logger.warning("addtask contained multiple '%s' keywords, only one is supported" % word)
+        after = ""
+        before = ""
+        tasks = m.group(1).split(" before ")[0].split(" after ")[0]

lib/bb/parse/parse_py/BBHandler.py def feeder(lineno, s, fn, root, statements, eof=False): · line 254

Quoted 10 lines
lib/bb/parse/parse_py/BBHandler.py +10 -0
+
+        for exp in m.group(1).split(" before "):
+            exp2 = exp.split(" after ")
+            if len(exp2) > 1:
+                after = after + " ".join(exp2[1:])
+
+        for exp in m.group(1).split(" after "):
+            exp2 = exp.split(" before ")
+            if len(exp2) > 1:
+                before = before + " ".join(exp2[1:])

I found it hard to understand what the code above is actually doing. How about something like this instead (untested):

cur = "tasks"
tasks = {"tasks": [], "before": [], "after": []}
for task in m.group(1).split():
if task in ("before", "after"):
cur = task
else:
# Check and warn for having a task with a keyword as part of the task name
if any(("%s_" % keyword) in task for keyword in bb.data_smart.__setvar_keyword__):
raise ParseError("Task name '%s' contains a keyword which is not recommended/supported.\nPlease rename the task not to include the keyword.\n%s" % (task, ("\n".join(map(str, bb.data_smart.__setvar_keyword__)))), fn)

tasks[cur].append(task)

if tasks["tasks"]:
ast.handleAddTask(statements, fn, lineno, tasks["tasks"], tasks["before"], tasks["after"])
return

Quoted 47 lines
lib/bb/parse/parse_py/BBHandler.py +8 -3
-        # Check and warn for having task with exprssion as part of task name
+        # Check and warn for having task with a keyword as part of task name
+        taskexpression = s.split()
         for te in taskexpression:
             if any( ( "%s_" % keyword ) in te for keyword in bb.data_smart.__setvar_keyword__ ):
                 raise ParseError("Task name '%s' contains a keyword which is not recommended/supported.\nPlease rename the task not to include the keyword.\n%s" % (te, ("\n".join(map(str, bb.data_smart.__setvar_keyword__)))), fn)
-        ast.handleAddTask(statements, fn, lineno, m)
+
+        if tasks is not None:
+            ast.handleAddTask(statements, fn, lineno, tasks, before, after)
         return
 
     m = __deltask_regexp__.match(s)
     if m:
-        ast.handleDelTask(statements, fn, lineno, m)
+        task = m.group(1)
+        if task is not None:
+            ast.handleDelTask(statements, fn, lineno, task)
         return
 
     m = __addhandler_regexp__.match(s)
lib/bb/tests/parse.py +3 -5
index d076fcc208..97df2c4590 100644
@@ -177,7 +177,7 @@ python () {
 
     addtask_deltask = """
 addtask do_patch after do_foo after do_unpack before do_configure before do_compile
-addtask do_fetch do_patch
+addtask do_fetch2 do_patch2
 
 addtask do_myplaintask
 addtask do_myplaintask2
@@ -194,18 +194,11 @@ deltask do_fetch ${MYVAR} ${EMPTYVAR}
 deltask ${EMPTYVAR}
 """
     def test_parse_addtask_deltask(self):
-        import sys
 
-        with self.assertLogs() as logs:
-            f = self.parsehelper(self.addtask_deltask)
-            d = bb.parse.handle(f.name, self.d)['']
+        f = self.parsehelper(self.addtask_deltask)
+        d = bb.parse.handle(f.name, self.d)['']
 

lib/bb/tests/parse.py deltask do_fetch ${MYVAR} ${EMPTYVAR} · line 204

Quoted 10 lines
lib/bb/tests/parse.py +1 -6
-        output = "".join(logs.output)
-        self.assertTrue("addtask contained multiple 'before' keywords" in output)
-        self.assertTrue("addtask contained multiple 'after' keywords" in output)
-        self.assertTrue('addtask ignored: " do_patch"' in output)
-        self.assertEqual(['do_myplaintask', 'do_mytask', 'do_mytask2'], d.getVar("__BBTASKS"))
-        #self.assertTrue('dependent task do_foo for do_patch does not exist' in output)
+        self.assertEqual(['do_fetch2', 'do_patch2', 'do_myplaintask', 'do_mytask', 'do_mytask2'], d.getVar("__BBTASKS"))
 
     broken_multiline_comment = """
 # First line of comment \\

//Peter

#5 lore raw

Re: [bitbake-devel] [PATCH 3/4] BBHandler/ast: Improve addtask handling

Quoted 131 lines · Peter Kjellerstedt
Quoted 107 lines

-----Original Message-----
From: [email protected] <[email protected]> On Behalf Of Richard Purdie
Sent: den 12 augusti 2024 17:54
To: [email protected]
Subject: [bitbake-devel] [PATCH 3/4] BBHandler/ast: Improve addtask handling

The recent addtask improvement to handle comments complicated the regex significantly and there are already a number of corner cases in that code which aren't handled well.

Instead of trying to complicate the regex further, switch to code logic instead. This means the following cases are now handled:

* addtask with multiple task names
* addtask with multiple before constraints
* addtask with multiple after constraints

The testcase is updated to match the improvements.

---
 lib/bb/parse/ast.py                | 26 +++++++------------- lib/bb/parse/parse_py/BBHandler.py | 38 +++++++++++++++++------------- lib/bb/tests/parse.py              | 15 ++++--------

 3 files changed, 35 insertions(+), 44 deletions(-)
lib/bb/parse/ast.py +0 -0
index 7581d003fd..001ba8d289 100644
@@ -240,14 +240,16 @@ class ExportFuncsNode(AstNode):
                  data.setVar(func, sentinel + "    " + calledfunc + "\n", parsing=True)
 

 class AddTaskNode(AstNode):
-    def __init__(self, filename, lineno, func, before, after):
+    def __init__(self, filename, lineno, tasks, before, after):
         AstNode.__init__(self, filename, lineno)
-        self.func = func
+        self.tasks = tasks
         self.before = before
         self.after = after

     def eval(self, data):
-        bb.build.addtask(self.func, self.before, self.after, data) +        tasks = self.tasks.split()
+        for task in tasks:
+            bb.build.addtask(task, self.before, self.after, data)

 class DelTaskNode(AstNode):
     def __init__(self, filename, lineno, tasks):

lib/bb/parse/ast.py +0 -0
@@ -348,21 +350,11 @@ def handlePythonMethod(statements, filename, lineno, funcname, modulename, body)

 def handleExportFuncs(statements, filename, lineno, m, classname):
     statements.append(ExportFuncsNode(filename, lineno, m.group(1), classname))

lib/bb/parse/ast.py +4 -14
-def handleAddTask(statements, filename, lineno, m):
-    func = m.group("func")
-    before = m.group("before")
-    after = m.group("after")
-    if func is None:
-        return
-
-    statements.append(AddTaskNode(filename, lineno, func, before, after))
-
-def handleDelTask(statements, filename, lineno, m):
-    func = m.group(1)
-    if func is None:
-        return
+def handleAddTask(statements, filename, lineno, tasks, before, after):
+    statements.append(AddTaskNode(filename, lineno, tasks, before, after))
 
-    statements.append(DelTaskNode(filename, lineno, func))
+def handleDelTask(statements, filename, lineno, tasks):
+    statements.append(DelTaskNode(filename, lineno, tasks))

 def handleBBHandlers(statements, filename, lineno, m):
     statements.append(BBHandlerNode(filename, lineno, m.group(1)))

lib/bb/parse/parse_py/BBHandler.py +1 -1
index c1653faeee..87c03e9238 100644
@@ -23,7 +23,7 @@ __func_start_regexp__    = re.compile(r"(((?P<py>python(?=(\s|\()))|(?P<fr>faker
  __inherit_regexp__       = re.compile(r"inherit\s+(.+)" )
  __inherit_def_regexp__   = re.compile(r"inherit_defer\s+(.+)" )
  __export_func_regexp__   = re.compile(r"EXPORT_FUNCTIONS\s+(.+)" )
-__addtask_regexp__       = re.compile(r"addtask\s+(?P<func>\w+)\s*((before\s*(?P<before>(([^#\n]*(?=after))|([^#\n]*))))|(after\s*(?P<after>(([^#\n]*(?=before))|([^#\n]*)))))*(?P<comment>#.*|.*?)")
+__addtask_regexp__       = re.compile(r"addtask\s+([^#\n]+)(?P<comment>#.*|.*?)")
  __deltask_regexp__       = re.compile(r"deltask\s+([^#\n]+)(?P<comment>#.*|.*?)")
  __addhandler_regexp__    = re.compile(r"addhandler\s+(.+)" )
  __def_regexp__           = re.compile(r"def\s+(\w+).*:" )
@@ -239,29 +239,35 @@ def feeder(lineno, s, fn, root, statements, eof=False):
 
      m = __addtask_regexp__.match(s)

     if m:
-        if len(m.group().split()) == 2:
-            # Check and warn for "addtask task1 task2"
-            m2 = re.match(r"addtask\s+(?P<func>\w+)(?P<ignores>.*)", s) -            if m2 and m2.group('ignores'):
-                logger.warning('addtask ignored: "%s"' % m2.group('ignores'))

lib/bb/parse/parse_py/BBHandler.py +3 -7
-
-        # Check and warn for "addtask task1 before task2 before task3", the
-        # similar to "after"
-        taskexpression = s.split()
-        for word in ('before', 'after'):
-            if taskexpression.count(word) > 1:
-                logger.warning("addtask contained multiple '%s' keywords, only one is supported" % word)
+        after = ""
+        before = ""
+        tasks = m.group(1).split(" before ")[0].split(" after ")[0]

lib/bb/parse/parse_py/BBHandler.py def feeder(lineno, s, fn, root, statements, eof=False): · line 254

Quoted 10 lines
lib/bb/parse/parse_py/BBHandler.py +10 -0
+
+        for exp in m.group(1).split(" before "):
+            exp2 = exp.split(" after ")
+            if len(exp2) > 1:
+                after = after + " ".join(exp2[1:])
+
+        for exp in m.group(1).split(" after "):
+            exp2 = exp.split(" before ")
+            if len(exp2) > 1:
+                before = before + " ".join(exp2[1:])

I found it hard to understand what the code above is actually doing. How about something like this instead (untested):

        cur = "tasks"
        tasks = {"tasks": [], "before": [], "after": []}
        for task in m.group(1).split():
            if task in ("before", "after"):
                cur = task
            else:
                # Check and warn for having a task with a keyword as part of the task name
                if any(("%s_" % keyword) in task for keyword in bb.data_smart.__setvar_keyword__):
                    raise ParseError("Task name '%s' contains a keyword which is not recommended/supported.\nPlease rename the task not to include the keyword.\n%s" % (task, ("\n".join(map(str, bb.data_smart.__setvar_keyword__)))), fn)

Quoted 5 lines

                tasks[cur].append(task)

        if tasks["tasks"]:
            ast.handleAddTask(statements, fn, lineno, tasks["tasks"], tasks["before"], tasks["after"]) return

This isn't entirely straightforward. I was trying to split only on "before" and "after" and not on space characters. This leaves the expansion and splitting as late as possible. I appreciate it still isn't as late as it could be but it seemed to be a right step in the direction of allowing expressions which deltask does but addtask does not. The change brings them more into parity.

Cheers,

Richard

#6 lore raw

RE: [bitbake-devel] [PATCH 3/4] BBHandler/ast: Improve addtask handling

Quoted 184 lines

-----Original Message-----
From: [email protected] <bitbake- [email protected]> On Behalf Of Richard Purdie
Sent: den 13 augusti 2024 00:26
To: Peter Kjellerstedt <[email protected]>; bitbake- [email protected]
Subject: Re: [bitbake-devel] [PATCH 3/4] BBHandler/ast: Improve addtask handling

Quoted 2 lines · Peter Kjellerstedt
Quoted 2 lines

-----Original Message-----
From: [email protected] <bitbake-

[email protected]> On Behalf Of Richard Purdie

Quoted 3 lines
Quoted 3 lines

Sent: den 12 augusti 2024 17:54
To: [email protected]
Subject: [bitbake-devel] [PATCH 3/4] BBHandler/ast: Improve addtask

handling

Quoted 2 lines
Quoted 2 lines

The recent addtask improvement to handle comments complicated the

regex significantly

Quoted 1 line
Quoted 1 line

and there are already a number of corner cases in that code which

aren't handled well.

Quoted 2 lines
Quoted 2 lines

Instead of trying to complicate the regex further, switch to code

logic instead. This

Quoted 6 lines
Quoted 6 lines

means the following cases are now handled:

* addtask with multiple task names
* addtask with multiple before constraints
* addtask with multiple after constraints

Quoted 6 lines
Quoted 6 lines

The testcase is updated to match the improvements.

---
 lib/bb/parse/ast.py                | 26 +++++++------------- lib/bb/parse/parse_py/BBHandler.py | 38 +++++++++++++++++------------

-

Quoted 9 lines
Quoted 9 lines

 lib/bb/tests/parse.py              | 15 ++++--------

 3 files changed, 35 insertions(+), 44 deletions(-)
lib/bb/parse/ast.py +0 -0
index 7581d003fd..001ba8d289 100644
@@ -240,14 +240,16 @@ class ExportFuncsNode(AstNode):

                 data.setVar(func, sentinel + "    " + calledfunc +

"\n", parsing=True)

Quoted 16 lines
Quoted 16 lines

 class AddTaskNode(AstNode):
-    def __init__(self, filename, lineno, func, before, after):
+    def __init__(self, filename, lineno, tasks, before, after):
         AstNode.__init__(self, filename, lineno)
-        self.func = func
+        self.tasks = tasks
         self.before = before
         self.after = after

     def eval(self, data):
-        bb.build.addtask(self.func, self.before, self.after, data) +        tasks = self.tasks.split()
+        for task in tasks:
+            bb.build.addtask(task, self.before, self.after, data)

Quoted 3 lines

lib/bb/parse/ast.py def handlePythonMethod(statements, filename,

Quoted 3 lines

 class DelTaskNode(AstNode):
     def __init__(self, filename, lineno, tasks):

lib/bb/parse/ast.py +0 -0
@@ -348,21 +350,11 @@ def handlePythonMethod(statements, filename,

lineno, funcname, modulename, body)

Quoted 2 lines
Quoted 2 lines

 def handleExportFuncs(statements, filename, lineno, m, classname):
     statements.append(ExportFuncsNode(filename, lineno, m.group(1),

classname))

Quoted 9 lines

lib/bb/parse/ast.py def handlePythonMethod(statements, filename, lineno, funcname, modulename, body)

Quoted 9 lines
lib/bb/parse/ast.py +0 -8
-def handleAddTask(statements, filename, lineno, m):
-    func = m.group("func")
-    before = m.group("before")
-    after = m.group("after")
-    if func is None:
-        return
-
-    statements.append(AddTaskNode(filename, lineno, func, before,

after))

Quoted 6 lines

lib/bb/parse/ast.py def handlePythonMethod(statements, filename, lineno, funcname, modulename, body)

Quoted 6 lines
lib/bb/parse/ast.py +1 -5
-
-def handleDelTask(statements, filename, lineno, m):
-    func = m.group(1)
-    if func is None:
-        return
+def handleAddTask(statements, filename, lineno, tasks, before,

after):

Quoted 1 line
Quoted 1 line

+    statements.append(AddTaskNode(filename, lineno, tasks, before,

after))

Quoted 8 lines

Review

Quoted 8 lines

-    statements.append(DelTaskNode(filename, lineno, func)) +def handleDelTask(statements, filename, lineno, tasks):
+    statements.append(DelTaskNode(filename, lineno, tasks))

 def handleBBHandlers(statements, filename, lineno, m):
     statements.append(BBHandlerNode(filename, lineno, m.group(1)))

(quoted diff) +0 -0

b/lib/bb/parse/parse_py/BBHandler.py

Quoted 4 lines

lib/bb/parse/parse_py/BBHandler.py __func_start_regexp__    =

Quoted 4 lines

index c1653faeee..87c03e9238 100644

lib/bb/parse/parse_py/BBHandler.py +0 -0
@@ -23,7 +23,7 @@ __func_start_regexp__    =

re.compile(r"(((?P<py>python(?=(\s|\()))|(?P<fr>faker

Quoted 4 lines

lib/bb/parse/parse_py/BBHandler.py __func_start_regexp__ = re.compile(r"(((?P<py>python(?=(\s|\()))|(?P<fr>faker

Quoted 4 lines
lib/bb/parse/parse_py/BBHandler.py +0 -1
  __inherit_regexp__       = re.compile(r"inherit\s+(.+)" )
  __inherit_def_regexp__   = re.compile(r"inherit_defer\s+(.+)" )
  __export_func_regexp__   = re.compile(r"EXPORT_FUNCTIONS\s+(.+)" )
-__addtask_regexp__       =

re.compile(r"addtask\s+(?P<func>\w+)\s*((before\s*(?P<before>(([^#\n]*(?=a fter))|([^#\n]*))))|(after\s*(?P<after>(([^#\n]*(?=before))|([^#\n]*)))))* (?P<comment>#.*|.*?)")

Quoted 1 line

lib/bb/parse/parse_py/BBHandler.py __func_start_regexp__    = · line 26

Quoted 1 line
lib/bb/parse/parse_py/BBHandler.py +1 -0
+__addtask_regexp__       =

re.compile(r"addtask\s+([^#\n]+)(?P<comment>#.*|.*?)")

Quoted 1 line
Quoted 1 line

 __deltask_regexp__       =

re.compile(r"deltask\s+([^#\n]+)(?P<comment>#.*|.*?)")

Quoted 3 lines

lib/bb/parse/parse_py/BBHandler.py def feeder(lineno, s, fn, root, statements,

Quoted 3 lines

 __addhandler_regexp__    = re.compile(r"addhandler\s+(.+)" ) __def_regexp__           = re.compile(r"def\s+(\w+).*:" )

lib/bb/parse/parse_py/BBHandler.py +0 -0
@@ -239,29 +239,35 @@ def feeder(lineno, s, fn, root, statements,

eof=False):

Quoted 6 lines
Quoted 6 lines
lib/bb/parse/parse_py/BBHandler.py +0 -0
      m = __addtask_regexp__.match(s)

     if m:
-        if len(m.group().split()) == 2:
-            # Check and warn for "addtask task1 task2"
-            m2 = re.match(r"addtask\s+(?P<func>\w+)(?P<ignores>.*)",

s)

Quoted 2 lines
Quoted 2 lines

-            if m2 and m2.group('ignores'):
-                logger.warning('addtask ignored: "%s"' %

m2.group('ignores'))

Quoted 2 lines
Quoted 2 lines

-
-        # Check and warn for "addtask task1 before task2 before

task3", the

Quoted 5 lines
Quoted 5 lines

-        # similar to "after"
-        taskexpression = s.split()
-        for word in ('before', 'after'):
-            if taskexpression.count(word) > 1:
-                logger.warning("addtask contained multiple '%s'

keywords, only one is supported" % word)

Quoted 17 lines

lib/bb/parse/parse_py/BBHandler.py def feeder(lineno, s, fn, root, statements, eof=False): · line 254

Quoted 13 lines

+        after = ""
+        before = ""
+        tasks = m.group(1).split(" before ")[0].split(" after ")[0]

lib/bb/parse/parse_py/BBHandler.py +10 -0
+
+        for exp in m.group(1).split(" before "):
+            exp2 = exp.split(" after ")
+            if len(exp2) > 1:
+                after = after + " ".join(exp2[1:])
+
+        for exp in m.group(1).split(" after "):
+            exp2 = exp.split(" before ")
+            if len(exp2) > 1:
+                before = before + " ".join(exp2[1:])

I found it hard to understand what the code above is actually doing. How about something like this instead (untested):

Quoted 7 lines

        cur = "tasks"
        tasks = {"tasks": [], "before": [], "after": []} for task in m.group(1).split():
            if task in ("before", "after"):
                cur = task
            else:
                # Check and warn for having a task with a keyword as

part of the task name

Quoted 1 line

                if any(("%s_" % keyword) in task for keyword in

bb.data_smart.__setvar_keyword__):

Quoted 1 line

                    raise ParseError("Task name '%s' contains a keyword

which is not recommended/supported.\nPlease rename the task not to include the keyword.\n%s" % (task, ("\n".join(map(str, bb.data_smart.__setvar_keyword__)))), fn)

Quoted 5 lines

                tasks[cur].append(task)

        if tasks["tasks"]:
            ast.handleAddTask(statements, fn, lineno, tasks["tasks"],

tasks["before"], tasks["after"])

Quoted 1 line

        return

This isn't entirely straightforward. I was trying to split only on "before" and "after" and not on space characters. This leaves the expansion and splitting as late as possible. I appreciate it still isn't as late as it could be but it seemed to be a right step in the direction of allowing expressions which deltask does but addtask does not. The change brings them more into parity.

Quoted 3 lines

Cheers,

Richard

Ok, I understand. It might be a good idea to add a comment in the code along the above to explain why the code is doing what is doing.

//Peter

#7 lore raw

PATCH 4/4 build: Ensure addtask before/after tasknames have prefix applied

In reply to Richard Purdie

"addtask do_XXX before YYY after ZZZ "

where YYY or ZZZ is missing the "do_" prefix don't work as expected. Ajust the code so that it doesn't just silently do the wrong thing but works as expected.

Expand a test case to cover this.

---
 lib/bb/build.py       | 13 +++++++++----
 lib/bb/tests/parse.py |  6 +++++-
 2 files changed, 14 insertions(+), 5 deletions(-)
lib/bb/build.py +9 -4
index ab8bce3d57..d226aadacb 100644
@@ -932,9 +932,13 @@ def add_tasks(tasklist, d):
     # don't assume holding a reference
     d.setVar('_task_deps', task_deps)
 
+def ensure_task_prefix(name):
+    if name[:3] != "do_":
+        name = "do_" + name
+    return name
+
 def addtask(task, before, after, d):
-    if task[:3] != "do_":
-        task = "do_" + task
+    task = ensure_task_prefix(task)
 
     d.setVarFlag(task, "task", 1)
     bbtasks = d.getVar('__BBTASKS', False) or []
@@ -946,19 +950,20 @@ def addtask(task, before, after, d):
     if after is not None:
         # set up deps for function
         for entry in after.split():
+            entry = ensure_task_prefix(entry)
             if entry not in existing:
                 existing.append(entry)
     d.setVarFlag(task, "deps", existing)
     if before is not None:
         # set up things that depend on this func
         for entry in before.split():
+            entry = ensure_task_prefix(entry)
             existing = d.getVarFlag(entry, "deps", False) or []
             if task not in existing:
                 d.setVarFlag(entry, "deps", [task] + existing)
 
 def deltask(task, d):
-    if task[:3] != "do_":
-        task = "do_" + task
+    task = ensure_task_prefix(task)
 
     bbtasks = d.getVar('__BBTASKS', False) or []
     if task in bbtasks:
lib/bb/tests/parse.py +5 -1
index 97df2c4590..410679d5a1 100644
@@ -188,6 +188,9 @@ addtask do_mytask3
 deltask do_mytask3# comment
 deltask do_mytask4 # comment2
 
+# Ensure a missing task prefix on after works
+addtask do_mytask5 after mytask
+
 MYVAR = "do_patch"
 EMPTYVAR = ""
 deltask do_fetch ${MYVAR} ${EMPTYVAR}
@@ -198,7 +201,8 @@ deltask ${EMPTYVAR}
         f = self.parsehelper(self.addtask_deltask)
         d = bb.parse.handle(f.name, self.d)['']
 
-        self.assertEqual(['do_fetch2', 'do_patch2', 'do_myplaintask', 'do_mytask', 'do_mytask2'], d.getVar("__BBTASKS"))
+        self.assertEqual(['do_fetch2', 'do_patch2', 'do_myplaintask', 'do_mytask', 'do_mytask2', 'do_mytask5'], d.getVar("__BBTASKS"))
+        self.assertEqual(['do_mytask'], d.getVarFlag("do_mytask5", "deps"))
 
     broken_multiline_comment = """
 # First line of comment \\