Skip to content
Myr

walk.rs

This file

Path

src/walk.rs

672 lines · 22.7 KiB · Rust

Last changed by

Merge pull request #1517 from one230six/masterThayne McCombsbefore adoption68fe31d

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::{anyhow, Result};12use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, SendError, Sender};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::error::print_error;21use crate::exec;22use crate::exit_codes::{merge_exitcodes, ExitCode};23use crate::filesystem;24use crate::output;2526/// The receiver thread can either be buffering results or directly streaming to the console.27#[derive(PartialEq)]28enum ReceiverMode {29    /// Receiver is still buffering in order to sort the results, if the search finishes fast30    /// enough.31    Buffering,3233    /// Receiver is directly printing results to the output.34    Streaming,35}3637/// The Worker threads can result in a valid entry having PathBuf or an error.38#[allow(clippy::large_enum_variant)]39#[derive(Debug)]40pub enum WorkerResult {41    // Errors should be rare, so it's probably better to allow large_enum_variant than42    // to box the Entry variant43    Entry(DirEntry),44    Error(ignore::Error),45}4647/// A batch of WorkerResults to send over a channel.48#[derive(Clone)]49struct Batch {50    items: Arc<Mutex<Option<Vec<WorkerResult>>>>,51}5253impl Batch {54    fn new() -> Self {55        Self {56            items: Arc::new(Mutex::new(Some(vec![]))),57        }58    }5960    fn lock(&self) -> MutexGuard<'_, Option<Vec<WorkerResult>>> {61        self.items.lock().unwrap()62    }63}6465impl IntoIterator for Batch {66    type Item = WorkerResult;67    type IntoIter = std::vec::IntoIter<WorkerResult>;6869    fn into_iter(self) -> Self::IntoIter {70        self.lock().take().unwrap().into_iter()71    }72}7374/// Wrapper that sends batches of items at once over a channel.75struct BatchSender {76    batch: Batch,77    tx: Sender<Batch>,78    limit: usize,79}8081impl BatchSender {82    fn new(tx: Sender<Batch>, limit: usize) -> Self {83        Self {84            batch: Batch::new(),85            tx,86            limit,87        }88    }8990    /// Check if we need to flush a batch.91    fn needs_flush(&self, batch: Option<&Vec<WorkerResult>>) -> bool {92        match batch {93            // Limit the batch size to provide some backpressure94            Some(vec) => vec.len() >= self.limit,95            // Batch was already taken by the receiver, so make a new one96            None => true,97        }98    }99100    /// Add an item to a batch.101    fn send(&mut self, item: WorkerResult) -> Result<(), SendError<()>> {102        let mut batch = self.batch.lock();103104        if self.needs_flush(batch.as_ref()) {105            drop(batch);106            self.batch = Batch::new();107            batch = self.batch.lock();108        }109110        let items = batch.as_mut().unwrap();111        items.push(item);112113        if items.len() == 1 {114            // New batch, send it over the channel115            self.tx116                .send(self.batch.clone())117                .map_err(|_| SendError(()))?;118        }119120        Ok(())121    }122}123124/// Maximum size of the output buffer before flushing results to the console125const MAX_BUFFER_LENGTH: usize = 1000;126/// Default duration until output buffering switches to streaming.127const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);128129/// Wrapper for the receiver thread's buffering behavior.130struct ReceiverBuffer<'a, W> {131    /// The configuration.132    config: &'a Config,133    /// For shutting down the senders.134    quit_flag: &'a AtomicBool,135    /// The ^C notifier.136    interrupt_flag: &'a AtomicBool,137    /// Receiver for worker results.138    rx: Receiver<Batch>,139    /// Standard output.140    stdout: W,141    /// The current buffer mode.142    mode: ReceiverMode,143    /// The deadline to switch to streaming mode.144    deadline: Instant,145    /// The buffer of quickly received paths.146    buffer: Vec<DirEntry>,147    /// Result count.148    num_results: usize,149}150151impl<'a, W: Write> ReceiverBuffer<'a, W> {152    /// Create a new receiver buffer.153    fn new(state: &'a WorkerState, rx: Receiver<Batch>, stdout: W) -> Self {154        let config = &state.config;155        let quit_flag = state.quit_flag.as_ref();156        let interrupt_flag = state.interrupt_flag.as_ref();157        let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);158        let deadline = Instant::now() + max_buffer_time;159160        Self {161            config,162            quit_flag,163            interrupt_flag,164            rx,165            stdout,166            mode: ReceiverMode::Buffering,167            deadline,168            buffer: Vec::with_capacity(MAX_BUFFER_LENGTH),169            num_results: 0,170        }171    }172173    /// Process results until finished.174    fn process(&mut self) -> ExitCode {175        loop {176            if let Err(ec) = self.poll() {177                self.quit_flag.store(true, Ordering::Relaxed);178                return ec;179            }180        }181    }182183    /// Receive the next worker result.184    fn recv(&self) -> Result<Batch, RecvTimeoutError> {185        match self.mode {186            ReceiverMode::Buffering => {187                // Wait at most until we should switch to streaming188                self.rx.recv_deadline(self.deadline)189            }190            ReceiverMode::Streaming => {191                // Wait however long it takes for a result192                Ok(self.rx.recv()?)193            }194        }195    }196197    /// Wait for a result or state change.198    fn poll(&mut self) -> Result<(), ExitCode> {199        match self.recv() {200            Ok(batch) => {201                for result in batch {202                    match result {203                        WorkerResult::Entry(dir_entry) => {204                            if self.config.quiet {205                                return Err(ExitCode::HasResults(true));206                            }207208                            match self.mode {209                                ReceiverMode::Buffering => {210                                    self.buffer.push(dir_entry);211                                    if self.buffer.len() > MAX_BUFFER_LENGTH {212                                        self.stream()?;213                                    }214                                }215                                ReceiverMode::Streaming => {216                                    self.print(&dir_entry)?;217                                }218                            }219220                            self.num_results += 1;221                            if let Some(max_results) = self.config.max_results {222                                if self.num_results >= max_results {223                                    return self.stop();224                                }225                            }226                        }227                        WorkerResult::Error(err) => {228                            if self.config.show_filesystem_errors {229                                print_error(err.to_string());230                            }231                        }232                    }233                }234235                // If we don't have another batch ready, flush before waiting236                if self.mode == ReceiverMode::Streaming && self.rx.is_empty() {237                    self.flush()?;238                }239            }240            Err(RecvTimeoutError::Timeout) => {241                self.stream()?;242            }243            Err(RecvTimeoutError::Disconnected) => {244                return self.stop();245            }246        }247248        Ok(())249    }250251    /// Output a path.252    fn print(&mut self, entry: &DirEntry) -> Result<(), ExitCode> {253        output::print_entry(&mut self.stdout, entry, self.config);254255        if self.interrupt_flag.load(Ordering::Relaxed) {256            // Ignore any errors on flush, because we're about to exit anyway257            let _ = self.flush();258            return Err(ExitCode::KilledBySigint);259        }260261        Ok(())262    }263264    /// Switch ourselves into streaming mode.265    fn stream(&mut self) -> Result<(), ExitCode> {266        self.mode = ReceiverMode::Streaming;267268        let buffer = mem::take(&mut self.buffer);269        for path in buffer {270            self.print(&path)?;271        }272273        self.flush()274    }275276    /// Stop looping.277    fn stop(&mut self) -> Result<(), ExitCode> {278        if self.mode == ReceiverMode::Buffering {279            self.buffer.sort();280            self.stream()?;281        }282283        if self.config.quiet {284            Err(ExitCode::HasResults(self.num_results > 0))285        } else {286            Err(ExitCode::Success)287        }288    }289290    /// Flush stdout if necessary.291    fn flush(&mut self) -> Result<(), ExitCode> {292        if self.stdout.flush().is_err() {293            // Probably a broken pipe. Exit gracefully.294            return Err(ExitCode::GeneralError);295        }296        Ok(())297    }298}299300/// State shared by the sender and receiver threads.301struct WorkerState {302    /// The search patterns.303    patterns: Vec<Regex>,304    /// The command line configuration.305    config: Config,306    /// Flag for cleanly shutting down the parallel walk307    quit_flag: Arc<AtomicBool>,308    /// Flag specifically for quitting due to ^C309    interrupt_flag: Arc<AtomicBool>,310}311312impl WorkerState {313    fn new(patterns: Vec<Regex>, config: Config) -> Self {314        let quit_flag = Arc::new(AtomicBool::new(false));315        let interrupt_flag = Arc::new(AtomicBool::new(false));316317        Self {318            patterns,319            config,320            quit_flag,321            interrupt_flag,322        }323    }324325    fn build_overrides(&self, paths: &[PathBuf]) -> Result<Override> {326        let first_path = &paths[0];327        let config = &self.config;328329        let mut builder = OverrideBuilder::new(first_path);330331        for pattern in &config.exclude_patterns {332            builder333                .add(pattern)334                .map_err(|e| anyhow!("Malformed exclude pattern: {}", e))?;335        }336337        if config.read_vcsignore {338            builder.add("!.git/").expect("Invalid exclude pattern");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_ignore {371            if let Ok(basedirs) = etcetera::choose_base_strategy() {372                let global_ignore_file = basedirs.config_dir().join("fd").join("ignore");373                if global_ignore_file.is_file() {374                    let result = builder.add_ignore(global_ignore_file);375                    match result {376                        Some(ignore::Error::Partial(_)) => (),377                        Some(err) => {378                            print_error(format!(379                                "Malformed pattern in global ignore file. {}.",380                                err381                            ));382                        }383                        None => (),384                    }385                }386            }387        }388389        for ignore_file in &config.ignore_files {390            let result = builder.add_ignore(ignore_file);391            match result {392                Some(ignore::Error::Partial(_)) => (),393                Some(err) => {394                    print_error(format!("Malformed pattern in custom ignore file. {}.", err));395                }396                None => (),397            }398        }399400        for path in &paths[1..] {401            builder.add(path);402        }403404        let walker = builder.threads(config.threads).build_parallel();405        Ok(walker)406    }407408    /// Run the receiver work, either on this thread or a pool of background409    /// threads (for --exec).410    fn receive(&self, rx: Receiver<Batch>) -> ExitCode {411        let config = &self.config;412413        // This will be set to `Some` if the `--exec` argument was supplied.414        if let Some(ref cmd) = config.command {415            if cmd.in_batch_mode() {416                exec::batch(rx.into_iter().flatten(), cmd, config)417            } else {418                let out_perm = Mutex::new(());419420                thread::scope(|scope| {421                    // Each spawned job will store its thread handle in here.422                    let threads = config.threads;423                    let mut handles = Vec::with_capacity(threads);424                    for _ in 0..threads {425                        let rx = rx.clone();426427                        // Spawn a job thread that will listen for and execute inputs.428                        let handle = scope429                            .spawn(|| exec::job(rx.into_iter().flatten(), cmd, &out_perm, config));430431                        // Push the handle of the spawned thread into the vector for later joining.432                        handles.push(handle);433                    }434                    let exit_codes = handles.into_iter().map(|handle| handle.join().unwrap());435                    merge_exitcodes(exit_codes)436                })437            }438        } else {439            let stdout = io::stdout().lock();440            let stdout = io::BufWriter::new(stdout);441442            ReceiverBuffer::new(self, rx, stdout).process()443        }444    }445446    /// Spawn the sender threads.447    fn spawn_senders(&self, walker: WalkParallel, tx: Sender<Batch>) {448        walker.run(|| {449            let patterns = &self.patterns;450            let config = &self.config;451            let quit_flag = self.quit_flag.as_ref();452453            let mut limit = 0x100;454            if let Some(cmd) = &config.command {455                if !cmd.in_batch_mode() && config.threads > 1 {456                    // Evenly distribute work between multiple receivers457                    limit = 1;458                }459            }460            let mut tx = BatchSender::new(tx.clone(), limit);461462            Box::new(move |entry| {463                if quit_flag.load(Ordering::Relaxed) {464                    return WalkState::Quit;465                }466467                let entry = match entry {468                    Ok(ref e) if e.depth() == 0 => {469                        // Skip the root directory entry.470                        return WalkState::Continue;471                    }472                    Ok(e) => DirEntry::normal(e),473                    Err(ignore::Error::WithPath {474                        path,475                        err: inner_err,476                    }) => match inner_err.as_ref() {477                        ignore::Error::Io(io_error)478                            if io_error.kind() == io::ErrorKind::NotFound479                                && path480                                    .symlink_metadata()481                                    .ok()482                                    .map_or(false, |m| m.file_type().is_symlink()) =>483                        {484                            DirEntry::broken_symlink(path)485                        }486                        _ => {487                            return match tx.send(WorkerResult::Error(ignore::Error::WithPath {488                                path,489                                err: inner_err,490                            })) {491                                Ok(_) => WalkState::Continue,492                                Err(_) => WalkState::Quit,493                            }494                        }495                    },496                    Err(err) => {497                        return match tx.send(WorkerResult::Error(err)) {498                            Ok(_) => WalkState::Continue,499                            Err(_) => WalkState::Quit,500                        }501                    }502                };503504                if let Some(min_depth) = config.min_depth {505                    if entry.depth().map_or(true, |d| d < min_depth) {506                        return WalkState::Continue;507                    }508                }509510                // Check the name first, since it doesn't require metadata511                let entry_path = entry.path();512513                let search_str: Cow<OsStr> = if config.search_full_path {514                    let path_abs_buf = filesystem::path_absolute_form(entry_path)515                        .expect("Retrieving absolute path succeeds");516                    Cow::Owned(path_abs_buf.as_os_str().to_os_string())517                } else {518                    match entry_path.file_name() {519                        Some(filename) => Cow::Borrowed(filename),520                        None => unreachable!(521                            "Encountered file system entry without a file name. This should only \522                             happen for paths like 'foo/bar/..' or '/' which are not supposed to \523                             appear in a file system traversal."524                        ),525                    }526                };527528                if !patterns529                    .iter()530                    .all(|pat| pat.is_match(&filesystem::osstr_to_bytes(search_str.as_ref())))531                {532                    return WalkState::Continue;533                }534535                // Filter out unwanted extensions.536                if let Some(ref exts_regex) = config.extensions {537                    if let Some(path_str) = entry_path.file_name() {538                        if !exts_regex.is_match(&filesystem::osstr_to_bytes(path_str)) {539                            return WalkState::Continue;540                        }541                    } else {542                        return WalkState::Continue;543                    }544                }545546                // Filter out unwanted file types.547                if let Some(ref file_types) = config.file_types {548                    if file_types.should_ignore(&entry) {549                        return WalkState::Continue;550                    }551                }552553                #[cfg(unix)]554                {555                    if let Some(ref owner_constraint) = config.owner_constraint {556                        if let Some(metadata) = entry.metadata() {557                            if !owner_constraint.matches(metadata) {558                                return WalkState::Continue;559                            }560                        } else {561                            return WalkState::Continue;562                        }563                    }564                }565566                // Filter out unwanted sizes if it is a file and we have been given size constraints.567                if !config.size_constraints.is_empty() {568                    if entry_path.is_file() {569                        if let Some(metadata) = entry.metadata() {570                            let file_size = metadata.len();571                            if config572                                .size_constraints573                                .iter()574                                .any(|sc| !sc.is_within(file_size))575                            {576                                return WalkState::Continue;577                            }578                        } else {579                            return WalkState::Continue;580                        }581                    } else {582                        return WalkState::Continue;583                    }584                }585586                // Filter out unwanted modification times587                if !config.time_constraints.is_empty() {588                    let mut matched = false;589                    if let Some(metadata) = entry.metadata() {590                        if let Ok(modified) = metadata.modified() {591                            matched = config592                                .time_constraints593                                .iter()594                                .all(|tf| tf.applies_to(&modified));595                        }596                    }597                    if !matched {598                        return WalkState::Continue;599                    }600                }601602                if config.is_printing() {603                    if let Some(ls_colors) = &config.ls_colors {604                        // Compute colors in parallel605                        entry.style(ls_colors);606                    }607                }608609                let send_result = tx.send(WorkerResult::Entry(entry));610611                if send_result.is_err() {612                    return WalkState::Quit;613                }614615                // Apply pruning.616                if config.prune {617                    return WalkState::Skip;618                }619620                WalkState::Continue621            })622        });623    }624625    /// Perform the recursive scan.626    fn scan(&self, paths: &[PathBuf]) -> Result<ExitCode> {627        let config = &self.config;628        let walker = self.build_walker(paths)?;629630        if config.ls_colors.is_some() && config.is_printing() {631            let quit_flag = Arc::clone(&self.quit_flag);632            let interrupt_flag = Arc::clone(&self.interrupt_flag);633634            ctrlc::set_handler(move || {635                quit_flag.store(true, Ordering::Relaxed);636637                if interrupt_flag.fetch_or(true, Ordering::Relaxed) {638                    // Ctrl-C has been pressed twice, exit NOW639                    ExitCode::KilledBySigint.exit();640                }641            })642            .unwrap();643        }644645        let (tx, rx) = bounded(2 * config.threads);646647        let exit_code = thread::scope(|scope| {648            // Spawn the receiver thread(s)649            let receiver = scope.spawn(|| self.receive(rx));650651            // Spawn the sender threads.652            self.spawn_senders(walker, tx);653654            receiver.join().unwrap()655        });656657        if self.interrupt_flag.load(Ordering::Relaxed) {658            Ok(ExitCode::KilledBySigint)659        } else {660            Ok(exit_code)661        }662    }663}664665/// Recursively scan the given search path for files / pathnames matching the patterns.666///667/// If the `--exec` argument was supplied, this will create a thread pool for executing668/// jobs in parallel from a given command line and the discovered paths. Otherwise, each669/// path will simply be written to standard output.670pub fn scan(paths: &[PathBuf], patterns: Vec<Regex>, config: Config) -> Result<ExitCode> {671    WorkerState::new(patterns, config).scan(paths)672}