Skip to content

Commit

Permalink
Add a replace function that supports regex
Browse files Browse the repository at this point in the history
  • Loading branch information
miles170 committed Nov 8, 2022
1 parent dc2fe21 commit 6fdee27
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ lazy_static! {
("path_exists", Unary(path_exists)),
("quote", Unary(quote)),
("replace", Ternary(replace)),
("replace_regex", Ternary(replace_regex)),
("sha256", Unary(sha256)),
("sha256_file", Unary(sha256_file)),
("shoutykebabcase", Unary(shoutykebabcase)),
Expand Down Expand Up @@ -283,6 +284,18 @@ fn replace(_context: &FunctionContext, s: &str, from: &str, to: &str) -> Result<
Ok(s.replace(from, to))
}

fn replace_regex(
_context: &FunctionContext,
s: &str,
from: &str,
to: &str,
) -> Result<String, String> {
let re =
Regex::new(from).map_err(|err| format!("Failed to compile regular expression: {}", err))?;

Ok(re.replace_all(s, to).to_string())
}

fn sha256(_context: &FunctionContext, s: &str) -> Result<String, String> {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
Expand Down
28 changes: 28 additions & 0 deletions tests/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,34 @@ test! {
stderr: "echo foofoofoo\n",
}

test! {
name: replace_regex,
justfile: "
foo:
echo {{ replace_regex('123bar123bar123bar', '\\d+bar', 'foo') }}
",
stdout: "foofoofoo\n",
stderr: "echo foofoofoo\n",
}

test! {
name: invalid_replace_regex,
justfile: "
foo:
echo {{ replace_regex('barbarbar', 'foo\\', 'foo') }}
",
stderr:
"error: Call to function `replace_regex` failed: Failed to compile regular expression: regex parse error:
foo\\
^
error: incomplete escape sequence, reached end of pattern prematurely
|
2 | echo {{ replace_regex('barbarbar', 'foo\\', 'foo') }}
| ^^^^^^^^^^^^^
",
status: EXIT_FAILURE,
}

test! {
name: capitalize,
justfile: "
Expand Down

0 comments on commit 6fdee27

Please sign in to comment.