summaryrefslogtreecommitdiff
path: root/lib/spack/spack/test/cmd/config.py
blob: 6bc19831a5f2b3b96d91be7c66ed5c35df1b4d63 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# Copyright 2013-2024 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import functools
import os

import pytest

import llnl.util.filesystem as fs

import spack.config
import spack.database
import spack.environment as ev
import spack.main
import spack.schema.config
import spack.spec
import spack.store
import spack.util.spack_yaml as syaml

config = spack.main.SpackCommand("config")
env = spack.main.SpackCommand("env")


def _create_config(scope=None, data={}, section="packages"):
    scope = scope or spack.config.default_modify_scope()
    cfg_file = spack.config.CONFIG.get_config_filename(scope, section)
    with open(cfg_file, "w") as f:
        syaml.dump(data, stream=f)
    return cfg_file


@pytest.fixture()
def config_yaml_v015(mutable_config):
    """Create a packages.yaml in the old format"""
    old_data = {
        "config": {"install_tree": "/fake/path", "install_path_scheme": "{name}-{version}"}
    }
    return functools.partial(_create_config, data=old_data, section="config")


def test_get_config_scope(mock_low_high_config):
    assert config("get", "compilers").strip() == "compilers: {}"


def test_get_config_scope_merged(mock_low_high_config):
    low_path = mock_low_high_config.scopes["low"].path
    high_path = mock_low_high_config.scopes["high"].path

    fs.mkdirp(low_path)
    fs.mkdirp(high_path)

    with open(os.path.join(low_path, "repos.yaml"), "w") as f:
        f.write(
            """\
repos:
- repo3
"""
        )

    with open(os.path.join(high_path, "repos.yaml"), "w") as f:
        f.write(
            """\
repos:
- repo1
- repo2
"""
        )

    assert (
        config("get", "repos").strip()
        == """repos:
- repo1
- repo2
- repo3"""
    )


def test_config_edit(mutable_config, working_env):
    """Ensure `spack config edit` edits the right paths."""

    dms = spack.config.default_modify_scope("compilers")
    dms_path = spack.config.CONFIG.scopes[dms].path
    user_path = spack.config.CONFIG.scopes["user"].path

    comp_path = os.path.join(dms_path, "compilers.yaml")
    repos_path = os.path.join(user_path, "repos.yaml")

    assert config("edit", "--print-file", "compilers").strip() == comp_path
    assert config("edit", "--print-file", "repos").strip() == repos_path


def test_config_get_gets_spack_yaml(mutable_mock_env_path):
    with ev.create("test") as env:
        assert "mpileaks" not in config("get")
        env.add("mpileaks")
        env.write()
        assert "mpileaks" in config("get")


def test_config_edit_edits_spack_yaml(mutable_mock_env_path):
    env = ev.create("test")
    with env:
        assert config("edit", "--print-file").strip() == env.manifest_path


def test_config_add_with_scope_adds_to_scope(mutable_config, mutable_mock_env_path):
    """Test adding to non-env config scope with an active environment"""
    env = ev.create("test")
    with env:
        config("--scope=user", "add", "config:install_tree:root:/usr")
    assert spack.config.get("config:install_tree:root", scope="user") == "/usr"


def test_config_edit_fails_correctly_with_no_env(mutable_mock_env_path):
    output = config("edit", "--print-file", fail_on_error=False)
    assert "requires a section argument or an active environment" in output


def test_config_list():
    output = config("list")
    assert "compilers" in output
    assert "packages" in output


def test_config_add(mutable_empty_config):
    config("add", "config:dirty:true")
    output = config("get", "config")

    assert (
        output
        == """config:
  dirty: true
"""
    )


def test_config_add_list(mutable_empty_config):
    config("add", "config:template_dirs:test1")
    config("add", "config:template_dirs:[test2]")
    config("add", "config:template_dirs:test3")
    output = config("get", "config")

    assert (
        output
        == """config:
  template_dirs:
  - test3
  - test2
  - test1
"""
    )


