Skip to content

Commit 39490a9

Browse files
committed
Add Error definition
1 parent 1c874cf commit 39490a9

3 files changed

Lines changed: 71 additions & 0 deletions

File tree

src/distribution.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
use std::str::FromStr;
2+
3+
use crate::Error;
4+
use mailparse::MailHeaderMap;
5+
16
#[derive(Debug, Clone, Default, PartialEq)]
27
pub struct Distribution {
38
/// Version of the file format; legal values are “1.0”, “1.1”, “1.2”, “2.1” and “2.2”.
@@ -62,3 +67,31 @@ pub struct Distribution {
6267
/// so that tools can intelligently render the description.
6368
pub description_content_type: Option<String>,
6469
}
70+
71+
impl FromStr for Distribution {
72+
type Err = Error;
73+
74+
fn from_str(s: &str) -> Result<Self, Self::Err> {
75+
let msg = mailparse::parse_mail(s.as_bytes())?;
76+
let headers = msg.get_headers();
77+
let metadata_version = headers
78+
.get_first_value("Metadata-Version")
79+
.ok_or_else(|| Error::KeyError("Metadata-Version"))?;
80+
Ok(Distribution {
81+
metadata_version,
82+
..Default::default()
83+
})
84+
}
85+
}
86+
87+
#[cfg(test)]
88+
mod tests {
89+
use super::Distribution;
90+
91+
#[test]
92+
fn test_parse_from_str() {
93+
let s = "Metadata-Version: 1.0";
94+
let dist: Distribution = s.parse().unwrap();
95+
assert_eq!(dist.metadata_version, "1.0");
96+
}
97+
}

src/error.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
use std::{error, fmt};
2+
3+
use mailparse::MailParseError;
4+
5+
/// The error type
6+
#[derive(Debug)]
7+
pub enum Error {
8+
/// mail parse error
9+
MailParse(MailParseError),
10+
/// Metadata key error
11+
KeyError(&'static str),
12+
}
13+
14+
impl fmt::Display for Error {
15+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16+
match self {
17+
Error::MailParse(err) => err.fmt(f),
18+
Error::KeyError(key) => write!(f, "metadata key {} not found", key),
19+
}
20+
}
21+
}
22+
23+
impl error::Error for Error {
24+
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
25+
match self {
26+
Error::MailParse(err) => Some(err),
27+
Error::KeyError(_) => None,
28+
}
29+
}
30+
}
31+
32+
impl From<MailParseError> for Error {
33+
fn from(err: MailParseError) -> Self {
34+
Self::MailParse(err)
35+
}
36+
}

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
mod distribution;
2+
mod error;
23

34
pub use crate::distribution::Distribution;
5+
pub use crate::error::Error;

0 commit comments

Comments
 (0)