nextest-runner 0.114.0

Core runner logic for cargo nextest.
Documentation
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
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Nextest version configuration.

use super::{NextestConfig, ToolConfigFile, ToolName};
use crate::errors::{ConfigParseError, ConfigParseErrorKind};
use camino::{Utf8Path, Utf8PathBuf};
use semver::Version;
use serde::{
    Deserialize, Deserializer,
    de::{MapAccess, SeqAccess, Visitor},
};
use std::{borrow::Cow, collections::BTreeSet, fmt, str::FromStr};

/// A "version-only" form of the nextest configuration.
///
/// This is used as a first pass to determine the required nextest version before parsing the rest
/// of the configuration. That avoids issues parsing incompatible configuration.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct VersionOnlyConfig {
    /// The nextest version configuration.
    nextest_version: NextestVersionConfig,

    /// Experimental features configuration.
    experimental: ExperimentalConfig,
}

impl VersionOnlyConfig {
    /// Reads the nextest version configuration from the given sources.
    ///
    /// See [`NextestConfig::from_sources`] for more details.
    pub fn from_sources<'a, I>(
        workspace_root: &Utf8Path,
        config_file: Option<&Utf8Path>,
        tool_config_files: impl IntoIterator<IntoIter = I>,
    ) -> Result<Self, ConfigParseError>
    where
        I: Iterator<Item = &'a ToolConfigFile> + DoubleEndedIterator,
    {
        let tool_config_files_rev = tool_config_files.into_iter().rev();

        Self::read_from_sources(workspace_root, config_file, tool_config_files_rev)
    }

    /// Returns the nextest version requirement.
    pub fn nextest_version(&self) -> &NextestVersionConfig {
        &self.nextest_version
    }

    /// Returns the experimental features configuration.
    pub fn experimental(&self) -> &ExperimentalConfig {
        &self.experimental
    }

    fn read_from_sources<'a>(
        workspace_root: &Utf8Path,
        config_file: Option<&Utf8Path>,
        tool_config_files_rev: impl Iterator<Item = &'a ToolConfigFile>,
    ) -> Result<Self, ConfigParseError> {
        let mut nextest_version = NextestVersionConfig::default();
        let mut known = BTreeSet::new();
        let mut unknown = BTreeSet::new();

        // Merge in tool configs.
        for ToolConfigFile { config_file, tool } in tool_config_files_rev {
            if let Some(v) = Self::read_and_deserialize(config_file, Some(tool))?.nextest_version {
                nextest_version.accumulate(v, Some(tool.clone()));
            }
        }

        // Finally, merge in the repo config.
        let config_file = match config_file {
            Some(file) => Some(Cow::Borrowed(file)),
            None => {
                let config_file = workspace_root.join(NextestConfig::CONFIG_PATH);
                config_file.exists().then_some(Cow::Owned(config_file))
            }
        };
        if let Some(config_file) = config_file {
            let d = Self::read_and_deserialize(&config_file, None)?;
            if let Some(v) = d.nextest_version {
                nextest_version.accumulate(v, None);
            }

            // Process experimental features. Unknown features are stored rather
            // than immediately causing an error, so that the nextest version
            // check can run first.
            known.extend(d.experimental.known);
            unknown.extend(d.experimental.unknown);
        }

        Ok(Self {
            nextest_version,
            experimental: ExperimentalConfig { known, unknown },
        })
    }

    fn read_and_deserialize(
        config_file: &Utf8Path,
        tool: Option<&ToolName>,
    ) -> Result<VersionOnlyDeserialize, ConfigParseError> {
        let toml_str = std::fs::read_to_string(config_file.as_str()).map_err(|error| {
            ConfigParseError::new(
                config_file,
                tool,
                ConfigParseErrorKind::VersionOnlyReadError(error),
            )
        })?;
        let toml_de = toml::de::Deserializer::parse(&toml_str).map_err(|error| {
            ConfigParseError::new(
                config_file,
                tool,
                ConfigParseErrorKind::TomlParseError(Box::new(error)),
            )
        })?;
        let v: VersionOnlyDeserialize =
            serde_path_to_error::deserialize(toml_de).map_err(|error| {
                ConfigParseError::new(
                    config_file,
                    tool,
                    ConfigParseErrorKind::VersionOnlyDeserializeError(Box::new(error)),
                )
            })?;
        if tool.is_some() && !v.experimental.is_empty() {
            return Err(ConfigParseError::new(
                config_file,
                tool,
                ConfigParseErrorKind::ExperimentalFeaturesInToolConfig {
                    features: v.experimental.feature_names(),
                },
            ));
        }

        Ok(v)
    }
}

