bitbake: utils: add environment updating context manager

bb.utils.environment() is a context manager to alter os.environ inside
a specific block, restoring it after the block is closed.

(Bitbake rev: 9974848f67581ff7d76cef52a94f505af99b4932)

Signed-off-by: Ross Burton <ross.burton@arm.com>
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
This commit is contained in:
Ross Burton
2021-08-10 17:55:06 +01:00
committed by Richard Purdie
parent 0975ff9b69
commit 62098f9041
2 changed files with 34 additions and 0 deletions

View File

@@ -666,3 +666,21 @@ class GetReferencedVars(unittest.TestCase):
layers = [{"SRC_URI"}, {"QT_GIT", "QT_MODULE", "QT_MODULE_BRANCH_PARAM", "QT_GIT_PROTOCOL"}, {"QT_GIT_PROJECT", "QT_MODULE_BRANCH", "BPN"}, {"PN", "SPECIAL_PKGSUFFIX"}]
self.check_referenced("${SRC_URI}", layers)
class EnvironmentTests(unittest.TestCase):
def test_environment(self):
os.environ["A"] = "this is A"
self.assertIn("A", os.environ)
self.assertEqual(os.environ["A"], "this is A")
self.assertNotIn("B", os.environ)
with bb.utils.environment(B="this is B"):
self.assertIn("A", os.environ)
self.assertEqual(os.environ["A"], "this is A")
self.assertIn("B", os.environ)
self.assertEqual(os.environ["B"], "this is B")
self.assertIn("A", os.environ)
self.assertEqual(os.environ["A"], "this is A")
self.assertNotIn("B", os.environ)

View File

@@ -1681,3 +1681,19 @@ def rename(src, dst):
shutil.move(src, dst)
else:
raise err
@contextmanager
def environment(**envvars):
"""
Context manager to selectively update the environment with the specified mapping.
"""
backup = dict(os.environ)
try:
os.environ.update(envvars)
yield
finally:
for var in envvars:
if var in backup:
os.environ[var] = backup[var]
else:
del os.environ[var]