Return Error on str replace RegEx parse fail (#6695)

This commit is contained in:
Jake Albert 2022-10-10 21:27:01 +09:00 committed by GitHub
parent fde56cfe99
commit 34c8b276ab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -9,8 +9,8 @@ use std::sync::Arc;
struct Arguments {
all: bool,
find: String,
replace: String,
find: Spanned<String>,
replace: Spanned<String>,
column_paths: Vec<CellPath>,
literal_replace: bool,
no_regex: bool,
@ -168,8 +168,8 @@ fn operate(
let options = Arc::new(Arguments {
all: call.has_flag("all"),
find: find.item,
replace: replace.item,
find,
replace,
column_paths: call.rest(engine_state, stack, 2)?,
literal_replace,
no_regex,
@ -214,23 +214,23 @@ fn action(
) -> Value {
match input {
Value::String { val, .. } => {
let FindReplace(find, replacement) = FindReplace(find, replace);
let FindReplace(find_str, replace_str) = FindReplace(&find.item, &replace.item);
if *no_regex {
// just use regular string replacement vs regular expressions
if *all {
Value::String {
val: val.replace(find, replacement),
val: val.replace(find_str, replace_str),
span: head,
}
} else {
Value::String {
val: val.replacen(find, replacement, 1),
val: val.replacen(find_str, replace_str, 1),
span: head,
}
}
} else {
// use regular expressions to replace strings
let regex = Regex::new(find);
let regex = Regex::new(find_str);
match regex {
Ok(re) => {
@ -238,9 +238,9 @@ fn action(
Value::String {
val: {
if *literal_replace {
re.replace_all(val, NoExpand(replacement)).to_string()
re.replace_all(val, NoExpand(replace_str)).to_string()
} else {
re.replace_all(val, replacement).to_string()
re.replace_all(val, replace_str).to_string()
}
},
span: head,
@ -249,18 +249,17 @@ fn action(
Value::String {
val: {
if *literal_replace {
re.replace(val, NoExpand(replacement)).to_string()
re.replace(val, NoExpand(replace_str)).to_string()
} else {
re.replace(val, replacement).to_string()
re.replace(val, replace_str).to_string()
}
},
span: head,
}
}
}
Err(_) => Value::String {
val: val.to_string(),
span: head,
Err(e) => Value::Error {
error: ShellError::UnsupportedInput(format!("{e}"), find.span),
},
}
}
@ -282,6 +281,13 @@ mod tests {
use super::*;
use super::{action, Arguments, SubCommand};
fn test_spanned_string(val: &str) -> Spanned<String> {
Spanned {
item: String::from(val),
span: Span::test_data(),
}
}
#[test]
fn test_examples() {
use crate::test_examples;
@ -297,8 +303,8 @@ mod tests {
};
let options = Arguments {
find: String::from("Cargo.(.+)"),
replace: String::from("Carga.$1"),
find: test_spanned_string("Cargo.(.+)"),
replace: test_spanned_string("Carga.$1"),
column_paths: vec![],
literal_replace: false,
all: false,