pub fn escape_single_quote(s: &str) -> String {
s.replace('\'', r"'\''")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShellEscaped(String);
impl ShellEscaped {
pub fn single_quote(s: &str) -> Self {
Self(escape_single_quote(s))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_inner(self) -> String {
self.0
}
}
impl AsRef<str> for ShellEscaped {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for ShellEscaped {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_escape_single_quote_no_quotes() {
assert_eq!(escape_single_quote("password"), "password");
}
#[test]
fn test_escape_single_quote_with_quotes() {
assert_eq!(escape_single_quote("pass'word"), "pass'\\''word");
}
#[test]
fn test_escape_single_quote_multiple_quotes() {
assert_eq!(
escape_single_quote("'multiple'quotes'"),
"'\\''multiple'\\''quotes'\\''",
);
}
#[test]
fn test_shell_escaped_wrapper() {
let escaped = ShellEscaped::single_quote("test'value");
assert_eq!(escaped.as_str(), "test'\\''value");
assert_eq!(escaped.to_string(), "test'\\''value");
}
}