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 fileTake it
Relicense under MIT/Apache-2.0Antti Keränenbefore adoption701b8f2
lines 1–8why, one step back1// 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.8Workaround for the `unsafe` block.sharkdpbefore adoption9d26b74
line 9why, one step back9use exec;break main into separate modulesGarrett Squirebefore adoptionccb899a
line 10why, one step back10use fshelper;Refactor path handling (fixes #113)J.Wbefore adoption8d85deb
line 11why, one step back11use internal::{error, FdOptions};break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 12–13why, one step back12use output;13Use a uniform output format for searching ../J.Wbefore adoptione649c8f
line 14why, one step back14use std::path::Path;Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
line 15why, one step back15use std::sync::{Arc, Mutex};break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 16–20why, one step back16use std::sync::mpsc::channel;17use std::thread;18use std::time;1920use ignore::{self, WalkBuilder};Add support for exclude-patternssharkdpbefore adoption5ad69fb
line 21why, one step back21use ignore::overrides::OverrideBuilder;Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
line 22why, one step back22use regex::Regex;break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 23–42why, one step back2324/// 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}42Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
lines 43–47why, one step back43/// 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.Refactor path handling (fixes #113)J.Wbefore adoption8d85deb
line 48why, one step back48pub fn scan(root: &Path, pattern: Arc<Regex>, config: Arc<FdOptions>) {break main into separate modulesGarrett Squirebefore adoptionccb899a
line 49why, one step back49 let (tx, rx) = channel();Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
line 50why, one step back50 let threads = config.threads;break main into separate modulesGarrett Squirebefore adoptionccb899a
line 51why, one step back51Add support for exclude-patternssharkdpbefore adoption5ad69fb
lines 52–53why, one step back52 let mut override_builder = OverrideBuilder::new(root);53Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 54why, one step back54 for pattern in &config.exclude_patterns {Add support for exclude-patternssharkdpbefore adoption5ad69fb
lines 55–63why, one step back55 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 });63break main into separate modulesGarrett Squirebefore adoptionccb899a
line 64why, one step back64 let walker = WalkBuilder::new(root)Format the source code using `rustfmt`Antti Keränenbefore adoption049b9ec
lines 65–70why, one step back65 .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)Add support for exclude-patternssharkdpbefore adoption5ad69fb
line 71why, one step back71 .overrides(overrides)Format the source code using `rustfmt`Antti Keränenbefore adoption049b9ec
lines 72–73why, one step back72 .follow_links(config.follow_links)73 .max_depth(config.max_depth)Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
line 74why, one step back74 .threads(threads)Format the source code using `rustfmt`Antti Keränenbefore adoption049b9ec
line 75why, one step back75 .build_parallel();break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 76–79why, one step back7677 // Spawn the thread that receives all results through the channel.78 let rx_config = Arc::clone(&config);79 let receiver_thread = thread::spawn(move || {Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
lines 80–82why, one step back80 // 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));break main into separate modulesGarrett Squirebefore adoptionccb899a
line 83why, one step back83Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
line 84why, one step back84 let out_perm = Arc::new(Mutex::new(()));break main into separate modulesGarrett Squirebefore adoptionccb899a
line 85why, one step back85Workaround for the `unsafe` block.sharkdpbefore adoption9d26b74
lines 86–90why, one step back86 // 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());break main into separate modulesGarrett Squirebefore adoptionccb899a
line 91why, one step back91Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
lines 92–94why, one step back92 // Each spawned job will store it's thread handle in here.93 let mut handles = Vec::with_capacity(threads);94 for _ in 0..threads {Updates and preparations for v5.0sharkdpbefore adoptione9cf8af
lines 95–97why, one step back95 let rx = Arc::clone(&shared_rx);96 let cmd = Arc::clone(&cmd);97 let out_perm = Arc::clone(&out_perm);break main into separate modulesGarrett Squirebefore adoptionccb899a
line 98why, one step back98Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
line 99why, one step back99 // Spawn a job thread that will listen for and execute inputs.Refactor path handling (fixes #113)J.Wbefore adoption8d85deb
line 100why, one step back100 let handle = thread::spawn(move || exec::job(rx, cmd, out_perm));break main into separate modulesGarrett Squirebefore adoptionccb899a
line 101why, one step back101Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
lines 102–131why, one step back102 // 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 {Updates and preparations for v5.0sharkdpbefore adoptione9cf8af
line 132why, one step back132 output::print_entry(v, &rx_config);Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
lines 133–138why, one step back133 }134 buffer.clear();135136 // Start streaming137 mode = ReceiverMode::Streaming;138 }break main into separate modulesGarrett Squirebefore adoptionccb899a
line 139why, one step back139 }Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
line 140why, one step back140 ReceiverMode::Streaming => {Refactor path handling (fixes #113)J.Wbefore adoption8d85deb
line 141why, one step back141 output::print_entry(&value, &rx_config);Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
line 142why, one step back142 }Format the source code using `rustfmt`Antti Keränenbefore adoption049b9ec
line 143why, one step back143 }break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 144–145why, one step back144 }145Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
lines 146–150why, one step back146 // 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 {Refactor path handling (fixes #113)J.Wbefore adoption8d85deb
line 151why, one step back151 output::print_entry(&value, &rx_config);Merge pull request #116 from mmstick/execDavid Peterbefore adoptione0eab07
line 152why, one step back152 }break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 153–161why, one step back153 }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();Use absolute path to perform search, fixes #81sharkdpbefore adoption8fc3a83
line 162why, one step back162 let root = root.to_owned();break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 163–169why, one step back163164 Box::new(move |entry_o| {165 let entry = match entry_o {166 Ok(e) => e,167 Err(_) => return ignore::WalkState::Continue,168 };169Use absolute path to perform search, fixes #81sharkdpbefore adoption8fc3a83
lines 170–175why, one step back170 let entry_path = entry.path();171172 if entry_path == root {173 return ignore::WalkState::Continue;174 }175break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 176–178why, one step back176 // Filter out unwanted file types.177 match config.file_type {178 FileType::Any => (),Format the source code using `rustfmt`Antti Keränenbefore adoption049b9ec
line 179why, one step back179 FileType::RegularFile => {Fix --type: skip if file type is unknownJ.Wbefore adoptione38b7d7
line 180why, one step back180 if entry.file_type().map_or(true, |ft| !ft.is_file()) {Format the source code using `rustfmt`Antti Keränenbefore adoption049b9ec
lines 181–184why, one step back181 return ignore::WalkState::Continue;182 }183 }184 FileType::Directory => {Fix --type: skip if file type is unknownJ.Wbefore adoptione38b7d7
line 185why, one step back185 if entry.file_type().map_or(true, |ft| !ft.is_dir()) {Format the source code using `rustfmt`Antti Keränenbefore adoption049b9ec
lines 186–189why, one step back186 return ignore::WalkState::Continue;187 }188 }189 FileType::SymLink => {Fix --type: skip if file type is unknownJ.Wbefore adoptione38b7d7
line 190why, one step back190 if entry.file_type().map_or(true, |ft| !ft.is_symlink()) {Format the source code using `rustfmt`Antti Keränenbefore adoption049b9ec
lines 191–193why, one step back191 return ignore::WalkState::Continue;192 }193 }break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 194–197why, one step back194 }195196 // Filter out unwanted extensions.197 if let Some(ref filter_ext) = config.extension {Use absolute path to perform search, fixes #81sharkdpbefore adoption8fc3a83
lines 198–200why, one step back198 let entry_ext = entry_path.extension().map(199 |e| e.to_string_lossy().to_lowercase(),200 );break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 201–205why, one step back201 if entry_ext.map_or(true, |ext| ext != *filter_ext) {202 return ignore::WalkState::Continue;203 }204 }205Format the source code using `rustfmt`Antti Keränenbefore adoption049b9ec
line 206why, one step back206 let search_str_o = if config.search_full_path {Updates and preparations for v5.0sharkdpbefore adoptione9cf8af
line 207why, one step back207 match fshelper::path_absolute_form(entry_path) {Refactor path handling (fixes #113)J.Wbefore adoption8d85deb
lines 208–210why, one step back208 Ok(path_abs_buf) => Some(path_abs_buf.to_string_lossy().into_owned().into()),209 Err(_) => error("Error: unable to get full path."),210 }Format the source code using `rustfmt`Antti Keränenbefore adoption049b9ec
line 211why, one step back211 } else {Use absolute path to perform search, fixes #81sharkdpbefore adoption8fc3a83
line 212why, one step back212 entry_path.file_name().map(|f| f.to_string_lossy())Format the source code using `rustfmt`Antti Keränenbefore adoption049b9ec
line 213why, one step back213 };break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 214–215why, one step back214215 if let Some(search_str) = search_str_o {Refactor path handling (fixes #113)J.Wbefore adoption8d85deb
line 216why, one step back216 if pattern.is_match(&*search_str) {Use absolute path to perform search, fixes #81sharkdpbefore adoption8fc3a83
line 217why, one step back217 // TODO: take care of the unwrap callRefactor path handling (fixes #113)J.Wbefore adoption8d85deb
lines 218–219why, one step back218 tx_thread.send(entry_path.to_owned()).unwrap()219 }break main into separate modulesGarrett Squirebefore adoptionccb899a
lines 220–232why, one step back220 }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}