summaryrefslogtreecommitdiffstats
path: root/src/tools/cargo/tests/testsuite/config.rs
blob: 7078fc445fb8be6dcd89d0319050e1bcb633b014 (plain)
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
//! Tests for config settings.

use cargo::core::{PackageIdSpec, Shell};
use cargo::util::config::{self, Config, Definition, JobsConfig, SslVersionConfig, StringList};
use cargo::util::interning::InternedString;
use cargo::util::toml::{self as cargo_toml, TomlDebugInfo, VecStringOrBool as VSOB};
use cargo::CargoResult;
use cargo_test_support::compare;
use cargo_test_support::{panic_error, paths, project, symlink_supported, t};
use serde::Deserialize;
use std::borrow::Borrow;
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io;
use std::os;
use std::path::{Path, PathBuf};

/// Helper for constructing a `Config` object.
pub struct ConfigBuilder {
    env: HashMap<String, String>,
    unstable: Vec<String>,
    config_args: Vec<String>,
    cwd: Option<PathBuf>,
    enable_nightly_features: bool,
}

impl ConfigBuilder {
    pub fn new() -> ConfigBuilder {
        ConfigBuilder {
            env: HashMap::new(),
            unstable: Vec::new(),
            config_args: Vec::new(),
            cwd: None,
            enable_nightly_features: false,
        }
    }

    /// Passes a `-Z` flag.
    pub fn unstable_flag(&mut self, s: impl Into<String>) -> &mut Self {
        self.unstable.push(s.into());
        self
    }

    /// Sets an environment variable.
    pub fn env(&mut self, key: impl Into<String>, val: impl Into<String>) -> &mut Self {
        self.env.insert(key.into(), val.into());
        self
    }

    /// Unconditionally enable nightly features, even on stable channels.
    pub fn nightly_features_allowed(&mut self, allowed: bool) -> &mut Self {
        self.enable_nightly_features = allowed;
        self
    }

    /// Passes a `--config` flag.
    pub fn config_arg(&mut self, arg: impl Into<String>) -> &mut Self {
        self.config_args.push(arg.into());
        self
    }

    /// Sets the current working directory where config files will be loaded.
    pub fn cwd(&mut self, path: impl AsRef<Path>) -> &mut Self {
        self.cwd = Some(paths::root().join(path.as_ref()));
        self
    }

    /// Creates the `Config`.
    pub fn build(&self) -> Config {
        self.build_err().unwrap()
    }

    /// Creates the `Config`, returning a Result.
    pub fn build_err(&self) -> CargoResult<Config> {
        let output = Box::new(fs::File::create(paths::root().join("shell.out")).unwrap());
        let shell = Shell::from_write(output);
        let cwd = self.cwd.clone().unwrap_or_else(|| paths::root());
        let homedir = paths::home();
        let mut config = Config::new(shell, cwd, homedir);
        config.nightly_features_allowed = self.enable_nightly_features || !self.unstable.is_empty();
        config.set_env(self.env.clone());
        config.set_search_stop_path(paths::root());
        config.configure(
            0,
            false,
            None,
            false,
            false,
            false,
            &None,
            &self.unstable,
            &self.config_args,
        )?;
        Ok(config)
    }
}

fn new_config() -> Config {
    ConfigBuilder::new().build()
}

/// Read the output from Config.
pub fn read_output(config: Config) -> String {
    drop(config); // Paranoid about flushing the file.
    let path = paths::root().join("shell.out");
    fs::read_to_string(path).unwrap()
}

#[cargo_test]
fn read_env_vars_for_config() {
    let p = project()
        .file(
            "Cargo.toml",
            r#"
                [package]
                name = "foo"
                authors = []
                version = "0.0.0"
                build = "build.rs"
            "#,
        )
        .file("src/lib.rs", "")
        .file(
            "build.rs",
            r#"
                use std::env;
                fn main() {
                    assert_eq!(env::var("NUM_JOBS").unwrap(), "100");
                }
            "#,
        )
        .build();

    p.cargo("check").env("CARGO_BUILD_JOBS", "100").run();
}

pub fn write_config(config: &str) {
    write_config_at(paths::root().join(".cargo/config"), config);
}

pub fn write_config_at(path: impl AsRef<Path>, contents: &str) {
    let path = paths::root().join(path.as_ref());
    fs::create_dir_all(path.parent().unwrap()).unwrap();
    fs::write(path, contents).unwrap();
}

pub fn write_config_toml(config: &str) {
    write_config_at(paths::root().join(".cargo/config.toml"), config);
}

#[cfg(unix)]
fn symlink_file(target: &Path, link: &Path) -> io::Result<()> {
    os::unix::fs::symlink(target, link)
}

#[cfg(windows)]
fn symlink_file(target: &Path, link: &Path) -> io::Result<()> {
    os::windows::fs::symlink_file(target, link)
}

fn symlink_config_to_config_toml() {
    let toml_path = paths::root().join(".cargo/config.toml");
    let symlink_path = paths::root().join(".cargo/config");
    t!(symlink_file(&toml_path, &symlink_path));
}

#[track_caller]
pub fn assert_error<E: Borrow<anyhow::Error>>(error: E, msgs: &str) {
    let causes = error
        .borrow()
        .chain()
        .enumerate()
        .map(|(i, e)| {
            if i == 0 {
                e.to_string()
            } else {
                format!("Caused by:\n  {}", e)
            }
        })
        .collect::<Vec<_>>()
        .join("\n\n");
    assert_match(msgs, &causes);
}

#[track_caller]
pub fn assert_match(expected: &str, actual: &str) {
    if let Err(e) = compare::match_exact(expected, actual, "output", "", None) {
        panic_error("", e);
    }
}

#[cargo_test]
fn get_config() {
    write_config(
        "\
[S]
f1 = 123
",
    );

    let config = new_config();

    #[derive(Debug, Deserialize, Eq, PartialEq)]
    struct S {
        f1: Option<i64>,
    }
    let s: S = config.get("S").unwrap();
    assert_eq!(s, S { f1: Some(123) });
    let config = ConfigBuilder::new().env("CARGO_S_F1", "456").build();
    let s: S = config.get("S").unwrap();
    assert_eq!(s, S { f1: Some(456) });
}