def test_config_add_override(mutable_empty_config):
    config("--scope", "site", "add", "config:template_dirs:test1")
    config("add", "config:template_dirs:[test2]")
    output = config("get", "config")

    assert (
        output
        == """config:
  template_dirs:
  - test2
  - test1
"""
    )

    config("add", "config::template_dirs:[test2]")
    output = config("get", "config")

    assert (
        output
        == """config:
  template_dirs:
  - test2
"""
    )


def test_config_add_override_leaf(mutable_empty_config):
    config("--scope", "site", "add", "config:template_dirs:test1")
    config("add", "config:template_dirs:[test2]")
    output = config("get", "config")

    assert (
        output
        == """config:
  template_dirs:
  - test2
  - test1
"""
    )

    config("add", "config:template_dirs::[test2]")
    output = config("get", "config")

    assert (
        output
        == """config:
  'template_dirs:':
  - test2
"""
    )


def test_config_add_update_dict(mutable_empty_config):
    config("add", "packages:hdf5:version:[1.0.0]")
    output = config("get", "packages")

    expected = "packages:\n  hdf5:\n    version: [1.0.0]\n"
    assert output == expected


def test_config_with_c_argument(mutable_empty_config):
    # I don't know how to add a spack argument to a Spack Command, so we test this way
    config_file = "config:install_root:root:/path/to/config.yaml"
    parser = spack.main.make_argument_parser()
    args = parser.parse_args(["-c", config_file])
    assert config_file in args.config_vars

    # Add the path to the config
    config("add", args.config_vars[0], scope="command_line")
    output = config("get", "config")
    assert "config:\n  install_root:\n    root: /path/to/config.yaml" in output


def test_config_add_ordered_dict(mutable_empty_config):
    config("add", "mirrors:first:/path/to/first")
    config("add", "mirrors:second:/path/to/second")
    output = config("get", "mirrors")

    assert (
        output
        == """mirrors:
  first: /path/to/first
  second: /path/to/second
"""
    )


def test_config_add_interpret_oneof(mutable_empty_config):
    # Regression test for a bug that would raise a validation error
    config("add", "packages:all:target:[x86_64]")
    config("add", "packages:all:variants:~shared")


def test_config_add_invalid_fails(mutable_empty_config):
    config("add", "packages:all:variants:+debug")
    with pytest.raises((spack.config.ConfigFormatError, AttributeError)):
        config("add", "packages:all:True")


def test_config_add_from_file(mutable_empty_config, tmpdir):
    contents = """spack:
  config:
    dirty: true
"""

    file = str(tmpdir.join("spack.yaml"))
    with open(file, "w") as f:
        f.write(contents)
    config("add", "-f", file)
    output = config("get", "config")

    assert (
        output
        == """config:
  dirty: true
"""
    )


def test_config_add_from_file_multiple(mutable_empty_config, tmpdir):
    contents = """spack:
  config:
    dirty: true
    template_dirs: [test1]
"""

    file = str(tmpdir.join("spack.yaml"))
    with open(file, "w") as f:
        f.write(contents)
    config("add", "-f", file)
    output = config("get", "config")

    assert (
        output
        == """config:
  dirty: true
  template_dirs: [test1]
"""
    )


def test_config_add_override_from_file(mutable_empty_config, tmpdir):
    config("--scope", "site", "add", "config:template_dirs:test1")
    contents = """spack:
  config::
    template_dirs: [test2]
"""

    file = str(tmpdir.join("spack.yaml"))
    with open(file, "w") as f:
        f.write(contents)
    config("add", "-f", file)
    output = config("get", "config")

    assert (
        output
        == """config:
  template_dirs: [test2]
"""
    )


def test_config_add_override_leaf_from_file(mutable_empty_config, tmpdir):
    config("--scope", "site", "add", "config:template_dirs:test1")
    contents = """spack:
  config:
    template_dirs:: [test2]
"""

    file = str(tmpdir.join("spack.yaml"))
    with open(file, "w") as f:
        f.write(contents)
    config("add", "-f", file)
    output = config("get", "config")

    assert (
        output
        == """config:
  'template_dirs:': [test2]
"""
    )


