From 3e6e9829da433246b5777384d00d72af1c479ae8 Mon Sep 17 00:00:00 2001 From: Harmen Stoppels Date: Mon, 29 Apr 2024 16:53:27 +0200 Subject: [PATCH] compiler.py: fix early return (#43898) --- lib/spack/spack/compiler.py | 11 ++++------- lib/spack/spack/test/compilers/basics.py | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/lib/spack/spack/compiler.py b/lib/spack/spack/compiler.py index 251ce682c8..72d56e590f 100644 --- a/lib/spack/spack/compiler.py +++ b/lib/spack/spack/compiler.py @@ -20,6 +20,7 @@ import spack.compilers import spack.error +import spack.schema.environment import spack.spec import spack.util.executable import spack.util.libc @@ -683,8 +684,8 @@ def __str__(self): @contextlib.contextmanager def compiler_environment(self): - # yield immediately if no modules - if not self.modules: + # Avoid modifying os.environ if possible. + if not self.modules and not self.environment: yield return @@ -701,13 +702,9 @@ def compiler_environment(self): spack.util.module_cmd.load_module(module) # apply other compiler environment changes - env = spack.util.environment.EnvironmentModifications() - env.extend(spack.schema.environment.parse(self.environment)) - env.apply_modifications() + spack.schema.environment.parse(self.environment).apply_modifications() yield - except BaseException: - raise finally: # Restore environment regardless of whether inner code succeeded os.environ.clear() diff --git a/lib/spack/spack/test/compilers/basics.py b/lib/spack/spack/test/compilers/basics.py index 84b48adba8..2c46d434d1 100644 --- a/lib/spack/spack/test/compilers/basics.py +++ b/lib/spack/spack/test/compilers/basics.py @@ -943,3 +943,17 @@ def test_detection_requires_c_compiler(detected_versions, expected_length): """ result = spack.compilers.make_compiler_list(detected_versions) assert len(result) == expected_length + + +def test_compiler_environment(working_env): + """Test whether environment modifications from compilers are applied in compiler_environment""" + os.environ.pop("TEST", None) + compiler = Compiler( + "gcc@=13.2.0", + operating_system="ubuntu20.04", + target="x86_64", + paths=["/test/bin/gcc", "/test/bin/g++"], + environment={"set": {"TEST": "yes"}}, + ) + with compiler.compiler_environment(): + assert os.environ["TEST"] == "yes"