/// A version of configuration that only deserializes the nextest version.
#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct VersionOnlyDeserialize {
    #[serde(default)]
    nextest_version: Option<NextestVersionDeserialize>,
    #[serde(default)]
    experimental: ExperimentalDeserialize,
}

/// Intermediate representation for experimental config deserialization.
///
/// This supports both the table format (`[experimental] setup-scripts = true`)
/// and the array format (`experimental = ["setup-scripts"]`). The array format
/// will be deprecated in the future.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(crate) struct ExperimentalDeserialize {
    /// Known experimental features that are enabled.
    known: BTreeSet<ConfigExperimental>,
    /// Unknown feature names (for error reporting).
    unknown: BTreeSet<String>,
}

impl ExperimentalDeserialize {
    /// Returns true if no experimental features are specified.
    fn is_empty(&self) -> bool {
        self.known.is_empty() && self.unknown.is_empty()
    }

    /// Returns the feature names for error messages (used by tool config
    /// validation).
    fn feature_names(&self) -> BTreeSet<String> {
        let mut names = self.unknown.clone();
        for feature in &self.known {
            names.insert(feature.to_string());
        }
        names
    }
}

impl<'de> Deserialize<'de> for ExperimentalDeserialize {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ExperimentalVisitor;

        impl<'de> Visitor<'de> for ExperimentalVisitor {
            type Value = ExperimentalDeserialize;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str(
                    "a table ({ setup-scripts = true, benchmarks = true }) \
                     or an array ([\"setup-scripts\", \"benchmarks\"])",
                )
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                // Array format: parse each string to ConfigExperimental.
                let mut known = BTreeSet::new();
                let mut unknown = BTreeSet::new();
                while let Some(feature_str) = seq.next_element::<String>()? {
                    if let Ok(feature) = feature_str.parse::<ConfigExperimental>() {
                        known.insert(feature);
                    } else {
                        unknown.insert(feature_str);
                    }
                }
                Ok(ExperimentalDeserialize { known, unknown })
            }

            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                // Table format: use typed struct with serde_ignored for unknown
                // fields.
                #[derive(Deserialize)]
                #[serde(rename_all = "kebab-case")]
                struct TableConfig {
                    #[serde(default)]
                    setup_scripts: bool,
                    #[serde(default)]
                    wrapper_scripts: bool,
                    #[serde(default)]
                    benchmarks: bool,
                }

                let mut unknown = BTreeSet::new();
                let de = serde::de::value::MapAccessDeserializer::new(map);
                let mut cb = |path: serde_ignored::Path| {
                    unknown.insert(path.to_string());
                };
                let ignored_de = serde_ignored::Deserializer::new(de, &mut cb);
                let TableConfig {
                    setup_scripts,
                    wrapper_scripts,
                    benchmarks,
                } = Deserialize::deserialize(ignored_de).map_err(serde::de::Error::custom)?;

                let mut known = BTreeSet::new();
                if setup_scripts {
                    known.insert(ConfigExperimental::SetupScripts);
                }
                if wrapper_scripts {
                    known.insert(ConfigExperimental::WrapperScripts);
                }
                if benchmarks {
                    known.insert(ConfigExperimental::Benchmarks);
                }

                Ok(ExperimentalDeserialize { known, unknown })
            }
        }

        deserializer.deserialize_any(ExperimentalVisitor)
    }
}

