Skip to content
Myr

output.rs

This file

Path

src/output.rs

196 lines · 5.6 KiB · Rust

Last changed by

fix: Better sanitizingThayne McCombsbefore adoption24198d9

History of this file

Take it

1use std::borrow::Cow;2use std::io::{self, Write};34use lscolors::{Indicator, LsColors, Style};56use crate::config::Config;7use crate::dir_entry::DirEntry;8use crate::fmt::FormatTemplate;9use crate::hyperlink::PathUrl;10use crate::sanitize::sanitize_for_term;1112fn replace_path_separator(path: &str, new_path_separator: &str) -> String {13    path.replace(std::path::MAIN_SEPARATOR, new_path_separator)14}1516// 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.hyperlink20        && let Some(url) = PathUrl::new(entry.path())21    {22        write!(stdout, "\x1B]8;;{url}\x1B\\")?;23        has_hyperlink = true;24    }2526    if let Some(ref format) = config.format {27        print_entry_format(stdout, entry, config, format)?;28    } else if let Some(ref ls_colors) = config.ls_colors {29        print_entry_colorized(stdout, entry, config, ls_colors)?;30    } else {31        print_entry_uncolorized(stdout, entry, config)?;32    };3334    if has_hyperlink {35        write!(stdout, "\x1B]8;;\x1B\\")?;36    }3738    if config.null_separator {39        write!(stdout, "\0")40    } else {41        writeln!(stdout)42    }43}4445// Display a trailing slash if the path is a directory and the config option is enabled.46// If the path_separator option is set, display that instead.47// The trailing slash will not be colored.48#[inline]49fn print_trailing_slash<W: Write>(50    stdout: &mut W,51    entry: &DirEntry,52    config: &Config,53    style: Option<&Style>,54) -> io::Result<()> {55    if entry.file_type().is_some_and(|ft| ft.is_dir()) {56        write!(57            stdout,58            "{}",59            style60                .map(Style::to_nu_ansi_term_style)61                .unwrap_or_default()62                .paint(&config.actual_path_separator)63        )?;64    }65    Ok(())66}6768// TODO: this function is performance critical and can probably be optimized69fn print_entry_format<W: Write>(70    stdout: &mut W,71    entry: &DirEntry,72    config: &Config,73    format: &FormatTemplate,74) -> io::Result<()> {75    let output = format.generate(76        entry.stripped_path(config),77        config.path_separator.as_deref(),78    );79    // TODO: support writing raw bytes on unix?80    let s = output.to_string_lossy();81    write!(82        stdout,83        "{}",84        sanitize_for_term(&s, config.interactive_terminal)85    )86}8788// TODO: this function is performance critical and can probably be optimized89fn print_entry_colorized<W: Write>(90    stdout: &mut W,91    entry: &DirEntry,92    config: &Config,93    ls_colors: &LsColors,94) -> io::Result<()> {95    let mut offset = 0;96    let path = entry.stripped_path(config);97    let path_str = path.to_string_lossy();9899    if let Some(parent) = path.parent() {100        offset = parent.to_string_lossy().len();101        for c in path_str[offset..].chars() {102            if std::path::is_separator(c) {103                offset += c.len_utf8();104            } else {105                break;106            }107        }108    }109110    if offset > 0 {111        let mut parent_str = Cow::from(&path_str[..offset]);112        if let Some(ref separator) = config.path_separator {113            *parent_str.to_mut() = replace_path_separator(&parent_str, separator);114        }115116        let style = ls_colors117            .style_for_indicator(Indicator::Directory)118            .map(Style::to_nu_ansi_term_style)119            .unwrap_or_default();120        let safe_parent = sanitize_for_term(&parent_str, config.interactive_terminal);121        // We explicitly use prefix/suffix instead of paint so that we can use Sanitized122        write!(123            stdout,124            "{}{}{}",125            style.prefix(),126            safe_parent,127            style.suffix()128        )?;129    }130131    let style = entry132        .style(ls_colors)133        .map(Style::to_nu_ansi_term_style)134        .unwrap_or_default();135    let safe_basename = sanitize_for_term(&path_str[offset..], config.interactive_terminal);136    // We explicitly use prefix/suffix instead of paint so that we can use Sanitized137    write!(138        stdout,139        "{}{}{}",140        style.prefix(),141        safe_basename,142        style.suffix()143    )?;144145    print_trailing_slash(146        stdout,147        entry,148        config,149        ls_colors.style_for_indicator(Indicator::Directory),150    )?;151152    Ok(())153}154155// TODO: this function is performance critical and can probably be optimized156fn print_entry_uncolorized_base<W: Write>(157    stdout: &mut W,158    entry: &DirEntry,159    config: &Config,160) -> io::Result<()> {161    let path = entry.stripped_path(config);162163    let mut path_string = path.to_string_lossy();164    if let Some(ref separator) = config.path_separator {165        *path_string.to_mut() = replace_path_separator(&path_string, separator);166    }167    let safe = sanitize_for_term(&path_string, config.interactive_terminal);168    write!(stdout, "{safe}")?;169    print_trailing_slash(stdout, entry, config, None)170}171172#[cfg(not(unix))]173fn print_entry_uncolorized<W: Write>(174    stdout: &mut W,175    entry: &DirEntry,176    config: &Config,177) -> io::Result<()> {178    print_entry_uncolorized_base(stdout, entry, config)179}180181#[cfg(unix)]182fn print_entry_uncolorized<W: Write>(183    stdout: &mut W,184    entry: &DirEntry,185    config: &Config,186) -> io::Result<()> {187    use std::os::unix::ffi::OsStrExt;188189    if config.interactive_terminal || config.path_separator.is_some() {190        print_entry_uncolorized_base(stdout, entry, config)191    } else {192        // Piped output: raw bytes so invalid UTF-8 filenames reach downstream tools intact.193        stdout.write_all(entry.stripped_path(config).as_os_str().as_bytes())?;194        print_trailing_slash(stdout, entry, config, None)195    }196}