def test_config_add_update_dict_from_file(mutable_empty_config, tmpdir):
    config("add", "packages:all:compiler:[gcc]")

    # contents to add to file
    contents = """spack:
  packages:
    all:
      target: [x86_64]
"""

    # create temp file and add it to config
    file = str(tmpdir.join("spack.yaml"))
    with open(file, "w") as f:
        f.write(contents)
    config("add", "-f", file)

    # get results
    output = config("get", "packages")

    # added config comes before prior config
    expected = """packages:
  all:
    target: [x86_64]
    compiler: [gcc]
"""

    assert expected == output


def test_config_add_invalid_file_fails(tmpdir):
    # contents to add to file
    # invalid because version requires a list
    contents = """spack:
  packages:
    hdf5:
      version: 1.0.0
"""

    # create temp file and add it to config
    file = str(tmpdir.join("spack.yaml"))
    with open(file, "w") as f:
        f.write(contents)

    with pytest.raises((spack.config.ConfigFormatError)):
        config("add", "-f", file)


def test_config_remove_value(mutable_empty_config):
    config("add", "config:dirty:true")
    config("remove", "config:dirty:true")
    output = config("get", "config")

    assert (
        output
        == """config: {}
"""
    )


def test_config_remove_alias_rm(mutable_empty_config):
    config("add", "config:dirty:true")
    config("rm", "config:dirty:true")
    output = config("get", "config")

    assert (
        output
        == """config: {}
"""
    )


def test_config_remove_dict(mutable_empty_config):
    config("add", "config:dirty:true")
    config("rm", "config:dirty")
    output = config("get", "config")

    assert (
        output
        == """config: {}
"""
    )


def test_remove_from_list(mutable_empty_config):
    config("add", "config:template_dirs:test1")
    config("add", "config:template_dirs:[test2]")
    config("add", "config:template_dirs:test3")
    config("remove", "config:template_dirs:test2")
    output = config("get", "config")

    assert (
        output
        == """config:
  template_dirs:
  - test3
  - test1
"""
    )


def test_remove_list(mutable_empty_config):
    config("add", "config:template_dirs:test1")
    config("add", "config:template_dirs:[test2]")
    config("add", "config:template_dirs:test3")
    config("remove", "config:template_dirs:[test2]")
    output = config("get", "config")

    assert (
        output
        == """config:
  template_dirs:
  - test3
  - test1
"""
    )


def test_config_add_to_env(mutable_empty_config, mutable_mock_env_path):
    env("create", "test")
    with ev.read("test"):
        config("add", "config:dirty:true")
        output = config("get")

    expected = """  config:
    dirty: true
"""
    assert expected in output


def test_config_add_to_env_preserve_comments(mutable_empty_config, mutable_mock_env_path, tmpdir):
    filepath = str(tmpdir.join("spack.yaml"))
    manifest = """# comment
spack:  # comment
  # comment
  specs:  # comment
  - foo  # comment
  # comment
  view: true  # comment
  packages:  # comment
    # comment
    all: # comment
      # comment
      compiler: [gcc] # comment
"""
    with open(filepath, "w") as f:
        f.write(manifest)
    env = ev.Environment(str(tmpdir))
    with env:
        config("add", "config:dirty:true")
        output = config("get")

    assert "# comment" in output
    assert "dirty: true" in output


def test_config_remove_from_env(mutable_empty_config, mutable_mock_env_path):
    env("create", "test")
    with ev.read("test"):
        config("add", "config:dirty:true")
        output = config("get")
    assert "dirty: true" in output

    with ev.read("test"):
        config("rm", "config:dirty")
        output = config("get")
    assert "dirty: true" not in output


def test_config_update_config(config_yaml_v015):
    config_yaml_v015()
    config("update", "-y", "config")

    # Check the entires have been transformed
    data = spack.config.get("config")
    check_config_updated(data)


