STOP YELLING AT ME CLIPPY, GO BACK TO MS WORD

This commit is contained in:
lemon-sh 2022-01-26 19:34:54 +01:00
parent ac5f14a21e
commit 4224961c41
6 changed files with 60 additions and 57 deletions

View file

@ -1,4 +1,4 @@
use arrayvec::{ArrayString, CapacityError}; use arrayvec::{ArrayString};
use rand::Rng; use rand::Rng;
use std::{ use std::{
error::Error, error::Error,
@ -6,25 +6,25 @@ use std::{
}; };
#[derive(Debug)] #[derive(Debug)]
pub struct LeekCapacityError(CapacityError); pub struct CapacityError(arrayvec::CapacityError);
impl Display for LeekCapacityError { impl Display for CapacityError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.0, f) Display::fmt(&self.0, f)
} }
} }
impl Error for LeekCapacityError {} impl Error for CapacityError {}
impl<T> From<CapacityError<T>> for LeekCapacityError { impl<T> From<arrayvec::CapacityError<T>> for CapacityError {
fn from(e: CapacityError<T>) -> Self { fn from(e: arrayvec::CapacityError<T>) -> Self {
Self { 0: e.simplify() } Self(e.simplify())
} }
} }
type LeekResult = Result<ArrayString<512>, LeekCapacityError>; type LeekResult = Result<ArrayString<512>, CapacityError>;
fn mock(input: &str) -> LeekResult { fn mock(input: &str) -> ArrayString<512> {
let mut builder = ArrayString::<512>::new(); let mut builder = ArrayString::<512>::new();
for ch in input.chars() { for ch in input.chars() {
@ -35,10 +35,10 @@ fn mock(input: &str) -> LeekResult {
} }
} }
Ok(builder) builder
} }
fn leetify(input: &str) -> LeekResult { fn leetify(input: &str) -> ArrayString<512> {
let mut builder = ArrayString::<512>::new(); let mut builder = ArrayString::<512>::new();
for ch in input.chars() { for ch in input.chars() {
@ -55,7 +55,7 @@ fn leetify(input: &str) -> LeekResult {
}); });
} }
Ok(builder) builder
} }
fn owoify(input: &str) -> LeekResult { fn owoify(input: &str) -> LeekResult {
@ -102,16 +102,16 @@ fn owoify(input: &str) -> LeekResult {
Ok(builder) Ok(builder)
} }
#[derive(Debug)] #[derive(Debug, Clone, Copy)]
pub enum LeekCommand { pub enum Command {
Owo, Owo,
Leet, Leet,
Mock, Mock,
} }
pub fn execute_leek( pub fn execute(
state: &mut crate::AppState, state: &mut crate::AppState,
cmd: LeekCommand, cmd: Command,
target: &str, target: &str,
nick: &str, nick: &str,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
@ -119,9 +119,9 @@ pub fn execute_leek(
Some(msg) => { Some(msg) => {
tracing::debug!("Executing {:?} on {:?}", cmd, msg); tracing::debug!("Executing {:?} on {:?}", cmd, msg);
let output = match cmd { let output = match cmd {
LeekCommand::Owo => super::leek::owoify(msg)?, Command::Owo => super::leek::owoify(msg)?,
LeekCommand::Leet => super::leek::leetify(msg)?, Command::Leet => super::leek::leetify(msg),
LeekCommand::Mock => super::leek::mock(msg)?, Command::Mock => super::leek::mock(msg),
}; };
state.client.send_privmsg(target, &output)?; state.client.send_privmsg(target, &output)?;
} }

View file

@ -10,8 +10,8 @@ pub async fn get_waifu_pic(category: &str) -> anyhow::Result<Option<String>> {
.text() .text()
.await?; .await?;
let api_resp = api_resp.trim(); let api_resp = api_resp.trim();
let value: Value = serde_json::from_str(&api_resp)?; let value: Value = serde_json::from_str(api_resp)?;
let url = value["url"].as_str().map(|v| v.to_string()); let url = value["url"].as_str().map(ToString::to_string);
Ok(url) Ok(url)
} }

View file

@ -5,6 +5,7 @@ use fancy_regex::Regex;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use sedregex::find_and_replace; use sedregex::find_and_replace;
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)] #[derive(Debug)]
pub enum SedError { pub enum SedError {
Capacity(CapacityError), Capacity(CapacityError),
@ -52,7 +53,7 @@ pub fn resolve(prev_msg: &str, cmd: &str) -> SedResult {
if RE.is_match(cmd)? { if RE.is_match(cmd)? {
return if let Some(mat) = RE.find(cmd)? { return if let Some(mat) = RE.find(cmd)? {
let slice = &cmd[mat.start()..mat.end()]; let slice = &cmd[mat.start()..mat.end()];
let formatted = find_and_replace(&prev_msg, [slice])?; let formatted = find_and_replace(prev_msg, [slice])?;
Ok(Some(ArrayString::from(&formatted)?)) Ok(Some(ArrayString::from(&formatted)?))
} else { } else {
Ok(None) Ok(None)

View file

@ -101,7 +101,7 @@ impl Titlebot {
} }
pub async fn resolve(&mut self, message: &str) -> anyhow::Result<Option<String>> { pub async fn resolve(&mut self, message: &str) -> anyhow::Result<Option<String>> {
if let Some(m) = self.spotify_regex.captures(&message)? { if let Some(m) = self.spotify_regex.captures(message)? {
tracing::debug!("{}", message); tracing::debug!("{}", message);
let tp_group = m.get(1).unwrap(); let tp_group = m.get(1).unwrap();
let id_group = m.get(2).unwrap(); let id_group = m.get(2).unwrap();
@ -114,7 +114,7 @@ impl Titlebot {
) )
.await?, .await?,
)); ));
} else if let Some(m) = self.url_regex.find(&message)? { } else if let Some(m) = self.url_regex.find(message)? {
let url = &message[m.start()..m.end()]; let url = &message[m.start()..m.end()];
tracing::debug!("url: {}", url); tracing::debug!("url: {}", url);

View file

@ -1,3 +1,5 @@
#![allow(clippy::match_wildcard_for_single_variants)]
use std::fmt::Write; use std::fmt::Write;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
@ -154,7 +156,7 @@ async fn main() -> anyhow::Result<()> {
}; };
let message_loop_task = tokio::spawn(async move { let message_loop_task = tokio::spawn(async move {
if let Err(e) = message_loop(state).await { if let Err(e) = message_loop(state).await {
let _ = etx.send(e); let _err = etx.send(e);
} }
}); });
@ -219,6 +221,7 @@ fn separate_to_space(str: &str, prefix_len: usize) -> (&str, Option<&str>) {
} }
} }
#[allow(clippy::too_many_lines)]
async fn handle_privmsg( async fn handle_privmsg(
state: &mut AppState, state: &mut AppState,
author: &str, author: &str,
@ -255,32 +258,30 @@ async fn handle_privmsg(
"waifu" => { "waifu" => {
let category = remainder.unwrap_or("waifu"); let category = remainder.unwrap_or("waifu");
let url = misc::get_waifu_pic(category).await?; let url = misc::get_waifu_pic(category).await?;
let response = url let response = url.as_deref()
.as_ref()
.map(|v| v.as_str())
.unwrap_or("Invalid category. Valid categories: https://waifu.pics/docs"); .unwrap_or("Invalid category. Valid categories: https://waifu.pics/docs");
state.client.send_privmsg(origin, response)?; state.client.send_privmsg(origin, response)?;
} }
"mock" => { "mock" => {
leek::execute_leek( leek::execute(
state, state,
leek::LeekCommand::Mock, leek::Command::Mock,
origin, origin,
remainder.unwrap_or(author), remainder.unwrap_or(author),
)?; )?;
} }
"leet" => { "leet" => {
leek::execute_leek( leek::execute(
state, state,
leek::LeekCommand::Leet, leek::Command::Leet,
origin, origin,
remainder.unwrap_or(author), remainder.unwrap_or(author),
)?; )?;
} }
"owo" => { "owo" => {
leek::execute_leek( leek::execute(
state, state,
leek::LeekCommand::Owo, leek::Command::Owo,
origin, origin,
remainder.unwrap_or(author), remainder.unwrap_or(author),
)?; )?;
@ -315,7 +316,7 @@ async fn handle_privmsg(
} }
} }
"quot" => { "quot" => {
if let Some(quote) = state.db.get_quote(remainder.map(|v| v.to_string())).await { if let Some(quote) = state.db.get_quote(remainder.map(ToString::to_string)).await {
let mut resp = ArrayString::<512>::new(); let mut resp = ArrayString::<512>::new();
write!(resp, "\"{}\" ~{}", quote.0, quote.1)?; write!(resp, "\"{}\" ~{}", quote.0, quote.1)?;
state.client.send_privmsg(origin, &resp)?; state.client.send_privmsg(origin, &resp)?;

View file

@ -17,31 +17,48 @@ pub async fn run(
let quote_get = warp::path("quotes") let quote_get = warp::path("quotes")
.and(warp::get()) .and(warp::get())
.and(warp::any().map(move || db.clone())) .and(warp::any().map(move || db.clone()))
.then(handle_get_quote); .map(handle_get_quote);
let webhook_post = warp::path("webhook") let webhook_post = warp::path("webhook")
.and(warp::post()) .and(warp::post())
.and(warp::body::json()) .and(warp::body::json())
.and(warp::any().map(move || wh_irc.clone())) .and(warp::any().map(move || wh_irc.clone()))
.and(warp::any().map(move || wh_channel.clone())) .and(warp::any().map(move || wh_channel.clone()))
.then(handle_webhook); .map(handle_webhook);
let filter = quote_get.or(webhook_post); let filter = quote_get.or(webhook_post);
warp::serve(filter).bind_with_graceful_shutdown(listen, async move { warp::serve(filter).bind_with_graceful_shutdown(listen, async move {
let _ = cancel.recv().await; let _ = cancel.recv().await;
}).1.await; }).1.await;
tracing::info!("Web service finished") tracing::info!("Web service finished");
} }
async fn handle_get_quote(_: ExecutorConnection) -> impl Reply { fn handle_get_quote(_: ExecutorConnection) -> impl Reply {
reply::html(include_str!("res/quote_tmpl.html")) reply::html(include_str!("res/quote_tmpl.html"))
} }
async fn handle_webhook(json: serde_json::Value, irc: Arc<Client>, channel: String) -> impl Reply { #[allow(clippy::needless_pass_by_value)]
fn handle_webhook(json: serde_json::Value, irc: Arc<Client>, channel: String) -> impl Reply {
if json["commits"] != Null { if json["commits"] != Null {
let commits = json["commits"].as_array().unwrap(); let commits = json["commits"].as_array().unwrap();
let repo = &json["repository"]["full_name"].as_str().unwrap().trim(); let repo = &json["repository"]["full_name"].as_str().unwrap().trim();
if commits.len() != 1 { if commits.len() == 1 {
let author = &json["commits"][0]["author"]["name"]
.as_str()
.unwrap()
.trim();
let message = &json["commits"][0]["message"].as_str().unwrap().trim();
if let Err(e) = irc.send_privmsg(
channel,
format!("New commit on {}: {} - {}", repo, message, author),
) {
return reply::with_status(
format!("An error has occurred: {}", e),
StatusCode::INTERNAL_SERVER_ERROR,
)
.into_response();
}
} else {
if let Err(e) = irc.send_privmsg( if let Err(e) = irc.send_privmsg(
channel.clone(), channel.clone(),
format!("{} new commits on {}:", commits.len(), repo), format!("{} new commits on {}:", commits.len(), repo),
@ -65,22 +82,6 @@ async fn handle_webhook(json: serde_json::Value, irc: Arc<Client>, channel: Stri
.into_response(); .into_response();
} }
} }
} else {
let author = &json["commits"][0]["author"]["name"]
.as_str()
.unwrap()
.trim();
let message = &json["commits"][0]["message"].as_str().unwrap().trim();
if let Err(e) = irc.send_privmsg(
channel,
format!("New commit on {}: {} - {}", repo, message, author),
) {
return reply::with_status(
format!("An error has occurred: {}", e),
StatusCode::INTERNAL_SERVER_ERROR,
)
.into_response();
}
} }
} }
StatusCode::CREATED.into_response() StatusCode::CREATED.into_response()