| 1 |
use core::fmt::{self, Formatter, Write}; |
| 2 |
|
| 3 |
use unicode_width::UnicodeWidthChar; |
| 4 |
|
| 5 |
// Much of this code is similar to the Unix version. |
| 6 |
// Not all comments are repeated, so read that first. |
| 7 |
|
| 8 |
/// I'm not too familiar with PowerShell, much of this is based on |
| 9 |
/// experimentation rather than documentation or deep understanding. |
| 10 |
/// I have noticed that ~?*[] only get expanded in some contexts, so watch |
| 11 |
/// out for that if doing your own tests. |
| 12 |
/// Get-ChildItem seems unwilling to quote anything so it doesn't help. |
| 13 |
/// The omission of \ is important because it's used in file paths. |
| 14 |
const SPECIAL_SHELL_CHARS: &[u8] = b"|&;<>()$`\"'*?[]=,{} "; |
| 15 |
|
| 16 |
/// A single stand-alone exclamation mark seems to have some special meaning. |
| 17 |
/// Tildes are unclear: In Powershell on Linux, quoting a tilde keeps it from |
| 18 |
/// expanding if passed to an external program, but not if passed to Get-ChildItem. |
| 19 |
const SPECIAL_SHELL_CHARS_START: &[char] = &['~', '#', '@', '!']; |
| 20 |
|
| 21 |
const DOUBLE_UNSAFE: &[u8] = b"\"`$"; |
| 22 |
|
| 23 |
pub(crate) fn write( |
| 24 |
f: &mut Formatter<'_>, |
| 25 |
text: &str, |
| 26 |
force_quote: bool, |
| 27 |
external: bool, |
| 28 |
) -> fmt::Result { |
| 29 |
match text { |
| 30 |
"" if external => { |
| 31 |
// If we write '' PowerShell will swallow the argument. |
| 32 |
return f.write_str(r#"'""'"#); |
| 33 |
} |
| 34 |
"--%" if external => { |
| 35 |
// PowerShell doesn't want to pass this to external commands at all. |
| 36 |
// This does work: |
| 37 |
return f.write_str(r#"'"--%"'"#); |
| 38 |
// It does not work if PSNativeCommandArgumentPassing is enabled. |
| 39 |
} |
| 40 |
"--%" => { |
| 41 |
// This one's still special if used internally. |
| 42 |
return f.write_str("'--%'"); |
| 43 |
} |
| 44 |
_ => (), |
| 45 |
} |
| 46 |
|
| 47 |
let mut is_single_safe = true; |
| 48 |
let mut is_double_safe = true; |
| 49 |
let mut has_ascii_double = false; |
| 50 |
let mut requires_quote = force_quote; |
| 51 |
let mut is_bidi = false; |
| 52 |
|
| 53 |
if !requires_quote { |
| 54 |
let mut chars = text.chars(); |
| 55 |
if let Some(first) = chars.next() { |
| 56 |
let second = chars.next(); |
| 57 |
|
| 58 |
if SPECIAL_SHELL_CHARS_START.contains(&first) { |
| 59 |
requires_quote = true; |
| 60 |
} |
| 61 |
|
| 62 |
if !external { |
| 63 |
// PowerShell may parse bare strings as numbers in some contexts. |
| 64 |
// `echo 1d` just outputs "1d", but `Set-Variable s 1d` assigns |
| 65 |
// the number 1 to s. |
| 66 |
if !requires_quote && first.is_ascii_digit() { |
| 67 |
requires_quote = true; |
| 68 |
} |
| 69 |
|
| 70 |
// Annoyingly, .0d is another example. |
| 71 |
// And filenames start with . commonly enough that we shouldn't quote |
| 72 |
// too eagerly. |
| 73 |
if !requires_quote && first == '.' { |
| 74 |
if let Some(second) = second { |
| 75 |
if second.is_ascii_digit() { |
| 76 |
requires_quote = true; |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
// Unlike in Unix, quoting an argument may stop it |
| 83 |
// from being recognized as an option. I like that very much. |
| 84 |
if !requires_quote && unicode::is_dash(first) { |
| 85 |
if second.is_none() || second == Some('-') { |
| 86 |
// "-" is a common special argument we don't want to quote. |
| 87 |
// Something with multiple leading dashes won't be recognized |
| 88 |
// as an option. (Except for --% sorta.) |
| 89 |
// So do nothing. |
| 90 |
} else if external { |
| 91 |
// External commands aren't picky, no need to bother quoting. |
| 92 |
// However... |
| 93 |
if text.find(&[':', '.'][..]).is_some() { |
| 94 |
// A : must be followed by a value. Strictly speaking |
| 95 |
// we only have to check that it's followed by a character |
| 96 |
// that's not in SPECIAL_SHELL_CHARS_START, but let's |
| 97 |
// be cautious. |
| 98 |
// A . starts a new argument for some reason. |
| 99 |
requires_quote = true; |
| 100 |
} |
| 101 |
} else { |
| 102 |
// This looks like an option, so stop commandlets from |
| 103 |
// recognizing it as one. |
| 104 |
requires_quote = true; |
| 105 |
} |
| 106 |
} |
| 107 |
|
| 108 |
if !requires_quote && first.width().unwrap_or(0) == 0 { |
| 109 |
requires_quote = true; |
| 110 |
} |
| 111 |
} else { |
| 112 |
// Empty string. |
| 113 |
requires_quote = true; |
| 114 |
} |
| 115 |
} |
| 116 |
|
| 117 |
for ch in text.chars() { |
| 118 |
if ch.is_ascii() { |
| 119 |
let ch = ch as u8; |
| 120 |
if ch == b'\'' { |
| 121 |
is_single_safe = false; |
| 122 |
} |
| 123 |
if ch == b'"' { |
| 124 |
has_ascii_double = true; |
| 125 |
} |
| 126 |
if is_double_safe && DOUBLE_UNSAFE.contains(&ch) { |
| 127 |
is_double_safe = false; |
| 128 |
} |
| 129 |
if !requires_quote && SPECIAL_SHELL_CHARS.contains(&ch) { |
| 130 |
requires_quote = true; |
| 131 |
} |
| 132 |
if ch.is_ascii_control() { |
| 133 |
return write_escaped(f, text.chars().map(Ok), external); |
| 134 |
} |
| 135 |
} else { |
| 136 |
if !requires_quote && unicode::is_whitespace(ch) { |
| 137 |
requires_quote = true; |
| 138 |
} |
| 139 |
if (!requires_quote || is_double_safe) && unicode::is_double_quote(ch) { |
| 140 |
is_double_safe = false; |
| 141 |
requires_quote = true; |
| 142 |
} |
| 143 |
if (!requires_quote || is_single_safe) && unicode::is_single_quote(ch) { |
| 144 |
is_single_safe = false; |
| 145 |
requires_quote = true; |
| 146 |
} |
| 147 |
if crate::is_bidi(ch) { |
| 148 |
is_bidi = true; |
| 149 |
} |
| 150 |
if crate::requires_escape(ch) { |
| 151 |
return write_escaped(f, text.chars().map(Ok), external); |
| 152 |
} |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
if is_bidi && crate::is_suspicious_bidi(text) { |
| 157 |
return write_escaped(f, text.chars().map(Ok), external); |
| 158 |
} |
| 159 |
|
| 160 |
if !requires_quote { |
| 161 |
f.write_str(text) |
| 162 |
} else if external && has_ascii_double { |
| 163 |
write_external_escaped(f, text) |
| 164 |
} else if is_single_safe { |
| 165 |
write_simple(f, text, '\'') |
| 166 |
} else if is_double_safe { |
| 167 |
write_simple(f, text, '\"') |
| 168 |
} else { |
| 169 |
write_single_escaped(f, text) |
| 170 |
} |
| 171 |
} |
| 172 |
|
| 173 |
fn write_simple(f: &mut Formatter<'_>, text: &str, quote: char) -> fmt::Result { |
| 174 |
f.write_char(quote)?; |
| 175 |
f.write_str(text)?; |
| 176 |
f.write_char(quote)?; |
| 177 |
Ok(()) |
| 178 |
} |
| 179 |
|
| 180 |
fn write_single_escaped(f: &mut Formatter<'_>, text: &str) -> fmt::Result { |
| 181 |
// Quotes in PowerShell are escaped by doubling them. |
| 182 |
// The second quote is used, so '‘ becomes ‘. |
| 183 |
// Therefore we insert a ' before every quote we find. |
| 184 |
|
| 185 |
// If we think something is a single quote and quote it but the PowerShell |
| 186 |
// version doesn't (e.g. because it's old) then things go wrong. I don't |
| 187 |
// know of a way to solve this. A ` (backtick) escape only works between |
| 188 |
// double quotes or in a bare string. We can't unquote, use a bare string, |
| 189 |
// then requote, as we would in Unix: PowerShell sees that as multiple |
| 190 |
// arguments. |
| 191 |
f.write_char('\'')?; |
| 192 |
let mut pos = 0; |
| 193 |
for (index, _) in text.match_indices(unicode::is_single_quote) { |
| 194 |
f.write_str(&text[pos..index])?; |
| 195 |
f.write_char('\'')?; |
| 196 |
pos = index; |
| 197 |
} |
| 198 |
f.write_str(&text[pos..])?; |
| 199 |
f.write_char('\'')?; |
| 200 |
Ok(()) |
| 201 |
} |
| 202 |
|
| 203 |
fn write_external_escaped(f: &mut Formatter<'_>, text: &str) -> fmt::Result { |
| 204 |
f.write_char('\'')?; |
| 205 |
let mut pos = 0; |
| 206 |
for (index, quote) in text.match_indices(|ch: char| ch == '"' || unicode::is_single_quote(ch)) { |
| 207 |
f.write_str(&text[pos..index])?; |
| 208 |
if quote == "\"" { |
| 209 |
// Let n be the number of backslashes before the quote. |
| 210 |
// We need to turn that into 2n + 1 backslahes. |
| 211 |
// Therefore we need to write n + 1 more. |
| 212 |
// The logic behind this is that double quotes must be escaped with |
| 213 |
// backslashes, and backslashes must be escaped only if they precede |
| 214 |
// a double quote. |
| 215 |
let backslashes = text[..index] |
| 216 |
.chars() |
| 217 |
.rev() |
| 218 |
.take_while(|&ch| ch == '\\') |
| 219 |
.count() |
| 220 |
+ 1; |
| 221 |
for _ in 0..backslashes { |
| 222 |
f.write_char('\\')?; |
| 223 |
} |
| 224 |
} else { |
| 225 |
f.write_char('\'')?; |
| 226 |
} |
| 227 |
pos = index; |
| 228 |
} |
| 229 |
f.write_str(&text[pos..])?; |
| 230 |
f.write_char('\'')?; |
| 231 |
Ok(()) |
| 232 |
} |
| 233 |
|
| 234 |
pub(crate) fn write_escaped( |
| 235 |
f: &mut Formatter<'_>, |
| 236 |
text: impl Iterator<Item = Result<char, u16>>, |
| 237 |
external: bool, |
| 238 |
) -> fmt::Result { |
| 239 |
// ` takes the role of \ since \ is already used as the path separator. |
| 240 |
// Things are UTF-16-oriented, so we escape bad code units as "`u{1234}". |
| 241 |
|
| 242 |
f.write_char('"')?; |
| 243 |
let mut backslashes: u32 = 0; |
| 244 |
for ch in text { |
| 245 |
match ch { |
| 246 |
Ok(ch) => { |
| 247 |
match ch { |
| 248 |
'\0' => f.write_str("`0")?, |
| 249 |
'\r' => f.write_str("`r")?, |
| 250 |
'\n' => f.write_str("`n")?, |
| 251 |
'\t' => f.write_str("`t")?, |
| 252 |
// Code unit escapes are only supported in PowerShell Core, |
| 253 |
// so we're more willing to use weird escapes here than on Unix. |
| 254 |
// There's also `e, for \x1B, but that one's Core-exclusive. |
| 255 |
'\x07' => f.write_str("`a")?, |
| 256 |
'\x08' => f.write_str("`b")?, |
| 257 |
'\x0b' => f.write_str("`v")?, |
| 258 |
'\x0c' => f.write_str("`f")?, |
| 259 |
ch if crate::requires_escape(ch) || crate::is_bidi(ch) => { |
| 260 |
write!(f, "`u{{{:02X}}}", ch as u32)? |
| 261 |
} |
| 262 |
'`' => f.write_str("``")?, |
| 263 |
'$' => f.write_str("`$")?, |
| 264 |
'"' if external => { |
| 265 |
// First we need to escape all the backslashes that came before. |
| 266 |
for _ in 0..backslashes { |
| 267 |
f.write_char('\\')?; |
| 268 |
} |
| 269 |
// Then we need to escape this double quote for CommandLineToArgv. |
| 270 |
f.write_char('\\')?; |
| 271 |
// Then we need to escape it for the PowerShell string. |
| 272 |
f.write_char('`')?; |
| 273 |
// And then we can finally write the quote itself. |
| 274 |
f.write_char('"')?; |
| 275 |
} |
| 276 |
ch if unicode::is_double_quote(ch) => { |
| 277 |
// We can quote this with either ` or ". |
| 278 |
// But if we use " and the PowerShell version doesn't actually |
| 279 |
// see this as a double quote then we're in trouble. |
| 280 |
// ` is safer. |
| 281 |
f.write_char('`')?; |
| 282 |
f.write_char(ch)?; |
| 283 |
} |
| 284 |
ch => f.write_char(ch)?, |
| 285 |
} |
| 286 |
if ch == '\\' { |
| 287 |
backslashes += 1; |
| 288 |
} else { |
| 289 |
backslashes = 0; |
| 290 |
} |
| 291 |
} |
| 292 |
Err(unit) => write!(f, "`u{{{:04X}}}", unit)?, |
| 293 |
} |
| 294 |
} |
| 295 |
f.write_char('"')?; |
| 296 |
Ok(()) |
| 297 |
} |
| 298 |
|
| 299 |
/// PowerShell makes liberal use of Unicode: |
| 300 |
/// <https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/parser/CharTraits.cs> |
| 301 |
/// This may have to be updated in the future. |
| 302 |
mod unicode { |
| 303 |
/// PowerShell considers these to be whitespace: |
| 304 |
/// 1. ASCII: Space, Horizontal tab, Form feed, Carriage return |
| 305 |
/// 2. Unicode: No-break space, Next line |
| 306 |
/// 3. Everything that satisfies System.Char.IsSeparator, i.e. everything |
| 307 |
/// in the categories {space, line, paragraph} separator |
| 308 |
/// |
| 309 |
/// This overlaps with but is not identical to char::is_whitespace(). |
| 310 |
/// |
| 311 |
/// There is some redundancy throughout this implementation. We already |
| 312 |
/// know that ch is not ASCII, and \u{A0} is repeated. But that's all |
| 313 |
/// optimized away in the end so no need to worry about it. |
| 314 |
pub(crate) fn is_whitespace(ch: char) -> bool { |
| 315 |
match ch { |
| 316 |
' ' | '\t' | '\x0B' | '\x0C' => true, |
| 317 |
'\u{00A0}' | '\u{0085}' => true, |
| 318 |
// BRAILLE PATTERN BLANK |
| 319 |
// Not strictly whitespace but invisible enough to quote |
| 320 |
'\u{2800}' => true, |
| 321 |
c => is_separator(c), |
| 322 |
} |
| 323 |
} |
| 324 |
|
| 325 |
/// I don't want to add a dependency just for this, and |
| 326 |
/// as of writing, the unicode_categories crate is out of |
| 327 |
/// date anyway. So hardcode the category check. |
| 328 |
/// |
| 329 |
/// curl -s https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt \ |
| 330 |
/// | grep -e Zl -e Zp -e Zs | cut -d ';' -f 1 |
| 331 |
/// |
| 332 |
/// Up to date as of Unicode 16.0. |
| 333 |
fn is_separator(ch: char) -> bool { |
| 334 |
matches!( |
| 335 |
ch, |
| 336 |
'\u{0020}' |
| 337 |
| '\u{00A0}' |
| 338 |
| '\u{1680}' |
| 339 |
| '\u{2000}' |
| 340 |
| '\u{2001}' |
| 341 |
| '\u{2002}' |
| 342 |
| '\u{2003}' |
| 343 |
| '\u{2004}' |
| 344 |
| '\u{2005}' |
| 345 |
| '\u{2006}' |
| 346 |
| '\u{2007}' |
| 347 |
| '\u{2008}' |
| 348 |
| '\u{2009}' |
| 349 |
| '\u{200A}' |
| 350 |
| '\u{2028}' |
| 351 |
| '\u{2029}' |
| 352 |
| '\u{202F}' |
| 353 |
| '\u{205F}' |
| 354 |
| '\u{3000}' |
| 355 |
) |
| 356 |
} |
| 357 |
|
| 358 |
/// These can be used to start options. |
| 359 |
/// |
| 360 |
/// There exist others, but PowerShell doesn't care about them. |
| 361 |
pub(crate) fn is_dash(ch: char) -> bool { |
| 362 |
matches!(ch, '-' | '\u{2013}' | '\u{2014}' | '\u{2015}') |
| 363 |
} |
| 364 |
|
| 365 |
pub(crate) fn is_single_quote(ch: char) -> bool { |
| 366 |
matches!(ch, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}') |
| 367 |
} |
| 368 |
|
| 369 |
pub(crate) fn is_double_quote(ch: char) -> bool { |
| 370 |
matches!(ch, '"' | '\u{201C}' | '\u{201D}' | '\u{201E}') |
| 371 |
} |
| 372 |
} |