Merge pull request #297 from amousset/code-cleanup

style(transport): Improve code style
This commit is contained in:
Alexis Mousset
2018-05-31 15:49:20 +02:00
committed by GitHub
7 changed files with 53 additions and 53 deletions

View File

@@ -24,9 +24,9 @@ pub struct FileTransport {
impl FileTransport {
/// Creates a new transport to the given directory
pub fn new<P: AsRef<Path>>(path: P) -> FileTransport {
let mut path_buf = PathBuf::new();
path_buf.push(path);
FileTransport { path: path_buf }
FileTransport {
path: PathBuf::from(path.as_ref()),
}
}
}
@@ -48,16 +48,13 @@ impl<'a> Transport<'a> for FileTransport {
let mut file = self.path.clone();
file.push(format!("{}.json", message_id));
let mut f = File::create(file.as_path())?;
let serialized = serde_json::to_string(&SerializableEmail {
envelope,
message_id,
message: email.message_to_string()?.as_bytes().to_vec(),
})?;
f.write_all(serialized.as_bytes())?;
File::create(file.as_path())?.write_all(serialized.as_bytes())?;
Ok(())
}
}

View File

@@ -52,6 +52,7 @@ pub use sendmail::SendmailTransport;
pub use smtp::client::net::ClientTlsParameters;
#[cfg(feature = "smtp-transport")]
pub use smtp::{ClientSecurity, SmtpClient, SmtpTransport};
use std::ffi::OsStr;
use std::fmt::{self, Display, Formatter};
use std::io;
use std::io::Cursor;
@@ -85,6 +86,18 @@ impl Display for EmailAddress {
}
}
impl AsRef<str> for EmailAddress {
fn as_ref(&self) -> &str {
&self.0
}
}
impl AsRef<OsStr> for EmailAddress {
fn as_ref(&self) -> &OsStr {
&self.0.as_ref()
}
}
/// Simple email envelope representation
///
/// We only accept mailboxes, and do not support source routes (as per RFC).

View File

@@ -40,17 +40,17 @@ impl<'a> Transport<'a> for SendmailTransport {
let message_id = email.message_id().to_string();
// Spawn the sendmail command
let to_addresses: Vec<String> = email.envelope.to().iter().map(|x| x.to_string()).collect();
let mut process = Command::new(&self.command)
.args(&[
"-i",
"-f",
&match email.envelope().from() {
Some(address) => address.to_string(),
None => "\"\"".to_string(),
},
])
.args(&to_addresses)
.arg("-i")
.arg("-f")
.arg(
email
.envelope()
.from()
.map(|x| x.as_ref())
.unwrap_or("\"\""),
)
.args(email.envelope.to())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;

View File

@@ -102,10 +102,8 @@ impl Mechanism {
)),
},
Mechanism::Login => {
let decoded_challenge = match challenge {
Some(challenge) => challenge,
None => return Err(Error::Client("This mechanism does expect a challenge")),
};
let decoded_challenge =
challenge.ok_or(Error::Client("This mechanism does expect a challenge"))?;
if vec!["User Name", "Username:", "Username"].contains(&decoded_challenge) {
return Ok(credentials.authentication_identity.to_string());

View File

@@ -53,10 +53,7 @@ impl Display for MailCommand {
write!(
f,
"MAIL FROM:<{}>",
match self.sender {
Some(ref address) => address.to_string(),
None => "".to_string(),
}
self.sender.as_ref().map(|x| x.as_ref()).unwrap_or("")
)?;
for parameter in &self.parameters {
write!(f, " {}", parameter)?;
@@ -220,17 +217,12 @@ pub struct AuthCommand {
impl Display for AuthCommand {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let encoded_response = if self.response.is_some() {
Some(base64::encode_config(
self.response.as_ref().unwrap().as_bytes(),
base64::STANDARD,
))
} else {
None
};
let encoded_response = self.response
.as_ref()
.map(|r| base64::encode_config(r.as_bytes(), base64::STANDARD));
if self.mechanism.supports_initial_response() {
write!(f, "AUTH {} {}", self.mechanism, encoded_response.unwrap(),)?;
write!(f, "AUTH {} {}", self.mechanism, encoded_response.unwrap())?;
} else {
match encoded_response {
Some(response) => f.write_str(&response)?,
@@ -272,21 +264,12 @@ impl AuthCommand {
return Err(Error::ResponseParsing("Expecting a challenge"));
}
let encoded_challenge = match response.first_word() {
Some(challenge) => challenge.to_string(),
None => return Err(Error::ResponseParsing("Could not read auth challenge")),
};
let encoded_challenge = response
.first_word()
.ok_or(Error::ResponseParsing("Could not read auth challenge"))?;
debug!("auth encoded challenge: {}", encoded_challenge);
let decoded_challenge = match base64::decode(&encoded_challenge) {
Ok(challenge) => match String::from_utf8(challenge) {
Ok(value) => value,
Err(error) => return Err(Error::Utf8Parsing(error)),
},
Err(error) => return Err(Error::ChallengeParsing(error)),
};
let decoded_challenge = String::from_utf8(base64::decode(&encoded_challenge)?)?;
debug!("auth decoded challenge: {}", decoded_challenge);
let response = Some(mechanism.response(&credentials, Some(decoded_challenge.as_ref()))?);

View File

@@ -101,6 +101,18 @@ impl From<nom::simple_errors::Err> for Error {
}
}
impl From<DecodeError> for Error {
fn from(err: DecodeError) -> Error {
ChallengeParsing(err)
}
}
impl From<FromUtf8Error> for Error {
fn from(err: FromUtf8Error) -> Error {
Utf8Parsing(err)
}
}
impl From<Response> for Error {
fn from(response: Response) -> Error {
match response.code.severity {

View File

@@ -10,8 +10,8 @@ use std::fmt::{self, Display, Formatter};
use std::net::{Ipv4Addr, Ipv6Addr};
use std::result::Result;
/// Default ehlo clinet id
pub const DEFAULT_EHLO_HOSTNAME: &str = "localhost";
/// Default client id
pub const DEFAULT_DOMAIN_CLIENT_ID: &str = "localhost";
/// Client identifier, the parameter to `EHLO`
#[derive(PartialEq, Eq, Clone, Debug)]
@@ -44,10 +44,7 @@ impl ClientId {
/// Defines a `ClientId` with the current hostname, of `localhost` if hostname could not be
/// found
pub fn hostname() -> ClientId {
ClientId::Domain(match get_hostname() {
Some(name) => name,
None => DEFAULT_EHLO_HOSTNAME.to_string(),
})
ClientId::Domain(get_hostname().unwrap_or_else(|| DEFAULT_DOMAIN_CLIENT_ID.to_string()))
}
}