From d2f56830f1162ddf100d1a5e6634e83a1ede079c Mon Sep 17 00:00:00 2001
From: Massimiliano Culpo <massimiliano.culpo@gmail.com>
Date: Thu, 13 Aug 2020 18:54:07 +0200
Subject: [PATCH] "spack config update" can handle comments in YAML files
 (#18045)

fixes #18031

With this fix "spack config update" can update YAML
files that contain comments, while previously it
couldn't.
---
 lib/spack/spack/cmd/config.py      |  2 +-
 lib/spack/spack/test/cmd/config.py | 36 ++++++++++++++++++++++++++++++
 2 files changed, 37 insertions(+), 1 deletion(-)

diff --git a/lib/spack/spack/cmd/config.py b/lib/spack/spack/cmd/config.py
index e684364d8a..ea5b038e66 100644
--- a/lib/spack/spack/cmd/config.py
+++ b/lib/spack/spack/cmd/config.py
@@ -363,7 +363,7 @@ def config_update(args):
             scope.name, args.section
         )
         with open(cfg_file) as f:
-            data = syaml.load(f) or {}
+            data = syaml.load_config(f) or {}
             data = data.pop(args.section, {})
         update_fn(data)
 
diff --git a/lib/spack/spack/test/cmd/config.py b/lib/spack/spack/test/cmd/config.py
index 524636fed6..97b76dbee1 100644
--- a/lib/spack/spack/test/cmd/config.py
+++ b/lib/spack/spack/test/cmd/config.py
@@ -515,6 +515,42 @@ def test_updating_multiple_scopes_at_once(packages_yaml_v015):
         check_update(data)
 
 
+@pytest.mark.regression('18031')
+def test_config_update_can_handle_comments(mutable_config):
+    # Create an outdated config file with comments
+    scope = spack.config.default_modify_scope()
+    cfg_file = spack.config.config.get_config_filename(scope, 'packages')
+    with open(cfg_file, mode='w') as f:
+        f.write("""
+packages:
+  # system cmake in /usr
+  cmake:
+    paths:
+      cmake@3.14.0:  /usr
+    # Another comment after the outdated section
+    buildable: False
+""")
+
+    # Try to update it, it should not raise errors
+    config('update', '-y', 'packages')
+
+    # Check data
+    data = spack.config.get('packages', scope=scope)
+    assert 'paths' not in data['cmake']
+    assert 'externals' in data['cmake']
+    externals = data['cmake']['externals']
+    assert len(externals) == 1
+    assert externals[0]['spec'] == 'cmake@3.14.0'
+    assert externals[0]['prefix'] == '/usr'
+
+    # Check the comment is there
+    with open(cfg_file) as f:
+        text = ''.join(f.readlines())
+
+    assert '# system cmake in /usr' in text
+    assert '# Another comment after the outdated section' in text
+
+
 def check_update(data):
     """Check that the data from the packages_yaml_v015
     has been updated.
-- 
GitLab