Skip to content

Commit

Permalink
✨ Add more processors types
Browse files Browse the repository at this point in the history
- Add `replace` to replace string in source directly
- Add `replace-regexp` to replace string in source by regexp

See also: #13
  • Loading branch information
ShellWen committed Nov 28, 2023
1 parent f65c17d commit 6edd3d4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ lazy_static = "1.4.0"
ctor = "0.2.4"
toml = "0.8.1"
serde = { version = "1.0.188", features = ["derive"] }
regex = "1.10.2"

[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.51.1", features = [
Expand Down
33 changes: 33 additions & 0 deletions crates/core/src/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,19 @@ pub enum SourceProcessor {
InsertBeforeProcessor(InsertBeforeProcessor),
#[serde(rename = "insert-after")]
InsertAfterProcessor(InsertAfterProcessor),
#[serde(rename = "replace")]
ReplaceProcessor(ReplaceProcessor),
#[serde(rename = "replace-regexp")]
ReplaceRegexpProcessor(ReplaceRegexpProcessor),
}

impl SourceProcessor {
pub fn process<'a>(&self, source: &'a mut Source) -> Result<&'a mut Source, Error> {
match self {
SourceProcessor::InsertBeforeProcessor(processor) => processor.process(source),
SourceProcessor::InsertAfterProcessor(processor) => processor.process(source),
SourceProcessor::ReplaceProcessor(processor) => processor.process(source),
SourceProcessor::ReplaceRegexpProcessor(processor) => processor.process(source),
}
}
}
Expand Down Expand Up @@ -49,3 +55,30 @@ impl SourceProcessorTrait for InsertAfterProcessor {
Ok(source)
}
}

#[derive(Deserialize, Debug)]
pub struct ReplaceProcessor {
from: String,
to: String,
}

impl SourceProcessorTrait for ReplaceProcessor {
fn process<'a>(&self, source: &'a mut Source) -> Result<&'a mut Source, Error> {
source.source_string = source.source_string.replace(&self.from, &self.to);
Ok(source)
}
}

#[derive(Deserialize, Debug)]
pub struct ReplaceRegexpProcessor {
regexp: String,
to: String,
}

impl SourceProcessorTrait for ReplaceRegexpProcessor {
fn process<'a>(&self, source: &'a mut Source) -> Result<&'a mut Source, Error> {
let re = regex::Regex::new(&self.regexp).unwrap();
source.source_string = re.replace_all(&source.source_string, &self.to).to_string();
Ok(source)
}
}

0 comments on commit 6edd3d4

Please sign in to comment.