refactor: support multiple matchers in a single substitutor

This commit is contained in:
Harsh Shandilya 2022-02-20 02:45:00 +05:30
parent 0f67855571
commit 7be11d9a90
No known key found for this signature in database
GPG key ID: 366D7BBAD1031E80
2 changed files with 20 additions and 8 deletions

View file

@ -13,12 +13,21 @@ pub struct Replacements<'config> {
pub struct Substitutor<'config> { pub struct Substitutor<'config> {
#[serde(default)] #[serde(default)]
pub name: &'config str, pub name: &'config str,
#[serde(borrow)] #[serde(borrow, alias = "matcher")]
pub matcher: Matcher<'config>, pub matcher_type: MatcherType<'config>,
#[serde(borrow)] #[serde(borrow)]
pub action: Action<'config>, pub action: Action<'config>,
} }
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum MatcherType<'config> {
#[serde(borrow)]
Single(Matcher<'config>),
#[serde(borrow)]
Multiple(Vec<Matcher<'config>>),
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub enum Matcher<'config> { pub enum Matcher<'config> {
#[serde(rename = "starts_with")] #[serde(rename = "starts_with")]

View file

@ -11,7 +11,7 @@ use clipboard::{ClipboardContext, ClipboardProvider};
use dirs::config_dir; use dirs::config_dir;
use log::{debug, error}; use log::{debug, error};
use crate::config::{Act, Match, Replacements}; use crate::config::{Act, Match, MatcherType, Replacements};
const VERSION_ARGS: [&str; 3] = ["version", "-v", "--version"]; const VERSION_ARGS: [&str; 3] = ["version", "-v", "--version"];
@ -57,11 +57,14 @@ fn loop_clipboard<'a>(config: Replacements<'a>) {
ClipboardProvider::new().expect("Failed to get clipboard"); ClipboardProvider::new().expect("Failed to get clipboard");
let mut clipboard_contents = get_clipboard_contents(&mut clipboard); let mut clipboard_contents = get_clipboard_contents(&mut clipboard);
while let Ok(contents) = clipboard_contents.as_deref() { while let Ok(contents) = clipboard_contents.as_deref() {
if let Some(subst) = config if let Some(subst) = config.substitutors.iter().find(|subst| {
.substitutors return match &subst.matcher_type {
.iter() MatcherType::Single(matcher) => matcher.check_match(contents),
.find(|subst| subst.matcher.check_match(contents)) MatcherType::Multiple(matchers) => {
{ matchers.iter().all(|matcher| matcher.check_match(contents))
}
};
}) {
if subst.name.is_empty().not() { if subst.name.is_empty().not() {
debug!("{}: matched on {}...", &subst.name, truncate(&contents, 40)); debug!("{}: matched on {}...", &subst.name, truncate(&contents, 40));
} }