Skip to content

Commit

Permalink
Add quote(s) function for escaping strings
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
casey committed Nov 8, 2021
1 parent 8b49c0c commit edb9ef3
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,7 @@ The executable is at: /bin/just
==== String Manipulation

- `lowercase(s)` - Convert `s` to lowercase.
- `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.
- `replace(s, from, to)` - Replace all occurrences of `from` in `s` to `to`.
- `trim(s)` - Remove leading and trailing whitespace from `s`.
- `trim_end(s)` - Remove trailing whitespace from `s`.
Expand Down
5 changes: 5 additions & 0 deletions src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ lazy_static! {
("os", Nullary(os)),
("os_family", Nullary(os_family)),
("parent_directory", Unary(parent_directory)),
("quote", Unary(quote)),
("replace", Ternary(replace)),
("trim", Unary(trim)),
("trim_end", Unary(trim_end)),
Expand Down Expand Up @@ -206,6 +207,10 @@ fn parent_directory(_context: &FunctionContext, path: &str) -> Result<String, St
.ok_or_else(|| format!("Could not extract parent directory from `{}`", path))
}

fn quote(_context: &FunctionContext, s: &str) -> Result<String, String> {
Ok(format!("'{}'", s.replace('\'', "'\\''")))
}

fn replace(_context: &FunctionContext, s: &str, from: &str, to: &str) -> Result<String, String> {
Ok(s.replace(from, to))
}
Expand Down
1 change: 1 addition & 0 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ mod invocation_directory;
mod misc;
mod positional_arguments;
mod quiet;
mod quote;
mod readme;
mod regexes;
mod search;
Expand Down
43 changes: 43 additions & 0 deletions tests/quote.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use crate::common::*;

#[test]
fn single_quotes_are_prepended_and_appended() {
Test::new()
.justfile(
"
x := quote('abc')
",
)
.args(&["--evaluate", "x"])
.stdout("'abc'")
.run();
}

#[test]
fn quotes_are_escaped() {
Test::new()
.justfile(
r#"
x := quote("'")
"#,
)
.args(&["--evaluate", "x"])
.stdout(r"''\'''")
.run();
}

#[test]
fn quoted_strings_can_be_used_as_arguments() {
Test::new()
.justfile(
r#"
file := quote("foo ' bar")
@foo:
touch {{ file }}
ls -1
"#,
)
.stdout("foo ' bar\njustfile\n")
.run();
}

0 comments on commit edb9ef3

Please sign in to comment.