Skip to content
Myr

walk.rs

This file

Path

src/walk.rs

776 lines · 25.7 KiB · Rust

Last changed by

Merge pull request #2143 from tmccombs/broken-symlink-refactorThayne McCombsbefore adoption9fe5cb7

History of this file

Take it

1use std::borrow::Cow;2use std::ffi::OsStr;3use std::io::{self, Write};4use std::mem;5use std::path::PathBuf;6use std::sync::atomic::{AtomicBool, Ordering};7use std::sync::{Arc, Mutex, MutexGuard};8use std::thread;9use std::time::{Duration, Instant};1011use anyhow::{Result, anyhow};12use crossbeam_channel::{Receiver, RecvTimeoutError, SendError, Sender, bounded};13use etcetera::BaseStrategy;14use ignore::overrides::{Override, OverrideBuilder};15use ignore::{WalkBuilder, WalkParallel, WalkState};16use regex::bytes::Regex;1718use crate::config::Config;19use crate::dir_entry::DirEntry;20use crate::exec;21use crate::exit_codes::{ExitCode, merge_exitcodes};22use crate::filesystem;23use crate::output;2425/// The receiver thread can either be buffering results or directly streaming to the console.26#[derive(PartialEq)]27enum ReceiverMode {28    /// Receiver is still buffering in order to sort the results, if the search finishes fast29    /// enough.30    Buffering,3132    /// Receiver is directly printing results to the output.33    Streaming,34}3536/// The Worker threads can result in a valid entry having PathBuf or an error.37#[allow(clippy::large_enum_variant)]38#[derive(Debug)]39pub enum WorkerResult {40    // Errors should be rare, so it's probably better to allow large_enum_variant than41    // to box the Entry variant42    Entry(DirEntry),43    Error(ignore::Error),44}4546/// A batch of WorkerResults to send over a channel.47#[derive(Clone)]48struct Batch {49    items: Arc<Mutex<Option<Vec<WorkerResult>>>>,50}5152impl Batch {53    fn new() -> Self {54        Self {55            items: Arc::new(Mutex::new(Some(vec![]))),56        }57    }5859    fn lock(&self) -> MutexGuard<'_, Option<Vec<WorkerResult>>> {60        self.items.lock().unwrap()61    }62}6364impl IntoIterator for Batch {65    type Item = WorkerResult;66    type IntoIter = std::vec::IntoIter<WorkerResult>;6768    fn into_iter(self) -> Self::IntoIter {69        self.lock().take().unwrap().into_iter()70    }71}7273/// Wrapper that sends batches of items at once over a channel.74struct BatchSender {75    batch: Batch,76    tx: Sender<Batch>,77    limit: usize,78}7980impl BatchSender {81    fn new(tx: Sender<Batch>, limit: usize) -> Self {82        Self {83            batch: Batch::new(),84            tx,85            limit,86        }87    }8889    /// Check if we need to flush a batch.90    fn needs_flush(&self, batch: Option<&Vec<WorkerResult>>) -> bool {91        match batch {92            // Limit the batch size to provide some backpressure93            Some(vec) => vec.len() >= self.limit,94            // Batch was already taken by the receiver, so make a new one95            None => true,96        }97    }9899    /// Add an item to a batch.100    fn send(&mut self, item: WorkerResult) -> Result<(), SendError<()>> {101        let mut batch = self.batch.lock();102103        if self.needs_flush(batch.as_ref()) {104            drop(batch);105            self.batch = Batch::new();106            batch = self.batch.lock();107        }108109        let items = batch.as_mut().unwrap();110        items.push(item);111112        if items.len() == 1 {113            // New batch, send it over the channel114            self.tx115                .send(self.batch.clone())116                .map_err(|_| SendError(()))?;117        }118119        Ok(())120    }121}122123/// Maximum size of the output buffer before flushing results to the console124const MAX_BUFFER_LENGTH: usize = 1000;125/// Default duration until output buffering switches to streaming.126const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);127128/// Wrapper for the receiver thread's buffering behavior.129struct ReceiverBuffer<'a, W> {130    /// The configuration.131    config: &'a Config,132    /// For shutting down the senders.133    quit_flag: &'a AtomicBool,134    /// The ^C notifier.135    interrupt_flag: &'a AtomicBool,136    /// Receiver for worker results.137    rx: Receiver<Batch>,138    /// Standard output.139    stdout: W,140    /// The current buffer mode.141    mode: ReceiverMode,142    /// The deadline to switch to streaming mode.143    deadline: Instant,144    /// The buffer of quickly received paths.145    buffer: Vec<DirEntry>,146    /// Result count.147    num_results: usize,148}149150impl<'a, W: Write> ReceiverBuffer<'a, W> {151    /// Create a new receiver buffer.152    fn new(state: &'a WorkerState, rx: Receiver<Batch>, stdout: W) -> Self {153        let config = &state.config;154        let quit_flag = state.quit_flag.as_ref();155        let interrupt_flag = state.interrupt_flag.as_ref();156        let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);157        let deadline = Instant::now() + max_buffer_time;158159        Self {160            config,161            quit_flag,162            interrupt_flag,163            rx,164            stdout,165            mode: ReceiverMode::Buffering,166            deadline,167            buffer: Vec::with_capacity(MAX_BUFFER_LENGTH),168            num_results: 0,169        }170    }171172    /// Process results until finished.173    fn process(&mut self) -> ExitCode {174        loop {175            if let Err(ec) = self.poll() {176                self.quit_flag.store(true, Ordering::Relaxed);177                return ec;178            }179        }180    }181182    /// Receive the next worker result.183    fn recv(&self) -> Result<Batch, RecvTimeoutError> {184        match self.mode {185            ReceiverMode::Buffering => {186                // Wait at most until we should switch to streaming187                self.rx.recv_deadline(self.deadline)188            }189            ReceiverMode::Streaming => {190                // Wait however long it takes for a result191                Ok(self.rx.recv()?)192            }193        }194    }195196    /// Wait for a result or state change.197    fn poll(&mut self) -> Result<(), ExitCode> {198        match self.recv() {199            Ok(batch) => {200                for result in batch {201                    match result {202                        WorkerResult::Entry(dir_entry) => {203                            if self.config.quiet {204                                return Err(ExitCode::HasResults(true));205                            }206207                            match self.mode {208                                ReceiverMode::Buffering => {209                                    self.buffer.push(dir_entry);210                                    if self.buffer.len() > MAX_BUFFER_LENGTH {211                                        self.stream()?;212                                    }213                                }214                                ReceiverMode::Streaming => {215                                    self.print(&dir_entry)?;216                                }217                            }218219                            self.num_results += 1;220                            if let Some(max_results) = self.config.max_results221                                && self.num_results >= max_results222                            {223                                return self.stop();224                            }225                        }226                        WorkerResult::Error(err) => {227                            if self.config.show_filesystem_errors {228                                print_error!("{}", err);229                            }230                        }231                    }232                }233234                // If we don't have another batch ready, flush before waiting235                if self.mode == ReceiverMode::Streaming && self.rx.is_empty() {236                    self.flush()?;237                }238            }239            Err(RecvTimeoutError::Timeout) => {240                self.stream()?;241            }242            Err(RecvTimeoutError::Disconnected) => {243                return self.stop();244            }245        }246247        Ok(())248    }249250    /// Output a path.251    fn print(&mut self, entry: &DirEntry) -> Result<(), ExitCode> {252        if let Err(e) = output::print_entry(&mut self.stdout, entry, self.config)253            && e.kind() != ::std::io::ErrorKind::BrokenPipe254        {255            print_error!("Could not write to output: {}", e);256            return Err(ExitCode::GeneralError);257        }258259        if self.interrupt_flag.load(Ordering::Relaxed) {260            // Ignore any errors on flush, because we're about to exit anyway261            let _ = self.flush();262            return Err(ExitCode::KilledBySigint);263        }264265        Ok(())266    }267268    /// Switch ourselves into streaming mode.269    fn stream(&mut self) -> Result<(), ExitCode> {270        self.mode = ReceiverMode::Streaming;271272        let buffer = mem::take(&mut self.buffer);273        for path in buffer {274            self.print(&path)?;275        }276277        self.flush()278    }279280    /// Stop looping.281    fn stop(&mut self) -> Result<(), ExitCode> {282        if self.mode == ReceiverMode::Buffering {283            self.buffer.sort();284            self.stream()?;285        }286287        if self.config.quiet {288            Err(ExitCode::HasResults(self.num_results > 0))289        } else {290            Err(ExitCode::Success)291        }292    }293294    /// Flush stdout if necessary.295    fn flush(&mut self) -> Result<(), ExitCode> {296        if self.stdout.flush().is_err() {297            // Probably a broken pipe. Exit gracefully.298            return Err(ExitCode::GeneralError);299        }300        Ok(())301    }302}303304/// State shared by the sender and receiver threads.305struct WorkerState {306    /// The search patterns.307    patterns: Vec<Regex>,308    /// The command line configuration.309    config: Config,310    /// Flag for cleanly shutting down the parallel walk311    quit_flag: Arc<AtomicBool>,312    /// Flag specifically for quitting due to ^C313    interrupt_flag: Arc<AtomicBool>,314}315316impl WorkerState {317    fn new(patterns: Vec<Regex>, config: Config) -> Self {318        let quit_flag = Arc::new(AtomicBool::new(false));319        let interrupt_flag = Arc::new(AtomicBool::new(false));320321        Self {322            patterns,323            config,324            quit_flag,325            interrupt_flag,326        }327    }328329    fn build_overrides(&self, paths: &[PathBuf]) -> Result<Override> {330        let first_path = &paths[0];331        let config = &self.config;332333        let mut builder = OverrideBuilder::new(first_path);334335        for pattern in &config.exclude_patterns {336            builder337                .add(pattern)338                .map_err(|e| anyhow!("Malformed exclude pattern: {}", e))?;339        }340341        builder342            .build()343            .map_err(|_| anyhow!("Mismatch in exclude patterns"))344    }345346    fn build_walker(&self, paths: &[PathBuf]) -> Result<WalkParallel> {347        let first_path = &paths[0];348        let config = &self.config;349        let overrides = self.build_overrides(paths)?;350351        let mut builder = WalkBuilder::new(first_path);352        builder353            .hidden(config.ignore_hidden)354            .ignore(config.read_fdignore)355            .parents(config.read_parent_ignore && (config.read_fdignore || config.read_vcsignore))356            .git_ignore(config.read_vcsignore)357            .git_global(config.read_vcsignore)358            .git_exclude(config.read_vcsignore)359            .require_git(config.require_git_to_read_vcsignore)360            .overrides(overrides)361            .follow_links(config.follow_links)362            // No need to check for supported platforms, option is unavailable on unsupported ones363            .same_file_system(config.one_file_system)364            .max_depth(config.max_depth);365366        if config.read_fdignore {367            builder.add_custom_ignore_filename(".fdignore");368        }369370        if config.read_global_ignore371            && let Ok(basedirs) = etcetera::choose_base_strategy()372        {373            let global_ignore_file = basedirs.config_dir().join("fd").join("ignore");374            if global_ignore_file.is_file() {375                let result = builder.add_ignore(global_ignore_file);376                match result {377                    Some(ignore::Error::Partial(_)) => (),378                    Some(err) => {379                        print_error!("Malformed pattern in global ignore file. {}.", err);380                    }381                    None => (),382                }383            }384        }385386        for ignore_file in &config.ignore_files {387            let result = builder.add_ignore(ignore_file);388            match result {389                Some(ignore::Error::Partial(_)) => (),390                Some(err) => {391                    print_error!("Malformed pattern in custom ignore file. {}.", err);392                }393                None => (),394            }395        }396397        for path in &paths[1..] {398            builder.add(path);399        }400401        let walker = builder.threads(config.threads).build_parallel();402        Ok(walker)403    }404405    /// Run the receiver work, either on this thread or a pool of background406    /// threads (for --exec).407    fn receive(&self, rx: Receiver<Batch>) -> ExitCode {408        let config = &self.config;409410        // This will be set to `Some` if the `--exec` argument was supplied.411        if let Some(ref cmd) = config.command {412            if cmd.in_batch_mode() {413                exec::batch(rx.into_iter().flatten(), cmd, config)414            } else {415                thread::scope(|scope| {416                    // Each spawned job will store its thread handle in here.417                    let threads = config.threads;418                    let mut handles = Vec::with_capacity(threads);419                    for _ in 0..threads {420                        let rx = rx.clone();421422                        // Spawn a job thread that will listen for and execute inputs.423                        let handle =424                            scope.spawn(|| exec::job(rx.into_iter().flatten(), cmd, config));425426                        // Push the handle of the spawned thread into the vector for later joining.427                        handles.push(handle);428                    }429                    let exit_codes = handles.into_iter().map(|handle| handle.join().unwrap());430                    merge_exitcodes(exit_codes)431                })432            }433        } else {434            let stdout = io::stdout().lock();435            let stdout = io::BufWriter::new(stdout);436437            ReceiverBuffer::new(self, rx, stdout).process()438        }439    }440441    /// Spawn the sender threads.442    fn spawn_senders(&self, walker: WalkParallel, tx: Sender<Batch>) {443        walker.run(|| {444            let patterns = &self.patterns;445            let config = &self.config;446            let quit_flag = self.quit_flag.as_ref();447448            let mut limit = 0x100;449            if let Some(cmd) = &config.command450                && !cmd.in_batch_mode()451                && config.threads > 1452            {453                // Evenly distribute work between multiple receivers454                limit = 1;455            }456            let mut tx = BatchSender::new(tx.clone(), limit);457458            Box::new(move |entry| {459                if quit_flag.load(Ordering::Relaxed) {460                    return WalkState::Quit;461                }462463                if let Ok(e) = &entry {464                    // If the entry is a directory that contains a465                    // "ignore contain" file", we want to skip this466                    // directory.467                    // Check the filetype first to avoid unnecessary468                    // syscalls.469                    if e.file_type().is_some_and(|t| t.is_dir()) {470                        let entry_path = e.path();471                        if config472                            .ignore_contain473                            .iter()474                            .any(|ic| entry_path.join(ic).exists())475                        {476                            return WalkState::Skip;477                        }478                    }479                    if e.depth() == 0 {480                        // Skip the root directory entry.481                        return WalkState::Continue;482                    }483                }484                let entry = match entry {485                    Ok(e) => DirEntry::normal(e),486                    Err(err) => match broken_symlink_from_err(err) {487                        Ok(entry) => entry,488                        Err(err) => {489                            return match tx.send(WorkerResult::Error(err)) {490                                Ok(_) => WalkState::Continue,491                                Err(_) => WalkState::Quit,492                            };493                        }494                    },495                };496497                if let Some(min_depth) = config.min_depth498                    && entry.depth().is_none_or(|d| d < min_depth)499                {500                    return WalkState::Continue;501                }502503                // Check the name first, since it doesn't require metadata504                let entry_path = entry.path();505506                let search_str = search_str_for_entry(entry_path, config.full_path_base.as_deref());507508                if !patterns509                    .iter()510                    .all(|pat| pat.is_match(&filesystem::osstr_to_bytes(search_str.as_ref())))511                {512                    return WalkState::Continue;513                }514515                // Filter out unwanted extensions.516                if let Some(ref exts_regex) = config.extensions {517                    if let Some(path_str) = entry_path.file_name() {518                        if !exts_regex.is_match(&filesystem::osstr_to_bytes(path_str)) {519                            return WalkState::Continue;520                        }521                    } else {522                        return WalkState::Continue;523                    }524                }525526                // Filter out unwanted file types.527                if let Some(ref file_types) = config.file_types528                    && file_types.should_ignore(&entry)529                {530                    return WalkState::Continue;531                }532533                #[cfg(unix)]534                {535                    if let Some(ref owner_constraint) = config.owner_constraint {536                        if let Some(metadata) = entry.metadata() {537                            if !owner_constraint.matches(metadata) {538                                return WalkState::Continue;539                            }540                        } else {541                            return WalkState::Continue;542                        }543                    }544                }545546                // Filter out unwanted sizes if it is a file and we have been given size constraints.547                if !config.size_constraints.is_empty() {548                    if entry_path.is_file() {549                        if let Some(metadata) = entry.metadata() {550                            let file_size = metadata.len();551                            if config552                                .size_constraints553                                .iter()554                                .any(|sc| !sc.is_within(file_size))555                            {556                                return WalkState::Continue;557                            }558                        } else {559                            return WalkState::Continue;560                        }561                    } else {562                        return WalkState::Continue;563                    }564                }565566                // Filter out unwanted modification times567                if !config.time_constraints.is_empty() {568                    let mut matched = false;569                    if let Some(metadata) = entry.metadata()570                        && let Ok(modified) = metadata.modified()571                    {572                        matched = config573                            .time_constraints574                            .iter()575                            .all(|tf| tf.applies_to(&modified));576                    }577                    if !matched {578                        return WalkState::Continue;579                    }580                }581582                if config.is_printing()583                    && let Some(ls_colors) = &config.ls_colors584                {585                    // Compute colors in parallel586                    entry.style(ls_colors);587                }588589                let send_result = tx.send(WorkerResult::Entry(entry));590591                if send_result.is_err() {592                    return WalkState::Quit;593                }594595                // Apply pruning.596                if config.prune {597                    return WalkState::Skip;598                }599600                WalkState::Continue601            })602        });603    }604605    /// Perform the recursive scan.606    fn scan(&self, paths: &[PathBuf]) -> Result<ExitCode> {607        let config = &self.config;608        let walker = self.build_walker(paths)?;609610        if config.ls_colors.is_some() && config.is_printing() {611            let quit_flag = Arc::clone(&self.quit_flag);612            let interrupt_flag = Arc::clone(&self.interrupt_flag);613614            ctrlc::set_handler(move || {615                quit_flag.store(true, Ordering::Relaxed);616617                if interrupt_flag.fetch_or(true, Ordering::Relaxed) {618                    // Ctrl-C has been pressed twice, exit NOW619                    ExitCode::KilledBySigint.exit();620                }621            })622            .unwrap();623        }624625        let (tx, rx) = bounded(2 * config.threads);626627        let exit_code = thread::scope(|scope| {628            // Spawn the receiver thread(s)629            let receiver = scope.spawn(|| self.receive(rx));630631            // Spawn the sender threads.632            self.spawn_senders(walker, tx);633634            receiver.join().unwrap()635        });636637        if self.interrupt_flag.load(Ordering::Relaxed) {638            Ok(ExitCode::KilledBySigint)639        } else {640            Ok(exit_code)641        }642    }643}644645/// If `err` is for a broken symlink, create a broken symlink DirEntry,646/// otherwise, return the original error.647fn broken_symlink_from_err(mut err: ignore::Error) -> Result<DirEntry, ignore::Error> {648    use ignore::Error::*;649    let mut depth = None;650    let mut path = None;651    let mut current = &mut err;652    // Loop through the items in the chain, and extract the path and depth as we find them.653    // Then once we get to the (terminal) io error, check that it is for a broken symlink.654    loop {655        match current {656            WithPath { err, path: p } => {657                path = Some(p);658                current = err;659            }660            WithDepth { err, depth: d } => {661                depth = Some(*d);662                current = err;663            }664            Io(e) if e.kind() == io::ErrorKind::NotFound => {665                if let Some(path) = path666                    && path667                        .symlink_metadata()668                        .ok()669                        .is_some_and(|m| m.file_type().is_symlink())670                {671                    // Since we no longer need the original error, we can take the PathBuf of the672                    // path out of it.673                    return Ok(DirEntry::broken_symlink(mem::take(path), depth));674                } else {675                    // This is pretty unlikely.676                    return Err(err);677                }678            }679            // We don't care about Loop because that won't happen680            // for broken symlinks, and there are two paths involved681            // and we don't care about WithLineNumber because that only applies682            // to errors while parsing ignore files.683            _ => return Err(err),684        }685    }686}687688fn search_str_for_entry<'a>(689    entry_path: &'a std::path::Path,690    full_path_base: Option<&std::path::Path>,691) -> Cow<'a, OsStr> {692    if let Some(cwd) = full_path_base {693        // If full_path_base is some, that means that we need to return694        // the absolute path695        if entry_path.is_absolute() {696            return Cow::Borrowed(entry_path.as_os_str());697        }698        let path = entry_path.strip_prefix(".").unwrap_or(entry_path);699        Cow::Owned(cwd.join(path).into())700    } else {701        match entry_path.file_name() {702            Some(filename) => Cow::Borrowed(filename),703            None => unreachable!(704                "Encountered file system entry without a file name. This should only \705                 happen for paths like 'foo/bar/..' or '/' which are not supposed to \706                 appear in a file system traversal."707            ),708        }709    }710}711712/// Recursively scan the given search path for files / pathnames matching the patterns.713///714/// If the `--exec` argument was supplied, this will create a thread pool for executing715/// jobs in parallel from a given command line and the discovered paths. Otherwise, each716/// path will simply be written to standard output.717pub fn scan(paths: &[PathBuf], patterns: Vec<Regex>, config: Config) -> Result<ExitCode> {718    WorkerState::new(patterns, config).scan(paths)719}720721#[cfg(test)]722mod tests {723    use super::search_str_for_entry;724    use std::path::{Path, PathBuf};725726    #[test]727    fn search_str_for_entry_with_relative_path() {728        let full_path_base = Some(Path::new("/home/user"));729        assert_eq!(730            search_str_for_entry(Path::new("foo/bar"), full_path_base),731            PathBuf::from("/home/user/foo/bar")732        );733    }734735    #[test]736    fn search_str_for_entry_strips_dot_prefix() {737        let full_path_base = Some(Path::new("/home/user"));738        assert_eq!(739            search_str_for_entry(Path::new("./foo/bar"), full_path_base),740            PathBuf::from("/home/user/foo/bar")741        );742    }743744    #[test]745    fn search_str_for_entry_with_absolute_path() {746        let full_path_base = Some(Path::new("/home/user"));747        assert_eq!(748            search_str_for_entry(Path::new("/absolute/path"), full_path_base),749            PathBuf::from("/absolute/path")750        );751    }752753    #[test]754    fn search_str_no_base_dir() {755        assert_eq!(756            search_str_for_entry(Path::new("./foo/bar"), None),757            PathBuf::from("bar")758        );759    }760761    #[test]762    fn search_str_no_base_dir_with_plain_relative_path() {763        assert_eq!(764            search_str_for_entry(Path::new("foo/bar"), None),765            PathBuf::from("bar")766        );767    }768769    #[test]770    fn search_str_no_base_dir_with_file_in_current_dir() {771        assert_eq!(772            search_str_for_entry(Path::new("foo"), None),773            PathBuf::from("foo")774        );775    }776}