#[cfg(windows)]
#[cargo_test]
fn environment_variable_casing() {
    // Issue #11814: Environment variable names are case-insensitive on Windows.
    let config = ConfigBuilder::new()
        .env("Path", "abc")
        .env("Two-Words", "abc")
        .env("two_words", "def")
        .build();

    let var = config.get_env("PATH").unwrap();
    assert_eq!(var, String::from("abc"));

    let var = config.get_env("path").unwrap();
    assert_eq!(var, String::from("abc"));

    let var = config.get_env("TWO-WORDS").unwrap();
    assert_eq!(var, String::from("abc"));

    // Make sure that we can still distinguish between dashes and underscores
    // in variable names.
    let var = config.get_env("Two_Words").unwrap();
    assert_eq!(var, String::from("def"));
}

#[cargo_test]
fn config_works_with_extension() {
    write_config_toml(
        "\
[foo]
f1 = 1
",
    );

    let config = new_config();

    assert_eq!(config.get::<Option<i32>>("foo.f1").unwrap(), Some(1));
}

#[cargo_test]
fn config_ambiguous_filename_symlink_doesnt_warn() {
    // Windows requires special permissions to create symlinks.
    // If we don't have permission, just skip this test.
    if !symlink_supported() {
        return;
    };

    write_config_toml(
        "\
[foo]
f1 = 1
",
    );

    symlink_config_to_config_toml();

    let config = new_config();

    assert_eq!(config.get::<Option<i32>>("foo.f1").unwrap(), Some(1));

    // It should NOT have warned for the symlink.
    let output = read_output(config);
    assert_eq!(output, "");
}

#[cargo_test]
fn config_ambiguous_filename() {
    write_config(
        "\
[foo]
f1 = 1
",
    );

    write_config_toml(
        "\
[foo]
f1 = 2
",
    );

    let config = new_config();

    // It should use the value from the one without the extension for
    // backwards compatibility.
    assert_eq!(config.get::<Option<i32>>("foo.f1").unwrap(), Some(1));

    // But it also should have warned.
    let output = read_output(config);
    let expected = "\
warning: Both `[..]/.cargo/config` and `[..]/.cargo/config.toml` exist. Using `[..]/.cargo/config`
";
    assert_match(expected, &output);
}

#[cargo_test]
fn config_unused_fields() {
    write_config(
        "\
[S]
unused = 456
",
    );

    let config = ConfigBuilder::new()
        .env("CARGO_S_UNUSED2", "1")
        .env("CARGO_S2_UNUSED", "2")
        .build();

    #[derive(Debug, Deserialize, Eq, PartialEq)]
    struct S {
        f1: Option<i64>,
    }
    // This prints a warning (verified below).
    let s: S = config.get("S").unwrap();
    assert_eq!(s, S { f1: None });
    // This does not print anything, we cannot easily/reliably warn for
    // environment variables.
    let s: S = config.get("S2").unwrap();
    assert_eq!(s, S { f1: None });

    // Verify the warnings.
    let output = read_output(config);
    let expected = "\
warning: unused config key `S.unused` in `[..]/.cargo/config`
";
    assert_match(expected, &output);
}

#[cargo_test]
fn config_load_toml_profile() {
    write_config(
        "\
[profile.dev]
opt-level = 's'
lto = true
codegen-units=4
debug = true
debug-assertions = true
rpath = true
panic = 'abort'
overflow-checks = true
incremental = true

[profile.dev.build-override]
opt-level = 1

[profile.dev.package.bar]
codegen-units = 9

[profile.no-lto]
inherits = 'dev'
dir-name = 'without-lto'
lto = false
",
    );

    let config = ConfigBuilder::new()
        .unstable_flag("advanced-env")
        .env("CARGO_PROFILE_DEV_CODEGEN_UNITS", "5")
        .env("CARGO_PROFILE_DEV_BUILD_OVERRIDE_CODEGEN_UNITS", "11")
        .env("CARGO_PROFILE_DEV_PACKAGE_env_CODEGEN_UNITS", "13")
        .env("CARGO_PROFILE_DEV_PACKAGE_bar_OPT_LEVEL", "2")
        .build();

    // TODO: don't use actual `tomlprofile`.
    let p: cargo_toml::TomlProfile = config.get("profile.dev").unwrap();
    let mut packages = BTreeMap::new();
    let key =
        cargo_toml::ProfilePackageSpec::Spec(::cargo::core::PackageIdSpec::parse("bar").unwrap());
    let o_profile = cargo_toml::TomlProfile {
        opt_level: Some(cargo_toml::TomlOptLevel("2".to_string())),
        codegen_units: Some(9),
        ..Default::default()
    };
    packages.insert(key, o_profile);
    let key =
        cargo_toml::ProfilePackageSpec::Spec(::cargo::core::PackageIdSpec::parse("env").unwrap());
    let o_profile = cargo_toml::TomlProfile {
        codegen_units: Some(13),
        ..Default::default()
    };
    packages.insert(key, o_profile);

    assert_eq!(
        p,
        cargo_toml::TomlProfile {
            opt_level: Some(cargo_toml::TomlOptLevel("s".to_string())),
            lto: Some(cargo_toml::StringOrBool::Bool(true)),
            codegen_units: Some(5),
            debug: Some(cargo_toml::TomlDebugInfo::Full),
            debug_assertions: Some(true),
            rpath: Some(true),
            panic: Some("abort".to_string()),
            overflow_checks: Some(true),
            incremental: Some(true),
            package: Some(packages),
            build_override: Some(Box::new(cargo_toml::TomlProfile {
                opt_level: Some(cargo_toml::TomlOptLevel("1".to_string())),
                codegen_units: Some(11),
                ..Default::default()
            })),
            ..Default::default()
        }
    );

    let p: cargo_toml::TomlProfile = config.get("profile.no-lto").unwrap();
    assert_eq!(
        p,
        cargo_toml::TomlProfile {
            lto: Some(cargo_toml::StringOrBool::Bool(false)),
            dir_name: Some(InternedString::new("without-lto")),
            inherits: Some(InternedString::new("dev")),
            ..Default::default()
        }
    );
}

