Skip to content

Commit

Permalink
Add FromStr impl for Edition and BoxError alias
Browse files Browse the repository at this point in the history
This commit moves the parsing code we did for Edition in the Manifest
type to a FromStr impl so that we can instead use this in other places
as well if need be and have the parsing code for Manifest be more about
parsing out fields and not doing adhoc type conversions in that parsing
if we can move it into the type itself somehow. We also alias `Box<dyn Error>`
to `BoxError` so that we can easily use that for our Error type for now.
  • Loading branch information
mgattozzi committed Jul 24, 2023
1 parent 5e0e310 commit 5966b05
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
16 changes: 5 additions & 11 deletions src/config.rs
@@ -1,8 +1,9 @@
use super::BoxError;
use super::Edition;
use super::Result;
use std::error::Error;
use std::fs;
use std::path::Path;
use std::str::FromStr;

pub struct Manifest {
pub crate_name: String,
Expand All @@ -22,21 +23,14 @@ impl Manifest {

match field {
"name" => crate_name = Some(value.replace('"', "")),
"edition" => {
edition = Some(match value.replace('"', "").parse()? {
2015 => Edition::E2015,
2018 => Edition::E2018,
2021 => Edition::E2021,
edition => return Err(format!("Edition {edition} is unsupported").into()),
})
}
"edition" => edition = Some(Edition::from_str(&value.replace('"', ""))?),
field => return Err(format!("Field {field} is unsupported").into()),
}
}

Ok(Self {
crate_name: crate_name.ok_or::<Box<dyn Error>>("name is a required field".into())?,
edition: edition.ok_or::<Box<dyn Error>>("edition is a required field".into())?,
crate_name: crate_name.ok_or::<BoxError>("name is a required field".into())?,
edition: edition.ok_or::<BoxError>("edition is a required field".into())?,
})
}
}
16 changes: 15 additions & 1 deletion src/lib.rs
Expand Up @@ -8,8 +8,10 @@ use std::fmt::Display;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::str::FromStr;

pub type Result<T> = std::result::Result<T, Box<dyn Error>>;
pub type Result<T> = std::result::Result<T, BoxError>;
pub type BoxError = Box<dyn Error>;

pub fn build() -> Result<()> {
let root_dir = root_dir()?;
Expand Down Expand Up @@ -201,6 +203,18 @@ impl Display for Edition {
}
}

impl FromStr for Edition {
type Err = BoxError;
fn from_str(input: &str) -> Result<Self> {
match input {
"2015" => Ok(Self::E2015),
"2018" => Ok(Self::E2018),
"2021" => Ok(Self::E2021),
edition => Err(format!("Edition {edition} is not supported").into()),
}
}
}

pub enum CrateType {
Bin,
Lib,
Expand Down

0 comments on commit 5966b05

Please sign in to comment.