/// Nextest version configuration.
///
/// Similar to the [`rust-version`
/// field](https://doc.rust-lang.org/cargo/reference/manifest.html#the-rust-version-field),
/// `nextest-version` lets you specify the minimum required version of nextest for a repository.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct NextestVersionConfig {
    /// The minimum version of nextest to produce an error before.
    pub required: NextestVersionReq,

    /// The minimum version of nextest to produce a warning before.
    ///
    /// This might be lower than [`Self::required`], in which case it is ignored. [`Self::eval`]
    /// checks for required versions before it checks for recommended versions.
    pub recommended: NextestVersionReq,
}

impl NextestVersionConfig {
    /// Accumulates a deserialized version requirement into this configuration.
    pub(crate) fn accumulate(&mut self, v: NextestVersionDeserialize, v_tool: Option<ToolName>) {
        if let Some(version) = v.required {
            self.required.accumulate(version, v_tool.clone());
        }
        if let Some(version) = v.recommended {
            self.recommended.accumulate(version, v_tool);
        }
    }

    /// Returns whether the given version satisfies the nextest version requirement.
    pub fn eval(
        &self,
        current_version: &Version,
        override_version_check: bool,
    ) -> NextestVersionEval {
        match self.required.satisfies(current_version) {
            Ok(()) => {}
            Err((required, tool)) => {
                if override_version_check {
                    return NextestVersionEval::ErrorOverride {
                        required: required.clone(),
                        current: current_version.clone(),
                        tool: tool.cloned(),
                    };
                } else {
                    return NextestVersionEval::Error {
                        required: required.clone(),
                        current: current_version.clone(),
                        tool: tool.cloned(),
                    };
                }
            }
        }

        match self.recommended.satisfies(current_version) {
            Ok(()) => NextestVersionEval::Satisfied,
            Err((recommended, tool)) => {
                if override_version_check {
                    NextestVersionEval::WarnOverride {
                        recommended: recommended.clone(),
                        current: current_version.clone(),
                        tool: tool.cloned(),
                    }
                } else {
                    NextestVersionEval::Warn {
                        recommended: recommended.clone(),
                        current: current_version.clone(),
                        tool: tool.cloned(),
                    }
                }
            }
        }
    }
}

/// Experimental features configuration.
///
/// This stores both known and unknown experimental features. Unknown features are stored rather
/// than immediately causing an error, so that the nextest version check can run first.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ExperimentalConfig {
    /// Known experimental features that are enabled.
    known: BTreeSet<ConfigExperimental>,

    /// Unknown experimental feature names.
    unknown: BTreeSet<String>,
}

impl ExperimentalConfig {
    /// Returns the known experimental features that are enabled.
    pub fn known(&self) -> &BTreeSet<ConfigExperimental> {
        &self.known
    }

    /// Evaluates the experimental configuration.
    ///
    /// This should be called after the nextest version check, so that the version error takes
    /// precedence over unknown experimental features (a future version may have new features).
    pub fn eval(&self) -> ExperimentalConfigEval {
        if self.unknown.is_empty() {
            ExperimentalConfigEval::Satisfied
        } else {
            ExperimentalConfigEval::UnknownFeatures {
                unknown: self.unknown.clone(),
                known: ConfigExperimental::known_features().collect(),
            }
        }
    }
}

/// The result of evaluating an [`ExperimentalConfig`].
///
/// Returned by [`ExperimentalConfig::eval`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExperimentalConfigEval {
    /// All experimental features are known.
    Satisfied,

    /// Unknown experimental features were found.
    UnknownFeatures {
        /// The set of unknown feature names.
        unknown: BTreeSet<String>,

        /// The set of known features.
        known: BTreeSet<ConfigExperimental>,
    },
}

impl ExperimentalConfigEval {
    /// Converts this eval result into an error, if it represents an error condition.
    ///
    /// Returns `Some(ConfigParseError)` if this is `UnknownFeatures`, and `None` if `Satisfied`.
    pub fn into_error(self, config_file: impl Into<Utf8PathBuf>) -> Option<ConfigParseError> {
        match self {
            ExperimentalConfigEval::Satisfied => None,
            ExperimentalConfigEval::UnknownFeatures { unknown, known } => {
                Some(ConfigParseError::new(
                    config_file,
                    None,
                    ConfigParseErrorKind::UnknownExperimentalFeatures { unknown, known },
                ))
            }
        }
    }
}

