diff options
| author | Jokler <jokler.contact@gmail.com> | 2018-02-12 20:31:56 +0100 |
|---|---|---|
| committer | Jokler <jokler.contact@gmail.com> | 2018-02-12 20:31:56 +0100 |
| commit | 72f1411f1c72a9271c7d3993a3e307050e8d1b31 (patch) | |
| tree | 92cbd36b13d09134ad5d8f23bf933c7aba0d7bb4 | |
| parent | d761a8ad9650b4797a673230c2cc924235aafc98 (diff) | |
| download | frippy-72f1411f1c72a9271c7d3993a3e307050e8d1b31.tar.gz frippy-72f1411f1c72a9271c7d3993a3e307050e8d1b31.zip | |
Run latest rustfmt
| -rw-r--r-- | src/lib.rs | 74 | ||||
| -rw-r--r-- | src/main.rs | 50 | ||||
| -rw-r--r-- | src/plugin.rs | 18 | ||||
| -rw-r--r-- | src/plugins/currency.rs | 64 | ||||
| -rw-r--r-- | src/plugins/emoji.rs | 22 | ||||
| -rw-r--r-- | src/plugins/keepnick.rs | 7 | ||||
| -rw-r--r-- | src/plugins/url.rs | 38 |
7 files changed, 137 insertions, 136 deletions
@@ -1,5 +1,5 @@ -#![cfg_attr(feature="clippy", feature(plugin))] -#![cfg_attr(feature="clippy", plugin(clippy))] +#![cfg_attr(feature = "clippy", feature(plugin))] +#![cfg_attr(feature = "clippy", plugin(clippy))] //! Frippy is an IRC bot that runs plugins on each message //! received. @@ -30,11 +30,11 @@ //! which might be of interest. #[macro_use] -extern crate log; +extern crate frippy_derive; #[macro_use] extern crate lazy_static; #[macro_use] -extern crate frippy_derive; +extern crate log; extern crate irc; @@ -70,7 +70,9 @@ impl Bot { /// let mut bot = Bot::new(); /// ``` pub fn new() -> Bot { - Bot { plugins: ThreadedPlugins::new() } + Bot { + plugins: ThreadedPlugins::new(), + } } /// Adds the [`Plugin`](plugin/trait.Plugin.html). @@ -103,10 +105,13 @@ impl Bot { self.plugins.remove(name) } - /// This connects the `Bot` to IRC and creates a task on the [`IrcReactor`](../irc/client/reactor/struct.IrcReactor.html) - /// which returns an Ok if the connection was cleanly closed and an Err if the connection was lost. + /// This connects the `Bot` to IRC and creates a task on the + /// [`IrcReactor`](../irc/client/reactor/struct.IrcReactor.html) + /// which returns an Ok if the connection was cleanly closed and + /// an Err if the connection was lost. /// - /// You need to run the [`IrcReactor`](../irc/client/reactor/struct.IrcReactor.html), so that the `Bot` + /// You need to run the [`IrcReactor`](../irc/client/reactor/struct.IrcReactor.html), + /// so that the `Bot` /// can actually do its work. /// /// # Examples @@ -151,11 +156,11 @@ impl Bot { } } -fn process_msg(server: &IrcClient, - mut plugins: ThreadedPlugins, - message: Message) - -> Result<(), IrcError> { - +fn process_msg( + server: &IrcClient, + mut plugins: ThreadedPlugins, + message: Message, +) -> Result<(), IrcError> { // Log any channels we join if let Command::JOIN(ref channel, _, _) = message.command { if message.source_nickname().unwrap() == server.current_nickname() { @@ -185,7 +190,9 @@ struct ThreadedPlugins { impl ThreadedPlugins { pub fn new() -> ThreadedPlugins { - ThreadedPlugins { plugins: HashMap::new() } + ThreadedPlugins { + plugins: HashMap::new(), + } } pub fn add<T: Plugin + 'static>(&mut self, plugin: T) { @@ -208,10 +215,11 @@ impl ThreadedPlugins { ExecutionStatus::Done => (), ExecutionStatus::Err(e) => error!("Error in {} - {}", name, e), ExecutionStatus::RequiresThread => { - - debug!("Spawning thread to execute {} with {}", - name, - message.to_string().replace("\r\n", "")); + debug!( + "Spawning thread to execute {} with {}", + name, + message.to_string().replace("\r\n", "") + ); // Clone everything before the move - the server uses an Arc internally too let plugin = Arc::clone(&plugin); @@ -229,11 +237,11 @@ impl ThreadedPlugins { } } - pub fn handle_command(&mut self, - server: &IrcClient, - mut command: PluginCommand) - -> Result<(), IrcError> { - + pub fn handle_command( + &mut self, + server: &IrcClient, + mut command: PluginCommand, + ) -> Result<(), IrcError> { if !command.tokens.iter().any(|s| !s.is_empty()) { let help = format!("Use \"{} help\" to get help", server.current_nickname()); return server.send_notice(&command.source, &help); @@ -241,7 +249,6 @@ impl ThreadedPlugins { // Check if the command is for this plugin if let Some(plugin) = self.plugins.get(&command.tokens[0].to_lowercase()) { - // The first token contains the name of the plugin let name = command.tokens.remove(0); @@ -251,18 +258,19 @@ impl ThreadedPlugins { let server = server.clone(); let plugin = Arc::clone(plugin); spawn(move || { - if let Err(e) = plugin.command(&server, command) { - error!("Error in {} command - {}", name, e); - }; - }); + if let Err(e) = plugin.command(&server, command) { + error!("Error in {} command - {}", name, e); + }; + }); Ok(()) - } else { - let help = format!("\"{} {}\" is not a command, \ - try \"{0} help\" instead.", - server.current_nickname(), - command.tokens[0]); + let help = format!( + "\"{} {}\" is not a command, \ + try \"{0} help\" instead.", + server.current_nickname(), + command.tokens[0] + ); server.send_notice(&command.source, &help) } diff --git a/src/main.rs b/src/main.rs index 7df8b3b..9a96791 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,15 +1,15 @@ -#![cfg_attr(feature="clippy", feature(plugin))] -#![cfg_attr(feature="clippy", plugin(clippy))] +#![cfg_attr(feature = "clippy", feature(plugin))] +#![cfg_attr(feature = "clippy", plugin(clippy))] extern crate frippy; -extern crate time; -extern crate irc; extern crate glob; +extern crate irc; +extern crate time; #[macro_use] extern crate log; -use log::{Record, Level, LevelFilter, Metadata}; +use log::{Level, LevelFilter, Metadata, Record}; use irc::client::reactor::IrcReactor; use glob::glob; @@ -27,16 +27,20 @@ impl log::Log for Logger { fn log(&self, record: &Record) { if self.enabled(record.metadata()) { if record.metadata().level() >= Level::Debug { - println!("[{}]({}) {} -> {}", - time::now().rfc822(), - record.level(), - record.target(), - record.args()); + println!( + "[{}]({}) {} -> {}", + time::now().rfc822(), + record.level(), + record.target(), + record.args() + ); } else { - println!("[{}]({}) {}", - time::now().rfc822(), - record.level(), - record.args()); + println!( + "[{}]({}) {}", + time::now().rfc822(), + record.level(), + record.args() + ); } } } @@ -47,12 +51,11 @@ impl log::Log for Logger { static LOGGER: Logger = Logger; fn main() { - log::set_max_level(if cfg!(debug_assertions) { - LevelFilter::Debug - } else { - LevelFilter::Info - }); + LevelFilter::Debug + } else { + LevelFilter::Info + }); log::set_logger(&LOGGER).unwrap(); @@ -82,14 +85,10 @@ fn main() { // Open a connection and add work for each config for config in configs { - let mut disabled_plugins = None; if let Some(ref options) = config.options { if let Some(disabled) = options.get("disabled_plugins") { - disabled_plugins = Some(disabled - .split(',') - .map(|p| p.trim()) - .collect::<Vec<_>>()); + disabled_plugins = Some(disabled.split(',').map(|p| p.trim()).collect::<Vec<_>>()); } } @@ -109,7 +108,8 @@ fn main() { } } - bot.connect(&mut reactor, &config).expect("Failed to connect"); + bot.connect(&mut reactor, &config) + .expect("Failed to connect"); } // Run the bots until they throw an error - an error could be loss of connection diff --git a/src/plugin.rs b/src/plugin.rs index e343a2c..a67d68f 100644 --- a/src/plugin.rs +++ b/src/plugin.rs @@ -30,7 +30,7 @@ pub trait Plugin: PluginName + Send + Sync + fmt::Debug { fn evaluate(&self, server: &IrcClient, command: PluginCommand) -> Result<String, String>; } -/// `PluginName` is required by [`Plugin`](trait.Plugin.html). +/// `PluginName` is required by [`Plugin`](trait.Plugin.html). /// /// To implement it simply add `#[derive(PluginName)]` /// above the definition of the struct. @@ -64,25 +64,19 @@ impl PluginCommand { /// if it contains a [`PRIVMSG`](../../irc/proto/command/enum.Command.html#variant.PRIVMSG) /// that starts with the provided `nick`. pub fn from(nick: &str, message: &Message) -> Option<PluginCommand> { - // Get the actual message out of PRIVMSG if let Command::PRIVMSG(_, ref content) = message.command { - // Split content by spaces and filter empty tokens let mut tokens: Vec<String> = content.split(' ').map(ToOwned::to_owned).collect(); // Commands start with our name if tokens[0].to_lowercase().starts_with(nick) { - // Remove the bot's name from the first token tokens[0].drain(..nick.len()); // We assume that only ':' and ',' are used as suffixes on IRC // If there are any other chars we assume that it is not ment for the bot - tokens[0] = tokens[0] - .chars() - .filter(|&c| !":,".contains(c)) - .collect(); + tokens[0] = tokens[0].chars().filter(|&c| !":,".contains(c)).collect(); if !tokens[0].is_empty() { return None; } @@ -91,10 +85,10 @@ impl PluginCommand { tokens.remove(0); Some(PluginCommand { - source: message.source_nickname().unwrap().to_string(), - target: message.response_target().unwrap().to_string(), - tokens: tokens, - }) + source: message.source_nickname().unwrap().to_string(), + target: message.response_target().unwrap().to_string(), + tokens: tokens, + }) } else { None } diff --git a/src/plugins/currency.rs b/src/plugins/currency.rs index 21330a1..393df9b 100644 --- a/src/plugins/currency.rs +++ b/src/plugins/currency.rs @@ -34,7 +34,6 @@ macro_rules! try_option { impl<'a> ConvertionRequest<'a> { fn send(&self) -> Option<f64> { - let response = Client::new() .get("https://api.fixer.io/latest") .form(&[("base", self.source)]) @@ -49,7 +48,6 @@ impl<'a> ConvertionRequest<'a> { let convertion_rates: Result<Value, _> = serde_json::from_str(&body); match convertion_rates { Ok(convertion_rates) => { - let rates: &Value = try_option!(convertion_rates.get("rates")); let target_rate: &Value = try_option!(rates.get(self.target.to_uppercase())); @@ -68,14 +66,15 @@ impl Currency { Currency {} } - fn eval_command<'a>(&self, - tokens: &'a [String]) - -> Result<ConvertionRequest<'a>, ParseFloatError> { + fn eval_command<'a>( + &self, + tokens: &'a [String], + ) -> Result<ConvertionRequest<'a>, ParseFloatError> { Ok(ConvertionRequest { - value: tokens[0].parse()?, - source: &tokens[1], - target: &tokens[2], - }) + value: tokens[0].parse()?, + source: &tokens[1], + target: &tokens[2], + }) } fn convert(&self, client: &IrcClient, command: &mut PluginCommand) -> Result<String, String> { @@ -92,33 +91,41 @@ impl Currency { match request.send() { Some(response) => { - let response = format!("{} {} => {:.4} {}", - request.value, - request.source.to_lowercase(), - response / 1.00000000, - request.target.to_lowercase()); + let response = format!( + "{} {} => {:.4} {}", + request.value, + request.source.to_lowercase(), + response / 1.00000000, + request.target.to_lowercase() + ); Ok(response) } - None => Err(String::from("An error occured during the conversion of the given currency")), + None => Err(String::from( + "An error occured during the conversion of the given currency", + )), } } fn help(&self, client: &IrcClient) -> String { - format!("usage: {} currency value from_currency to_currency\r\n\ - example: {0} currency 1.5 eur usd\r\n\ - available currencies: AUD, BGN, BRL, CAD, \ - CHF, CNY, CZK, DKK, GBP, HKD, HRK, HUF, \ - IDR, ILS, INR, JPY, KRW, MXN, MYR, NOK, \ - NZD, PHP, PLN, RON, RUB, SEK, SGD, THB, \ - TRY, USD, ZAR", - client.current_nickname()) + format!( + "usage: {} currency value from_currency to_currency\r\n\ + example: {0} currency 1.5 eur usd\r\n\ + available currencies: AUD, BGN, BRL, CAD, \ + CHF, CNY, CZK, DKK, GBP, HKD, HRK, HUF, \ + IDR, ILS, INR, JPY, KRW, MXN, MYR, NOK, \ + NZD, PHP, PLN, RON, RUB, SEK, SGD, THB, \ + TRY, USD, ZAR", + client.current_nickname() + ) } fn invalid_command(&self, client: &IrcClient) -> String { - format!("Incorrect Command. \ - Send \"{} currency help\" for help.", - client.current_nickname()) + format!( + "Incorrect Command. \ + Send \"{} currency help\" for help.", + client.current_nickname() + ) } } @@ -132,7 +139,6 @@ impl Plugin for Currency { } fn command(&self, client: &IrcClient, mut command: PluginCommand) -> Result<(), IrcError> { - if command.tokens.is_empty() { return client.send_notice(&command.source, &self.invalid_command(client)); } @@ -142,11 +148,11 @@ impl Plugin for Currency { _ => match self.convert(client, &mut command) { Ok(msg) => client.send_privmsg(&command.target, &msg), Err(msg) => client.send_notice(&command.source, &msg), - } + }, } } - fn evaluate(&self, client: &IrcClient, mut command: PluginCommand) -> Result<String, String>{ + fn evaluate(&self, client: &IrcClient, mut command: PluginCommand) -> Result<String, String> { if command.tokens.is_empty() { return Err(self.invalid_command(client)); } diff --git a/src/plugins/emoji.rs b/src/plugins/emoji.rs index 02a31f8..fcb04d1 100644 --- a/src/plugins/emoji.rs +++ b/src/plugins/emoji.rs @@ -14,7 +14,6 @@ struct EmojiHandle { impl fmt::Display for EmojiHandle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let name = match unicode_names::name(self.symbol) { Some(sym) => sym.to_string().to_lowercase(), None => String::from("UNKNOWN"), @@ -52,7 +51,6 @@ impl Emoji { count: 0, }; - for c in string.chars() { if !self.is_emoji(&c) { continue; @@ -60,7 +58,6 @@ impl Emoji { if current.symbol == c { current.count += 1; - } else { if current.count > 0 { emojis.push(current); @@ -99,13 +96,12 @@ impl Emoji { impl Plugin for Emoji { fn execute(&self, client: &IrcClient, message: &Message) -> ExecutionStatus { match message.command { - Command::PRIVMSG(_, ref content) => { - match client.send_privmsg(message.response_target().unwrap(), - &self.emoji(content)) { - Ok(_) => ExecutionStatus::Done, - Err(e) => ExecutionStatus::Err(e), - } - } + Command::PRIVMSG(_, ref content) => match client + .send_privmsg(message.response_target().unwrap(), &self.emoji(content)) + { + Ok(_) => ExecutionStatus::Done, + Err(e) => ExecutionStatus::Err(e), + }, _ => ExecutionStatus::Done, } } @@ -115,8 +111,10 @@ impl Plugin for Emoji { } fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), IrcError> { - client.send_notice(&command.source, - "This Plugin does not implement any commands.") + client.send_notice( + &command.source, + "This Plugin does not implement any commands.", + ) } fn evaluate(&self, _: &IrcClient, command: PluginCommand) -> Result<String, String> { diff --git a/src/plugins/keepnick.rs b/src/plugins/keepnick.rs index e973769..73f4893 100644 --- a/src/plugins/keepnick.rs +++ b/src/plugins/keepnick.rs @@ -29,7 +29,6 @@ impl KeepNick { Ok(_) => ExecutionStatus::Done, Err(e) => ExecutionStatus::Err(e), } - } else { ExecutionStatus::Done } @@ -51,8 +50,10 @@ impl Plugin for KeepNick { } fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), IrcError> { - client.send_notice(&command.source, - "This Plugin does not implement any commands.") + client.send_notice( + &command.source, + "This Plugin does not implement any commands.", + ) } fn evaluate(&self, _: &IrcClient, _: PluginCommand) -> Result<String, String> { diff --git a/src/plugins/url.rs b/src/plugins/url.rs index 9ce5a6a..455aa4e 100644 --- a/src/plugins/url.rs +++ b/src/plugins/url.rs @@ -29,7 +29,7 @@ pub struct Url { impl Url { /// If a file is larger than `max_kib` KiB the download is stopped pub fn new(max_kib: usize) -> Url { - Url {max_kib: max_kib} + Url { max_kib: max_kib } } fn grep_url(&self, msg: &str) -> Option<String> { @@ -44,10 +44,7 @@ impl Url { } fn download(&self, url: &str) -> Option<String> { - let response = Client::new() - .get(url) - .header(Connection::close()) - .send(); + let response = Client::new().get(url).header(Connection::close()).send(); match response { Ok(mut response) => { @@ -81,10 +78,12 @@ impl Url { // Check if the file is too large to download if written > self.max_kib * 1024 { - debug!("Stopping download - File from {:?} is larger than {} KiB", url, self.max_kib); + debug!( + "Stopping download - File from {:?} is larger than {} KiB", + url, self.max_kib + ); return None; } - } Some(body) // once told me } @@ -98,15 +97,11 @@ impl Url { fn url(&self, text: &str) -> Result<String, &str> { let url = match self.grep_url(text) { Some(url) => url, - None => { - return Err("No Url was found.") - } + None => return Err("No Url was found."), }; - match self.download(&url) { Some(body) => { - let doc = Document::from(body.as_ref()); if let Some(title) = doc.find(Name("title")).next() { let title = title.children().next().unwrap(); @@ -115,12 +110,11 @@ impl Url { debug!("Text: {:?}", title_text); Ok(title_text) - } else { Err("No title was found.") } } - None => Err("Failed to download document.") + None => Err("Failed to download document."), } } } @@ -139,19 +133,19 @@ impl Plugin for Url { fn execute_threaded(&self, client: &IrcClient, message: &Message) -> Result<(), IrcError> { match message.command { - Command::PRIVMSG(_, ref content) => { - match self.url(content) { - Ok(title) => client.send_privmsg(message.response_target().unwrap(), &title), - Err(_) => Ok(()), - } - } + Command::PRIVMSG(_, ref content) => match self.url(content) { + Ok(title) => client.send_privmsg(message.response_target().unwrap(), &title), + Err(_) => Ok(()), + }, _ => Ok(()), } } fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), IrcError> { - client.send_notice(&command.source, - "This Plugin does not implement any commands.") + client.send_notice( + &command.source, + "This Plugin does not implement any commands.", + ) } fn evaluate(&self, _: &IrcClient, command: PluginCommand) -> Result<String, String> { |
