Made unspecified server or nickname into errors instead of simply panics.

This commit is contained in:
Aaron Weiss 2018-01-27 20:26:56 +01:00
parent c3863ed76b
commit ce158fc612
No known key found for this signature in database
GPG key ID: 047D32DF25DC22EF
5 changed files with 27 additions and 16 deletions

View file

@ -108,7 +108,7 @@ impl Connection {
if config.use_mock_connection() { if config.use_mock_connection() {
Ok(ConnectionFuture::Mock(config)) Ok(ConnectionFuture::Mock(config))
} else if config.use_ssl() { } else if config.use_ssl() {
let domain = format!("{}", config.server()); let domain = format!("{}", config.server()?);
info!("Connecting via SSL to {}.", domain); info!("Connecting via SSL to {}.", domain);
let mut builder = TlsConnector::builder()?; let mut builder = TlsConnector::builder()?;
if let Some(cert_path) = config.cert_path() { if let Some(cert_path) = config.cert_path() {
@ -133,7 +133,7 @@ impl Connection {
)); ));
Ok(ConnectionFuture::Secured(config, stream)) Ok(ConnectionFuture::Secured(config, stream))
} else { } else {
info!("Connecting to {}.", config.server()); info!("Connecting to {}.", config.server()?);
Ok(ConnectionFuture::Unsecured( Ok(ConnectionFuture::Unsecured(
config, config,
TcpStream::connect(&config.socket_addr()?, handle), TcpStream::connect(&config.socket_addr()?, handle),

View file

@ -259,9 +259,8 @@ impl Config {
} }
/// Gets the nickname specified in the configuration. /// Gets the nickname specified in the configuration.
/// This will panic if not specified. pub fn nickname(&self) -> Result<&str> {
pub fn nickname(&self) -> &str { self.nickname.as_ref().map(|s| &s[..]).ok_or(error::ErrorKind::NicknameNotSpecified.into())
self.nickname.as_ref().map(|s| &s[..]).unwrap()
} }
/// Gets the bot's nickserv password specified in the configuration. /// Gets the bot's nickserv password specified in the configuration.
@ -282,19 +281,19 @@ impl Config {
/// Gets the username specified in the configuration. /// Gets the username specified in the configuration.
/// This defaults to the user's nickname when not specified. /// This defaults to the user's nickname when not specified.
pub fn username(&self) -> &str { pub fn username(&self) -> &str {
self.username.as_ref().map_or(self.nickname(), |s| &s) self.username.as_ref().map_or(self.nickname().unwrap_or("user"), |s| &s)
} }
/// Gets the real name specified in the configuration. /// Gets the real name specified in the configuration.
/// This defaults to the user's nickname when not specified. /// This defaults to the user's nickname when not specified.
pub fn real_name(&self) -> &str { pub fn real_name(&self) -> &str {
self.realname.as_ref().map_or(self.nickname(), |s| &s) self.realname.as_ref().map_or(self.nickname().unwrap_or("irc"), |s| &s)
} }
/// Gets the address of the server specified in the configuration. /// Gets the address of the server specified in the configuration.
/// This panics when not specified. pub fn server(&self) -> Result<&str> {
pub fn server(&self) -> &str { self.server.as_ref().map(|s| &s[..]).ok_or(error::ErrorKind::NicknameNotSpecified.into())
self.server.as_ref().map(|s| &s[..]).unwrap()
} }
/// Gets the port of the server specified in the configuration. /// Gets the port of the server specified in the configuration.
@ -310,7 +309,7 @@ impl Config {
/// Gets the server and port as a `SocketAddr`. /// Gets the server and port as a `SocketAddr`.
/// This panics when server is not specified or the address is malformed. /// This panics when server is not specified or the address is malformed.
pub fn socket_addr(&self) -> Result<SocketAddr> { pub fn socket_addr(&self) -> Result<SocketAddr> {
format!("{}:{}", self.server(), self.port()).to_socket_addrs() format!("{}:{}", self.server()?, self.port()).to_socket_addrs()
.map(|mut i| i.next().unwrap()) .map(|mut i| i.next().unwrap())
.map_err(|e| e.into()) .map_err(|e| e.into())
} }

View file

@ -326,7 +326,9 @@ impl ServerState {
let alt_nicks = self.config().alternate_nicknames(); let alt_nicks = self.config().alternate_nicknames();
let index = self.alt_nick_index.read().unwrap(); let index = self.alt_nick_index.read().unwrap();
match *index { match *index {
0 => self.config().nickname(), 0 => self.config().nickname().expect(
"current_nickname should not be callable if nickname is not defined."
),
i => alt_nicks[i - 1], i => alt_nicks[i - 1],
} }
} }
@ -348,6 +350,7 @@ impl ServerState {
trace!("[RECV] {}", msg.to_string()); trace!("[RECV] {}", msg.to_string());
match msg.command { match msg.command {
JOIN(ref chan, _, _) => self.handle_join(msg.source_nickname().unwrap_or(""), chan), JOIN(ref chan, _, _) => self.handle_join(msg.source_nickname().unwrap_or(""), chan),
/// This will panic if not specified.
PART(ref chan, _) => self.handle_part(msg.source_nickname().unwrap_or(""), chan), PART(ref chan, _) => self.handle_part(msg.source_nickname().unwrap_or(""), chan),
QUIT(_) => self.handle_quit(msg.source_nickname().unwrap_or("")), QUIT(_) => self.handle_quit(msg.source_nickname().unwrap_or("")),
NICK(ref new_nick) => { NICK(ref new_nick) => {
@ -420,12 +423,12 @@ impl ServerState {
self.send(NICKSERV(format!( self.send(NICKSERV(format!(
"{} {} {}", "{} {} {}",
seq, seq,
self.config().nickname(), self.config().nickname()?,
self.config().nick_password() self.config().nick_password()
)))?; )))?;
} }
*index = 0; *index = 0;
self.send(NICK(self.config().nickname().to_owned()))? self.send(NICK(self.config().nickname()?.to_owned()))?
} }
self.send(NICKSERV( self.send(NICKSERV(
format!("IDENTIFY {}", self.config().nick_password()), format!("IDENTIFY {}", self.config().nick_password()),

View file

@ -95,7 +95,7 @@ pub trait ServerExt: Server {
if self.config().password() != "" { if self.config().password() != "" {
self.send(PASS(self.config().password().to_owned()))?; self.send(PASS(self.config().password().to_owned()))?;
} }
self.send(NICK(self.config().nickname().to_owned()))?; self.send(NICK(self.config().nickname()?.to_owned()))?;
self.send(USER( self.send(USER(
self.config().username().to_owned(), self.config().username().to_owned(),
"0".to_owned(), "0".to_owned(),

View file

@ -1,5 +1,4 @@
//! Errors for `irc` crate using `error_chain`. //! Errors for `irc` crate using `error_chain`.
#![allow(missing_docs)] #![allow(missing_docs)]
error_chain! { error_chain! {
@ -54,5 +53,15 @@ error_chain! {
description("The connection timed out due to no ping response.") description("The connection timed out due to no ping response.")
display("The connection timed out due to no ping response.") display("The connection timed out due to no ping response.")
} }
NicknameNotSpecified {
description("No nickname was specified for use with this IrcServer.")
display("No nickname was specified for use with this IrcServer.")
}
ServerNotSpecified {
description("No server was specified to connect to.")
display("No server was specified to connect to.")
}
} }
} }