Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- pub fn escape_shell_arg(arg: &str) -> String {
- let mut output = String::new();
- for ch in arg.chars() {
- match ch {
- // Output a closing single quote, an escaped single quote, and then
- // resume the string by outputting a single quote.
- '\'' => output.extend(r"'\''".chars()),
- // Output a closing single quote, an escaped backslash, and then
- // resume the string literal by outputting a single quote.
- '\\' => output.extend(r"'\\'".chars()),
- // Other characters should be safe
- ch => output.push(ch),
- }
- }
- <[&str]>::join(&["'", &output, "'"], "")
- }
- #[cfg(test)]
- mod test {
- use super::escape_shell_arg;
- // static INPUTS: &[&str] = [
- // "hello, world",
- // "i'm tricky",
- // r#"this "one" is \"weird\""#,
- // ];
- #[test]
- fn hello_world() {
- assert_eq!("'hello, world'", escape_shell_arg("hello, world"));
- }
- #[test]
- fn escape_single_quote() {
- assert_eq!(r"'i'\''m tricky'", escape_shell_arg("i'm tricky"));
- }
- #[test]
- fn escape_backslash() {
- assert_eq!(r"'C:'\\'Windows'\\'System32'", escape_shell_arg(r"C:\Windows\System32"));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement