From 03d18413853de8e1feb3068acf7f19e54c21dd12 Mon Sep 17 00:00:00 2001 From: Massimiliano Culpo Date: Wed, 3 May 2023 13:01:16 +0200 Subject: Allow adding specs to an environment without the 'specs' attribute (#37378) --- lib/spack/spack/environment/environment.py | 4 ++-- lib/spack/spack/test/env.py | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/spack/spack/environment/environment.py b/lib/spack/spack/environment/environment.py index eedca8daaa..9c1c2e4346 100644 --- a/lib/spack/spack/environment/environment.py +++ b/lib/spack/spack/environment/environment.py @@ -2606,8 +2606,8 @@ class EnvironmentManifestFile(collections.abc.Mapping): Args: user_spec: user spec to be appended """ - config_dict(self.pristine_yaml_content)["specs"].append(user_spec) - config_dict(self.yaml_content)["specs"].append(user_spec) + config_dict(self.pristine_yaml_content).setdefault("specs", []).append(user_spec) + config_dict(self.yaml_content).setdefault("specs", []).append(user_spec) self.changed = True def remove_user_spec(self, user_spec: str) -> None: diff --git a/lib/spack/spack/test/env.py b/lib/spack/spack/test/env.py index 913eb7bf9e..16a8cb4ff8 100644 --- a/lib/spack/spack/test/env.py +++ b/lib/spack/spack/test/env.py @@ -363,3 +363,25 @@ def test_error_on_nonempty_view_dir(tmpdir): with pytest.raises(SpackEnvironmentViewError): _error_on_nonempty_view_dir("file") + + +def test_can_add_specs_to_environment_without_specs_attribute(tmp_path, mock_packages, config): + """Sometimes users have template manifest files, and save one line in the YAML file by + removing the empty 'specs: []' attribute. This test ensures that adding a spec to an + environment without the 'specs' attribute, creates the attribute first instead of returning + an error. + """ + spack_yaml = tmp_path / "spack.yaml" + spack_yaml.write_text( + """ +spack: + view: true + concretizer: + unify: true + """ + ) + env = ev.Environment(tmp_path) + env.add("a") + + assert len(env.user_specs) == 1 + assert env.manifest.pristine_yaml_content["spack"]["specs"] == ["a"] -- cgit v1.2.3-60-g2f50