Skip to content
Myr

optimize

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by curious-rabbit · committed by curious-rabbit · parent 9d536e1 · Browse files · 7 files+88 added−36 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+88 added−36 removed

  • other:+88 added−36 removed

7 files+88 added−36 removed

modified:src/exec/job.rs+1 added-1 removed
30 unmodified lines
31 };3233 // Generate a command, execute it and store its exit code.34 let code = cmd.execute(35 &dir_entry.stripped_path(config),35 dir_entry.stripped_path(config),36 config.path_separator.as_deref(),37 config.null_separator,38 buffer_output,39 );
25 unmodified lines
modified:src/dir_entry.rs+5 added-6 removed
1use std::borrow::Cow;1use std::cell::OnceCell;2use std::ffi::OsString;3use std::fs::{FileType, Metadata};4use std::path::{Path, PathBuf};
50 unmodified lines
5556 /// Returns the path as it should be presented to the user.57 /// When stripping `./` would leave the path starting with `-`, keep the original58 /// (with `./`) so downstream tools don't interpret it as an option.60 pub fn stripped_path(&self, config: &Config) -> Cow<'_, Path> {59 pub fn stripped_path(&self, config: &Config) -> &Path {60 let path = self.path();61 if config.strip_cwd_prefix {62 let stripped = strip_current_dir(path);63 if starts_with_dash(stripped) {65 Cow::Borrowed(path)64 path65 } else {67 Cow::Borrowed(stripped)66 stripped67 }68 } else {70 Cow::Borrowed(path)69 path70 }71 }7273 /// Returns the path as it should be presented to the user.74 pub fn into_stripped_path(self, config: &Config) -> PathBuf {75 if config.strip_cwd_prefix {77 self.stripped_path(config).into_owned()76 self.stripped_path(config).to_path_buf()77 } else {78 self.into_path()79 }80 }
109 unmodified lines
modified:src/error.rs+3 added-6 removed
1use std::io::IsTerminal;23use crate::sanitize::sanitize_for_terminal;3use crate::sanitize::maybe_sanitize;45pub fn print_error(msg: impl Into<String>) {6 let msg = msg.into();7 if std::io::stderr().is_terminal() {8 eprintln!("[fd error]: {}", sanitize_for_terminal(&msg));9 } else {10 eprintln!("[fd error]: {msg}");11 }7 let safe = maybe_sanitize(&msg, std::io::stderr().is_terminal());8 eprintln!("[fd error]: {safe}");9}
modified:src/output.rs+13 added-15 removed
5 unmodified lines
6use crate::config::Config;7use crate::dir_entry::DirEntry;8use crate::fmt::FormatTemplate;9use crate::hyperlink::PathUrl;10use crate::sanitize::sanitize_for_terminal;10use crate::sanitize::{Sanitized, maybe_sanitize};1112fn replace_path_separator(path: &str, new_path_separator: &str) -> String {13 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)14}1516/// Sanitize a string for terminal output only; raw bytes pass through on pipes.17fn maybe_sanitize<'a>(s: &'a str, config: &Config) -> Cow<'a, str> {18 if config.interactive_terminal {19 sanitize_for_terminal(s)20 } else {21 Cow::Borrowed(s)22 }23}2416// TODO: this function is performance critical and can probably be optimized17pub fn print_entry<W: Write>(stdout: &mut W, entry: &DirEntry, config: &Config) -> io::Result<()> {18 let mut has_hyperlink = false;19 if config.hyperlink
57 unmodified lines
77 config.path_separator.as_deref(),78 );79 // TODO: support writing raw bytes on unix?80 let s = output.to_string_lossy();90 write!(stdout, "{}", maybe_sanitize(&s, config))81 if config.interactive_terminal {82 write!(stdout, "{}", Sanitized(&s))83 } else {84 write!(stdout, "{s}")85 }86}8788// TODO: this function is performance critical and can probably be optimized89fn print_entry_colorized<W: Write>(
26 unmodified lines
116 let style = ls_colors117 .style_for_indicator(Indicator::Directory)118 .map(Style::to_nu_ansi_term_style)119 .unwrap_or_default();125 let safe_parent = maybe_sanitize(&parent_str, config);120 let safe_parent = maybe_sanitize(&parent_str, config.interactive_terminal);121 write!(stdout, "{}", style.paint(safe_parent.as_ref()))?;122 }123124 let style = entry125 .style(ls_colors)126 .map(Style::to_nu_ansi_term_style)127 .unwrap_or_default();133 let safe_basename = maybe_sanitize(&path_str[offset..], config);128 let safe_basename = maybe_sanitize(&path_str[offset..], config.interactive_terminal);129 write!(stdout, "{}", style.paint(safe_basename.as_ref()))?;130131 print_trailing_slash(132 stdout,
16 unmodified lines
149 let mut path_string = path.to_string_lossy();150 if let Some(ref separator) = config.path_separator {151 *path_string.to_mut() = replace_path_separator(&path_string, separator);152 }158 let safe = maybe_sanitize(&path_string, config);159 write!(stdout, "{safe}")?;153 if config.interactive_terminal {154 write!(stdout, "{}", Sanitized(&path_string))?;155 } else {156 write!(stdout, "{path_string}")?;157 }158 print_trailing_slash(stdout, entry, config, None)159}160161#[cfg(not(unix))]
24 unmodified lines
modified:src/sanitize.rs+58 added-4 removed
1//! TTY-output sanitization to prevent terminal escape injection via filenames.23use std::borrow::Cow;4use std::fmt::Write;4use std::fmt::{self, Display, Formatter, Write};56/// True for any char that is neither printable nor permitted whitespace (only HT).7/// Covers C0/C1/DEL, bidi overrides, zero-width and format chars, and tag chars.8#[inline]
13 unmodified lines
22 | '\u{E0000}'..='\u{E007F}' // language tags23 )24}2526/// Replace dangerous chars with `\xNN` / `\u{NNNN}` so the original is recoverable.26/// Streams `s` to a formatter, escaping dangerous chars as `\xNN` / `\u{NNNN}`.27/// Allocation-free wrapper for use with `write!`, `format!`, etc.28pub struct Sanitized<'a>(pub &'a str);2930impl Display for Sanitized<'_> {31 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {32 for c in self.0.chars() {33 if needs_escape(c) {34 let v = c as u32;35 if v <= 0xFF {36 write!(f, "\\x{v:02X}")?;37 } else {38 write!(f, "\\u{{{v:04X}}}")?;39 }40 } else {41 f.write_char(c)?;42 }43 }44 Ok(())45 }46}4748/// Returns a `Cow<str>` borrowing `s` when no escaping is needed, otherwise an owned49/// escaped copy. Use this when an owned `&str`/`String` is required (e.g. ANSI paint).50pub fn sanitize_for_terminal(s: &str) -> Cow<'_, str> {51 if !s.chars().any(needs_escape) {52 return Cow::Borrowed(s);53 }
1 unmodified line
55 for c in s.chars() {56 if needs_escape(c) {57 let v = c as u32;58 if v <= 0xFF {36 let _ = write!(out, "\\x{:02X}", v);59 let _ = write!(out, "\\x{v:02X}");60 } else {38 let _ = write!(out, "\\u{{{:04X}}}", v);61 let _ = write!(out, "\\u{{{v:04X}}}");62 }63 } else {64 out.push(c);65 }66 }67 Cow::Owned(out)68}6970/// Sanitize for terminal output only; raw bytes pass through on pipes/files.71pub fn maybe_sanitize<'a>(s: &'a str, is_terminal: bool) -> Cow<'a, str> {72 if is_terminal {73 sanitize_for_terminal(s)74 } else {75 Cow::Borrowed(s)76 }77}7879#[cfg(test)]80mod tests {81 use super::*;82
11 unmodified lines
94 matches!(sanitize_for_terminal(s), Cow::Borrowed(_)),95 "{s:?}"96 );97 assert_eq!(sanitize_for_terminal(s), s);98 // Display matches Cow output.99 assert_eq!(Sanitized(s).to_string(), s);100 }101 }102103 #[test]
73 unmodified lines
177 "{s:?}"178 );179 }180 }181182 #[test]183 fn display_streams_without_intermediate_string() {184 // Sanitized<'_> implements Display directly; produces same bytes as Cow form.185 let attack = "x\x1byb";186 let mut out = String::new();187 write!(out, "{}", Sanitized(attack)).unwrap();188 assert_eq!(out, "x\\x1Byb");189 }190191 #[test]192 fn maybe_sanitize_passthrough_when_not_terminal() {193 let attack = "x\x1by";194 // Pipe context: bytes pass through unchanged (zero-copy).195 let out = maybe_sanitize(attack, false);196 assert!(matches!(out, Cow::Borrowed(_)));197 assert_eq!(out, attack);198 // TTY context: escapes apply.199 assert_eq!(maybe_sanitize(attack, true), "x\\x1By");200 }201}
modified:Cargo.toml+1 added-1 removed
modified:CHANGELOG.md+7 added-3 removed
1# Unreleased23## Features4- Add `--ignore-parent` option to override `--no-ignore-parent`, see #1958 (@tmchow)53## Bugfixes4- Sanitize control characters and bidirectional override characters in filenames5 when output goes to a terminal, and prefix paths starting with `-` with `./` to6 prevent argument injection. Also reject placeholders as the executable in7 `--exec`/`--exec-batch` (was previously checked only for `--exec-batch`).8- Handle invalid working directories gracefully when using `--full-path`, see #1900 (@Xavrir).910## Features11- Add `--ignore-parent` option to override `--no-ignore-parent`, see #1958 (@tmchow)1213# 10.4.21415## Bugfixes16- Fixed performance regression due to `--ignore-contain`; see #1913 and #1914
845 unmodified lines