feat(config): add config validation

This commit is contained in:
Harsh Shandilya 2022-07-13 16:11:14 +05:30
parent a8b4b579a7
commit 0e4fe250d7
No known key found for this signature in database
GPG key ID: 366D7BBAD1031E80
2 changed files with 55 additions and 0 deletions

View file

@ -1,5 +1,6 @@
use std::str::FromStr;
use anyhow::{bail, Result};
use regex::Regex;
use serde_derive::Deserialize;
use tracing::trace;
@ -66,6 +67,36 @@ pub trait Act {
fn apply_action(&self, input: &str) -> String;
}
impl Replacements<'_> {
pub fn validate(&self) -> Result<()> {
for subst in self.substitutors.iter() {
match &subst.matcher {
MatcherType::Single(matcher) => match matcher {
Matcher::Regex { pattern } => {
if let Err(e) = Regex::from_str(pattern) {
bail!(e);
}
}
_ => {}
},
MatcherType::Multiple(matchers) => {
for matcher in matchers.iter() {
match matcher {
Matcher::Regex { pattern } => {
if let Err(e) = Regex::from_str(pattern) {
bail!(e);
}
}
_ => {}
}
}
}
}
}
Ok(())
}
}
impl Match for Matcher<'_> {
fn check_match(&self, string: &str) -> bool {
trace!(?self, ?string, "Checking for match");

View file

@ -72,3 +72,27 @@ fn parse_with_single_matcher() {
assert!(matches!(subst.matcher, MatcherType::Single(_)));
assert!(matches!(subst.action, Action::Prefix { .. }));
}
#[assay]
fn config_validation_success() {
let config = r#"
[[substitutor]]
name = "vxTwitter"
matcher = { regex = { pattern = "^https://(?P<host>(?:mobile.)?twitter.com)/.*/status/[0-9]+.*" } }
action = { replace = { from = "twitter.com", to = "vxtwitter.com" } }
"#;
let config: Replacements<'_> = toml::from_str(config)?;
assert!(matches!(config.validate(), Ok(_)));
}
#[assay]
fn config_validation_failure() {
let config = r#"
[[substitutor]]
name = "vxTwitter"
matcher = { regex = { pattern = "^https://(?P<>(?:mobile.)?twitter.com)/.*/status/[0-9]+.*" } }
action = { replace = { from = "twitter.com", to = "vxtwitter.com" } }
"#;
let config: Replacements<'_> = toml::from_str(config)?;
assert!(matches!(config.validate(), Err(_)));
}