Skip to content
Myr

walk.rs

This file

Path

src/walk.rs

232 lines · 8.2 KiB · Rust

Last changed by

Fix some clippy warningssharkdpbefore adoptionbba5c4f

History of this file

Take it

1// Copyright (c) 2017 fd developers2// Licensed under the Apache License, Version 2.03// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>4// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,5// at your option. All files in the project carrying such6// notice may not be copied, modified, or distributed except7// according to those terms.89use exec;10use fshelper;11use internal::{error, FdOptions};12use output;1314use std::path::Path;15use std::sync::{Arc, Mutex};16use std::sync::mpsc::channel;17use std::thread;18use std::time;1920use ignore::{self, WalkBuilder};21use ignore::overrides::OverrideBuilder;22use regex::Regex;2324/// The receiver thread can either be buffering results or directly streaming to the console.25enum ReceiverMode {26    /// Receiver is still buffering in order to sort the results, if the search finishes fast27    /// enough.28    Buffering,2930    /// Receiver is directly printing results to the output.31    Streaming,32}3334/// The type of file to search for.35#[derive(Copy, Clone)]36pub enum FileType {37    Any,38    RegularFile,39    Directory,40    SymLink,41}4243/// Recursively scan the given search path for files / pathnames matching the pattern.44///45/// If the `--exec` argument was supplied, this will create a thread pool for executing46/// jobs in parallel from a given command line and the discovered paths. Otherwise, each47/// path will simply be written to standard output.48pub fn scan(root: &Path, pattern: Arc<Regex>, config: Arc<FdOptions>) {49    let (tx, rx) = channel();50    let threads = config.threads;5152    let mut override_builder = OverrideBuilder::new(root);5354    for pattern in &config.exclude_patterns {55        let res = override_builder.add(pattern);56        if res.is_err() {57            error(&format!("Error: malformed exclude pattern '{}'", pattern));58        }59    }60    let overrides = override_builder.build().unwrap_or_else(|_| {61        error("Mismatch in exclude patterns");62    });6364    let walker = WalkBuilder::new(root)65        .hidden(config.ignore_hidden)66        .ignore(config.read_ignore)67        .git_ignore(config.read_ignore)68        .parents(config.read_ignore)69        .git_global(config.read_ignore)70        .git_exclude(config.read_ignore)71        .overrides(overrides)72        .follow_links(config.follow_links)73        .max_depth(config.max_depth)74        .threads(threads)75        .build_parallel();7677    // Spawn the thread that receives all results through the channel.78    let rx_config = Arc::clone(&config);79    let receiver_thread = thread::spawn(move || {80        // This will be set to `Some` if the `--exec` argument was supplied.81        if let Some(ref cmd) = rx_config.command {82            let shared_rx = Arc::new(Mutex::new(rx));8384            let out_perm = Arc::new(Mutex::new(()));8586            // TODO: the following line is a workaround to replace the `unsafe` block that was87            // previously used here to avoid the (unnecessary?) cloning of the command. The88            // `unsafe` block caused problems on some platforms (SIGILL instructions on Linux) and89            // therefore had to be removed.90            let cmd = Arc::new(cmd.clone());9192            // Each spawned job will store it's thread handle in here.93            let mut handles = Vec::with_capacity(threads);94            for _ in 0..threads {95                let rx = Arc::clone(&shared_rx);96                let cmd = Arc::clone(&cmd);97                let out_perm = Arc::clone(&out_perm);9899                // Spawn a job thread that will listen for and execute inputs.100                let handle = thread::spawn(move || exec::job(rx, cmd, out_perm));101102                // Push the handle of the spawned thread into the vector for later joining.103                handles.push(handle);104            }105106            // Wait for all threads to exit before exiting the program.107            for h in handles {108                h.join().unwrap();109            }110        } else {111            let start = time::Instant::now();112113            let mut buffer = vec![];114115            // Start in buffering mode116            let mut mode = ReceiverMode::Buffering;117118            // Maximum time to wait before we start streaming to the console.119            let max_buffer_time = rx_config.max_buffer_time.unwrap_or_else(120                || time::Duration::from_millis(100),121            );122123            for value in rx {124                match mode {125                    ReceiverMode::Buffering => {126                        buffer.push(value);127128                        // Have we reached the maximum time?129                        if time::Instant::now() - start > max_buffer_time {130                            // Flush the buffer131                            for v in &buffer {132                                output::print_entry(v, &rx_config);133                            }134                            buffer.clear();135136                            // Start streaming137                            mode = ReceiverMode::Streaming;138                        }139                    }140                    ReceiverMode::Streaming => {141                        output::print_entry(&value, &rx_config);142                    }143                }144            }145146            // If we have finished fast enough (faster than max_buffer_time), we haven't streamed147            // anything to the console, yet. In this case, sort the results and print them:148            if !buffer.is_empty() {149                buffer.sort();150                for value in buffer {151                    output::print_entry(&value, &rx_config);152                }153            }154        }155    });156157    // Spawn the sender threads.158    walker.run(|| {159        let config = Arc::clone(&config);160        let pattern = Arc::clone(&pattern);161        let tx_thread = tx.clone();162        let root = root.to_owned();163164        Box::new(move |entry_o| {165            let entry = match entry_o {166                Ok(e) => e,167                Err(_) => return ignore::WalkState::Continue,168            };169170            let entry_path = entry.path();171172            if entry_path == root {173                return ignore::WalkState::Continue;174            }175176            // Filter out unwanted file types.177            match config.file_type {178                FileType::Any => (),179                FileType::RegularFile => {180                    if entry.file_type().map_or(true, |ft| !ft.is_file()) {181                        return ignore::WalkState::Continue;182                    }183                }184                FileType::Directory => {185                    if entry.file_type().map_or(true, |ft| !ft.is_dir()) {186                        return ignore::WalkState::Continue;187                    }188                }189                FileType::SymLink => {190                    if entry.file_type().map_or(true, |ft| !ft.is_symlink()) {191                        return ignore::WalkState::Continue;192                    }193                }194            }195196            // Filter out unwanted extensions.197            if let Some(ref filter_ext) = config.extension {198                let entry_ext = entry_path.extension().map(199                    |e| e.to_string_lossy().to_lowercase(),200                );201                if entry_ext.map_or(true, |ext| ext != *filter_ext) {202                    return ignore::WalkState::Continue;203                }204            }205206            let search_str_o = if config.search_full_path {207                match fshelper::path_absolute_form(entry_path) {208                    Ok(path_abs_buf) => Some(path_abs_buf.to_string_lossy().into_owned().into()),209                    Err(_) => error("Error: unable to get full path."),210                }211            } else {212                entry_path.file_name().map(|f| f.to_string_lossy())213            };214215            if let Some(search_str) = search_str_o {216                if pattern.is_match(&*search_str) {217                    // TODO: take care of the unwrap call218                    tx_thread.send(entry_path.to_owned()).unwrap()219                }220            }221222            ignore::WalkState::Continue223        })224    });225226    // Drop the initial sender. If we don't do this, the receiver will block even227    // if all threads have finished, since there is still one sender around.228    drop(tx);229230    // Wait for the receiver thread to print out all results.231    receiver_thread.join().unwrap();232}