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
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::{fmt::Display, str::FromStr};

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, Default)]
pub enum ToolChain {
    Stable,
    Beta,
    Nightly,
    // cargo with no +argument, it can be different from the above
    #[default]
    Default,
}

impl FromStr for ToolChain {
    type Err = Box<dyn std::error::Error>;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "stable" => Ok(ToolChain::Stable),
            "beta" => Ok(ToolChain::Beta),
            "nightly" => Ok(ToolChain::Nightly),
            "default" => Ok(ToolChain::Default),
            _ => Err("Unknown toolchain".into()),
        }
    }
}

impl ToolChain {
    pub(crate) fn as_arg(&self) -> &str {
        match self {
            ToolChain::Stable => "+stable",
            ToolChain::Beta => "+beta",
            ToolChain::Nightly => "+nightly",
            // The caller should not call as_arg for the default toolchain
            ToolChain::Default => unreachable!(),
        }
    }
}

impl Display for ToolChain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ToolChain::Stable => write!(f, "stable"),
            ToolChain::Beta => write!(f, "beta"),
            ToolChain::Nightly => write!(f, "nightly"),
            ToolChain::Default => write!(f, "default"),
        }
    }
}