Skip to content

Commit 3f80e43

Browse files
committed
Represent config version as an enum
1 parent aae9de3 commit 3f80e43

File tree

1 file changed

+35
-15
lines changed

1 file changed

+35
-15
lines changed

src/dist/config.rs

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,22 @@
1-
use anyhow::{bail, Context, Result};
1+
use std::fmt;
2+
use std::str::FromStr;
3+
4+
use anyhow::{Context, Result};
25

36
use super::manifest::Component;
47
use crate::errors::*;
58
use crate::utils::toml_utils::*;
69

7-
pub(crate) const SUPPORTED_CONFIG_VERSIONS: [&str; 1] = ["1"];
8-
pub(crate) const DEFAULT_CONFIG_VERSION: &str = "1";
9-
10-
#[derive(Clone, Debug)]
10+
#[derive(Clone, Debug, Default)]
1111
pub struct Config {
12-
pub config_version: String,
12+
pub config_version: ConfigVersion,
1313
pub components: Vec<Component>,
1414
}
1515

1616
impl Config {
1717
pub(crate) fn from_toml(mut table: toml::value::Table, path: &str) -> Result<Self> {
1818
let config_version = get_string(&mut table, "config_version", path)?;
19-
if !SUPPORTED_CONFIG_VERSIONS.contains(&&*config_version) {
20-
bail!(RustupError::UnsupportedVersion(config_version));
21-
}
19+
let config_version = ConfigVersion::from_str(&config_version)?;
2220

2321
let components = get_array(&mut table, "components", path)?;
2422
let components =
@@ -33,7 +31,7 @@ impl Config {
3331
let mut result = toml::value::Table::new();
3432
result.insert(
3533
"config_version".to_owned(),
36-
toml::Value::String(self.config_version),
34+
toml::Value::String(self.config_version.as_str().to_owned()),
3735
);
3836
let components = Self::components_to_toml(self.components);
3937
if !components.is_empty() {
@@ -77,11 +75,33 @@ impl Config {
7775
}
7876
}
7977

80-
impl Default for Config {
81-
fn default() -> Self {
82-
Self {
83-
config_version: DEFAULT_CONFIG_VERSION.to_owned(),
84-
components: Vec::new(),
78+
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
79+
pub(crate) enum ConfigVersion {
80+
#[default]
81+
V1,
82+
}
83+
84+
impl ConfigVersion {
85+
pub fn as_str(&self) -> &'static str {
86+
match self {
87+
Self::V1 => "1",
8588
}
8689
}
8790
}
91+
92+
impl FromStr for ConfigVersion {
93+
type Err = RustupError;
94+
95+
fn from_str(s: &str) -> Result<Self, Self::Err> {
96+
match s {
97+
"1" => Ok(Self::V1),
98+
_ => Err(RustupError::UnsupportedVersion(s.to_owned())),
99+
}
100+
}
101+
}
102+
103+
impl fmt::Display for ConfigVersion {
104+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105+
write!(f, "{}", self.as_str())
106+
}
107+
}

0 commit comments

Comments
 (0)