Refactor path handling (fixes #113)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Fix path check * Fix full path matching * Allow more simple driver names in Windows tests * Factor out special is_dir() check for "." and ".."
authored by J.W · committed by David Peter · parent 37def9b · Browse files · 9 files·+112 added−126 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+112 added−126 removed
- tests:+68 added−15 removed
- other:+44 added−111 removed
Provenance
- Commit
8d85deb- Tree
888831f- Author
J.W <iology@users.noreply.github.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
37def9b
9 files changed+112 added−126 removed
modified:src/exec/job.rs+1 added-7 removed
7 unmodified lines8 /// generate a command with the supplied command template. The generated command will then9 /// be executed, and this process will continue until the receiver's sender has closed.10 pub fn job(11 rx: Arc<Mutex<Receiver<PathBuf>>>,12- base: Arc<Option<PathBuf>>,12 cmd: Arc<TokenizedCommand>,13 out_perm: Arc<Mutex<()>>,14 ) {15 // A string buffer that will be re-used in each iteration.5 unmodified lines21 22 // Obtain the next path from the receiver, else if the channel23 // has closed, exit from the loop24 let value: PathBuf = match lock.recv() {26- Ok(value) => {27- match *base {28- Some(ref base) => base.join(&value),29- None => value,30- }31- }25+ Ok(value) => value,26 Err(_) => break,27 };28 29 // Drop the lock so that other threads can read from the the receiver.7 unmodified linesmodified:src/exec/mod.rs+2 added
107 unmodified lines108 command: &'a mut String,109 input: &Path,110 out_perm: Arc<Mutex<()>>,111 ) -> CommandTicket<'a> {112+ let input = input.strip_prefix(".").unwrap_or(input);113+114 for token in &self.tokens {115 match *token {116 Token::Basename => *command += basename(&input.to_string_lossy()),117 Token::BasenameNoExt => {48 unmodified linesmodified:src/fshelper/mod.rs+17 added-39 removed
1+use std::env::current_dir;2 use std::path::{Path, PathBuf};3 use std::io;4 4-/// Get a relative path with respect to a certain base path.5-/// See: https://stackoverflow.com/a/39343127/7048316-pub fn path_relative_from(path: &Path, base: &Path) -> Option<PathBuf> {7- use std::path::Component;8-9- if path.is_absolute() != base.is_absolute() {10- if path.is_absolute() {11- Some(PathBuf::from(path))12- } else {13- Some(PathBuf::from(base.join(path)))14- }5+pub fn path_absolute_form(path: &Path) -> io::Result<PathBuf> {6+ if path.is_absolute() {7+ Ok(path.to_path_buf())8 } else {16- let mut ita = path.components();17- let mut itb = base.components();18- let mut comps: Vec<Component> = vec![];19- loop {20- match (ita.next(), itb.next()) {21- (None, None) => break,22- (Some(a), None) => {23- comps.push(a);24- comps.extend(ita.by_ref());25- break;26- }27- (None, _) => comps.push(Component::ParentDir),28- (Some(a), Some(b)) if comps.is_empty() && a == b => (),29- (Some(a), Some(b)) if b == Component::CurDir => comps.push(a),30- (Some(_), Some(b)) if b == Component::ParentDir => return None,31- (Some(a), Some(_)) => {32- comps.push(Component::ParentDir);33- for _ in itb {34- comps.push(Component::ParentDir);35- }36- comps.push(a);37- comps.extend(ita.by_ref());38- break;39- }40- }41- }42- Some(comps.iter().map(|c| c.as_os_str()).collect())9+ let path = path.strip_prefix(".").unwrap_or(path);10+ current_dir().map(|path_buf| path_buf.join(path))11 }12 }13 14 pub fn absolute_path(path: &Path) -> io::Result<PathBuf> {47- let path_buf = path.canonicalize()?;15+ let path_buf = path_absolute_form(path)?;16 17 #[cfg(windows)]18 let path_buf = Path::new(path_buf.as_path().to_string_lossy().trim_left_matches(19 r"\\?\",20 )).to_path_buf();21 22 Ok(path_buf)23 }24+25+// Path::is_dir() is not guarandteed to be intuitively correct for "." and ".."26+// See: https://github.com/rust-lang/rust/issues/4530227+pub fn is_dir(path: &Path) -> bool {28+ if path.file_name().is_some() {29+ path.is_dir()30+ } else {31+ path.is_dir() && path.canonicalize().is_ok()32+ }33+}modified:src/internal.rs-7 removed
5 unmodified lines6 use lscolors::LsColors;7 use walk::FileType;8 use regex_syntax::{Expr, ExprBuilder};9 10-/// Root directory11-#[cfg(unix)]12-pub static ROOT_DIR: &'static str = "/";13-14-#[cfg(windows)]15-pub static ROOT_DIR: &'static str = "";16-10 /// Defines how to display search result paths.11 #[derive(PartialEq)]12 pub enum PathDisplay {13 /// As an absolute path90 unmodified linesmodified:src/main.rs+4 added-15 removed
27 unmodified lines28 use atty::Stream;29 use regex::RegexBuilder;30 31 use exec::TokenizedCommand;32-use internal::{error, pattern_has_uppercase_char, FdOptions, PathDisplay, ROOT_DIR};32+use internal::{error, pattern_has_uppercase_char, FdOptions, PathDisplay};33 use lscolors::LsColors;34 use walk::FileType;35 36 fn main() {4 unmodified lines41 let pattern = matches.value_of("pattern").unwrap_or(&empty_pattern);42 43 // Get the current working directory44 let current_dir = Path::new(".");45- // .is_dir() is not guarandteed to be intuitively correct for "." and ".."46- if let Err(_) = current_dir.canonicalize() {45+ if !fshelper::is_dir(¤t_dir) {46 error("Error: could not get current directory.");47 }48 49 // Get the root directory for the search50 let mut root_dir_buf = match matches.value_of("path") {51 Some(path) => PathBuf::from(path),52 None => current_dir.to_path_buf(),53 };55- if let Err(_) = root_dir_buf.canonicalize() {54+ if !fshelper::is_dir(&root_dir_buf) {55 error(&format!(56 "Error: '{}' is not a directory.",57 root_dir_buf.to_string_lossy()58 ));71 unmodified lines130 }),131 command,132 };133 135- // If base_dir is ROOT_DIR, then root_dir must be absolute.136- // Otherwise root_dir/entry cannot be turned into an existing relative path from base_dir.137- //138- // We utilize ROOT_DIR to avoid resolving the components of root_dir.139- let base_dir_buf = match config.path_display {140- PathDisplay::Relative => current_dir.to_path_buf(),141- PathDisplay::Absolute => PathBuf::from(ROOT_DIR),142- };143- let base_dir = base_dir_buf.as_path();144-134 match RegexBuilder::new(pattern)135 .case_insensitive(!config.case_sensitive)136 .dot_matches_new_line(true)137 .build() {149- Ok(re) => walk::scan(root_dir, Arc::new(re), base_dir, Arc::new(config)),138+ Ok(re) => walk::scan(root_dir, Arc::new(re), Arc::new(config)),139 Err(err) => error(err.description()),140 }141 }modified:src/output.rs+7 added-22 removed
1-use internal::{FdOptions, PathDisplay};1+use internal::FdOptions;2 use lscolors::LsColors;3 4 use std::{fs, process};5 use std::io::{self, Write};3 unmodified lines9 use std::os::unix::fs::PermissionsExt;10 11 use ansi_term;12 13-pub fn print_entry(base: &Path, entry: &PathBuf, config: &FdOptions) {14- let path_full = if !entry.as_os_str().is_empty() {15- base.join(entry)16- } else {17- base.to_path_buf()18- };13+pub fn print_entry(entry: &PathBuf, config: &FdOptions) {14+ let path = entry.strip_prefix(".").unwrap_or(entry);15 20- let path_to_print = if config.path_display == PathDisplay::Absolute {21- &path_full22- } else {23- entry24- };25-16 let r = if let Some(ref ls_colors) = config.ls_colors {27- print_entry_colorized(base, path_to_print, config, ls_colors)17+ print_entry_colorized(path, config, ls_colors)18 } else {29- print_entry_uncolorized(path_to_print, config)19+ print_entry_uncolorized(path, config)20 };21 22 if r.is_err() {23 // Probably a broken pipe. Exit gracefully.24 process::exit(0);25 }26 }27 38-fn print_entry_colorized(39- base: &Path,40- path: &Path,41- config: &FdOptions,42- ls_colors: &LsColors,43-) -> io::Result<()> {28+fn print_entry_colorized(path: &Path, config: &FdOptions, ls_colors: &LsColors) -> io::Result<()> {29 let default_style = ansi_term::Style::default();30 31 let stdout = io::stdout();32 let mut handle = stdout.lock();1 unmodified line34 // Separator to use before the current component.35 let mut separator = String::new();36 37 // Full path to the current component.53- let mut component_path = base.to_path_buf();38+ let mut component_path = PathBuf::new();39 40 // Traverse the path and colorize each component41 for component in path.components() {42 let comp_str = component.as_os_str().to_string_lossy();71 unmodified linesmodified:src/walk.rs+13 added-21 removed
1 use exec::{self, TokenizedCommand};2 use fshelper;3-use internal::{error, FdOptions, PathDisplay};3+use internal::{error, FdOptions};4 use output;5 6 use std::path::Path;7 use std::sync::{Arc, Mutex};27 unmodified lines35 ///36 /// If the `--exec` argument was supplied, this will create a thread pool for executing37 /// jobs in parallel from a given command line and the discovered paths. Otherwise, each38 /// path will simply be written to standard output.39-pub fn scan(root: &Path, pattern: Arc<Regex>, base: &Path, config: Arc<FdOptions>) {39+pub fn scan(root: &Path, pattern: Arc<Regex>, config: Arc<FdOptions>) {40 let (tx, rx) = channel();41 let threads = config.threads;42 43 let walker = WalkBuilder::new(root)9 unmodified lines53 .build_parallel();54 55 // Spawn the thread that receives all results through the channel.56 let rx_config = Arc::clone(&config);57- let rx_base = base.to_owned();58- let is_absolute = config.path_display == PathDisplay::Absolute;57 let receiver_thread = thread::spawn(move || {58 // This will be set to `Some` if the `--exec` argument was supplied.59 if let Some(ref cmd) = rx_config.command {60 let shared_rx = Arc::new(Mutex::new(rx));61 62 let out_perm = Arc::new(Mutex::new(()));63 66- let base = Arc::new(if is_absolute { Some(rx_base) } else { None });67-64 // This is safe because `cmd` will exist beyond the end of this scope.65 // It's required to tell Rust that it's safe to share across threads.66 let cmd = unsafe { Arc::from_raw(cmd as *const TokenizedCommand) };67 1 unmodified line69 let mut handles = Vec::with_capacity(threads);70 for _ in 0..threads {71 let rx = shared_rx.clone();72 let cmd = cmd.clone();77- let base = base.clone();73 let out_perm = out_perm.clone();74 75 // Spawn a job thread that will listen for and execute inputs.81- let handle = thread::spawn(move || exec::job(rx, base, cmd, out_perm));76+ let handle = thread::spawn(move || exec::job(rx, cmd, out_perm));77 78 // Push the handle of the spawned thread into the vector for later joining.79 handles.push(handle);80 }23 unmodified lines104 // Have we reached the maximum time?105 if time::Instant::now() - start > max_buffer_time {106 // Flush the buffer107 for v in &buffer {113- output::print_entry(&rx_base, v, &rx_config);108+ output::print_entry(&v, &rx_config);109 }110 buffer.clear();111 112 // Start streaming113 mode = ReceiverMode::Streaming;114 }115 }116 ReceiverMode::Streaming => {122- output::print_entry(&rx_base, &value, &rx_config);117+ output::print_entry(&value, &rx_config);118 }119 }120 }121 1 unmodified line123 // anything to the console, yet. In this case, sort the results and print them:124 if !buffer.is_empty() {125 buffer.sort();126 for value in buffer {132- output::print_entry(&rx_base, &value, &rx_config);127+ output::print_entry(&value, &rx_config);128 }129 }130 }131 });132 133 // Spawn the sender threads.134 walker.run(|| {140- let base = base.to_owned();135 let config = Arc::clone(&config);136 let pattern = Arc::clone(&pattern);137 let tx_thread = tx.clone();138 let root = root.to_owned();40 unmodified lines179 }180 }181 182 let search_str_o = if config.search_full_path {189- Some(entry_path.to_string_lossy())183+ match fshelper::path_absolute_form(&entry_path) {184+ Ok(path_abs_buf) => Some(path_abs_buf.to_string_lossy().into_owned().into()),185+ Err(_) => error("Error: unable to get full path."),186+ }187 } else {188 entry_path.file_name().map(|f| f.to_string_lossy())189 };190 191 if let Some(search_str) = search_str_o {195- pattern.find(&*search_str).map(|_| {196- let path_rel_buf = match fshelper::path_relative_from(entry_path, &*base) {197- Some(p) => p,198- None => error("Error: could not get relative path for directory entry."),199- };200-192+ if pattern.is_match(&*search_str) {193 // TODO: take care of the unwrap call202- tx_thread.send(path_rel_buf.to_owned()).unwrap()203- });194+ tx_thread.send(entry_path.to_owned()).unwrap()195+ }196 }197 198 ignore::WalkState::Continue199 })9 unmodified linesmodified:tests/testenv/mod.rs+7 added-1 removed
134 unmodified lines135 }136 }137 138 /// Get the root directory for the tests.139- pub fn root(&self) -> PathBuf {139+ pub fn test_root(&self) -> PathBuf {140 self.temp_dir.path().to_path_buf()141 }142 143+ /// Get the root directory of the file system.144+ pub fn system_root(&self) -> PathBuf {145+ let mut components = self.temp_dir.path().components();146+ PathBuf::from(components.next().expect("root directory").as_os_str())147+ }148+149 /// Assert that calling *fd* with the specified arguments produces the expected output.150 pub fn assert_output(&self, args: &[&str], expected: &str) {151 self.assert_output_subdirectory(".", args, expected)152 }32 unmodified linesmodified:tests/tests.rs+61 added-14 removed
1 //! Integration tests for the CLI interface of fd.2 3+extern crate regex;4+5 mod testenv;6 7 use testenv::TestEnv;8+use regex::escape;9 10 fn get_absolute_root_path(env: &TestEnv) -> String {8- let path = env.root()11+ let path = env.test_root()12 .canonicalize()13 .expect("absolute path")14 .to_str()15 .expect("string")163 unmodified lines179 #[test]180 fn test_full_path() {181 let te = TestEnv::new();182 183+ let root = te.system_root();184+ let prefix = escape(&root.to_string_lossy());185+186 te.assert_output(181- &["--full-path", "three.*foo"],187+ &[188+ "--full-path",189+ &format!("^{prefix}.*three.*foo$", prefix = prefix),190+ ],191 "one/two/three/d.foo192 one/two/three/directory_foo",193 );194 }156 unmodified lines351 {abs_path}/one/two/three352 {abs_path}/one/two/three/d.foo353 {abs_path}/one/two/three/directory_foo354 {abs_path}/symlink",346- abs_path = abs_path355+ abs_path = &abs_path356 ),357 );358 359 te.assert_output(4 unmodified lines364 {abs_path}/one/two/c.foo365 {abs_path}/one/two/C.Foo2366 {abs_path}/one/two/three/d.foo367 {abs_path}/one/two/three/directory_foo",359- abs_path = abs_path368+ abs_path = &abs_path369 ),370 );371 372 te.assert_output(4 unmodified lines377 {abs_path}/one/two/c.foo378 {abs_path}/one/two/C.Foo2379 {abs_path}/one/two/three/d.foo380 {abs_path}/one/two/three/directory_foo",372- abs_path = abs_path381+ abs_path = &abs_path382 ),383 );384 }385 57 unmodified lines443 // The getcwd() function shall place an absolute pathname of the current working directory in444 // the array pointed to by buf, and return buf. The pathname shall contain no components that445 // are dot or dot-dot, or are symbolic links.446 //438- // Symlinks on Unix are aliases to real paths, only has one redirection.447+ // Key points:448+ // 1. The path of the current working directory of a Unix process cannot contain symlinks.449+ // 2. The path of the current working directory of a Windows process can contain symlinks.450 //440- // Symlinks on Windows can refer to symlinks, and are resolved after logical step "..".451+ // More:452+ // 1. On Windows, symlinks are resolved after the ".." component.453+ // 2. On Unix, symlinks are resolved immediately as encountered.454 455 let parent_parent = if cfg!(windows) { ".." } else { "../.." };456 te.assert_output_subdirectory(457 "symlink",16 unmodified lines474 te.assert_output_subdirectory(475 "symlink",476 &["--absolute-path"],477 &format!(465- "{abs_path}/one/two/c.foo466- {abs_path}/one/two/C.Foo2467- {abs_path}/one/two/three468- {abs_path}/one/two/three/d.foo469- {abs_path}/one/two/three/directory_foo",470- abs_path = abs_path478+ "{abs_path}/{dir}/c.foo479+ {abs_path}/{dir}/C.Foo2480+ {abs_path}/{dir}/three481+ {abs_path}/{dir}/three/d.foo482+ {abs_path}/{dir}/three/directory_foo",483+ dir = if cfg!(windows) { "symlink" } else { "one/two" },484+ abs_path = &abs_path485 ),486 );487 488 te.assert_output(3 unmodified lines492 {abs_path}/symlink/C.Foo2493 {abs_path}/symlink/three494 {abs_path}/symlink/three/d.foo495 {abs_path}/symlink/three/directory_foo",482- abs_path = abs_path496+ abs_path = &abs_path497 ),498 );499+500+ let root = te.system_root();501+ let prefix = escape(&root.to_string_lossy());502+503+ te.assert_output_subdirectory(504+ "symlink",505+ &[506+ "--absolute-path",507+ "--full-path",508+ &format!("^{prefix}.*three", prefix = prefix),509+ ],510+ &format!(511+ "{abs_path}/{dir}/three512+ {abs_path}/{dir}/three/d.foo513+ {abs_path}/{dir}/three/directory_foo",514+ dir = if cfg!(windows) { "symlink" } else { "one/two" },515+ abs_path = &abs_path516+ ),517+ );518+519+ te.assert_output(520+ &[521+ "--full-path",522+ &format!("^{prefix}.*symlink.*three", prefix = prefix),523+ &format!("{abs_path}/symlink", abs_path = abs_path),524+ ],525+ &format!(526+ "{abs_path}/symlink/three527+ {abs_path}/symlink/three/d.foo528+ {abs_path}/symlink/three/directory_foo",529+ abs_path = &abs_path530+ ),531+ );532 }