From 89ccf42ddfd4ad443e68a9c42b5e0ddc68d1a038 Mon Sep 17 00:00:00 2001 From: Saheed Adeleye <126640223+gyreas@users.noreply.github.com> Date: Sat, 18 May 2024 00:23:59 +0100 Subject: [PATCH] Add prepend() function (#2045) --- README.md | 6 +++++- src/function.rs | 12 +++++++++++- tests/functions.rs | 22 ++++++++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 23ee60d..7848d65 100644 --- a/README.md +++ b/README.md @@ -1397,8 +1397,12 @@ The process ID is: 420 #### String Manipulation + - `append(suffix, s)`master Append `suffix` to whitespace-separated - strings in `s`. + strings in `s`. `append('/src', 'foo bar baz')` → `'foo/src bar/src baz/src'` +- `prepend(prefix, s)`master Prepend `prefix` to + whitespace-separated strings in `s`. `prepend('src/', 'foo bar baz')` → + `'src/foo src/bar src/baz'` - `quote(s)` - Replace all single quotes with `'\''` and prepend and append single quotes to `s`. This is sufficient to escape special characters for many shells, including most Bourne shell descendants. diff --git a/src/function.rs b/src/function.rs index 2ed0983..64f607e 100644 --- a/src/function.rs +++ b/src/function.rs @@ -24,8 +24,8 @@ pub(crate) fn get(name: &str) -> Option { "arch" => Nullary(arch), "blake3" => Unary(blake3), "blake3_file" => Unary(blake3_file), - "canonicalize" => Unary(canonicalize), "cache_directory" => Nullary(|_| dir("cache", dirs::cache_dir)), + "canonicalize" => Unary(canonicalize), "capitalize" => Unary(capitalize), "clean" => Unary(clean), "config_directory" => Nullary(|_| dir("config", dirs::config_dir)), @@ -56,6 +56,7 @@ pub(crate) fn get(name: &str) -> Option { "os_family" => Nullary(os_family), "parent_directory" => Unary(parent_directory), "path_exists" => Unary(path_exists), + "prepend" => Binary(prepend), "quote" => Unary(quote), "replace" => Ternary(replace), "replace_regex" => Ternary(replace_regex), @@ -265,6 +266,15 @@ fn invocation_directory_native(context: &FunctionContext) -> Result Result { + Ok( + s.split_whitespace() + .map(|s| format!("{prefix}{s}")) + .collect::>() + .join(" "), + ) +} + fn join( _context: &FunctionContext, base: &str, diff --git a/tests/functions.rs b/tests/functions.rs index 3cc1d40..a9fb98b 100644 --- a/tests/functions.rs +++ b/tests/functions.rs @@ -501,6 +501,28 @@ fn append() { ); } +#[test] +fn prepend() { + assert_eval_eq("prepend('8', 'r s t\n \n ')", "8r 8s 8t"); + assert_eval_eq( + "prepend('src/', 'main sar x11')", + "src/main src/sar src/x11", + ); + assert_eval_eq("prepend('-', 'c\tv h\ny')", "-c -v -h -y"); + assert_eval_eq( + "prepend('0000', '11 10 01 00')", + "000011 000010 000001 000000", + ); + assert_eval_eq( + "prepend('April-', ' + 1st, + 17th, + 20th, + ')", + "April-1st, April-17th, April-20th,", + ); +} + #[test] #[cfg(not(windows))] fn join() {