Skip to content
Myr

break main into separate modules

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Garrett Squire · committed by David Peter · parent affe419 · Browse files · 4 files+354 added−330 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+354 added−330 removed

  • other:+354 added−330 removed

4 files+354 added−330 removed

added:src/internal.rs+80 added
1use std::process;2use std::time;3use std::io::Write;45use lscolors::LsColors;6use walk::FileType;78/// Root directory9#[cfg(unix)]10pub static ROOT_DIR: &'static str = "/";1112#[cfg(windows)]13pub static ROOT_DIR: &'static str = "";1415/// Defines how to display search result paths.16#[derive(PartialEq)]17pub enum PathDisplay {18 /// As an absolute path19 Absolute,2021 /// As a relative path22 Relative,23}2425/// Configuration options for *fd*.26pub struct FdOptions {27 /// Determines whether the regex search is case-sensitive or case-insensitive.28 pub case_sensitive: bool,2930 /// Whether to search within the full file path or just the base name (filename or directory31 /// name).32 pub search_full_path: bool,3334 /// Whether to ignore hidden files and directories (or not).35 pub ignore_hidden: bool,3637 /// Whether to respect VCS ignore files (`.gitignore`, `.ignore`, ..) or not.38 pub read_ignore: bool,3940 /// Whether to follow symlinks or not.41 pub follow_links: bool,4243 /// Whether elements of output should be separated by a null character44 pub null_separator: bool,4546 /// The maximum search depth, or `None` if no maximum search depth should be set.47 ///48 /// A depth of `1` includes all files under the current directory, a depth of `2` also includes49 /// all files under subdirectories of the current directory, etc.50 pub max_depth: Option<usize>,5152 /// The number of threads to use.53 pub threads: usize,5455 /// Time to buffer results internally before streaming to the console. This is useful to56 /// provide a sorted output, in case the total execution time is shorter than57 /// `max_buffer_time`.58 pub max_buffer_time: Option<time::Duration>,5960 /// Display results as relative or absolute path.61 pub path_display: PathDisplay,6263 /// `None` if the output should not be colorized. Otherwise, a `LsColors` instance that defines64 /// how to style different filetypes.65 pub ls_colors: Option<LsColors>,6667 /// The type of file to search for. All files other than the specified type will be ignored.68 pub file_type: FileType,6970 /// The extension to search for. Only entries matching the extension will be included.71 ///72 /// The value (if present) will be a lowercase string without leading dots.73 pub extension: Option<String>,74}7576/// Print error message to stderr and exit with status `1`.77pub fn error(message: &str) -> ! {78 writeln!(&mut ::std::io::stderr(), "{}", message).expect("Failed writing to stderr");79 process::exit(1);80}
modified:src/main.rs+8 added-330 removed
7 unmodified lines
89pub mod lscolors;10pub mod fshelper;11mod app;12mod internal;13mod output;14mod walk;1516use std::env;17use std::error::Error;15use std::io::Write;16use std::ops::Deref;17#[cfg(unix)]18use std::os::unix::fs::PermissionsExt;19use std::path::{Path, PathBuf};20use std::process;18use std::path::Path;19use std::sync::Arc;22use std::sync::mpsc::channel;23use std::thread;20use std::time;2122use atty::Stream;27use regex::{Regex, RegexBuilder};28use ignore::WalkBuilder;23use regex::RegexBuilder;2425use internal::{error, FdOptions, PathDisplay, ROOT_DIR};26use lscolors::LsColors;27use walk::FileType;2832/// Defines how to display search result paths.33#[derive(PartialEq)]34enum PathDisplay {35 /// As an absolute path36 Absolute,3738 /// As a relative path39 Relative,40}4142/// The type of file to search for.43#[derive(Copy, Clone)]44enum FileType {45 Any,46 RegularFile,47 Directory,48 SymLink,49}5051/// Configuration options for *fd*.52struct FdOptions {53 /// Determines whether the regex search is case-sensitive or case-insensitive.54 case_sensitive: bool,5556 /// Whether to search within the full file path or just the base name (filename or directory57 /// name).58 search_full_path: bool,5960 /// Whether to ignore hidden files and directories (or not).61 ignore_hidden: bool,6263 /// Whether to respect VCS ignore files (`.gitignore`, `.ignore`, ..) or not.64 read_ignore: bool,6566 /// Whether to follow symlinks or not.67 follow_links: bool,6869 /// Whether elements of output should be separated by a null character70 null_separator: bool,7172 /// The maximum search depth, or `None` if no maximum search depth should be set.73 ///74 /// A depth of `1` includes all files under the current directory, a depth of `2` also includes75 /// all files under subdirectories of the current directory, etc.76 max_depth: Option<usize>,7778 /// The number of threads to use.79 threads: usize,8081 /// Time to buffer results internally before streaming to the console. This is useful to82 /// provide a sorted output, in case the total execution time is shorter than83 /// `max_buffer_time`.84 max_buffer_time: Option<time::Duration>,8586 /// Display results as relative or absolute path.87 path_display: PathDisplay,8889 /// `None` if the output should not be colorized. Otherwise, a `LsColors` instance that defines90 /// how to style different filetypes.91 ls_colors: Option<LsColors>,9293 /// The type of file to search for. All files other than the specified type will be ignored.94 file_type: FileType,9596 /// The extension to search for. Only entries matching the extension will be included.97 ///98 /// The value (if present) will be a lowercase string without leading dots.99 extension: Option<String>,100}101102/// The receiver thread can either be buffering results or directly streaming to the console.103enum ReceiverMode {104 /// Receiver is still buffering in order to sort the results, if the search finishes fast105 /// enough.106 Buffering,107108 /// Receiver is directly printing results to the output.109 Streaming,110}111112/// Root directory113#[cfg(unix)]114static ROOT_DIR: &'static str = "/";115116#[cfg(windows)]117static ROOT_DIR: &'static str = "";118119/// Print a search result to the console.120fn print_entry(base: &Path, entry: &PathBuf, config: &FdOptions) {121 let path_full = base.join(entry);122123 let path_str = entry.to_string_lossy();124125 #[cfg(unix)]126 let is_executable = |p: Option<&std::fs::Metadata>| {127 p.map(|f| f.permissions().mode() & 0o111 != 0)128 .unwrap_or(false)129 };130131 #[cfg(windows)]132 let is_executable = |_: Option<&std::fs::Metadata>| false;133134 let stdout = std::io::stdout();135 let mut handle = stdout.lock();136137 if let Some(ref ls_colors) = config.ls_colors {138 let default_style = ansi_term::Style::default();139140 let mut component_path = base.to_path_buf();141142 if config.path_display == PathDisplay::Absolute {143 print!("{}", ls_colors.directory.paint(ROOT_DIR));144 }145146 // Traverse the path and colorize each component147 for component in entry.components() {148 let comp_str = component.as_os_str().to_string_lossy();149150 component_path.push(Path::new(comp_str.deref()));151152 let metadata = component_path.metadata().ok();153 let is_directory = metadata.as_ref().map(|md| md.is_dir()).unwrap_or(false);154155 let style =156 if component_path.symlink_metadata()157 .map(|md| md.file_type().is_symlink())158 .unwrap_or(false) {159 &ls_colors.symlink160 } else if is_directory {161 &ls_colors.directory162 } else if is_executable(metadata.as_ref()) {163 &ls_colors.executable164 } else {165 // Look up file name166 let o_style =167 component_path.file_name()168 .and_then(|n| n.to_str())169 .and_then(|n| ls_colors.filenames.get(n));170171 match o_style {172 Some(s) => s,173 None =>174 // Look up file extension175 component_path.extension()176 .and_then(|e| e.to_str())177 .and_then(|e| ls_colors.extensions.get(e))178 .unwrap_or(&default_style)179 }180 };181182 write!(handle, "{}", style.paint(comp_str)).ok();183184 if is_directory && component_path != path_full {185 let sep = std::path::MAIN_SEPARATOR.to_string();186 write!(handle, "{}", style.paint(sep)).ok();187 }188 }189190 let r = if config.null_separator {191 write!(handle, "\0")192 } else {193 writeln!(handle, "")194 };195 if r.is_err() {196 // Probably a broken pipe. Exit gracefully.197 process::exit(0);198 }199 } else {200 // Uncolorized output201202 let prefix = if config.path_display == PathDisplay::Absolute { ROOT_DIR } else { "" };203 let separator = if config.null_separator { "\0" } else { "\n" };204205 let r = write!(&mut std::io::stdout(), "{}{}{}", prefix, path_str, separator);206207 if r.is_err() {208 // Probably a broken pipe. Exit gracefully.209 process::exit(0);210 }211 }212}213214/// Recursively scan the given search path and search for files / pathnames matching the pattern.215fn scan(root: &Path, pattern: Arc<Regex>, base: &Path, config: Arc<FdOptions>) {216 let (tx, rx) = channel();217218 let walker = WalkBuilder::new(root)219 .hidden(config.ignore_hidden)220 .ignore(config.read_ignore)221 .git_ignore(config.read_ignore)222 .parents(config.read_ignore)223 .git_global(config.read_ignore)224 .git_exclude(config.read_ignore)225 .follow_links(config.follow_links)226 .max_depth(config.max_depth)227 .threads(config.threads)228 .build_parallel();229230 // Spawn the thread that receives all results through the channel.231 let rx_config = Arc::clone(&config);232 let rx_base = base.to_owned();233 let receiver_thread = thread::spawn(move || {234 let start = time::Instant::now();235236 let mut buffer = vec![];237238 // Start in buffering mode239 let mut mode = ReceiverMode::Buffering;240241 // Maximum time to wait before we start streaming to the console.242 let max_buffer_time = rx_config.max_buffer_time243 .unwrap_or_else(|| time::Duration::from_millis(100));244245 for value in rx {246 match mode {247 ReceiverMode::Buffering => {248 buffer.push(value);249250 // Have we reached the maximum time?251 if time::Instant::now() - start > max_buffer_time {252 // Flush the buffer253 for v in &buffer {254 print_entry(&rx_base, v, &rx_config);255 }256 buffer.clear();257258 // Start streaming259 mode = ReceiverMode::Streaming;260 }261 },262 ReceiverMode::Streaming => {263 print_entry(&rx_base, &value, &rx_config);264 }265 }266 }267268 // If we have finished fast enough (faster than max_buffer_time), we haven't streamed269 // anything to the console, yet. In this case, sort the results and print them:270 if !buffer.is_empty() {271 buffer.sort();272 for value in buffer {273 print_entry(&rx_base, &value, &rx_config);274 }275 }276 });277278 // Spawn the sender threads.279 walker.run(|| {280 let base = base.to_owned();281 let config = Arc::clone(&config);282 let pattern = Arc::clone(&pattern);283 let tx_thread = tx.clone();284285 Box::new(move |entry_o| {286 let entry = match entry_o {287 Ok(e) => e,288 Err(_) => return ignore::WalkState::Continue,289 };290291 // Filter out unwanted file types.292 match config.file_type {293 FileType::Any => (),294 FileType::RegularFile => if entry.file_type().map_or(false, |ft| !ft.is_file()) {295 return ignore::WalkState::Continue;296 },297 FileType::Directory => if entry.file_type().map_or(false, |ft| !ft.is_dir()) {298 return ignore::WalkState::Continue;299 },300 FileType::SymLink => if entry.file_type().map_or(false, |ft| !ft.is_symlink()) {301 return ignore::WalkState::Continue;302 },303 }304305 // Filter out unwanted extensions.306 if let Some(ref filter_ext) = config.extension {307 let entry_ext = entry.path().extension().map(|e| e.to_string_lossy().to_lowercase());308 if entry_ext.map_or(true, |ext| ext != *filter_ext) {309 return ignore::WalkState::Continue;310 }311 }312313 let path_rel_buf = match fshelper::path_relative_from(entry.path(), &*base) {314 Some(p) => p,315 None => error("Error: could not get relative path for directory entry.")316 };317 let path_rel = path_rel_buf.as_path();318319 let search_str_o =320 if config.search_full_path {321 Some(path_rel.to_string_lossy())322 } else {323 path_rel.file_name()324 .map(|f| f.to_string_lossy())325 };326327 if let Some(search_str) = search_str_o {328 // TODO: take care of the unwrap call329 pattern.find(&*search_str)330 .map(|_| tx_thread.send(path_rel_buf.to_owned()).unwrap());331 }332333 ignore::WalkState::Continue334 })335 });336337 // Drop the initial sender. If we don't do this, the receiver will block even338 // if all threads have finished, since there is still one sender around.339 drop(tx);340341 // Wait for the receiver thread to print out all results.342 receiver_thread.join().unwrap();343}344345/// Print error message to stderr and exit with status `1`.346fn error(message: &str) -> ! {347 writeln!(&mut std::io::stderr(), "{}", message).expect("Failed writing to stderr");348 process::exit(1);349}35029fn main() {30 let matches = app::build_app().get_matches();3132 // Get the search pattern
92 unmodified lines
125126 match RegexBuilder::new(pattern)127 .case_insensitive(!config.case_sensitive)128 .build() {451 Ok(re) => scan(root_dir, Arc::new(re), base, Arc::new(config)),129 Ok(re) => walk::scan(root_dir, Arc::new(re), base, Arc::new(config)),130 Err(err) => error(err.description())131 }132}
added:src/output.rs+104 added
1use internal::{FdOptions, PathDisplay, ROOT_DIR};23use std::{fs, process};4use std::io::{self, Write};5use std::ops::Deref;6use std::path::{self, Path, PathBuf};7#[cfg(unix)]8use std::os::unix::fs::PermissionsExt;910use ansi_term;1112pub fn print_entry(base: &Path, entry: &PathBuf, config: &FdOptions) {13 let path_full = base.join(entry);1415 let path_str = entry.to_string_lossy();1617 #[cfg(unix)]18 let is_executable = |p: Option<&fs::Metadata>| {19 p.map(|f| f.permissions().mode() & 0o111 != 0)20 .unwrap_or(false)21 };2223 #[cfg(windows)]24 let is_executable = |_: Option<&fs::Metadata>| false;2526 let stdout = io::stdout();27 let mut handle = stdout.lock();2829 if let Some(ref ls_colors) = config.ls_colors {30 let default_style = ansi_term::Style::default();3132 let mut component_path = base.to_path_buf();3334 if config.path_display == PathDisplay::Absolute {35 print!("{}", ls_colors.directory.paint(ROOT_DIR));36 }3738 // Traverse the path and colorize each component39 for component in entry.components() {40 let comp_str = component.as_os_str().to_string_lossy();4142 component_path.push(Path::new(comp_str.deref()));4344 let metadata = component_path.metadata().ok();45 let is_directory = metadata.as_ref().map(|md| md.is_dir()).unwrap_or(false);4647 let style =48 if component_path.symlink_metadata()49 .map(|md| md.file_type().is_symlink())50 .unwrap_or(false) {51 &ls_colors.symlink52 } else if is_directory {53 &ls_colors.directory54 } else if is_executable(metadata.as_ref()) {55 &ls_colors.executable56 } else {57 // Look up file name58 let o_style =59 component_path.file_name()60 .and_then(|n| n.to_str())61 .and_then(|n| ls_colors.filenames.get(n));6263 match o_style {64 Some(s) => s,65 None =>66 // Look up file extension67 component_path.extension()68 .and_then(|e| e.to_str())69 .and_then(|e| ls_colors.extensions.get(e))70 .unwrap_or(&default_style)71 }72 };7374 write!(handle, "{}", style.paint(comp_str)).ok();7576 if is_directory && component_path != path_full {77 let sep = path::MAIN_SEPARATOR.to_string();78 write!(handle, "{}", style.paint(sep)).ok();79 }80 }8182 let r = if config.null_separator {83 write!(handle, "\0")84 } else {85 writeln!(handle, "")86 };87 if r.is_err() {88 // Probably a broken pipe. Exit gracefully.89 process::exit(0);90 }91 } else {92 // Uncolorized output9394 let prefix = if config.path_display == PathDisplay::Absolute { ROOT_DIR } else { "" };95 let separator = if config.null_separator { "\0" } else { "\n" };9697 let r = write!(&mut io::stdout(), "{}{}{}", prefix, path_str, separator);9899 if r.is_err() {100 // Probably a broken pipe. Exit gracefully.101 process::exit(0);102 }103 }104}
added:src/walk.rs+162 added
1use internal::{error, FdOptions};2use fshelper;3use output;45use std::path::Path;6use std::sync::Arc;7use std::sync::mpsc::channel;8use std::thread;9use std::time;1011use regex::Regex;12use ignore::{self, WalkBuilder};1314/// The receiver thread can either be buffering results or directly streaming to the console.15enum ReceiverMode {16 /// Receiver is still buffering in order to sort the results, if the search finishes fast17 /// enough.18 Buffering,1920 /// Receiver is directly printing results to the output.21 Streaming,22}2324/// The type of file to search for.25#[derive(Copy, Clone)]26pub enum FileType {27 Any,28 RegularFile,29 Directory,30 SymLink,31}3233/// Recursively scan the given search path and search for files / pathnames matching the pattern.34pub fn scan(root: &Path, pattern: Arc<Regex>, base: &Path, config: Arc<FdOptions>) {35 let (tx, rx) = channel();3637 let walker = WalkBuilder::new(root)38 .hidden(config.ignore_hidden)39 .ignore(config.read_ignore)40 .git_ignore(config.read_ignore)41 .parents(config.read_ignore)42 .git_global(config.read_ignore)43 .git_exclude(config.read_ignore)44 .follow_links(config.follow_links)45 .max_depth(config.max_depth)46 .threads(config.threads)47 .build_parallel();4849 // Spawn the thread that receives all results through the channel.50 let rx_config = Arc::clone(&config);51 let rx_base = base.to_owned();52 let receiver_thread = thread::spawn(move || {53 let start = time::Instant::now();5455 let mut buffer = vec![];5657 // Start in buffering mode58 let mut mode = ReceiverMode::Buffering;5960 // Maximum time to wait before we start streaming to the console.61 let max_buffer_time = rx_config.max_buffer_time62 .unwrap_or_else(|| time::Duration::from_millis(100));6364 for value in rx {65 match mode {66 ReceiverMode::Buffering => {67 buffer.push(value);6869 // Have we reached the maximum time?70 if time::Instant::now() - start > max_buffer_time {71 // Flush the buffer72 for v in &buffer {73 output::print_entry(&rx_base, v, &rx_config);74 }75 buffer.clear();7677 // Start streaming78 mode = ReceiverMode::Streaming;79 }80 },81 ReceiverMode::Streaming => {82 output::print_entry(&rx_base, &value, &rx_config);83 }84 }85 }8687 // If we have finished fast enough (faster than max_buffer_time), we haven't streamed88 // anything to the console, yet. In this case, sort the results and print them:89 if !buffer.is_empty() {90 buffer.sort();91 for value in buffer {92 output::print_entry(&rx_base, &value, &rx_config);93 }94 }95 });9697 // Spawn the sender threads.98 walker.run(|| {99 let base = base.to_owned();100 let config = Arc::clone(&config);101 let pattern = Arc::clone(&pattern);102 let tx_thread = tx.clone();103104 Box::new(move |entry_o| {105 let entry = match entry_o {106 Ok(e) => e,107 Err(_) => return ignore::WalkState::Continue,108 };109110 // Filter out unwanted file types.111 match config.file_type {112 FileType::Any => (),113 FileType::RegularFile => if entry.file_type().map_or(false, |ft| !ft.is_file()) {114 return ignore::WalkState::Continue;115 },116 FileType::Directory => if entry.file_type().map_or(false, |ft| !ft.is_dir()) {117 return ignore::WalkState::Continue;118 },119 FileType::SymLink => if entry.file_type().map_or(false, |ft| !ft.is_symlink()) {120 return ignore::WalkState::Continue;121 },122 }123124 // Filter out unwanted extensions.125 if let Some(ref filter_ext) = config.extension {126 let entry_ext = entry.path().extension().map(|e| e.to_string_lossy().to_lowercase());127 if entry_ext.map_or(true, |ext| ext != *filter_ext) {128 return ignore::WalkState::Continue;129 }130 }131132 let path_rel_buf = match fshelper::path_relative_from(entry.path(), &*base) {133 Some(p) => p,134 None => error("Error: could not get relative path for directory entry.")135 };136 let path_rel = path_rel_buf.as_path();137138 let search_str_o =139 if config.search_full_path {140 Some(path_rel.to_string_lossy())141 } else {142 path_rel.file_name()143 .map(|f| f.to_string_lossy())144 };145146 if let Some(search_str) = search_str_o {147 // TODO: take care of the unwrap call148 pattern.find(&*search_str)149 .map(|_| tx_thread.send(path_rel_buf.to_owned()).unwrap());150 }151152 ignore::WalkState::Continue153 })154 });155156 // Drop the initial sender. If we don't do this, the receiver will block even157 // if all threads have finished, since there is still one sender around.158 drop(tx);159160 // Wait for the receiver thread to print out all results.161 receiver_thread.join().unwrap();162}