Debian Codegraph @

debian/rust-vendor/os_display/src/unix.rs

raw
1 use core::fmt::{self, Formatter, Write};
2 use core::str::from_utf8;
3
4 use unicode_width::UnicodeWidthChar;
5
6 /// Characters with special meaning outside quotes.
7 /// https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02
8 /// I don't know why % is in there. GNU doesn't quote it either.
9 /// zsh and fish have trouble with standalone {}.
10 /// ^ was used for piping in old shells and GNU quotes it.
11 const SPECIAL_SHELL_CHARS: &[u8] = b"|&;<>()$`\\\"'*?[]=^{} ";
12
13 /// Characters with a special meaning at the beginning of a name.
14 /// ~ expands a home directory.
15 /// # starts a comment.
16 /// ! is a common extension for expanding the shell history.
17 const SPECIAL_SHELL_CHARS_START: &[char] = &['~', '#', '!'];
18
19 /// Characters that are interpreted specially in a double-quoted string.
20 const DOUBLE_UNSAFE: &[u8] = b"\"`$\\";
21
22 pub(crate) fn write(f: &mut Formatter<'_>, text: &str, force_quote: bool) -> fmt::Result {
23 let mut is_single_safe = true;
24 let mut is_double_safe = true;
25 let mut requires_quote = force_quote;
26 let mut is_bidi = false;
27
28 if !requires_quote {
29 if let Some(first) = text.chars().next() {
30 if SPECIAL_SHELL_CHARS_START.contains(&first) {
31 requires_quote = true;
32 }
33
34 // gnome-terminal (VTE), xterm, urxvt, tmux, screen, and VS Code's
35 // builtin terminal all include zero-width characters at the end of the
36 // selection but not at the start.
37 // terminology and st seem to have trouble displaying them at all.
38 // So if there's a zero-width character at the start we need quotes, but
39 // if it's at the end we don't need to bother.
40 // (This also ensures non-empty zero-width strings end up quoted.)
41 if !requires_quote && first.width().unwrap_or(0) == 0 {
42 // .width() returns Some(1) for unassigned codepoints.
43 // This means we can't pre-emptively quote unknown codepoints in
44 // case they become zero-width in the future.
45 // (None is only returned for certain ASCII characters.)
46 requires_quote = true;
47 }
48 } else {
49 // Empty string
50 requires_quote = true;
51 }
52 }
53
54 for ch in text.chars() {
55 if ch.is_ascii() {
56 let ch = ch as u8;
57 if ch == b'\'' {
58 is_single_safe = false;
59 }
60 if is_double_safe && DOUBLE_UNSAFE.contains(&ch) {
61 is_double_safe = false;
62 }
63 if !requires_quote && SPECIAL_SHELL_CHARS.contains(&ch) {
64 requires_quote = true;
65 }
66 if ch.is_ascii_control() {
67 return write_escaped(f, text.as_bytes());
68 }
69 } else {
70 if !requires_quote && (ch.is_whitespace() || ch == '\u{2800}') {
71 // yash splits on unicode whitespace.
72 // fish ignores unicode whitespace at the start of a bare string.
73 // Therefore we quote unicode whitespace.
74 // U+2800 BRAILLE PATTERN BLANK is not technically whitespace but we
75 // quote it too.
76 // This check goes stale when new whitespace codepoints are assigned.
77 requires_quote = true;
78 }
79 if crate::is_bidi(ch) {
80 is_bidi = true;
81 }
82 if crate::requires_escape(ch) {
83 return write_escaped(f, text.as_bytes());
84 }
85 }
86 }
87
88 if is_bidi && crate::is_suspicious_bidi(text) {
89 return write_escaped(f, text.as_bytes());
90 }
91
92 if !requires_quote {
93 f.write_str(text)
94 } else if is_single_safe {
95 write_simple(f, text, '\'')
96 } else if is_double_safe {
97 write_simple(f, text, '\"')
98 } else {
99 write_single_escaped(f, text)
100 }
101 }
102
103 fn write_simple(f: &mut Formatter<'_>, text: &str, quote: char) -> fmt::Result {
104 f.write_char(quote)?;
105 f.write_str(text)?;
106 f.write_char(quote)?;
107 Ok(())
108 }
109
110 fn write_single_escaped(f: &mut Formatter<'_>, text: &str) -> fmt::Result {
111 let mut iter = text.split('\'');
112 if let Some(chunk) = iter.next() {
113 if !chunk.is_empty() {
114 write_simple(f, chunk, '\'')?;
115 }
116 }
117 for chunk in iter {
118 f.write_str("\\'")?;
119 if !chunk.is_empty() {
120 write_simple(f, chunk, '\'')?;
121 }
122 }
123 Ok(())
124 }
125
126 /// Write using the syntax described here:
127 /// https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html
128 ///
129 /// Supported by these shells:
130 /// - bash
131 /// - zsh
132 /// - busybox sh
133 /// - mksh
134 /// - ksh93
135 ///
136 /// Not supported by these:
137 /// - fish
138 /// - dash
139 /// - tcsh
140 ///
141 /// There's a proposal to add it to POSIX:
142 /// https://www.austingroupbugs.net/view.php?id=249
143 pub(crate) fn write_escaped(f: &mut Formatter<'_>, text: &[u8]) -> fmt::Result {
144 f.write_str("$'")?;
145 // ksh variants accept more than two digits for a \x escape code,
146 // e.g. \xA691. We have to take care to not accidentally output
147 // something like that. If necessary we interrupt the quoting with
148 // `'$'`.
149 let mut in_escape = false;
150 for chunk in from_utf8_iter(text) {
151 match chunk {
152 Ok(chunk) => {
153 for ch in chunk.chars() {
154 let was_escape = in_escape;
155 in_escape = false;
156 match ch {
157 '\n' => f.write_str("\\n")?,
158 '\t' => f.write_str("\\t")?,
159 '\r' => f.write_str("\\r")?,
160 // We could do \a, \b, \f, \v, but those are
161 // rare enough to be confusing.
162 // \0 is actually a case of the octal \nnn syntax,
163 // and null bytes can't appear in arguments anyway,
164 // so let's stay clear of that.
165 // Some but not all shells have \e for \x1B.
166 ch if crate::requires_escape(ch) || crate::is_bidi(ch) => {
167 // Most shells support \uXXXX escape codes, but busybox sh
168 // doesn't, so we always encode the raw UTF-8. Bit unfortunate,
169 // but GNU does the same.
170 for &byte in ch.encode_utf8(&mut [0; 4]).as_bytes() {
171 write!(f, "\\x{:02X}", byte)?;
172 }
173 in_escape = true;
174 }
175 '\\' | '\'' => {
176 // '?' and '"' can also be escaped this way
177 // but AFAICT there's no reason to do so.
178 f.write_char('\\')?;
179 f.write_char(ch)?;
180 }
181 ch if was_escape && ch.is_ascii_hexdigit() => {
182 f.write_str("'$'")?;
183 f.write_char(ch)?;
184 }
185 ch => {
186 f.write_char(ch)?;
187 }
188 }
189 }
190 }
191 Err(unit) => {
192 write!(f, "\\x{:02X}", unit)?;
193 in_escape = true;
194 }
195 }
196 }
197 f.write_char('\'')?;
198 Ok(())
199 }
200
201 fn from_utf8_iter(bytes: &[u8]) -> impl Iterator<Item = Result<&str, u8>> {
202 struct Iter<'a> {
203 bytes: &'a [u8],
204 }
205
206 impl<'a> Iterator for Iter<'a> {
207 type Item = Result<&'a str, u8>;
208
209 fn next(&mut self) -> Option<Self::Item> {
210 if self.bytes.is_empty() {
211 return None;
212 }
213 match from_utf8(self.bytes) {
214 Ok(text) => {
215 self.bytes = &[];
216 Some(Ok(text))
217 }
218 Err(err) if err.valid_up_to() == 0 => {
219 let res = self.bytes[0];
220 self.bytes = &self.bytes[1..];
221 Some(Err(res))
222 }
223 Err(err) => {
224 let (valid, rest) = self.bytes.split_at(err.valid_up_to());
225 self.bytes = rest;
226 Some(Ok(from_utf8(valid).unwrap()))
227 }
228 }
229 }
230 }
231
232 Iter { bytes }
233 }
234
235 #[cfg(feature = "std")]
236 #[cfg(test)]
237 mod tests {
238 use super::*;
239
240 use std::vec::Vec;
241
242 #[test]
243 fn test_utf8_iter() {
244 type ByteStr = &'static [u8];
245 type Chunk = Result<&'static str, u8>;
246 const CASES: &[(ByteStr, &[Chunk])] = &[
247 (b"", &[]),
248 (b"hello", &[Ok("hello")]),
249 // Immediately invalid
250 (b"\xFF", &[Err(b'\xFF')]),
251 // Incomplete UTF-8
252 (b"\xC2", &[Err(b'\xC2')]),
253 (b"\xF4\x8F", &[Err(b'\xF4'), Err(b'\x8F')]),
254 (b"\xFF\xFF", &[Err(b'\xFF'), Err(b'\xFF')]),
255 (b"hello\xC2", &[Ok("hello"), Err(b'\xC2')]),
256 (b"\xFFhello", &[Err(b'\xFF'), Ok("hello")]),
257 (b"\xFF\xC2hello", &[Err(b'\xFF'), Err(b'\xC2'), Ok("hello")]),
258 (b"foo\xFFbar", &[Ok("foo"), Err(b'\xFF'), Ok("bar")]),
259 (
260 b"foo\xF4\x8Fbar",
261 &[Ok("foo"), Err(b'\xF4'), Err(b'\x8F'), Ok("bar")],
262 ),
263 (
264 b"foo\xFF\xC2bar",
265 &[Ok("foo"), Err(b'\xFF'), Err(b'\xC2'), Ok("bar")],
266 ),
267 ];
268 for &(case, expected) in CASES {
269 assert_eq!(
270 from_utf8_iter(case).collect::<Vec<_>>().as_slice(),
271 expected
272 );
273 }
274 }
275 }