dir_entry.rs
This file
Path
src/dir_entry.rs
191 lines · 5.3 KiB · Rust
Last changed by
Merge pull request #2039 from hexbinoct/fix/min-depth-broken-symlinkThayne McCombsbefore adoptionce97e47
History of this fileTake it
1use std::cell::OnceCell;2use std::ffi::OsString;3use std::fs::{FileType, Metadata};4use std::path::{Path, PathBuf};56use lscolors::{Colorable, LsColors, Style};78use crate::config::Config;9use crate::filesystem::strip_current_dir;1011#[derive(Debug)]12enum DirEntryInner {13 Normal(ignore::DirEntry),14 // Broken symlinks reach us as walk errors rather than entries, so we carry15 // over the depth the walker recorded on the error.16 BrokenSymlink { path: PathBuf, depth: Option<usize> },17}1819#[derive(Debug)]20pub struct DirEntry {21 inner: DirEntryInner,22 metadata: OnceCell<Option<Metadata>>,23 style: OnceCell<Option<Style>>,24}2526impl DirEntry {27 #[inline]28 pub fn normal(e: ignore::DirEntry) -> Self {29 Self {30 inner: DirEntryInner::Normal(e),31 metadata: OnceCell::new(),32 style: OnceCell::new(),33 }34 }3536 pub fn broken_symlink(path: PathBuf, depth: Option<usize>) -> Self {37 Self {38 inner: DirEntryInner::BrokenSymlink { path, depth },39 metadata: OnceCell::new(),40 style: OnceCell::new(),41 }42 }4344 pub fn path(&self) -> &Path {45 match &self.inner {46 DirEntryInner::Normal(e) => e.path(),47 DirEntryInner::BrokenSymlink { path, .. } => path.as_path(),48 }49 }5051 pub fn into_path(self) -> PathBuf {52 match self.inner {53 DirEntryInner::Normal(e) => e.into_path(),54 DirEntryInner::BrokenSymlink { path, .. } => path,55 }56 }5758 /// Returns the path as it should be presented to the user.59 /// When stripping `./` would leave the path starting with `-`, keep the original60 /// (with `./`) so downstream tools don't interpret it as an option.61 pub fn stripped_path(&self, config: &Config) -> &Path {62 let path = self.path();63 if config.strip_cwd_prefix {64 let stripped = strip_current_dir(path);65 if starts_with_dash(stripped) {66 path67 } else {68 stripped69 }70 } else {71 path72 }73 }7475 /// Returns the path as it should be presented to the user.76 pub fn into_stripped_path(self, config: &Config) -> PathBuf {77 if config.strip_cwd_prefix {78 self.stripped_path(config).to_path_buf()79 } else {80 self.into_path()81 }82 }8384 pub fn file_type(&self) -> Option<FileType> {85 match &self.inner {86 DirEntryInner::Normal(e) => e.file_type(),87 DirEntryInner::BrokenSymlink { .. } => self.metadata().map(|m| m.file_type()),88 }89 }9091 pub fn metadata(&self) -> Option<&Metadata> {92 self.metadata93 .get_or_init(|| match &self.inner {94 DirEntryInner::Normal(e) => e.metadata().ok(),95 DirEntryInner::BrokenSymlink { path, .. } => path.symlink_metadata().ok(),96 })97 .as_ref()98 }99100 pub fn depth(&self) -> Option<usize> {101 match &self.inner {102 DirEntryInner::Normal(e) => Some(e.depth()),103 DirEntryInner::BrokenSymlink { depth, .. } => *depth,104 }105 }106107 pub fn style(&self, ls_colors: &LsColors) -> Option<&Style> {108 self.style109 .get_or_init(|| ls_colors.style_for(self).cloned())110 .as_ref()111 }112}113114fn starts_with_dash(path: &Path) -> bool {115 path.as_os_str().as_encoded_bytes().first() == Some(&b'-')116}117118impl PartialEq for DirEntry {119 #[inline]120 fn eq(&self, other: &Self) -> bool {121 self.path() == other.path()122 }123}124125impl Eq for DirEntry {}126127impl PartialOrd for DirEntry {128 #[inline]129 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {130 Some(self.cmp(other))131 }132}133134impl Ord for DirEntry {135 #[inline]136 fn cmp(&self, other: &Self) -> std::cmp::Ordering {137 self.path().cmp(other.path())138 }139}140141impl Colorable for DirEntry {142 fn path(&self) -> PathBuf {143 self.path().to_owned()144 }145146 fn file_name(&self) -> OsString {147 let name = match &self.inner {148 DirEntryInner::Normal(e) => e.file_name(),149 DirEntryInner::BrokenSymlink { path, .. } => {150 // Path::file_name() only works if the last component is Normal,151 // but we want it for all component types, so we open code it.152 // Copied from LsColors::style_for_path_with_metadata().153 path.components()154 .next_back()155 .map(|c| c.as_os_str())156 .unwrap_or_else(|| path.as_os_str())157 }158 };159 name.to_owned()160 }161162 fn file_type(&self) -> Option<FileType> {163 self.file_type()164 }165166 fn metadata(&self) -> Option<Metadata> {167 self.metadata().cloned()168 }169}170171#[cfg(test)]172mod tests {173 use super::starts_with_dash;174 use std::path::Path;175176 #[test]177 fn dash_prefixed_paths_detected() {178 assert!(starts_with_dash(Path::new("-rf")));179 assert!(starts_with_dash(Path::new("--delete")));180 assert!(starts_with_dash(Path::new("-")));181 }182183 #[test]184 fn safe_paths_not_flagged() {185 assert!(!starts_with_dash(Path::new("foo")));186 assert!(!starts_with_dash(Path::new("./foo")));187 assert!(!starts_with_dash(Path::new("sub/-rf")));188 assert!(!starts_with_dash(Path::new("")));189 assert!(!starts_with_dash(Path::new(" -rf")));190 }191}