#[cargo_test]
fn profile_env_var_prefix() {
    // Check for a bug with collision on DEBUG vs DEBUG_ASSERTIONS.
    let config = ConfigBuilder::new()
        .env("CARGO_PROFILE_DEV_DEBUG_ASSERTIONS", "false")
        .build();
    let p: cargo_toml::TomlProfile = config.get("profile.dev").unwrap();
    assert_eq!(p.debug_assertions, Some(false));
    assert_eq!(p.debug, None);

    let config = ConfigBuilder::new()
        .env("CARGO_PROFILE_DEV_DEBUG", "1")
        .build();
    let p: cargo_toml::TomlProfile = config.get("profile.dev").unwrap();
    assert_eq!(p.debug_assertions, None);
    assert_eq!(p.debug, Some(cargo_toml::TomlDebugInfo::Limited));

    let config = ConfigBuilder::new()
        .env("CARGO_PROFILE_DEV_DEBUG_ASSERTIONS", "false")
        .env("CARGO_PROFILE_DEV_DEBUG", "1")
        .build();
    let p: cargo_toml::TomlProfile = config.get("profile.dev").unwrap();
    assert_eq!(p.debug_assertions, Some(false));
    assert_eq!(p.debug, Some(cargo_toml::TomlDebugInfo::Limited));
}

#[cargo_test]
fn config_deserialize_any() {
    // Some tests to exercise deserialize_any for deserializers that need to
    // be told the format.
    write_config(
        "\
a = true
b = ['b']
c = ['c']
",
    );

    // advanced-env
    let config = ConfigBuilder::new()
        .unstable_flag("advanced-env")
        .env("CARGO_ENVB", "false")
        .env("CARGO_C", "['d']")
        .env("CARGO_ENVL", "['a', 'b']")
        .build();
    assert_eq!(config.get::<VSOB>("a").unwrap(), VSOB::Bool(true));
    assert_eq!(
        config.get::<VSOB>("b").unwrap(),
        VSOB::VecString(vec!["b".to_string()])
    );
    assert_eq!(
        config.get::<VSOB>("c").unwrap(),
        VSOB::VecString(vec!["c".to_string(), "d".to_string()])
    );
    assert_eq!(config.get::<VSOB>("envb").unwrap(), VSOB::Bool(false));
    assert_eq!(
        config.get::<VSOB>("envl").unwrap(),
        VSOB::VecString(vec!["a".to_string(), "b".to_string()])
    );

    // Demonstrate where merging logic isn't very smart. This could be improved.
    let config = ConfigBuilder::new().env("CARGO_A", "x y").build();
    assert_error(
        config.get::<VSOB>("a").unwrap_err(),
        "\
error in environment variable `CARGO_A`: could not load config key `a`

Caused by:
  invalid type: string \"x y\", expected a boolean or vector of strings",
    );

    // Normal env.
    let config = ConfigBuilder::new()
        .unstable_flag("advanced-env")
        .env("CARGO_B", "d e")
        .env("CARGO_C", "f g")
        .build();
    assert_eq!(
        config.get::<VSOB>("b").unwrap(),
        VSOB::VecString(vec!["b".to_string(), "d".to_string(), "e".to_string()])
    );
    assert_eq!(
        config.get::<VSOB>("c").unwrap(),
        VSOB::VecString(vec!["c".to_string(), "f".to_string(), "g".to_string()])
    );

    // config-cli
    // This test demonstrates that ConfigValue::merge isn't very smart.
    // It would be nice if it was smarter.
    let config = ConfigBuilder::new().config_arg("a = ['a']").build_err();
    assert_error(
        config.unwrap_err(),
        "\
failed to merge --config key `a` into `[..]/.cargo/config`

Caused by:
  failed to merge config value from `--config cli option` into `[..]/.cargo/config`: \
expected boolean, but found array",
    );

    // config-cli and advanced-env
    let config = ConfigBuilder::new()
        .unstable_flag("advanced-env")
        .config_arg("b=['clib']")
        .config_arg("c=['clic']")
        .env("CARGO_B", "env1 env2")
        .env("CARGO_C", "['e1', 'e2']")
        .build();
    assert_eq!(
        config.get::<VSOB>("b").unwrap(),
        VSOB::VecString(vec![
            "b".to_string(),
            "env1".to_string(),
            "env2".to_string(),
            "clib".to_string(),
        ])
    );
    assert_eq!(
        config.get::<VSOB>("c").unwrap(),
        VSOB::VecString(vec![
            "c".to_string(),
            "e1".to_string(),
            "e2".to_string(),
            "clic".to_string(),
        ])
    );
}

#[cargo_test]
fn config_toml_errors() {
    write_config(
        "\
[profile.dev]
opt-level = 'foo'
",
    );

    let config = new_config();

    assert_error(
        config
            .get::<cargo_toml::TomlProfile>("profile.dev")
            .unwrap_err(),
        "\
error in [..]/.cargo/config: could not load config key `profile.dev.opt-level`

Caused by:
  must be `0`, `1`, `2`, `3`, `s` or `z`, but found the string: \"foo\"",
    );

    let config = ConfigBuilder::new()
        .env("CARGO_PROFILE_DEV_OPT_LEVEL", "asdf")
        .build();

    assert_error(
        config.get::<cargo_toml::TomlProfile>("profile.dev").unwrap_err(),
        "\
error in environment variable `CARGO_PROFILE_DEV_OPT_LEVEL`: could not load config key `profile.dev.opt-level`

Caused by:
  must be `0`, `1`, `2`, `3`, `s` or `z`, but found the string: \"asdf\"",
    );
}

#[cargo_test]
fn load_nested() {
    write_config(
        "\
[nest.foo]
f1 = 1
f2 = 2
[nest.bar]
asdf = 3
",
    );

    let config = ConfigBuilder::new()
        .unstable_flag("advanced-env")
        .env("CARGO_NEST_foo_f2", "3")
        .env("CARGO_NESTE_foo_f1", "1")
        .env("CARGO_NESTE_foo_f2", "3")
        .env("CARGO_NESTE_bar_asdf", "3")
        .build();

    type Nested = HashMap<String, HashMap<String, u8>>;

    let n: Nested = config.get("nest").unwrap();
    let mut expected = HashMap::new();
    let mut foo = HashMap::new();
    foo.insert("f1".to_string(), 1);
    foo.insert("f2".to_string(), 3);
    expected.insert("foo".to_string(), foo);
    let mut bar = HashMap::new();
    bar.insert("asdf".to_string(), 3);
    expected.insert("bar".to_string(), bar);
    assert_eq!(n, expected);

    let n: Nested = config.get("neste").unwrap();
    assert_eq!(n, expected);
}

