Skip to content

Commit

Permalink
Add append() function (#2046)
Browse files Browse the repository at this point in the history
  • Loading branch information
gyreas authored May 17, 2024
1 parent a9b0912 commit eb60518
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1397,7 +1397,8 @@ The process ID is: 420


#### String Manipulation

- `append(suffix, s)`<sup>master</sup> Append `suffix` to whitespace-separated
strings in `s`.
- `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.
Expand Down
10 changes: 10 additions & 0 deletions src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub(crate) enum Function {
pub(crate) fn get(name: &str) -> Option<Function> {
let function = match name {
"absolute_path" => Unary(absolute_path),
"append" => Binary(append),
"arch" => Nullary(arch),
"blake3" => Unary(blake3),
"blake3_file" => Unary(blake3_file),
Expand Down Expand Up @@ -105,6 +106,15 @@ fn absolute_path(context: &FunctionContext, path: &str) -> Result<String, String
}
}

fn append(_context: &FunctionContext, suffix: &str, s: &str) -> Result<String, String> {
Ok(
s.split_whitespace()
.map(|s| format!("{s}{suffix}"))
.collect::<Vec<String>>()
.join(" "),
)
}

fn arch(_context: &FunctionContext) -> Result<String, String> {
Ok(target::arch().to_owned())
}
Expand Down
20 changes: 20 additions & 0 deletions tests/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,26 @@ fn trim_end() {
assert_eval_eq("trim_end(' f ')", " f");
}

#[test]
fn append() {
assert_eval_eq("append('8', 'r s t')", "r8 s8 t8");
assert_eval_eq("append('.c', 'main sar x11')", "main.c sar.c x11.c");
assert_eval_eq("append('-', 'c v h y')", "c- v- h- y-");
assert_eval_eq(
"append('0000', '11 10 01 00')",
"110000 100000 010000 000000",
);
assert_eval_eq(
"append('tion', '
Determina
Acquisi
Motiva
Conjuc
')",
"Determination Acquisition Motivation Conjuction",
);
}

#[test]
#[cfg(not(windows))]
fn join() {
Expand Down

0 comments on commit eb60518

Please sign in to comment.