def test_config_update_not_needed(mutable_config):
    data_before = spack.config.get("repos")
    config("update", "-y", "repos")
    data_after = spack.config.get("repos")
    assert data_before == data_after


@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, "config")
    with open(cfg_file, mode="w") as f:
        f.write(
            """
config:
  # system cmake in /usr
  install_tree: './foo'
  # Another comment after the outdated section
  install_hash_length: 7
"""
        )

    # Try to update it, it should not raise errors
    config("update", "-y", "config")

    # Check data
    data = spack.config.get("config", scope=scope)
    assert "root" in data["install_tree"]

    # 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


@pytest.mark.regression("18050")
def test_config_update_works_for_empty_paths(mutable_config):
    scope = spack.config.default_modify_scope()
    cfg_file = spack.config.CONFIG.get_config_filename(scope, "config")
    with open(cfg_file, mode="w") as f:
        f.write(
            """
config:
    install_tree: ''
"""
        )

    # Try to update it, it should not raise errors
    output = config("update", "-y", "config")

    # This ensures that we updated the configuration
    assert "[backup=" in output


def check_config_updated(data):
    assert isinstance(data["install_tree"], dict)
    assert data["install_tree"]["root"] == "/fake/path"
    assert data["install_tree"]["projections"] == {"all": "{name}-{version}"}


def test_config_update_shared_linking(mutable_config):
    # Old syntax: config:shared_linking:rpath/runpath
    # New syntax: config:shared_linking:{type:rpath/runpath,bind:True/False}
    with spack.config.override("config:shared_linking", "runpath"):
        assert spack.config.get("config:shared_linking:type") == "runpath"
        assert not spack.config.get("config:shared_linking:bind")


def test_config_prefer_upstream(
    tmpdir_factory, install_mockery, mock_fetch, mutable_config, gen_mock_layout, monkeypatch
):
    """Check that when a dependency package is recorded as installed in
    an upstream database that it is not reinstalled.
    """

    mock_db_root = str(tmpdir_factory.mktemp("mock_db_root"))
    prepared_db = spack.database.Database(mock_db_root)

    upstream_layout = gen_mock_layout("/a/")

    for spec in ["hdf5 +mpi", "hdf5 ~mpi", "boost+debug~icu+graph", "dependency-install", "patch"]:
        dep = spack.spec.Spec(spec)
        dep.concretize()
        prepared_db.add(dep, upstream_layout)

    downstream_db_root = str(tmpdir_factory.mktemp("mock_downstream_db_root"))
    db_for_test = spack.database.Database(downstream_db_root, upstream_dbs=[prepared_db])
    monkeypatch.setattr(spack.store.STORE, "db", db_for_test)

    output = config("prefer-upstream")
    scope = spack.config.default_modify_scope("packages")
    cfg_file = spack.config.CONFIG.get_config_filename(scope, "packages")
    packages = syaml.load(open(cfg_file))["packages"]

    # Make sure only the non-default variants are set.
    assert packages["all"] == {"compiler": ["gcc@=10.2.1"]}
    assert packages["boost"] == {"variants": "+debug +graph", "version": ["1.63.0"]}
    assert packages["dependency-install"] == {"version": ["2.0"]}
    # Ensure that neither variant gets listed for hdf5, since they conflict
    assert packages["hdf5"] == {"version": ["2.3"]}

    # Make sure a message about the conflicting hdf5's was given.
    assert "- hdf5" in output


def test_environment_config_update(tmpdir, mutable_config, monkeypatch):
    with open(tmpdir.join("spack.yaml"), "w") as f:
        f.write(
            """\
spack:
  config:
    ccache: true
"""
        )

    def update_config(data):
        data["ccache"] = False
        return True

    monkeypatch.setattr(spack.schema.config, "update", update_config)

    with ev.Environment(str(tmpdir)):
        config("update", "-y", "config")

    with ev.Environment(str(tmpdir)) as e:
        assert not e.manifest.pristine_yaml_content["spack"]["config"]["ccache"]