#[cargo_test]
fn get_errors() {
    write_config(
        "\
[S]
f1 = 123
f2 = 'asdf'
big = 123456789
",
    );

    let config = ConfigBuilder::new()
        .env("CARGO_E_S", "asdf")
        .env("CARGO_E_BIG", "123456789")
        .build();
    assert_error(
        config.get::<i64>("foo").unwrap_err(),
        "missing config key `foo`",
    );
    assert_error(
        config.get::<i64>("foo.bar").unwrap_err(),
        "missing config key `foo.bar`",
    );
    assert_error(
        config.get::<i64>("S.f2").unwrap_err(),
        "error in [..]/.cargo/config: `S.f2` expected an integer, but found a string",
    );
    assert_error(
        config.get::<u8>("S.big").unwrap_err(),
        "\
error in [..].cargo/config: could not load config key `S.big`

Caused by:
  invalid value: integer `123456789`, expected u8",
    );

    // Environment variable type errors.
    assert_error(
        config.get::<i64>("e.s").unwrap_err(),
        "error in environment variable `CARGO_E_S`: invalid digit found in string",
    );
    assert_error(
        config.get::<i8>("e.big").unwrap_err(),
        "\
error in environment variable `CARGO_E_BIG`: could not load config key `e.big`

Caused by:
  invalid value: integer `123456789`, expected i8",
    );

    #[derive(Debug, Deserialize)]
    #[allow(dead_code)]
    struct S {
        f1: i64,
        f2: String,
        f3: i64,
        big: i64,
    }
    assert_error(config.get::<S>("S").unwrap_err(), "missing field `f3`");
}

#[cargo_test]
fn config_get_option() {
    write_config(
        "\
[foo]
f1 = 1
",
    );

    let config = ConfigBuilder::new().env("CARGO_BAR_ASDF", "3").build();

    assert_eq!(config.get::<Option<i32>>("a").unwrap(), None);
    assert_eq!(config.get::<Option<i32>>("a.b").unwrap(), None);
    assert_eq!(config.get::<Option<i32>>("foo.f1").unwrap(), Some(1));
    assert_eq!(config.get::<Option<i32>>("bar.asdf").unwrap(), Some(3));
    assert_eq!(config.get::<Option<i32>>("bar.zzzz").unwrap(), None);
}

#[cargo_test]
fn config_bad_toml() {
    write_config("asdf");
    let config = new_config();
    assert_error(
        config.get::<i32>("foo").unwrap_err(),
        "\
could not load Cargo configuration

Caused by:
  could not parse TOML configuration in `[..]/.cargo/config`

Caused by:
  TOML parse error at line 1, column 5
  |
1 | asdf
  |     ^
expected `.`, `=`",
    );
}

#[cargo_test]
fn config_get_list() {
    write_config(
        "\
l1 = []
l2 = ['one', 'two']
l3 = 123
l4 = ['one', 'two']

[nested]
l = ['x']

[nested2]
l = ['y']

[nested-empty]
",
    );

    type L = Vec<String>;

    let config = ConfigBuilder::new()
        .unstable_flag("advanced-env")
        .env("CARGO_L4", "['three', 'four']")
        .env("CARGO_L5", "['a']")
        .env("CARGO_ENV_EMPTY", "[]")
        .env("CARGO_ENV_BLANK", "")
        .env("CARGO_ENV_NUM", "1")
        .env("CARGO_ENV_NUM_LIST", "[1]")
        .env("CARGO_ENV_TEXT", "asdf")
        .env("CARGO_LEPAIR", "['a', 'b']")
        .env("CARGO_NESTED2_L", "['z']")
        .env("CARGO_NESTEDE_L", "['env']")
        .env("CARGO_BAD_ENV", "[zzz]")
        .build();

    assert_eq!(config.get::<L>("unset").unwrap(), vec![] as Vec<String>);
    assert_eq!(config.get::<L>("l1").unwrap(), vec![] as Vec<String>);
    assert_eq!(config.get::<L>("l2").unwrap(), vec!["one", "two"]);
    assert_error(
        config.get::<L>("l3").unwrap_err(),
        "\
invalid configuration for key `l3`
expected a list, but found a integer for `l3` in [..]/.cargo/config",
    );
    assert_eq!(
        config.get::<L>("l4").unwrap(),
        vec!["one", "two", "three", "four"]
    );
    assert_eq!(config.get::<L>("l5").unwrap(), vec!["a"]);
    assert_eq!(config.get::<L>("env-empty").unwrap(), vec![] as Vec<String>);
    assert_eq!(config.get::<L>("env-blank").unwrap(), vec![] as Vec<String>);
    assert_eq!(config.get::<L>("env-num").unwrap(), vec!["1".to_string()]);
    assert_error(
        config.get::<L>("env-num-list").unwrap_err(),
        "error in environment variable `CARGO_ENV_NUM_LIST`: \
         expected string, found integer",
    );
    assert_eq!(
        config.get::<L>("env-text").unwrap(),
        vec!["asdf".to_string()]
    );
    // "invalid number" here isn't the best error, but I think it's just toml.rs.
    assert_error(
        config.get::<L>("bad-env").unwrap_err(),
        "\
error in environment variable `CARGO_BAD_ENV`: could not parse TOML list: TOML parse error at line 1, column 2
  |
1 | [zzz]
  |  ^
invalid array
expected `]`
",
    );

    // Try some other sequence-like types.
    assert_eq!(
        config
            .get::<(String, String, String, String)>("l4")
            .unwrap(),
        (
            "one".to_string(),
            "two".to_string(),
            "three".to_string(),
            "four".to_string()
        )
    );
    assert_eq!(config.get::<(String,)>("l5").unwrap(), ("a".to_string(),));

    // Tuple struct
    #[derive(Debug, Deserialize, Eq, PartialEq)]
    struct TupS(String, String);
    assert_eq!(
        config.get::<TupS>("lepair").unwrap(),
        TupS("a".to_string(), "b".to_string())
    );

    // Nested with an option.
    #[derive(Debug, Deserialize, Eq, PartialEq)]
    struct S {
        l: Option<Vec<String>>,
    }
    assert_eq!(config.get::<S>("nested-empty").unwrap(), S { l: None });
    assert_eq!(
        config.get::<S>("nested").unwrap(),
        S {
            l: Some(vec!["x".to_string()]),
        }
    );
    assert_eq!(
        config.get::<S>("nested2").unwrap(),
        S {
            l: Some(vec!["y".to_string(), "z".to_string()]),
        }
    );
    assert_eq!(
        config.get::<S>("nestede").unwrap(),
        S {
            l: Some(vec!["env".to_string()]),
        }
    );
}