/// Experimental configuration features.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[non_exhaustive]
pub enum ConfigExperimental {
    /// Enable support for setup scripts.
    SetupScripts,
    /// Enable support for wrapper scripts.
    WrapperScripts,
    /// Enable support for benchmarks.
    Benchmarks,
}

impl ConfigExperimental {
    /// Returns an iterator over all known experimental features.
    pub fn known_features() -> impl Iterator<Item = Self> {
        vec![Self::SetupScripts, Self::WrapperScripts, Self::Benchmarks].into_iter()
    }

    /// Returns the environment variable name for this feature, if any.
    pub fn env_var(self) -> Option<&'static str> {
        match self {
            Self::SetupScripts => None,
            Self::WrapperScripts => None,
            Self::Benchmarks => Some("NEXTEST_EXPERIMENTAL_BENCHMARKS"),
        }
    }

    /// Returns the set of experimental features enabled via environment variables.
    pub fn from_env() -> std::collections::BTreeSet<Self> {
        let mut set = std::collections::BTreeSet::new();
        for feature in Self::known_features() {
            if let Some(env_var) = feature.env_var()
                && std::env::var(env_var).as_deref() == Ok("1")
            {
                set.insert(feature);
            }
        }
        set
    }
}

impl FromStr for ConfigExperimental {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "setup-scripts" => Ok(Self::SetupScripts),
            "wrapper-scripts" => Ok(Self::WrapperScripts),
            "benchmarks" => Ok(Self::Benchmarks),
            _ => Err(()),
        }
    }
}

impl fmt::Display for ConfigExperimental {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SetupScripts => write!(f, "setup-scripts"),
            Self::WrapperScripts => write!(f, "wrapper-scripts"),
            Self::Benchmarks => write!(f, "benchmarks"),
        }
    }
}

/// Specification for a nextest version. Part of [`NextestVersionConfig`].
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub enum NextestVersionReq {
    /// A version was specified.
    Version {
        /// The version to warn before.
        version: Version,

        /// The tool which produced this version specification.
        tool: Option<ToolName>,
    },

    /// No version was specified.
    #[default]
    None,
}

impl NextestVersionReq {
    /// Returns the version, if one was specified.
    pub fn version(&self) -> Option<&Version> {
        match self {
            NextestVersionReq::Version { version, .. } => Some(version),
            NextestVersionReq::None => None,
        }
    }

    fn accumulate(&mut self, v: Version, v_tool: Option<ToolName>) {
        match self {
            NextestVersionReq::Version { version, tool } => {
                // This is v >= version rather than v > version, so that if multiple tools specify
                // the same version, the last tool wins.
                if &v >= version {
                    *version = v;
                    *tool = v_tool;
                }
            }
            NextestVersionReq::None => {
                *self = NextestVersionReq::Version {
                    version: v,
                    tool: v_tool,
                };
            }
        }
    }

    fn satisfies(&self, version: &Version) -> Result<(), (&Version, Option<&ToolName>)> {
        match self {
            NextestVersionReq::Version {
                version: required,
                tool,
            } => {
                if version >= required {
                    Ok(())
                } else {
                    Err((required, tool.as_ref()))
                }
            }
            NextestVersionReq::None => Ok(()),
        }
    }
}

/// The result of checking whether a [`NextestVersionConfig`] satisfies a requirement.
///
/// Returned by [`NextestVersionConfig::eval`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NextestVersionEval {
    /// The version satisfies the requirement.
    Satisfied,

    /// An error should be produced.
    Error {
        /// The minimum version required.
        required: Version,
        /// The current version.
        current: Version,
        /// The tool which produced this version specification.
        tool: Option<ToolName>,
    },

    /// A warning should be produced.
    Warn {
        /// The minimum version recommended.
        recommended: Version,
        /// The current version.
        current: Version,
        /// The tool which produced this version specification.
        tool: Option<ToolName>,
    },

    /// An error should be produced but the version is overridden.
    ErrorOverride {
        /// The minimum version recommended.
        required: Version,
        /// The current version.
        current: Version,
        /// The tool which produced this version specification.
        tool: Option<ToolName>,
    },

    /// A warning should be produced but the version is overridden.
    WarnOverride {
        /// The minimum version recommended.
        recommended: Version,
        /// The current version.
        current: Version,
        /// The tool which produced this version specification.
        tool: Option<ToolName>,
    },
}

