Crate yash_quote
source ·Expand description
This crate provides a function that quotes a string according to the POSIX shell quoting rules.
When used in a POSIX shell script, the resultant string will expand to a single field having the same value as the original string.
POSIX specifies several types of quoting mechanisms we can use. This crate picks one according to the following decision rules:
- If the string is not empty and contains no characters that need quoting, the string is returned intact.
- Otherwise, if the string contains no single quote, the whole string is single-quoted.
- Otherwise, the whole string is double-quoted, and all occurrences of
"
,`
,$
, and\
are backslash-escaped.
The following characters need quoting:
;
,&
,|
,(
,)
,<
, and>
- A space, tab, newline, or any other whitespace character
$
,`
,\
,"
, and'
=
,*
, and?
#
or~
occurring at the beginning of the string:
immediately followed by~
{
preceding}
[
preceding]
The quoted
function wraps a string in Quoted
, which implements
Display
to produce the quoted version of the string with a formatter. The
quote
function returns a Cow<str>
, avoiding unnecessary clone of the
string if it requires no quoting.
Examples
assert_eq!(format!("value={}", quoted("foo")), "value=foo");
assert_eq!(format!("value={}", quoted("")), "value=''");
assert_eq!(format!("value={}", quoted("$foo")), "value='$foo'");
assert_eq!(format!("value={}", quoted("'$foo'")), r#"value="'\$foo'""#);
assert_eq!(quote("foo"), "foo");
assert_eq!(quote(""), "''");
assert_eq!(quote("$foo"), "'$foo'");
assert_eq!(quote("'$foo'"), r#""'\$foo'""#);
Structs
- Wrapper for quoting a string.
Functions
- Quotes the argument.
- Wraps a string in
Quoted
.