#[cargo_test]
fn config_get_other_types() {
    write_config(
        "\
ns = 123
ns2 = 456
",
    );

    let config = ConfigBuilder::new()
        .env("CARGO_NSE", "987")
        .env("CARGO_NS2", "654")
        .build();

    #[derive(Debug, Deserialize, Eq, PartialEq)]
    #[serde(transparent)]
    struct NewS(i32);
    assert_eq!(config.get::<NewS>("ns").unwrap(), NewS(123));
    assert_eq!(config.get::<NewS>("ns2").unwrap(), NewS(654));
    assert_eq!(config.get::<NewS>("nse").unwrap(), NewS(987));
    assert_error(
        config.get::<NewS>("unset").unwrap_err(),
        "missing config key `unset`",
    );
}

#[cargo_test]
fn config_relative_path() {
    write_config(&format!(
        "\
p1 = 'foo/bar'
p2 = '../abc'
p3 = 'b/c'
abs = '{}'
",
        paths::home().display(),
    ));

    let config = ConfigBuilder::new()
        .env("CARGO_EPATH", "a/b")
        .env("CARGO_P3", "d/e")
        .build();

    assert_eq!(
        config
            .get::<config::ConfigRelativePath>("p1")
            .unwrap()
            .resolve_path(&config),
        paths::root().join("foo/bar")
    );
    assert_eq!(
        config
            .get::<config::ConfigRelativePath>("p2")
            .unwrap()
            .resolve_path(&config),
        paths::root().join("../abc")
    );
    assert_eq!(
        config
            .get::<config::ConfigRelativePath>("p3")
            .unwrap()
            .resolve_path(&config),
        paths::root().join("d/e")
    );
    assert_eq!(
        config
            .get::<config::ConfigRelativePath>("abs")
            .unwrap()
            .resolve_path(&config),
        paths::home()
    );
    assert_eq!(
        config
            .get::<config::ConfigRelativePath>("epath")
            .unwrap()
            .resolve_path(&config),
        paths::root().join("a/b")
    );
}

#[cargo_test]
fn config_get_integers() {
    write_config(
        "\
npos = 123456789
nneg = -123456789
i64max = 9223372036854775807
",
    );

    let config = ConfigBuilder::new()
        .env("CARGO_EPOS", "123456789")
        .env("CARGO_ENEG", "-1")
        .env("CARGO_EI64MAX", "9223372036854775807")
        .build();

    assert_eq!(
        config.get::<u64>("i64max").unwrap(),
        9_223_372_036_854_775_807
    );
    assert_eq!(
        config.get::<i64>("i64max").unwrap(),
        9_223_372_036_854_775_807
    );
    assert_eq!(
        config.get::<u64>("ei64max").unwrap(),
        9_223_372_036_854_775_807
    );
    assert_eq!(
        config.get::<i64>("ei64max").unwrap(),
        9_223_372_036_854_775_807
    );

    assert_error(
        config.get::<u32>("nneg").unwrap_err(),
        "\
error in [..].cargo/config: could not load config key `nneg`

Caused by:
  invalid value: integer `-123456789`, expected u32",
    );
    assert_error(
        config.get::<u32>("eneg").unwrap_err(),
        "\
error in environment variable `CARGO_ENEG`: could not load config key `eneg`

Caused by:
  invalid value: integer `-1`, expected u32",
    );
    assert_error(
        config.get::<i8>("npos").unwrap_err(),
        "\
error in [..].cargo/config: could not load config key `npos`

Caused by:
  invalid value: integer `123456789`, expected i8",
    );
    assert_error(
        config.get::<i8>("epos").unwrap_err(),
        "\
error in environment variable `CARGO_EPOS`: could not load config key `epos`

Caused by:
  invalid value: integer `123456789`, expected i8",
    );
}

#[cargo_test]
fn config_get_ssl_version_missing() {
    write_config(
        "\
[http]
hello = 'world'
",
    );

    let config = new_config();

    assert!(config
        .get::<Option<SslVersionConfig>>("http.ssl-version")
        .unwrap()
        .is_none());
}

#[cargo_test]
fn config_get_ssl_version_single() {
    write_config(
        "\
[http]
ssl-version = 'tlsv1.2'
",
    );

    let config = new_config();

    let a = config
        .get::<Option<SslVersionConfig>>("http.ssl-version")
        .unwrap()
        .unwrap();
    match a {
        SslVersionConfig::Single(v) => assert_eq!(&v, "tlsv1.2"),
        SslVersionConfig::Range(_) => panic!("Did not expect ssl version min/max."),
    };
}

#[cargo_test]
fn config_get_ssl_version_min_max() {
    write_config(
        "\
[http]
ssl-version.min = 'tlsv1.2'
ssl-version.max = 'tlsv1.3'
",
    );

    let config = new_config();

    let a = config
        .get::<Option<SslVersionConfig>>("http.ssl-version")
        .unwrap()
        .unwrap();
    match a {
        SslVersionConfig::Single(_) => panic!("Did not expect exact ssl version."),
        SslVersionConfig::Range(range) => {
            assert_eq!(range.min, Some(String::from("tlsv1.2")));
            assert_eq!(range.max, Some(String::from("tlsv1.3")));
        }
    };
}

#[cargo_test]
fn config_get_ssl_version_both_forms_configured() {
    // this is not allowed
    write_config(
        "\
[http]
ssl-version = 'tlsv1.1'
ssl-version.min = 'tlsv1.2'
ssl-version.max = 'tlsv1.3'
",
    );

    let config = new_config();

    assert_error(
        config
            .get::<SslVersionConfig>("http.ssl-version")
            .unwrap_err(),
        "\
could not load Cargo configuration

Caused by:
  could not parse TOML configuration in `[..]/.cargo/config`

Caused by:
  TOML parse error at line 3, column 1
  |
3 | ssl-version.min = 'tlsv1.2'
  | ^
dotted key `ssl-version` attempted to extend non-table type (string)
",
    );
}

#[cargo_test]
/// Assert that unstable options can be configured with the `unstable` table in
/// cargo config files
fn unstable_table_notation() {
    write_config(
        "\
[unstable]
print-im-a-teapot = true
",
    );
    let config = ConfigBuilder::new().nightly_features_allowed(true).build();
    assert_eq!(config.cli_unstable().print_im_a_teapot, true);
}

