main.rs
This file
Path
src/main.rs
399 lines · 13.6 KiB · Rust
Last changed by
Add new `--type socket` and `--type pipe` filterssharkdpbefore adoptioncb56add
History of this fileTake it
1mod app;2mod error;3mod exec;4mod exit_codes;5mod filesystem;6mod filetypes;7mod filter;8mod options;9mod output;10mod regex_helper;11mod walk;1213use std::env;14use std::path::{Path, PathBuf};15use std::process;16use std::sync::Arc;17use std::time;1819use anyhow::{anyhow, Context, Result};20use atty::Stream;21use globset::GlobBuilder;22use lscolors::LsColors;23use regex::bytes::{RegexBuilder, RegexSetBuilder};2425use crate::exec::CommandTemplate;26use crate::exit_codes::ExitCode;27use crate::filetypes::FileTypes;28use crate::filter::{SizeFilter, TimeFilter};29use crate::options::Options;30use crate::regex_helper::pattern_has_uppercase_char;3132// We use jemalloc for performance reasons, see https://github.com/sharkdp/fd/pull/48133#[cfg(all(not(windows), not(target_env = "musl")))]34#[global_allocator]35static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;3637fn run() -> Result<ExitCode> {38 let matches = app::build_app().get_matches_from(env::args_os());3940 // Set the current working directory of the process41 if let Some(base_directory) = matches.value_of_os("base-directory") {42 let base_directory = Path::new(base_directory);43 if !filesystem::is_dir(base_directory) {44 return Err(anyhow!(45 "The '--base-directory' path '{}' is not a directory.",46 base_directory.to_string_lossy()47 ));48 }49 env::set_current_dir(base_directory).with_context(|| {50 format!(51 "Could not set '{}' as the current working directory.",52 base_directory.to_string_lossy()53 )54 })?;55 }5657 let current_directory = Path::new(".");58 if !filesystem::is_dir(current_directory) {59 return Err(anyhow!(60 "Could not retrieve current directory (has it been deleted?)."61 ));62 }6364 // Get the search pattern65 let pattern = matches66 .value_of_os("pattern")67 .map(|p| {68 p.to_str().ok_or(anyhow!(69 "The search pattern includes invalid UTF-8 sequences."70 ))71 })72 .transpose()?73 .unwrap_or("");7475 // Get one or more root directories to search.76 let mut dir_vec: Vec<_> = match matches77 .values_of_os("path")78 .or_else(|| matches.values_of_os("search-path"))79 {80 Some(paths) => paths81 .map(|path| {82 let path_buffer = PathBuf::from(path);83 if filesystem::is_dir(&path_buffer) {84 Ok(path_buffer)85 } else {86 Err(anyhow!(87 "Search path '{}' is not a directory.",88 path_buffer.to_string_lossy()89 ))90 }91 })92 .collect::<Result<Vec<_>>>()?,93 None => vec![current_directory.to_path_buf()],94 };9596 if matches.is_present("absolute-path") {97 dir_vec = dir_vec98 .iter()99 .map(|path_buffer| {100 path_buffer101 .canonicalize()102 .and_then(|pb| filesystem::absolute_path(pb.as_path()))103 .unwrap()104 })105 .collect();106 }107108 // Detect if the user accidentally supplied a path instead of a search pattern109 if !matches.is_present("full-path")110 && pattern.contains(std::path::MAIN_SEPARATOR)111 && filesystem::is_dir(Path::new(pattern))112 {113 return Err(anyhow!(114 "The search pattern '{pattern}' contains a path-separation character ('{sep}') \115 and will not lead to any search results.\n\n\116 If you want to search for all files inside the '{pattern}' directory, use a match-all pattern:\n\n \117 fd . '{pattern}'\n\n\118 Instead, if you want your pattern to match the full file path, use:\n\n \119 fd --full-path '{pattern}'",120 pattern = pattern,121 sep = std::path::MAIN_SEPARATOR,122 ));123 }124125 let pattern_regex = if matches.is_present("glob") {126 let glob = GlobBuilder::new(pattern).literal_separator(true).build()?;127 glob.regex().to_owned()128 } else if matches.is_present("fixed-strings") {129 // Treat pattern as literal string if '--fixed-strings' is used130 regex::escape(pattern)131 } else {132 String::from(pattern)133 };134135 // The search will be case-sensitive if the command line flag is set or136 // if the pattern has an uppercase character (smart case).137 let case_sensitive = !matches.is_present("ignore-case")138 && (matches.is_present("case-sensitive") || pattern_has_uppercase_char(&pattern_regex));139140 let interactive_terminal = atty::is(Stream::Stdout);141 let colored_output = match matches.value_of("color") {142 Some("always") => true,143 Some("never") => false,144 _ => env::var_os("NO_COLOR").is_none() && interactive_terminal,145 };146147 let path_separator = matches.value_of("path-separator").map(|str| str.to_owned());148149 #[cfg(windows)]150 ansi_term::enable_ansi_support().ok();151152 let ls_colors = if colored_output {153 Some(LsColors::from_env().unwrap_or_default())154 } else {155 None156 };157158 let command = if let Some(args) = matches.values_of("exec") {159 Some(CommandTemplate::new(args))160 } else if let Some(args) = matches.values_of("exec-batch") {161 Some(CommandTemplate::new_batch(args)?)162 } else if matches.is_present("list-details") {163 let color = matches.value_of("color").unwrap_or("auto");164 let color_arg = ["--color=", color].concat();165166 #[allow(unused)]167 let gnu_ls = |command_name| {168 vec![169 command_name,170 "-l", // long listing format171 "--human-readable", // human readable file sizes172 "--directory", // list directories themselves, not their contents173 &color_arg,174 ]175 };176177 let cmd: Vec<&str> = if cfg!(unix) {178 if !cfg!(target_os = "macos") {179 // Non-MacOS Unix180 gnu_ls("ls")181 } else {182 // MacOS183 use std::process::{Command, Stdio};184185 // Use GNU ls, if available (support for --color=auto, better LS_COLORS support)186 let gnu_ls_exists = Command::new("gls")187 .arg("--version")188 .stdout(Stdio::null())189 .stderr(Stdio::null())190 .status()191 .is_ok();192193 if gnu_ls_exists {194 gnu_ls("gls")195 } else {196 let mut cmd = vec![197 "ls", // MacOS version of ls198 "-l", // long listing format199 "-h", // '--human-readable' is not available on MacOS, '-h' is200 "-d", // '--directory' is not available, but '-d' is201 ];202203 if colored_output {204 cmd.push("-G");205 }206207 cmd208 }209 }210 } else if cfg!(windows) {211 use std::process::{Command, Stdio};212213 // Use GNU ls, if available214 let gnu_ls_exists = Command::new("ls")215 .arg("--version")216 .stdout(Stdio::null())217 .stderr(Stdio::null())218 .status()219 .is_ok();220221 if gnu_ls_exists {222 gnu_ls("ls")223 } else {224 return Err(anyhow!(225 "'fd --list-details' is not supported on Windows unless GNU 'ls' is installed."226 ));227 }228 } else {229 return Err(anyhow!(230 "'fd --list-details' is not supported on this platform."231 ));232 };233234 Some(CommandTemplate::new_batch(&cmd).unwrap())235 } else {236 None237 };238239 let size_limits = if let Some(vs) = matches.values_of("size") {240 vs.map(|sf| {241 SizeFilter::from_string(sf).ok_or(anyhow!(242 "'{}' is not a valid size constraint. See 'fd --help'.",243 sf244 ))245 })246 .collect::<Result<Vec<_>>>()?247 } else {248 vec![]249 };250251 let now = time::SystemTime::now();252 let mut time_constraints: Vec<TimeFilter> = Vec::new();253 if let Some(t) = matches.value_of("changed-within") {254 if let Some(f) = TimeFilter::after(&now, t) {255 time_constraints.push(f);256 } else {257 return Err(anyhow!(258 "'{}' is not a valid date or duration. See 'fd --help'.",259 t260 ));261 }262 }263 if let Some(t) = matches.value_of("changed-before") {264 if let Some(f) = TimeFilter::before(&now, t) {265 time_constraints.push(f);266 } else {267 return Err(anyhow!(268 "'{}' is not a valid date or duration. See 'fd --help'.",269 t270 ));271 }272 }273274 let config = Options {275 case_sensitive,276 search_full_path: matches.is_present("full-path"),277 ignore_hidden: !(matches.is_present("hidden")278 || matches.occurrences_of("rg-alias-hidden-ignore") >= 2),279 read_fdignore: !(matches.is_present("no-ignore")280 || matches.is_present("rg-alias-hidden-ignore")),281 read_vcsignore: !(matches.is_present("no-ignore")282 || matches.is_present("rg-alias-hidden-ignore")283 || matches.is_present("no-ignore-vcs")),284 follow_links: matches.is_present("follow"),285 one_file_system: matches.is_present("one-file-system"),286 null_separator: matches.is_present("null_separator"),287 max_depth: matches288 .value_of("max-depth")289 .or_else(|| matches.value_of("rg-depth"))290 .or_else(|| matches.value_of("exact-depth"))291 .and_then(|n| usize::from_str_radix(n, 10).ok()),292 min_depth: matches293 .value_of("min-depth")294 .or_else(|| matches.value_of("exact-depth"))295 .and_then(|n| usize::from_str_radix(n, 10).ok()),296 threads: std::cmp::max(297 matches298 .value_of("threads")299 .and_then(|n| usize::from_str_radix(n, 10).ok())300 .unwrap_or_else(num_cpus::get),301 1,302 ),303 max_buffer_time: matches304 .value_of("max-buffer-time")305 .and_then(|n| u64::from_str_radix(n, 10).ok())306 .map(time::Duration::from_millis),307 ls_colors,308 interactive_terminal,309 file_types: matches.values_of("file-type").map(|values| {310 let mut file_types = FileTypes::default();311 for value in values {312 match value {313 "f" | "file" => file_types.files = true,314 "d" | "directory" => file_types.directories = true,315 "l" | "symlink" => file_types.symlinks = true,316 "x" | "executable" => {317 file_types.executables_only = true;318 file_types.files = true;319 }320 "e" | "empty" => file_types.empty_only = true,321 "s" | "socket" => file_types.sockets = true,322 "p" | "pipe" => file_types.pipes = true,323 _ => unreachable!(),324 }325 }326327 // If only 'empty' was specified, search for both files and directories:328 if file_types.empty_only && !(file_types.files || file_types.directories) {329 file_types.files = true;330 file_types.directories = true;331 }332333 file_types334 }),335 extensions: matches336 .values_of("extension")337 .map(|exts| {338 let patterns = exts339 .map(|e| e.trim_start_matches('.'))340 .map(|e| format!(r".\.{}$", regex::escape(e)));341 RegexSetBuilder::new(patterns)342 .case_insensitive(true)343 .build()344 })345 .transpose()?,346 command: command.map(Arc::new),347 exclude_patterns: matches348 .values_of("exclude")349 .map(|v| v.map(|p| String::from("!") + p).collect())350 .unwrap_or_else(|| vec![]),351 ignore_files: matches352 .values_of("ignore-file")353 .map(|vs| vs.map(PathBuf::from).collect())354 .unwrap_or_else(|| vec![]),355 size_constraints: size_limits,356 time_constraints,357 show_filesystem_errors: matches.is_present("show-errors"),358 path_separator,359 max_results: matches360 .value_of("max-results")361 .and_then(|n| usize::from_str_radix(n, 10).ok())362 .filter(|&n| n != 0)363 .or_else(|| {364 if matches.is_present("max-one-result") {365 Some(1)366 } else {367 None368 }369 }),370 };371372 let re = RegexBuilder::new(&pattern_regex)373 .case_insensitive(!config.case_sensitive)374 .dot_matches_new_line(true)375 .build()376 .map_err(|e| {377 anyhow!(378 "{}\n\nNote: You can use the '--fixed-strings' option to search for a \379 literal string instead of a regular expression. Alternatively, you can \380 also use the '--glob' option to match on a glob pattern.",381 e.to_string()382 )383 })?;384385 walk::scan(&dir_vec, Arc::new(re), Arc::new(config))386}387388fn main() {389 let result = run();390 match result {391 Ok(exit_code) => {392 process::exit(exit_code.into());393 }394 Err(err) => {395 eprintln!("[fd error]: {}", err);396 process::exit(ExitCode::GeneralError.into());397 }398 }399}