Skip to content
Myr

output.rs

This file

Path

src/output.rs

144 lines · 4.2 KiB · Rust

Last changed by

Merge pull request #861 from jcaplan/no-strip/760David Peterbefore adoptionb211ded

History of this file

Take it

1use std::borrow::Cow;2use std::io::{self, StdoutLock, Write};3use std::path::Path;4use std::sync::atomic::{AtomicBool, Ordering};5use std::sync::Arc;67use lscolors::{Indicator, LsColors, Style};89use crate::config::Config;10use crate::error::print_error;11use crate::exit_codes::ExitCode;12use crate::filesystem::strip_current_dir;1314fn replace_path_separator(path: &str, new_path_separator: &str) -> String {15    path.replace(std::path::MAIN_SEPARATOR, new_path_separator)16}1718// TODO: this function is performance critical and can probably be optimized19pub fn print_entry(20    stdout: &mut StdoutLock,21    entry: &Path,22    config: &Config,23    wants_to_quit: &Arc<AtomicBool>,24) {25    let path = if config.strip_cwd_prefix {26        strip_current_dir(entry)27    } else {28        entry29    };3031    let r = if let Some(ref ls_colors) = config.ls_colors {32        print_entry_colorized(stdout, path, config, ls_colors, wants_to_quit)33    } else {34        print_entry_uncolorized(stdout, path, config)35    };3637    if let Err(e) = r {38        if e.kind() == ::std::io::ErrorKind::BrokenPipe {39            // Exit gracefully in case of a broken pipe (e.g. 'fd ... | head -n 3').40            ExitCode::Success.exit();41        } else {42            print_error(format!("Could not write to output: {}", e));43            ExitCode::GeneralError.exit();44        }45    }46}4748// TODO: this function is performance critical and can probably be optimized49fn print_entry_colorized(50    stdout: &mut StdoutLock,51    path: &Path,52    config: &Config,53    ls_colors: &LsColors,54    wants_to_quit: &Arc<AtomicBool>,55) -> io::Result<()> {56    // Split the path between the parent and the last component57    let mut offset = 0;58    let path_str = path.to_string_lossy();5960    if let Some(parent) = path.parent() {61        offset = parent.to_string_lossy().len();62        for c in path_str[offset..].chars() {63            if std::path::is_separator(c) {64                offset += c.len_utf8();65            } else {66                break;67            }68        }69    }7071    if offset > 0 {72        let mut parent_str = Cow::from(&path_str[..offset]);73        if let Some(ref separator) = config.path_separator {74            *parent_str.to_mut() = replace_path_separator(&parent_str, separator);75        }7677        let style = ls_colors78            .style_for_indicator(Indicator::Directory)79            .map(Style::to_ansi_term_style)80            .unwrap_or_default();81        write!(stdout, "{}", style.paint(parent_str))?;82    }8384    let style = ls_colors85        .style_for_path(path)86        .map(Style::to_ansi_term_style)87        .unwrap_or_default();88    write!(stdout, "{}", style.paint(&path_str[offset..]))?;8990    if config.null_separator {91        write!(stdout, "\0")?;92    } else {93        writeln!(stdout)?;94    }9596    if wants_to_quit.load(Ordering::Relaxed) {97        ExitCode::KilledBySigint.exit();98    }99100    Ok(())101}102103// TODO: this function is performance critical and can probably be optimized104fn print_entry_uncolorized_base(105    stdout: &mut StdoutLock,106    path: &Path,107    config: &Config,108) -> io::Result<()> {109    let separator = if config.null_separator { "\0" } else { "\n" };110111    let mut path_string = path.to_string_lossy();112    if let Some(ref separator) = config.path_separator {113        *path_string.to_mut() = replace_path_separator(&path_string, separator);114    }115    write!(stdout, "{}{}", path_string, separator)116}117118#[cfg(not(unix))]119fn print_entry_uncolorized(120    stdout: &mut StdoutLock,121    path: &Path,122    config: &Config,123) -> io::Result<()> {124    print_entry_uncolorized_base(stdout, path, config)125}126127#[cfg(unix)]128fn print_entry_uncolorized(129    stdout: &mut StdoutLock,130    path: &Path,131    config: &Config,132) -> io::Result<()> {133    use std::os::unix::ffi::OsStrExt;134135    if config.interactive_terminal || config.path_separator.is_some() {136        // Fall back to the base implementation137        print_entry_uncolorized_base(stdout, path, config)138    } else {139        // Print path as raw bytes, allowing invalid UTF-8 filenames to be passed to other processes140        let separator = if config.null_separator { b"\0" } else { b"\n" };141        stdout.write_all(path.as_os_str().as_bytes())?;142        stdout.write_all(separator)143    }144}