#[cargo_test]
/// Assert that dotted notation works for configuring unstable options
fn unstable_dotted_notation() {
    write_config(
        "\
unstable.print-im-a-teapot = true
",
    );
    let config = ConfigBuilder::new().nightly_features_allowed(true).build();
    assert_eq!(config.cli_unstable().print_im_a_teapot, true);
}

#[cargo_test]
/// Assert that Zflags on the CLI take precedence over those from config
fn unstable_cli_precedence() {
    write_config(
        "\
unstable.print-im-a-teapot = true
",
    );
    let config = ConfigBuilder::new().nightly_features_allowed(true).build();
    assert_eq!(config.cli_unstable().print_im_a_teapot, true);

    let config = ConfigBuilder::new()
        .unstable_flag("print-im-a-teapot=no")
        .build();
    assert_eq!(config.cli_unstable().print_im_a_teapot, false);
}

#[cargo_test]
/// Assert that attempting to set an unstable flag that doesn't exist via config
/// is ignored on stable
fn unstable_invalid_flag_ignored_on_stable() {
    write_config(
        "\
unstable.an-invalid-flag = 'yes'
",
    );
    assert!(ConfigBuilder::new().build_err().is_ok());
}

#[cargo_test]
/// Assert that unstable options can be configured with the `unstable` table in
/// cargo config files
fn unstable_flags_ignored_on_stable() {
    write_config(
        "\
[unstable]
print-im-a-teapot = true
",
    );
    // Enforce stable channel even when testing on nightly.
    let config = ConfigBuilder::new().nightly_features_allowed(false).build();
    assert_eq!(config.cli_unstable().print_im_a_teapot, false);
}

#[cargo_test]
fn table_merge_failure() {
    // Config::merge fails to merge entries in two tables.
    write_config_at(
        "foo/.cargo/config",
        "
        [table]
        key = ['foo']
        ",
    );
    write_config_at(
        ".cargo/config",
        "
        [table]
        key = 'bar'
        ",
    );

    #[derive(Debug, Deserialize)]
    #[allow(dead_code)]
    struct Table {
        key: StringList,
    }
    let config = ConfigBuilder::new().cwd("foo").build();
    assert_error(
        config.get::<Table>("table").unwrap_err(),
        "\
could not load Cargo configuration

Caused by:
  failed to merge configuration at `[..]/.cargo/config`

Caused by:
  failed to merge key `table` between [..]/foo/.cargo/config and [..]/.cargo/config

Caused by:
  failed to merge key `key` between [..]/foo/.cargo/config and [..]/.cargo/config

Caused by:
  failed to merge config value from `[..]/.cargo/config` into `[..]/foo/.cargo/config`: \
  expected array, but found string",
    );
}

#[cargo_test]
fn non_string_in_array() {
    // Currently only strings are supported.
    write_config("foo = [1, 2, 3]");
    let config = new_config();
    assert_error(
        config.get::<Vec<i32>>("foo").unwrap_err(),
        "\
could not load Cargo configuration

Caused by:
  failed to load TOML configuration from `[..]/.cargo/config`

Caused by:
  failed to parse key `foo`

Caused by:
  expected string but found integer in list",
    );
}

#[cargo_test]
fn struct_with_opt_inner_struct() {
    // Struct with a key that is Option of another struct.
    // Check that can be defined with environment variable.
    #[derive(Deserialize)]
    struct Inner {
        value: Option<i32>,
    }
    #[derive(Deserialize)]
    struct Foo {
        inner: Option<Inner>,
    }
    let config = ConfigBuilder::new()
        .env("CARGO_FOO_INNER_VALUE", "12")
        .build();
    let f: Foo = config.get("foo").unwrap();
    assert_eq!(f.inner.unwrap().value.unwrap(), 12);
}

#[cargo_test]
fn struct_with_default_inner_struct() {
    // Struct with serde defaults.
    // Check that can be defined with environment variable.
    #[derive(Deserialize, Default)]
    #[serde(default)]
    struct Inner {
        value: i32,
    }
    #[derive(Deserialize, Default)]
    #[serde(default)]
    struct Foo {
        inner: Inner,
    }
    let config = ConfigBuilder::new()
        .env("CARGO_FOO_INNER_VALUE", "12")
        .build();
    let f: Foo = config.get("foo").unwrap();
    assert_eq!(f.inner.value, 12);
}

#[cargo_test]
fn overlapping_env_config() {
    // Issue where one key is a prefix of another.
    #[derive(Deserialize)]
    #[serde(rename_all = "kebab-case")]
    struct Ambig {
        debug: Option<u32>,
        debug_assertions: Option<bool>,
    }
    let config = ConfigBuilder::new()
        .env("CARGO_AMBIG_DEBUG_ASSERTIONS", "true")
        .build();

    let s: Ambig = config.get("ambig").unwrap();
    assert_eq!(s.debug_assertions, Some(true));
    assert_eq!(s.debug, None);

    let config = ConfigBuilder::new().env("CARGO_AMBIG_DEBUG", "0").build();
    let s: Ambig = config.get("ambig").unwrap();
    assert_eq!(s.debug_assertions, None);
    assert_eq!(s.debug, Some(0));

    let config = ConfigBuilder::new()
        .env("CARGO_AMBIG_DEBUG", "1")
        .env("CARGO_AMBIG_DEBUG_ASSERTIONS", "true")
        .build();
    let s: Ambig = config.get("ambig").unwrap();
    assert_eq!(s.debug_assertions, Some(true));
    assert_eq!(s.debug, Some(1));
}

#[cargo_test]
fn overlapping_env_with_defaults_errors_out() {
    // Issue where one key is a prefix of another.
    // This is a limitation of mapping environment variables on to a hierarchy.
    // Check that we error out when we hit ambiguity in this way, rather than
    // the more-surprising defaulting through.
    // If, in the future, we can handle this more correctly, feel free to delete
    // this test.
    #[derive(Deserialize, Default)]
    #[serde(default, rename_all = "kebab-case")]
    struct Ambig {
        debug: u32,
        debug_assertions: bool,
    }
    let config = ConfigBuilder::new()
        .env("CARGO_AMBIG_DEBUG_ASSERTIONS", "true")
        .build();
    let err = config.get::<Ambig>("ambig").err().unwrap();
    assert!(format!("{}", err).contains("missing config key `ambig.debug`"));

    let config = ConfigBuilder::new().env("CARGO_AMBIG_DEBUG", "5").build();
    let s: Ambig = config.get("ambig").unwrap();
    assert_eq!(s.debug_assertions, bool::default());
    assert_eq!(s.debug, 5);

    let config = ConfigBuilder::new()
        .env("CARGO_AMBIG_DEBUG", "1")
        .env("CARGO_AMBIG_DEBUG_ASSERTIONS", "true")
        .build();
    let s: Ambig = config.get("ambig").unwrap();
    assert_eq!(s.debug_assertions, true);
    assert_eq!(s.debug, 1);
}

