output.rs
This file
Path
src/output.rs
160 lines · 4.8 KiB · Rust
Last changed by
Merge pull request #1192 from tmccombs/ansi-term-deprecatedTavian Barnesbefore adoption6e3eb26
History of this fileTake 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::error::print_error;9use crate::exit_codes::ExitCode;1011fn replace_path_separator(path: &str, new_path_separator: &str) -> String {12 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)13}1415// TODO: this function is performance critical and can probably be optimized16pub fn print_entry<W: Write>(stdout: &mut W, entry: &DirEntry, config: &Config) {17 let r = if let Some(ref ls_colors) = config.ls_colors {18 print_entry_colorized(stdout, entry, config, ls_colors)19 } else {20 print_entry_uncolorized(stdout, entry, config)21 };2223 if let Err(e) = r {24 if e.kind() == ::std::io::ErrorKind::BrokenPipe {25 // Exit gracefully in case of a broken pipe (e.g. 'fd ... | head -n 3').26 ExitCode::Success.exit();27 } else {28 print_error(format!("Could not write to output: {}", e));29 ExitCode::GeneralError.exit();30 }31 }32}3334// Display a trailing slash if the path is a directory and the config option is enabled.35// If the path_separator option is set, display that instead.36// The trailing slash will not be colored.37#[inline]38fn print_trailing_slash<W: Write>(39 stdout: &mut W,40 entry: &DirEntry,41 config: &Config,42 style: Option<&Style>,43) -> io::Result<()> {44 if entry.file_type().map_or(false, |ft| ft.is_dir()) {45 write!(46 stdout,47 "{}",48 style49 .map(Style::to_nu_ansi_term_style)50 .unwrap_or_default()51 .paint(&config.actual_path_separator)52 )?;53 }54 Ok(())55}5657// TODO: this function is performance critical and can probably be optimized58fn print_entry_colorized<W: Write>(59 stdout: &mut W,60 entry: &DirEntry,61 config: &Config,62 ls_colors: &LsColors,63) -> io::Result<()> {64 // Split the path between the parent and the last component65 let mut offset = 0;66 let path = entry.stripped_path(config);67 let path_str = path.to_string_lossy();6869 if let Some(parent) = path.parent() {70 offset = parent.to_string_lossy().len();71 for c in path_str[offset..].chars() {72 if std::path::is_separator(c) {73 offset += c.len_utf8();74 } else {75 break;76 }77 }78 }7980 if offset > 0 {81 let mut parent_str = Cow::from(&path_str[..offset]);82 if let Some(ref separator) = config.path_separator {83 *parent_str.to_mut() = replace_path_separator(&parent_str, separator);84 }8586 let style = ls_colors87 .style_for_indicator(Indicator::Directory)88 .map(Style::to_nu_ansi_term_style)89 .unwrap_or_default();90 write!(stdout, "{}", style.paint(parent_str))?;91 }9293 let style = entry94 .style(ls_colors)95 .map(Style::to_nu_ansi_term_style)96 .unwrap_or_default();97 write!(stdout, "{}", style.paint(&path_str[offset..]))?;9899 print_trailing_slash(100 stdout,101 entry,102 config,103 ls_colors.style_for_indicator(Indicator::Directory),104 )?;105106 if config.null_separator {107 write!(stdout, "\0")?;108 } else {109 writeln!(stdout)?;110 }111112 Ok(())113}114115// TODO: this function is performance critical and can probably be optimized116fn print_entry_uncolorized_base<W: Write>(117 stdout: &mut W,118 entry: &DirEntry,119 config: &Config,120) -> io::Result<()> {121 let separator = if config.null_separator { "\0" } else { "\n" };122 let path = entry.stripped_path(config);123124 let mut path_string = path.to_string_lossy();125 if let Some(ref separator) = config.path_separator {126 *path_string.to_mut() = replace_path_separator(&path_string, separator);127 }128 write!(stdout, "{}", path_string)?;129 print_trailing_slash(stdout, entry, config, None)?;130 write!(stdout, "{}", separator)131}132133#[cfg(not(unix))]134fn print_entry_uncolorized<W: Write>(135 stdout: &mut W,136 entry: &DirEntry,137 config: &Config,138) -> io::Result<()> {139 print_entry_uncolorized_base(stdout, entry, config)140}141142#[cfg(unix)]143fn print_entry_uncolorized<W: Write>(144 stdout: &mut W,145 entry: &DirEntry,146 config: &Config,147) -> io::Result<()> {148 use std::os::unix::ffi::OsStrExt;149150 if config.interactive_terminal || config.path_separator.is_some() {151 // Fall back to the base implementation152 print_entry_uncolorized_base(stdout, entry, config)153 } else {154 // Print path as raw bytes, allowing invalid UTF-8 filenames to be passed to other processes155 let separator = if config.null_separator { b"\0" } else { b"\n" };156 stdout.write_all(entry.stripped_path(config).as_os_str().as_bytes())?;157 print_trailing_slash(stdout, entry, config, None)?;158 stdout.write_all(separator)159 }160}