/// Nextest version configuration.
///
/// Similar to the [`rust-version`
/// field](https://doc.rust-lang.org/cargo/reference/manifest.html#the-rust-version-field),
/// `nextest-version` lets you specify the minimum required version of nextest for a repository.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct NextestVersionDeserialize {
    /// The minimum version of nextest that this repository requires.
    required: Option<Version>,

    /// The minimum version of nextest that this repository produces a warning against.
    recommended: Option<Version>,
}

impl<'de> Deserialize<'de> for NextestVersionDeserialize {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct V;

        impl<'de2> serde::de::Visitor<'de2> for V {
            type Value = NextestVersionDeserialize;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str(
                    "a table ({{ required = \"0.9.20\", recommended = \"0.9.30\" }}) or a string (\"0.9.50\")",
                )
            }

            fn visit_str<E>(self, s: &str) -> std::result::Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                let required = parse_version::<E>(s.to_owned())?;
                Ok(NextestVersionDeserialize {
                    required: Some(required),
                    recommended: None,
                })
            }

            fn visit_map<A>(self, map: A) -> std::result::Result<Self::Value, A::Error>
            where
                A: serde::de::MapAccess<'de2>,
            {
                #[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
                struct NextestVersionMap {
                    #[serde(default, deserialize_with = "deserialize_version_opt")]
                    required: Option<Version>,
                    #[serde(default, deserialize_with = "deserialize_version_opt")]
                    recommended: Option<Version>,
                }

                let NextestVersionMap {
                    required,
                    recommended,
                } = NextestVersionMap::deserialize(serde::de::value::MapAccessDeserializer::new(
                    map,
                ))?;

                if let (Some(required), Some(recommended)) = (&required, &recommended)
                    && required > recommended
                {
                    return Err(serde::de::Error::custom(format!(
                        "required version ({required}) must not be greater than recommended version ({recommended})"
                    )));
                }

                Ok(NextestVersionDeserialize {
                    required,
                    recommended,
                })
            }
        }

        deserializer.deserialize_any(V)
    }
}

/// This has similar logic to the [`rust-version`
/// field](https://doc.rust-lang.org/cargo/reference/manifest.html#the-rust-version-field).
///
/// Adapted from cargo_metadata
fn deserialize_version_opt<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<Version>, D::Error>
where
    D: Deserializer<'de>,
{
    let s = Option::<String>::deserialize(deserializer)?;
    s.map(parse_version::<D::Error>).transpose()
}

fn parse_version<E>(mut s: String) -> std::result::Result<Version, E>
where
    E: serde::de::Error,
{
    for ch in s.chars() {
        if ch == '-' {
            return Err(E::custom(
                "pre-release identifiers are not supported in nextest-version",
            ));
        } else if ch == '+' {
            return Err(E::custom(
                "build metadata is not supported in nextest-version",
            ));
        }
    }

    // The major.minor format is not used with nextest 0.9, but support it anyway to match
    // rust-version.
    if s.matches('.').count() == 1 {
        // e.g. 1.0 -> 1.0.0
        s.push_str(".0");
    }

    Version::parse(&s).map_err(E::custom)
}

#[cfg(test)]
mod tests {
    use super::*;
    use test_case::test_case;

