use candid::CandidType;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Clone, Debug, PartialEq, Eq, CandidType, Serialize, Deserialize)]
pub struct RegexString(pub String);
impl From<&str> for RegexString {
fn from(value: &str) -> Self {
RegexString(value.to_string())
}
}
impl RegexString {
pub fn compile(&self) -> Result<Regex, regex::Error> {
Regex::new(&self.0)
}
pub fn try_is_valid(&self, value: &str) -> Result<bool, regex::Error> {
Ok(self.compile()?.is_match(value))
}
}
#[derive(Clone, Debug, PartialEq, Eq, CandidType, Serialize, Deserialize)]
pub struct RegexSubstitution {
pub pattern: RegexString,
pub replacement: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, CandidType, Serialize, Deserialize)]
pub enum LogFilter {
#[default]
ShowAll,
HideAll,
ShowPattern(RegexString),
HidePattern(RegexString),
}
impl LogFilter {
pub fn is_match(&self, message: &str) -> bool {
match self {
Self::ShowAll => true,
Self::HideAll => false,
Self::ShowPattern(regex) => regex
.try_is_valid(message)
.expect("Invalid regex in ShowPattern log filter"),
Self::HidePattern(regex) => !regex
.try_is_valid(message)
.expect("Invalid regex in HidePattern log filter"),
}
}
}
#[derive(Copy, Clone, Debug, Deserialize, serde::Serialize)]
pub enum Sort {
Ascending,
Descending,
}
impl FromStr for Sort {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"asc" => Ok(Sort::Ascending),
"desc" => Ok(Sort::Descending),
_ => Err("could not recognize sort order".to_string()),
}
}
}