uberbot/src/bots/sed.rs

65 lines
1.5 KiB
Rust
Raw Normal View History

2022-01-02 14:58:54 -06:00
use std::{error::Error, fmt::Display};
2022-01-01 00:52:43 -06:00
use arrayvec::{ArrayString, CapacityError};
use fancy_regex::Regex;
use lazy_static::lazy_static;
use sedregex::find_and_replace;
#[allow(clippy::module_name_repetitions)]
2022-01-01 00:52:43 -06:00
#[derive(Debug)]
2022-01-01 06:37:51 -06:00
pub enum SedError {
2022-01-01 00:52:43 -06:00
Capacity(CapacityError),
Regex(fancy_regex::Error),
2022-01-02 14:58:54 -06:00
SedRegex(sedregex::ErrorKind),
2022-01-01 00:52:43 -06:00
}
2022-01-01 06:37:51 -06:00
impl Display for SedError {
2022-01-01 00:52:43 -06:00
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2022-01-01 06:37:51 -06:00
match self {
Self::Capacity(e) => e.fmt(f),
Self::Regex(e) => e.fmt(f),
Self::SedRegex(e) => e.fmt(f),
2022-01-01 00:52:43 -06:00
}
}
}
2022-01-01 06:37:51 -06:00
impl Error for SedError {}
2022-01-01 00:52:43 -06:00
2022-01-01 06:37:51 -06:00
impl<T> From<CapacityError<T>> for SedError {
2022-01-01 00:52:43 -06:00
fn from(e: CapacityError<T>) -> Self {
2022-01-01 06:37:51 -06:00
Self::Capacity(e.simplify())
2022-01-01 00:52:43 -06:00
}
}
2022-01-01 06:37:51 -06:00
impl From<fancy_regex::Error> for SedError {
2022-01-01 00:52:43 -06:00
fn from(e: fancy_regex::Error) -> Self {
2022-01-01 06:37:51 -06:00
Self::Regex(e)
2022-01-01 00:52:43 -06:00
}
}
2022-01-01 06:37:51 -06:00
impl From<sedregex::ErrorKind> for SedError {
2022-01-01 00:52:43 -06:00
fn from(e: sedregex::ErrorKind) -> Self {
2022-01-01 06:37:51 -06:00
Self::SedRegex(e)
2022-01-01 00:52:43 -06:00
}
}
2022-01-01 06:37:51 -06:00
type SedResult = Result<Option<ArrayString<512>>, SedError>;
2022-01-01 00:52:43 -06:00
pub fn resolve(prev_msg: &str, cmd: &str) -> SedResult {
lazy_static! {
2022-01-26 05:58:49 -06:00
static ref RE: Regex = Regex::new(r"^s/.*/.*").unwrap();
2022-01-01 00:52:43 -06:00
}
if RE.is_match(cmd)? {
2022-01-01 06:37:51 -06:00
return if let Some(mat) = RE.find(cmd)? {
2022-01-01 00:52:43 -06:00
let slice = &cmd[mat.start()..mat.end()];
let formatted = find_and_replace(prev_msg, [slice])?;
2022-01-01 06:37:51 -06:00
Ok(Some(ArrayString::from(&formatted)?))
2022-01-01 00:52:43 -06:00
} else {
2022-01-01 06:37:51 -06:00
Ok(None)
2022-01-02 14:58:54 -06:00
};
2022-01-01 00:52:43 -06:00
}
Ok(None)
2022-01-02 14:58:54 -06:00
}