]>
git.proxmox.com Git - rustc.git/blob - vendor/shell-escape/src/lib.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //! Escape characters that may have special meaning in a shell.
11 #![doc(html_root_url="https://docs.rs/shell-escape/0.1")]
16 /// Escape characters that may have special meaning in a shell.
17 pub fn escape(s
: Cow
<str>) -> Cow
<str> {
18 if cfg
!(unix
) || env
::var("MSYSTEM").is_ok() {
25 /// Windows-specific escaping.
28 use std
::iter
::repeat
;
30 /// Escape for the windows cmd.exe shell.
32 /// See [here][msdn] for more information.
34 /// [msdn]: http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
35 pub fn escape(s
: Cow
<str>) -> Cow
<str> {
36 let mut needs_escape
= s
.is_empty();
39 '
"' | '\t' | '\n' | ' ' => needs_escape = true,
46 let mut es = String::with_capacity(s.len());
48 let mut chars
= s
.chars().peekable();
51 while let Some(&'
\\'
) = chars
.peek() {
58 es.extend(repeat('\\').take(nslashes * 2 + 1));
62 es
.extend(repeat('
\\'
).take(nslashes
));
66 es
.extend(repeat('
\\'
).take(nslashes
* 2));
78 assert_eq!(escape("--aaa
=bbb
-ccc
".into()), "--aaa
=bbb
-ccc
");
79 assert_eq!(escape("linker
=gcc
-L
/foo
-Wl
,bar
".into()),
80 r#""linker=gcc -L/foo -Wl,bar""#);
81 assert_eq!(escape(r#"--features
="default""#.into()),
82 r#""--features=\"default\"""#);
83 assert_eq!(escape(r#"\path
\to
\my documents
\"#.into()),
84 r
#""\path\to\my documents\\""#);
85 assert_eq
!(escape("".into()), r
#""""#);
89 /// Unix-specific escaping.
93 fn non_whitelisted(ch
: char) -> bool
{
95 'a'
...'z'
| 'A'
...'Z'
| '
0'
...'
9'
| '
-'
| '_'
| '
='
| '
/'
| '
,'
| '
.'
| '
+'
=> false,
100 /// Escape characters that may have special meaning in a shell, including spaces.
101 pub fn escape(s
: Cow
<str>) -> Cow
<str> {
102 if !s
.is_empty() && !s
.contains(non_whitelisted
) {
106 let mut es
= String
::with_capacity(s
.len() + 2);
108 for ch
in s
.chars() {
125 escape("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_=/,.+".into()),
126 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_=/,.+"
128 assert_eq
!(escape("--aaa=bbb-ccc".into()), "--aaa=bbb-ccc");
129 assert_eq
!(escape("linker=gcc -L/foo -Wl,bar".into()), r
#"'linker=gcc -L/foo -Wl,bar'"#);
130 assert_eq
!(escape(r
#"--features="default""#.into()), r#"'--features="default"'"#);
131 assert_eq
!(escape(r
#"'!\$`\\\n "#.into()), r#"''\'''\!'\$`\\\n '"#);
132 assert_eq
!(escape("".into()), r
#"''"#);