    #[test_case(
        r#"
            nextest-version = "0.9"
        "#,
        NextestVersionDeserialize { required: Some("0.9.0".parse().unwrap()), recommended: None } ; "basic"
    )]
    #[test_case(
        r#"
            nextest-version = "0.9.30"
        "#,
        NextestVersionDeserialize { required: Some("0.9.30".parse().unwrap()), recommended: None } ; "basic with patch"
    )]
    #[test_case(
        r#"
            nextest-version = { recommended = "0.9.20" }
        "#,
        NextestVersionDeserialize { required: None, recommended: Some("0.9.20".parse().unwrap()) } ; "with warning"
    )]
    #[test_case(
        r#"
            nextest-version = { required = "0.9.20", recommended = "0.9.25" }
        "#,
        NextestVersionDeserialize {
            required: Some("0.9.20".parse().unwrap()),
            recommended: Some("0.9.25".parse().unwrap()),
        } ; "with error and warning"
    )]
    fn test_valid_nextest_version(input: &str, expected: NextestVersionDeserialize) {
        let actual: VersionOnlyDeserialize = toml::from_str(input).unwrap();
        assert_eq!(actual.nextest_version.unwrap(), expected);
    }

    #[test_case(
        r#"
            nextest-version = 42
        "#,
        "a table ({{ required = \"0.9.20\", recommended = \"0.9.30\" }}) or a string (\"0.9.50\")" ; "empty"
    )]
    #[test_case(
        r#"
            nextest-version = "0.9.30-rc.1"
        "#,
        "pre-release identifiers are not supported in nextest-version" ; "pre-release"
    )]
    #[test_case(
        r#"
            nextest-version = "0.9.40+mybuild"
        "#,
        "build metadata is not supported in nextest-version" ; "build metadata"
    )]
    #[test_case(
        r#"
            nextest-version = { required = "0.9.20", recommended = "0.9.10" }
        "#,
        "required version (0.9.20) must not be greater than recommended version (0.9.10)" ; "error greater than warning"
    )]
    fn test_invalid_nextest_version(input: &str, error_message: &str) {
        let err = toml::from_str::<VersionOnlyDeserialize>(input).unwrap_err();
        assert!(
            err.to_string().contains(error_message),
            "error `{err}` contains `{error_message}`"
        );
    }

    fn tool_name(s: &str) -> ToolName {
        ToolName::new(s.into()).unwrap()
    }

    #[test]
    fn test_accumulate() {
        let mut nextest_version = NextestVersionConfig::default();
        nextest_version.accumulate(
            NextestVersionDeserialize {
                required: Some("0.9.20".parse().unwrap()),
                recommended: None,
            },
            Some(tool_name("tool1")),
        );
        nextest_version.accumulate(
            NextestVersionDeserialize {
                required: Some("0.9.30".parse().unwrap()),
                recommended: Some("0.9.35".parse().unwrap()),
            },
            Some(tool_name("tool2")),
        );
        nextest_version.accumulate(
            NextestVersionDeserialize {
                required: None,
                // This recommended version is ignored since it is less than the last recommended
                // version.
                recommended: Some("0.9.25".parse().unwrap()),
            },
            Some(tool_name("tool3")),
        );
        nextest_version.accumulate(
            NextestVersionDeserialize {
                // This is accepted because it is the same as the last required version, and the
                // last tool wins.
                required: Some("0.9.30".parse().unwrap()),
                recommended: None,
            },
            Some(tool_name("tool4")),
        );

        assert_eq!(
            nextest_version,
            NextestVersionConfig {
                required: NextestVersionReq::Version {
                    version: "0.9.30".parse().unwrap(),
                    tool: Some(tool_name("tool4")),
                },
                recommended: NextestVersionReq::Version {
                    version: "0.9.35".parse().unwrap(),
                    tool: Some(tool_name("tool2")),
                },
            }
        );
    }

    #[test]
    fn test_from_env_benchmarks() {
        // SAFETY:
        // https://nexte.st/docs/configuration/env-vars/#altering-the-environment-within-tests
        unsafe { std::env::set_var("NEXTEST_EXPERIMENTAL_BENCHMARKS", "1") };
        assert!(ConfigExperimental::from_env().contains(&ConfigExperimental::Benchmarks));

        // Other values do not enable the feature.
        // SAFETY:
        // https://nexte.st/docs/configuration/env-vars/#altering-the-environment-within-tests
        unsafe { std::env::set_var("NEXTEST_EXPERIMENTAL_BENCHMARKS", "0") };
        assert!(!ConfigExperimental::from_env().contains(&ConfigExperimental::Benchmarks));

        // SAFETY:
        // https://nexte.st/docs/configuration/env-vars/#altering-the-environment-within-tests
        unsafe { std::env::set_var("NEXTEST_EXPERIMENTAL_BENCHMARKS", "true") };
        assert!(!ConfigExperimental::from_env().contains(&ConfigExperimental::Benchmarks));

        // SetupScripts and WrapperScripts have no env vars, so they are never
        // enabled via from_env.
        // SAFETY:
        // https://nexte.st/docs/configuration/env-vars/#altering-the-environment-within-tests
        unsafe { std::env::set_var("NEXTEST_EXPERIMENTAL_BENCHMARKS", "1") };
        let set = ConfigExperimental::from_env();
        assert!(!set.contains(&ConfigExperimental::SetupScripts));
        assert!(!set.contains(&ConfigExperimental::WrapperScripts));
    }

    #[test]
    fn test_experimental_formats() {
        // For the array format, valid features should parse correctly.
        let input = r#"experimental = ["setup-scripts", "benchmarks"]"#;
        let d: VersionOnlyDeserialize = toml::from_str(input).unwrap();
        assert_eq!(
            d.experimental.known,
            BTreeSet::from([
                ConfigExperimental::SetupScripts,
                ConfigExperimental::Benchmarks
            ]),
            "expected 2 known features"
        );
        assert!(d.experimental.unknown.is_empty());

        // An empty array is empty.
        let input = r#"experimental = []"#;
        let d: VersionOnlyDeserialize = toml::from_str(input).unwrap();
        assert!(
            d.experimental.is_empty(),
            "expected empty, got {:?}",
            d.experimental
        );

        // Unknown features in the array format are recorded.
        let input = r#"experimental = ["setup-scripts", "unknown-feature"]"#;
        let d: VersionOnlyDeserialize = toml::from_str(input).unwrap();
        assert_eq!(
            d.experimental.known,
            BTreeSet::from([ConfigExperimental::SetupScripts])
        );
        assert_eq!(
            d.experimental.unknown,
            BTreeSet::from(["unknown-feature".to_owned()])
        );

        // Table format: valid features parse correctly.
        let input = r#"
[experimental]
setup-scripts = true
benchmarks = true
"#;
        let d: VersionOnlyDeserialize = toml::from_str(input).unwrap();
        assert_eq!(
            d.experimental.known,
            BTreeSet::from([
                ConfigExperimental::SetupScripts,
                ConfigExperimental::Benchmarks
            ])
        );
        assert!(d.experimental.unknown.is_empty());

        // Empty table is empty.
        let input = r#"[experimental]"#;
        let d: VersionOnlyDeserialize = toml::from_str(input).unwrap();
        assert!(
            d.experimental.is_empty(),
            "expected empty, got {:?}",
            d.experimental
        );

        // If all features are false, the result is empty.
        let input = r#"
[experimental]
setup-scripts = false
"#;
        let d: VersionOnlyDeserialize = toml::from_str(input).unwrap();
        assert!(
            d.experimental.is_empty(),
            "expected empty, got {:?}",
            d.experimental
        );

        // Unknown features in the table format are recorded.
        let input = r#"
[experimental]
setup-scripts = true
unknown-feature = true
"#;
        let d: VersionOnlyDeserialize = toml::from_str(input).unwrap();
        assert_eq!(
            d.experimental.known,
            BTreeSet::from([ConfigExperimental::SetupScripts])
        );
        assert!(d.experimental.unknown.contains("unknown-feature"));

        // An invalid type shows a helpful error mentioning both formats.
        let input = r#"experimental = 42"#;
        let err = toml::from_str::<VersionOnlyDeserialize>(input).unwrap_err();
        let err_str = err.to_string();
        assert!(
            err_str.contains("expected a table") && err_str.contains("or an array"),
            "expected error to mention both formats, got: {}",
            err_str
        );

        let input = r#"experimental = "setup-scripts""#;
        let err = toml::from_str::<VersionOnlyDeserialize>(input).unwrap_err();
        let err_str = err.to_string();
        assert!(
            err_str.contains("expected a table") && err_str.contains("or an array"),
            "expected error to mention both formats, got: {}",
            err_str
        );
    }
}