#[cargo_test]
fn struct_with_overlapping_inner_struct_and_defaults() {
    // Struct with serde defaults.
    // Check that can be defined with environment variable.
    #[derive(Deserialize, Default)]
    #[serde(default)]
    struct Inner {
        value: i32,
    }

    // Containing struct with a prefix of inner
    //
    // This is a limitation of mapping environment variables on to a hierarchy.
    // Check that we error out when we hit ambiguity in this way, rather than
    // the more-surprising defaulting through.
    // If, in the future, we can handle this more correctly, feel free to delete
    // this case.
    #[derive(Deserialize, Default)]
    #[serde(default)]
    struct PrefixContainer {
        inn: bool,
        inner: Inner,
    }
    let config = ConfigBuilder::new()
        .env("CARGO_PREFIXCONTAINER_INNER_VALUE", "12")
        .build();
    let err = config
        .get::<PrefixContainer>("prefixcontainer")
        .err()
        .unwrap();
    assert!(format!("{}", err).contains("missing config key `prefixcontainer.inn`"));
    let config = ConfigBuilder::new()
        .env("CARGO_PREFIXCONTAINER_INNER_VALUE", "12")
        .env("CARGO_PREFIXCONTAINER_INN", "true")
        .build();
    let f: PrefixContainer = config.get("prefixcontainer").unwrap();
    assert_eq!(f.inner.value, 12);
    assert_eq!(f.inn, true);

    // Containing struct where the inner value's field is a prefix of another
    //
    // This is a limitation of mapping environment variables on to a hierarchy.
    // Check that we error out when we hit ambiguity in this way, rather than
    // the more-surprising defaulting through.
    // If, in the future, we can handle this more correctly, feel free to delete
    // this case.
    #[derive(Deserialize, Default)]
    #[serde(default)]
    struct InversePrefixContainer {
        inner_field: bool,
        inner: Inner,
    }
    let config = ConfigBuilder::new()
        .env("CARGO_INVERSEPREFIXCONTAINER_INNER_VALUE", "12")
        .build();
    let f: InversePrefixContainer = config.get("inverseprefixcontainer").unwrap();
    assert_eq!(f.inner_field, bool::default());
    assert_eq!(f.inner.value, 12);
}

#[cargo_test]
fn string_list_tricky_env() {
    // Make sure StringList handles typed env values.
    let config = ConfigBuilder::new()
        .env("CARGO_KEY1", "123")
        .env("CARGO_KEY2", "true")
        .env("CARGO_KEY3", "1 2")
        .build();
    let x = config.get::<StringList>("key1").unwrap();
    assert_eq!(x.as_slice(), &["123".to_string()]);
    let x = config.get::<StringList>("key2").unwrap();
    assert_eq!(x.as_slice(), &["true".to_string()]);
    let x = config.get::<StringList>("key3").unwrap();
    assert_eq!(x.as_slice(), &["1".to_string(), "2".to_string()]);
}

#[cargo_test]
fn string_list_wrong_type() {
    // What happens if StringList is given then wrong type.
    write_config("some_list = 123");
    let config = ConfigBuilder::new().build();
    assert_error(
        config.get::<StringList>("some_list").unwrap_err(),
        "\
invalid configuration for key `some_list`
expected a string or array of strings, but found a integer for `some_list` in [..]/.cargo/config",
    );

    write_config("some_list = \"1 2\"");
    let config = ConfigBuilder::new().build();
    let x = config.get::<StringList>("some_list").unwrap();
    assert_eq!(x.as_slice(), &["1".to_string(), "2".to_string()]);
}

#[cargo_test]
fn string_list_advanced_env() {
    // StringList with advanced env.
    let config = ConfigBuilder::new()
        .unstable_flag("advanced-env")
        .env("CARGO_KEY1", "[]")
        .env("CARGO_KEY2", "['1 2', '3']")
        .env("CARGO_KEY3", "[123]")
        .build();
    let x = config.get::<StringList>("key1").unwrap();
    assert_eq!(x.as_slice(), &[] as &[String]);
    let x = config.get::<StringList>("key2").unwrap();
    assert_eq!(x.as_slice(), &["1 2".to_string(), "3".to_string()]);
    assert_error(
        config.get::<StringList>("key3").unwrap_err(),
        "error in environment variable `CARGO_KEY3`: expected string, found integer",
    );
}

#[cargo_test]
fn parse_strip_with_string() {
    write_config(
        "\
[profile.release]
strip = 'debuginfo'
",
    );

    let config = new_config();

    let p: cargo_toml::TomlProfile = config.get("profile.release").unwrap();
    let strip = p.strip.unwrap();
    assert_eq!(
        strip,
        cargo_toml::StringOrBool::String("debuginfo".to_string())
    );
}

#[cargo_test]
fn cargo_target_empty_cfg() {
    write_config(
        "\
[build]
target-dir = ''
",
    );

    let config = new_config();

    assert_error(
        config.target_dir().unwrap_err(),
        "the target directory is set to an empty string in [..]/.cargo/config",
    );
}

#[cargo_test]
fn cargo_target_empty_env() {
    let project = project().build();

    project.cargo("check")
        .env("CARGO_TARGET_DIR", "")
        .with_stderr("error: the target directory is set to an empty string in the `CARGO_TARGET_DIR` environment variable")
        .with_status(101)
        .run()
}

