feat: add case preserving search and replace

This commit is contained in:
Ade Attwood 2024-05-11 15:20:43 +01:00
parent 4dc1042c1d
commit 23868e9df1
5 changed files with 39 additions and 4 deletions

11
Cargo.lock generated
View file

@ -196,6 +196,16 @@ version = "0.8.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345"
[[package]]
name = "cruet"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6132609543972496bc97b1e01f1ce6586768870aeb4cabeb3385f4e05b5caead"
dependencies = [
"once_cell",
"regex",
]
[[package]]
name = "cucumber"
version = "0.20.2"
@ -272,6 +282,7 @@ name = "dev_case"
version = "0.1.0"
dependencies = [
"clap",
"cruet",
"cucumber",
"futures",
"regex",

View file

@ -5,6 +5,7 @@ edition = "2021"
[dependencies]
clap = { version = "4.5.4", features = ["derive"] }
cruet = "0.14.0"
regex = "1.10.4"
[dev-dependencies]

View file

@ -1,9 +1,23 @@
use regex::Regex;
fn concert_replacement(original: &str, replacement: &str) -> String {
if cruet::is_camel_case(original) {
cruet::to_camel_case(replacement)
} else if cruet::is_kebab_case(original) {
cruet::to_kebab_case(replacement)
} else if cruet::is_pascal_case(original) {
cruet::to_pascal_case(replacement)
} else if cruet::is_snake_case(original) {
cruet::to_snake_case(replacement)
} else {
replacement.to_string()
}
}
pub fn replace(search: &String, replace: String, input: String) -> String {
let mut index = 0;
let mut output = input;
let search_pattern = Regex::new(search).unwrap();
let search_pattern = Regex::new(&format!("(?i){search}")).unwrap();
while let Some(search_match) = search_pattern.find_at(&output, index) {
let start = search_match.start();
@ -19,8 +33,10 @@ pub fn replace(search: &String, replace: String, input: String) -> String {
}
};
index = start + replacement.len();
output.replace_range(start..end, &replacement);
let converted_replacement = concert_replacement(&output[start..end], &replacement);
output.replace_range(start..end, &converted_replacement);
index = start + converted_replacement.len();
}
output

View file

@ -0,0 +1,7 @@
Feature: Case preserving search and replace
Scenario: You can search and replace with with a regular expression
Given Search is 'productid'
And Replace is 'catalogId'
And Input is 'function GetProductId(productId)'
Then Output is 'function GetCatalogId(catalogId)'

View file

@ -3,7 +3,7 @@ Feature: Regex search and replace
Scenario: You can search and replace with with a regular expression
Given Search is '(\w+)'
And Replace is 'new'
And Input is 'This is a'
And Input is 'this is a'
Then Output is 'new new new'
Scenario: You can use a '$' to replace a match group