diff mbox series

[1/2] tinfoil: Refactor temporary data tracking in a context manager

Message ID 20250314235214.1540-1-yoann.congal@smile.fr
State Accepted, archived
Commit 0fea4555d2143c6b23a79d3d5cf791103a68141b
Headers show
Series [1/2] tinfoil: Refactor temporary data tracking in a context manager | expand

Commit Message

Yoann Congal March 14, 2025, 11:52 p.m. UTC
From: Yoann Congal <yoann.congal@smile.fr>

A new context manager Tinfoil._data_tracked_if_enabled() is introduced to
replace the following structure:
  if self.tracking:
      self.run_command('enableDataTracking')
  # Code that need data tracking
  if self.tracking:
      self.run_command('disableDataTracking')

Signed-off-by: Yoann Congal <yoann.congal@smile.fr>
---
 lib/bb/tinfoil.py | 25 ++++++++++++++++++-------
 1 file changed, 18 insertions(+), 7 deletions(-)
diff mbox series

Patch

diff --git a/lib/bb/tinfoil.py b/lib/bb/tinfoil.py
index 13b05cec..60359a1a 100644
--- a/lib/bb/tinfoil.py
+++ b/lib/bb/tinfoil.py
@@ -15,6 +15,7 @@  import atexit
 import re
 from collections import OrderedDict, defaultdict
 from functools import partial
+from contextlib import contextmanager
 
 import bb.cache
 import bb.cooker
@@ -641,6 +642,22 @@  class Tinfoil:
         fn = self.get_recipe_file(pn)
         return self.parse_recipe_file(fn)
 
+    @contextmanager
+    def _data_tracked_if_enabled(self):
+        """
+        A context manager to enable data tracking for a code segment if data
+        tracking was enabled for this tinfoil instance.
+        """
+        if self.tracking:
+            # Enable history tracking just for the operation
+            self.run_command('enableDataTracking')
+
+        # Here goes the operation with the optional data tracking
+        yield
+
+        if self.tracking:
+            self.run_command('disableDataTracking')
+
     def finalizeData(self):
         """
         Run anonymous functions and expand keys
@@ -659,10 +676,7 @@  class Tinfoil:
             appendlist: optional list of bbappend files to apply, if you
                         want to filter them
         """
-        if self.tracking:
-            # Enable history tracking just for the parse operation
-            self.run_command('enableDataTracking')
-        try:
+        with self._data_tracked_if_enabled():
             if appends and appendlist == []:
                 appends = False
             if config_data:
@@ -674,9 +688,6 @@  class Tinfoil:
                 return self._reconvert_type(dscon, 'DataStoreConnectionHandle')
             else:
                 return None
-        finally:
-            if self.tracking:
-                self.run_command('disableDataTracking')
 
     def build_file(self, buildfile, task, internal=True):
         """