Implement matchers and actions

This commit is contained in:
Harsh Shandilya 2021-11-12 09:42:39 +05:30
parent 05201d7de7
commit 3fd078e51b
No known key found for this signature in database
GPG key ID: 366D7BBAD1031E80
4 changed files with 84 additions and 2 deletions

View file

@ -1,4 +1,7 @@
#![allow(dead_code)]
use std::str::FromStr;
use regex::Regex;
use serde_derive::Deserialize;
#[derive(Clone, Debug, Default, Deserialize)]
@ -13,6 +16,14 @@ pub struct Substitutor {
pub action: Action,
}
pub trait Match {
fn check_match<'a>(self: Self, string: &'a str) -> bool;
}
pub trait Act {
fn apply_action(self: Self, input: String) -> String;
}
#[derive(Clone, Debug, Deserialize)]
pub enum Matcher {
#[serde(rename = "starts_with")]
@ -25,6 +36,20 @@ pub enum Matcher {
Regex { pattern: String },
}
impl Match for Matcher {
fn check_match<'a>(self: Self, string: &'a str) -> bool {
return match self {
Matcher::StartsWith { prefix } => string.starts_with(&prefix),
Matcher::EndsWith { suffix } => string.ends_with(&suffix),
Matcher::Contains { substring } => string.contains(&substring),
Matcher::Regex { pattern } => {
let regex = Regex::from_str(&pattern).expect("Failed to parse regex");
regex.is_match(&string)
}
};
}
}
#[derive(Clone, Debug, Deserialize)]
pub enum Action {
#[serde(rename = "replace")]
@ -36,3 +61,14 @@ pub enum Action {
#[serde(rename = "remove")]
Remove { substring: String },
}
impl Act for Action {
fn apply_action(self: Self, input: String) -> String {
return match self {
Action::Replace { from, to } => input.replace(&from, &to),
Action::Prefix { prefix } => format!("{}{}", prefix, input),
Action::Suffix { suffix } => format!("{}{}", input, suffix),
Action::Remove { substring } => input.replace(&substring, ""),
};
}
}

View file

@ -1,9 +1,10 @@
mod config;
use anyhow::{anyhow, Result};
use clipboard::{ClipboardContext, ClipboardProvider};
use dirs::config_dir;
use crate::config::Replacements;
use crate::config::{Act, Match, Replacements};
fn main() -> Result<()> {
let mut config_path = config_dir().ok_or(anyhow!("Failed to get config dir"))?;
@ -16,5 +17,16 @@ fn main() -> Result<()> {
} else {
Replacements::default()
};
Ok(())
let mut clipboard: ClipboardContext = ClipboardProvider::new().expect("Failed to get clipboard");
loop {
let contents = clipboard.get_contents().expect("Failed to read clipboard");
if let Some(subst) = config
.substitutors
.iter()
.find(|subst| subst.matcher.clone().check_match(&contents))
{
let result = subst.action.clone().apply_action(contents);
let _ = clipboard.set_contents(result);
};
}
}