#[cargo_test]
fn all_profile_options() {
    // Check that all profile options can be serialized/deserialized.
    let base_settings = cargo_toml::TomlProfile {
        opt_level: Some(cargo_toml::TomlOptLevel("0".to_string())),
        lto: Some(cargo_toml::StringOrBool::String("thin".to_string())),
        codegen_backend: Some(InternedString::new("example")),
        codegen_units: Some(123),
        debug: Some(cargo_toml::TomlDebugInfo::Limited),
        split_debuginfo: Some("packed".to_string()),
        debug_assertions: Some(true),
        rpath: Some(true),
        panic: Some("abort".to_string()),
        overflow_checks: Some(true),
        incremental: Some(true),
        dir_name: Some(InternedString::new("dir_name")),
        inherits: Some(InternedString::new("debug")),
        strip: Some(cargo_toml::StringOrBool::String("symbols".to_string())),
        package: None,
        build_override: None,
        rustflags: None,
    };
    let mut overrides = BTreeMap::new();
    let key = cargo_toml::ProfilePackageSpec::Spec(PackageIdSpec::parse("foo").unwrap());
    overrides.insert(key, base_settings.clone());
    let profile = cargo_toml::TomlProfile {
        build_override: Some(Box::new(base_settings.clone())),
        package: Some(overrides),
        ..base_settings
    };
    let profile_toml = toml::to_string(&profile).unwrap();
    let roundtrip: cargo_toml::TomlProfile = toml::from_str(&profile_toml).unwrap();
    let roundtrip_toml = toml::to_string(&roundtrip).unwrap();
    compare::assert_match_exact(&profile_toml, &roundtrip_toml);
}

#[cargo_test]
fn value_in_array() {
    // Value<String> in an array should work
    let root_path = paths::root().join(".cargo/config.toml");
    write_config_at(
        &root_path,
        "\
[net.ssh]
known-hosts = [
    \"example.com ...\",
    \"example.net ...\",
]
",
    );

    let foo_path = paths::root().join("foo/.cargo/config.toml");
    write_config_at(
        &foo_path,
        "\
[net.ssh]
known-hosts = [
    \"example.org ...\",
]
",
    );

    let config = ConfigBuilder::new()
        .cwd("foo")
        // environment variables don't actually work for known-hosts due to
        // space splitting, but this is included here just to validate that
        // they work (particularly if other Vec<Value> config vars are added
        // in the future).
        .env("CARGO_NET_SSH_KNOWN_HOSTS", "env-example")
        .build();
    let net_config = config.net_config().unwrap();
    let kh = net_config
        .ssh
        .as_ref()
        .unwrap()
        .known_hosts
        .as_ref()
        .unwrap();
    assert_eq!(kh.len(), 4);
    assert_eq!(kh[0].val, "example.com ...");
    assert_eq!(kh[0].definition, Definition::Path(root_path.clone()));
    assert_eq!(kh[1].val, "example.net ...");
    assert_eq!(kh[1].definition, Definition::Path(root_path.clone()));
    assert_eq!(kh[2].val, "example.org ...");
    assert_eq!(kh[2].definition, Definition::Path(foo_path.clone()));
    assert_eq!(kh[3].val, "env-example");
    assert_eq!(
        kh[3].definition,
        Definition::Environment("CARGO_NET_SSH_KNOWN_HOSTS".to_string())
    );
}

#[cargo_test]
fn debuginfo_parsing() {
    let config = ConfigBuilder::new().build();
    let p: cargo_toml::TomlProfile = config.get("profile.dev").unwrap();
    assert_eq!(p.debug, None);

    let env_test_cases = [
        (TomlDebugInfo::None, ["false", "0", "none"].as_slice()),
        (TomlDebugInfo::LineDirectivesOnly, &["line-directives-only"]),
        (TomlDebugInfo::LineTablesOnly, &["line-tables-only"]),
        (TomlDebugInfo::Limited, &["1", "limited"]),
        (TomlDebugInfo::Full, &["true", "2", "full"]),
    ];
    for (expected, config_strs) in env_test_cases {
        for &val in config_strs {
            let config = ConfigBuilder::new()
                .env("CARGO_PROFILE_DEV_DEBUG", val)
                .build();
            let debug: TomlDebugInfo = config.get("profile.dev.debug").unwrap();
            assert_eq!(debug, expected, "failed to parse {val}");
        }
    }

    let toml_test_cases = [
        (TomlDebugInfo::None, ["false", "0", "\"none\""].as_slice()),
        (
            TomlDebugInfo::LineDirectivesOnly,
            &["\"line-directives-only\""],
        ),
        (TomlDebugInfo::LineTablesOnly, &["\"line-tables-only\""]),
        (TomlDebugInfo::Limited, &["1", "\"limited\""]),
        (TomlDebugInfo::Full, &["true", "2", "\"full\""]),
    ];
    for (expected, config_strs) in toml_test_cases {
        for &val in config_strs {
            let config = ConfigBuilder::new()
                .config_arg(format!("profile.dev.debug={val}"))
                .build();
            let debug: TomlDebugInfo = config.get("profile.dev.debug").unwrap();
            assert_eq!(debug, expected, "failed to parse {val}");
        }
    }

    let toml_err_cases = ["\"\"", "\"unrecognized\"", "3"];
    for err_val in toml_err_cases {
        let config = ConfigBuilder::new()
            .config_arg(format!("profile.dev.debug={err_val}"))
            .build();
        let err = config
            .get::<TomlDebugInfo>("profile.dev.debug")
            .unwrap_err();
        assert!(err
            .to_string()
            .ends_with("could not load config key `profile.dev.debug`"));
    }
}

#[cargo_test]
fn build_jobs_missing() {
    write_config(
        "\
[build]
",
    );

    let config = new_config();

    assert!(config
        .get::<Option<JobsConfig>>("build.jobs")
        .unwrap()
        .is_none());
}

#[cargo_test]
fn build_jobs_default() {
    write_config(
        "\
[build]
jobs = \"default\"
",
    );

    let config = new_config();

    let a = config
        .get::<Option<JobsConfig>>("build.jobs")
        .unwrap()
        .unwrap();

    match a {
        JobsConfig::String(v) => assert_eq!(&v, "default"),
        JobsConfig::Integer(_) => panic!("Did not except an integer."),
    }
}

#[cargo_test]
fn build_jobs_integer() {
    write_config(
        "\
[build]
jobs = 2
",
    );

    let config = new_config();

    let a = config
        .get::<Option<JobsConfig>>("build.jobs")
        .unwrap()
        .unwrap();

    match a {
        JobsConfig::String(_) => panic!("Did not except an integer."),
        JobsConfig::Integer(v) => assert_eq!(v, 2),
    }
}