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
Provenance
- Commit
ccb899a- Tree
5bd813a- Author
Garrett Squire <garrett.squire@crowdstrike.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
affe419
4 files changed+354 added−330 removed
added:src/internal.rs+80 added
1+use std::process;2+use std::time;3+use std::io::Write;4+5+use lscolors::LsColors;6+use walk::FileType;7+8+/// Root directory9+#[cfg(unix)]10+pub static ROOT_DIR: &'static str = "/";11+12+#[cfg(windows)]13+pub static ROOT_DIR: &'static str = "";14+15+/// Defines how to display search result paths.16+#[derive(PartialEq)]17+pub enum PathDisplay {18+ /// As an absolute path19+ Absolute,20+21+ /// As a relative path22+ Relative,23+}24+25+/// Configuration options for *fd*.26+pub struct FdOptions {27+ /// Determines whether the regex search is case-sensitive or case-insensitive.28+ pub case_sensitive: bool,29+30+ /// Whether to search within the full file path or just the base name (filename or directory31+ /// name).32+ pub search_full_path: bool,33+34+ /// Whether to ignore hidden files and directories (or not).35+ pub ignore_hidden: bool,36+37+ /// Whether to respect VCS ignore files (`.gitignore`, `.ignore`, ..) or not.38+ pub read_ignore: bool,39+40+ /// Whether to follow symlinks or not.41+ pub follow_links: bool,42+43+ /// Whether elements of output should be separated by a null character44+ pub null_separator: bool,45+46+ /// 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>,51+52+ /// The number of threads to use.53+ pub threads: usize,54+55+ /// 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>,59+60+ /// Display results as relative or absolute path.61+ pub path_display: PathDisplay,62+63+ /// `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>,66+67+ /// The type of file to search for. All files other than the specified type will be ignored.68+ pub file_type: FileType,69+70+ /// 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+}75+76+/// Print error message to stderr and exit with status `1`.77+pub 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 lines8 9 pub mod lscolors;10 pub mod fshelper;11 mod app;12+mod internal;13+mod output;14+mod walk;15 16 use std::env;17 use std::error::Error;15-use std::io::Write;16-use std::ops::Deref;17-#[cfg(unix)]18-use std::os::unix::fs::PermissionsExt;19-use std::path::{Path, PathBuf};20-use std::process;18+use std::path::Path;19 use std::sync::Arc;22-use std::sync::mpsc::channel;23-use std::thread;20 use std::time;21 22 use atty::Stream;27-use regex::{Regex, RegexBuilder};28-use ignore::WalkBuilder;23+use regex::RegexBuilder;24 25+use internal::{error, FdOptions, PathDisplay, ROOT_DIR};26 use lscolors::LsColors;27+use walk::FileType;28 32-/// Defines how to display search result paths.33-#[derive(PartialEq)]34-enum PathDisplay {35- /// As an absolute path36- Absolute,37-38- /// As a relative path39- Relative,40-}41-42-/// The type of file to search for.43-#[derive(Copy, Clone)]44-enum FileType {45- Any,46- RegularFile,47- Directory,48- SymLink,49-}50-51-/// Configuration options for *fd*.52-struct FdOptions {53- /// Determines whether the regex search is case-sensitive or case-insensitive.54- case_sensitive: bool,55-56- /// Whether to search within the full file path or just the base name (filename or directory57- /// name).58- search_full_path: bool,59-60- /// Whether to ignore hidden files and directories (or not).61- ignore_hidden: bool,62-63- /// Whether to respect VCS ignore files (`.gitignore`, `.ignore`, ..) or not.64- read_ignore: bool,65-66- /// Whether to follow symlinks or not.67- follow_links: bool,68-69- /// Whether elements of output should be separated by a null character70- null_separator: bool,71-72- /// 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>,77-78- /// The number of threads to use.79- threads: usize,80-81- /// 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>,85-86- /// Display results as relative or absolute path.87- path_display: PathDisplay,88-89- /// `None` if the output should not be colorized. Otherwise, a `LsColors` instance that defines90- /// how to style different filetypes.91- ls_colors: Option<LsColors>,92-93- /// The type of file to search for. All files other than the specified type will be ignored.94- file_type: FileType,95-96- /// 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-}101-102-/// The receiver thread can either be buffering results or directly streaming to the console.103-enum ReceiverMode {104- /// Receiver is still buffering in order to sort the results, if the search finishes fast105- /// enough.106- Buffering,107-108- /// Receiver is directly printing results to the output.109- Streaming,110-}111-112-/// Root directory113-#[cfg(unix)]114-static ROOT_DIR: &'static str = "/";115-116-#[cfg(windows)]117-static ROOT_DIR: &'static str = "";118-119-/// Print a search result to the console.120-fn print_entry(base: &Path, entry: &PathBuf, config: &FdOptions) {121- let path_full = base.join(entry);122-123- let path_str = entry.to_string_lossy();124-125- #[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- };130-131- #[cfg(windows)]132- let is_executable = |_: Option<&std::fs::Metadata>| false;133-134- let stdout = std::io::stdout();135- let mut handle = stdout.lock();136-137- if let Some(ref ls_colors) = config.ls_colors {138- let default_style = ansi_term::Style::default();139-140- let mut component_path = base.to_path_buf();141-142- if config.path_display == PathDisplay::Absolute {143- print!("{}", ls_colors.directory.paint(ROOT_DIR));144- }145-146- // Traverse the path and colorize each component147- for component in entry.components() {148- let comp_str = component.as_os_str().to_string_lossy();149-150- component_path.push(Path::new(comp_str.deref()));151-152- let metadata = component_path.metadata().ok();153- let is_directory = metadata.as_ref().map(|md| md.is_dir()).unwrap_or(false);154-155- 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));170-171- 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- };181-182- write!(handle, "{}", style.paint(comp_str)).ok();183-184- 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- }189-190- 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 output201-202- let prefix = if config.path_display == PathDisplay::Absolute { ROOT_DIR } else { "" };203- let separator = if config.null_separator { "\0" } else { "\n" };204-205- let r = write!(&mut std::io::stdout(), "{}{}{}", prefix, path_str, separator);206-207- if r.is_err() {208- // Probably a broken pipe. Exit gracefully.209- process::exit(0);210- }211- }212-}213-214-/// Recursively scan the given search path and search for files / pathnames matching the pattern.215-fn scan(root: &Path, pattern: Arc<Regex>, base: &Path, config: Arc<FdOptions>) {216- let (tx, rx) = channel();217-218- 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();229-230- // 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();235-236- let mut buffer = vec![];237-238- // Start in buffering mode239- let mut mode = ReceiverMode::Buffering;240-241- // 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));244-245- for value in rx {246- match mode {247- ReceiverMode::Buffering => {248- buffer.push(value);249-250- // 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();257-258- // Start streaming259- mode = ReceiverMode::Streaming;260- }261- },262- ReceiverMode::Streaming => {263- print_entry(&rx_base, &value, &rx_config);264- }265- }266- }267-268- // 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- });277-278- // 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();284-285- Box::new(move |entry_o| {286- let entry = match entry_o {287- Ok(e) => e,288- Err(_) => return ignore::WalkState::Continue,289- };290-291- // 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- }304-305- // 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- }312-313- 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();318-319- 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- };326-327- 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- }332-333- ignore::WalkState::Continue334- })335- });336-337- // 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);340-341- // Wait for the receiver thread to print out all results.342- receiver_thread.join().unwrap();343-}344-345-/// Print error message to stderr and exit with status `1`.346-fn error(message: &str) -> ! {347- writeln!(&mut std::io::stderr(), "{}", message).expect("Failed writing to stderr");348- process::exit(1);349-}350-29 fn main() {30 let matches = app::build_app().get_matches();31 32 // Get the search pattern92 unmodified lines125 126 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
1+use internal::{FdOptions, PathDisplay, ROOT_DIR};2+3+use std::{fs, process};4+use std::io::{self, Write};5+use std::ops::Deref;6+use std::path::{self, Path, PathBuf};7+#[cfg(unix)]8+use std::os::unix::fs::PermissionsExt;9+10+use ansi_term;11+12+pub fn print_entry(base: &Path, entry: &PathBuf, config: &FdOptions) {13+ let path_full = base.join(entry);14+15+ let path_str = entry.to_string_lossy();16+17+ #[cfg(unix)]18+ let is_executable = |p: Option<&fs::Metadata>| {19+ p.map(|f| f.permissions().mode() & 0o111 != 0)20+ .unwrap_or(false)21+ };22+23+ #[cfg(windows)]24+ let is_executable = |_: Option<&fs::Metadata>| false;25+26+ let stdout = io::stdout();27+ let mut handle = stdout.lock();28+29+ if let Some(ref ls_colors) = config.ls_colors {30+ let default_style = ansi_term::Style::default();31+32+ let mut component_path = base.to_path_buf();33+34+ if config.path_display == PathDisplay::Absolute {35+ print!("{}", ls_colors.directory.paint(ROOT_DIR));36+ }37+38+ // Traverse the path and colorize each component39+ for component in entry.components() {40+ let comp_str = component.as_os_str().to_string_lossy();41+42+ component_path.push(Path::new(comp_str.deref()));43+44+ let metadata = component_path.metadata().ok();45+ let is_directory = metadata.as_ref().map(|md| md.is_dir()).unwrap_or(false);46+47+ 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));62+63+ 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+ };73+74+ write!(handle, "{}", style.paint(comp_str)).ok();75+76+ if is_directory && component_path != path_full {77+ let sep = path::MAIN_SEPARATOR.to_string();78+ write!(handle, "{}", style.paint(sep)).ok();79+ }80+ }81+82+ 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 output93+94+ let prefix = if config.path_display == PathDisplay::Absolute { ROOT_DIR } else { "" };95+ let separator = if config.null_separator { "\0" } else { "\n" };96+97+ let r = write!(&mut io::stdout(), "{}{}{}", prefix, path_str, separator);98+99+ if r.is_err() {100+ // Probably a broken pipe. Exit gracefully.101+ process::exit(0);102+ }103+ }104+}added:src/walk.rs+162 added
1+use internal::{error, FdOptions};2+use fshelper;3+use output;4+5+use std::path::Path;6+use std::sync::Arc;7+use std::sync::mpsc::channel;8+use std::thread;9+use std::time;10+11+use regex::Regex;12+use ignore::{self, WalkBuilder};13+14+/// The receiver thread can either be buffering results or directly streaming to the console.15+enum ReceiverMode {16+ /// Receiver is still buffering in order to sort the results, if the search finishes fast17+ /// enough.18+ Buffering,19+20+ /// Receiver is directly printing results to the output.21+ Streaming,22+}23+24+/// The type of file to search for.25+#[derive(Copy, Clone)]26+pub enum FileType {27+ Any,28+ RegularFile,29+ Directory,30+ SymLink,31+}32+33+/// Recursively scan the given search path and search for files / pathnames matching the pattern.34+pub fn scan(root: &Path, pattern: Arc<Regex>, base: &Path, config: Arc<FdOptions>) {35+ let (tx, rx) = channel();36+37+ 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();48+49+ // 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();54+55+ let mut buffer = vec![];56+57+ // Start in buffering mode58+ let mut mode = ReceiverMode::Buffering;59+60+ // 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));63+64+ for value in rx {65+ match mode {66+ ReceiverMode::Buffering => {67+ buffer.push(value);68+69+ // 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();76+77+ // Start streaming78+ mode = ReceiverMode::Streaming;79+ }80+ },81+ ReceiverMode::Streaming => {82+ output::print_entry(&rx_base, &value, &rx_config);83+ }84+ }85+ }86+87+ // 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+ });96+97+ // 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();103+104+ Box::new(move |entry_o| {105+ let entry = match entry_o {106+ Ok(e) => e,107+ Err(_) => return ignore::WalkState::Continue,108+ };109+110+ // 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+ }123+124+ // 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+ }131+132+ 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();137+138+ 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+ };145+146+ 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+ }151+152+ ignore::WalkState::Continue153+ })154+ });155+156+ // 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);159+160+ // Wait for the receiver thread to print out all results.161+ receiver_thread.join().unwrap();162+}