main.rs
This file
Path
src/main.rs
568 lines · 25.1 KiB · Rust
Last changed by
Merge pull request #861 from jcaplan/no-strip/760David Peterbefore adoptionb211ded
History of this fileTake it
1mod app;2mod config;3mod error;4mod exec;5mod exit_codes;6mod filesystem;7mod filetypes;8mod filter;9mod output;10mod regex_helper;11mod walk;1213use std::env;14use std::path::{Path, PathBuf};15use std::sync::Arc;16use std::time;1718use anyhow::{anyhow, Context, Result};19use atty::Stream;20use globset::GlobBuilder;21use lscolors::LsColors;22use normpath::PathExt;23use regex::bytes::{RegexBuilder, RegexSetBuilder};2425use crate::config::Config;26use crate::error::print_error;27use crate::exec::CommandTemplate;28use crate::exit_codes::ExitCode;29use crate::filetypes::FileTypes;30#[cfg(unix)]31use crate::filter::OwnerFilter;32use crate::filter::{SizeFilter, TimeFilter};33use crate::regex_helper::{pattern_has_uppercase_char, pattern_matches_strings_with_leading_dot};3435// We use jemalloc for performance reasons, see https://github.com/sharkdp/fd/pull/48136// FIXME: re-enable jemalloc on macOS, see comment in Cargo.toml file for more infos37#[cfg(all(38 not(windows),39 not(target_os = "android"),40 not(target_os = "macos"),41 not(target_env = "musl")42))]43#[global_allocator]44static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;4546// vivid --color-mode 8-bit generate molokai47const DEFAULT_LS_COLORS: &str = "48ow=0:or=0;38;5;16;48;5;203:no=0:ex=1;38;5;203:cd=0;38;5;203;48;5;236:mi=0;38;5;16;48;5;203:*~=0;38;5;243:st=0:pi=0;38;5;16;48;5;81:fi=0:di=0;38;5;81:so=0;38;5;16;48;5;203:bd=0;38;5;81;48;5;236:tw=0:ln=0;38;5;203:*.m=0;38;5;48:*.o=0;38;5;243:*.z=4;38;5;203:*.a=1;38;5;203:*.r=0;38;5;48:*.c=0;38;5;48:*.d=0;38;5;48:*.t=0;38;5;48:*.h=0;38;5;48:*.p=0;38;5;48:*.cc=0;38;5;48:*.ll=0;38;5;48:*.jl=0;38;5;48:*css=0;38;5;48:*.md=0;38;5;185:*.gz=4;38;5;203:*.nb=0;38;5;48:*.mn=0;38;5;48:*.go=0;38;5;48:*.xz=4;38;5;203:*.so=1;38;5;203:*.rb=0;38;5;48:*.pm=0;38;5;48:*.bc=0;38;5;243:*.py=0;38;5;48:*.as=0;38;5;48:*.pl=0;38;5;48:*.rs=0;38;5;48:*.sh=0;38;5;48:*.7z=4;38;5;203:*.ps=0;38;5;186:*.cs=0;38;5;48:*.el=0;38;5;48:*.rm=0;38;5;208:*.hs=0;38;5;48:*.td=0;38;5;48:*.ui=0;38;5;149:*.ex=0;38;5;48:*.js=0;38;5;48:*.cp=0;38;5;48:*.cr=0;38;5;48:*.la=0;38;5;243:*.kt=0;38;5;48:*.ml=0;38;5;48:*.vb=0;38;5;48:*.gv=0;38;5;48:*.lo=0;38;5;243:*.hi=0;38;5;243:*.ts=0;38;5;48:*.ko=1;38;5;203:*.hh=0;38;5;48:*.pp=0;38;5;48:*.di=0;38;5;48:*.bz=4;38;5;203:*.fs=0;38;5;48:*.png=0;38;5;208:*.zsh=0;38;5;48:*.mpg=0;38;5;208:*.pid=0;38;5;243:*.xmp=0;38;5;149:*.iso=4;38;5;203:*.m4v=0;38;5;208:*.dot=0;38;5;48:*.ods=0;38;5;186:*.inc=0;38;5;48:*.sxw=0;38;5;186:*.aif=0;38;5;208:*.git=0;38;5;243:*.gvy=0;38;5;48:*.tbz=4;38;5;203:*.log=0;38;5;243:*.txt=0;38;5;185:*.ico=0;38;5;208:*.csx=0;38;5;48:*.vob=0;38;5;208:*.pgm=0;38;5;208:*.pps=0;38;5;186:*.ics=0;38;5;186:*.img=4;38;5;203:*.fon=0;38;5;208:*.hpp=0;38;5;48:*.bsh=0;38;5;48:*.sql=0;38;5;48:*TODO=1:*.php=0;38;5;48:*.pkg=4;38;5;203:*.ps1=0;38;5;48:*.csv=0;38;5;185:*.ilg=0;38;5;243:*.ini=0;38;5;149:*.pyc=0;38;5;243:*.psd=0;38;5;208:*.htc=0;38;5;48:*.swp=0;38;5;243:*.mli=0;38;5;48:*hgrc=0;38;5;149:*.bst=0;38;5;149:*.ipp=0;38;5;48:*.fsi=0;38;5;48:*.tcl=0;38;5;48:*.exs=0;38;5;48:*.out=0;38;5;243:*.jar=4;38;5;203:*.xls=0;38;5;186:*.ppm=0;38;5;208:*.apk=4;38;5;203:*.aux=0;38;5;243:*.rpm=4;38;5;203:*.dll=1;38;5;203:*.eps=0;38;5;208:*.exe=1;38;5;203:*.doc=0;38;5;186:*.wma=0;38;5;208:*.deb=4;38;5;203:*.pod=0;38;5;48:*.ind=0;38;5;243:*.nix=0;38;5;149:*.lua=0;38;5;48:*.epp=0;38;5;48:*.dpr=0;38;5;48:*.htm=0;38;5;185:*.ogg=0;38;5;208:*.bin=4;38;5;203:*.otf=0;38;5;208:*.yml=0;38;5;149:*.pro=0;38;5;149:*.cxx=0;38;5;48:*.tex=0;38;5;48:*.fnt=0;38;5;208:*.erl=0;38;5;48:*.sty=0;38;5;243:*.bag=4;38;5;203:*.rst=0;38;5;185:*.pdf=0;38;5;186:*.pbm=0;38;5;208:*.xcf=0;38;5;208:*.clj=0;38;5;48:*.gif=0;38;5;208:*.rar=4;38;5;203:*.elm=0;38;5;48:*.bib=0;38;5;149:*.tsx=0;38;5;48:*.dmg=4;38;5;203:*.tmp=0;38;5;243:*.bcf=0;38;5;243:*.mkv=0;38;5;208:*.svg=0;38;5;208:*.cpp=0;38;5;48:*.vim=0;38;5;48:*.bmp=0;38;5;208:*.ltx=0;38;5;48:*.fls=0;38;5;243:*.flv=0;38;5;208:*.wav=0;38;5;208:*.m4a=0;38;5;208:*.mid=0;38;5;208:*.hxx=0;38;5;48:*.pas=0;38;5;48:*.wmv=0;38;5;208:*.tif=0;38;5;208:*.kex=0;38;5;186:*.mp4=0;38;5;208:*.bak=0;38;5;243:*.xlr=0;38;5;186:*.dox=0;38;5;149:*.swf=0;38;5;208:*.tar=4;38;5;203:*.tgz=4;38;5;203:*.cfg=0;38;5;149:*.xml=0;4938;5;185:*.jpg=0;38;5;208:*.mir=0;38;5;48:*.sxi=0;38;5;186:*.bz2=4;38;5;203:*.odt=0;38;5;186:*.mov=0;38;5;208:*.toc=0;38;5;243:*.bat=1;38;5;203:*.asa=0;38;5;48:*.awk=0;38;5;48:*.sbt=0;38;5;48:*.vcd=4;38;5;203:*.kts=0;38;5;48:*.arj=4;38;5;203:*.blg=0;38;5;243:*.c++=0;38;5;48:*.odp=0;38;5;186:*.bbl=0;38;5;243:*.idx=0;38;5;243:*.com=1;38;5;203:*.mp3=0;38;5;208:*.avi=0;38;5;208:*.def=0;38;5;48:*.cgi=0;38;5;48:*.zip=4;38;5;203:*.ttf=0;38;5;208:*.ppt=0;38;5;186:*.tml=0;38;5;149:*.fsx=0;38;5;48:*.h++=0;38;5;48:*.rtf=0;38;5;186:*.inl=0;38;5;48:*.yaml=0;38;5;149:*.html=0;38;5;185:*.mpeg=0;38;5;208:*.java=0;38;5;48:*.hgrc=0;38;5;149:*.orig=0;38;5;243:*.conf=0;38;5;149:*.dart=0;38;5;48:*.psm1=0;38;5;48:*.rlib=0;38;5;243:*.fish=0;38;5;48:*.bash=0;38;5;48:*.make=0;38;5;149:*.docx=0;38;5;186:*.json=0;38;5;149:*.psd1=0;38;5;48:*.lisp=0;38;5;48:*.tbz2=4;38;5;203:*.diff=0;38;5;48:*.epub=0;38;5;186:*.xlsx=0;38;5;186:*.pptx=0;38;5;186:*.toml=0;38;5;149:*.h264=0;38;5;208:*.purs=0;38;5;48:*.flac=0;38;5;208:*.tiff=0;38;5;208:*.jpeg=0;38;5;208:*.lock=0;38;5;243:*.less=0;38;5;48:*.dyn_o=0;38;5;243:*.scala=0;38;5;48:*.mdown=0;38;5;185:*.shtml=0;38;5;185:*.class=0;38;5;243:*.cache=0;38;5;243:*.cmake=0;38;5;149:*passwd=0;38;5;149:*.swift=0;38;5;48:*shadow=0;38;5;149:*.xhtml=0;38;5;185:*.patch=0;38;5;48:*.cabal=0;38;5;48:*README=0;38;5;16;48;5;186:*.toast=4;38;5;203:*.ipynb=0;38;5;48:*COPYING=0;38;5;249:*.gradle=0;38;5;48:*.matlab=0;38;5;48:*.config=0;38;5;149:*LICENSE=0;38;5;249:*.dyn_hi=0;38;5;243:*.flake8=0;38;5;149:*.groovy=0;38;5;48:*INSTALL=0;38;5;16;48;5;186:*TODO.md=1:*.ignore=0;38;5;149:*Doxyfile=0;38;5;149:*TODO.txt=1:*setup.py=0;38;5;149:*Makefile=0;38;5;149:*.gemspec=0;38;5;149:*.desktop=0;38;5;149:*.rgignore=0;38;5;149:*.markdown=0;38;5;185:*COPYRIGHT=0;38;5;249:*configure=0;38;5;149:*.DS_Store=0;38;5;243:*.kdevelop=0;38;5;149:*.fdignore=0;38;5;149:*README.md=0;38;5;16;48;5;186:*.cmake.in=0;38;5;149:*SConscript=0;38;5;149:*CODEOWNERS=0;38;5;149:*.localized=0;38;5;243:*.gitignore=0;38;5;149:*Dockerfile=0;38;5;149:*.gitconfig=0;38;5;149:*INSTALL.md=0;38;5;16;48;5;186:*README.txt=0;38;5;16;48;5;186:*SConstruct=0;38;5;149:*.scons_opt=0;38;5;243:*.travis.yml=0;38;5;186:*.gitmodules=0;38;5;149:*.synctex.gz=0;38;5;243:*LICENSE-MIT=0;38;5;249:*MANIFEST.in=0;38;5;149:*Makefile.in=0;38;5;243:*Makefile.am=0;38;5;149:*INSTALL.txt=0;38;5;16;48;5;186:*configure.ac=0;38;5;149:*.applescript=0;38;5;48:*appveyor.yml=0;38;5;186:*.fdb_latexmk=0;38;5;243:*CONTRIBUTORS=0;38;5;16;48;5;186:*.clang-format=0;38;5;149:*LICENSE-APACHE=0;38;5;249:*CMakeLists.txt=0;38;5;149:*CMakeCache.txt=0;38;5;243:*.gitattributes=0;38;5;149:*CONTRIBUTORS.md=0;38;5;16;48;5;186:*.sconsign.dblite=0;38;5;243:*requirements.txt=0;38;5;149:*CONTRIBUTORS.txt=0;38;5;16;48;5;186:*package-lock.json=0;38;5;243:*.CFUserTextEncoding=0;38;5;24350";5152fn main() {53 let result = run();54 match result {55 Ok(exit_code) => {56 exit_code.exit();57 }58 Err(err) => {59 eprintln!("[fd error]: {:#}", err);60 ExitCode::GeneralError.exit();61 }62 }63}6465fn run() -> Result<ExitCode> {66 let matches = app::build_app().get_matches_from(env::args_os());6768 set_working_dir(&matches)?;69 let current_directory = Path::new(".");70 ensure_current_directory_exists(current_directory)?;71 let search_paths = extract_search_paths(&matches, current_directory)?;7273 let pattern = extract_search_pattern(&matches)?;74 ensure_search_pattern_is_not_a_path(&matches, pattern)?;75 let pattern_regex = build_pattern_regex(&matches, pattern)?;7677 let config = construct_config(matches, &pattern_regex)?;78 ensure_use_hidden_option_for_leading_dot_pattern(&config, &pattern_regex)?;79 let re = build_regex(pattern_regex, &config)?;80 walk::scan(&search_paths, Arc::new(re), Arc::new(config))81}8283fn set_working_dir(matches: &clap::ArgMatches) -> Result<()> {84 if let Some(base_directory) = matches.value_of_os("base-directory") {85 let base_directory = Path::new(base_directory);86 if !filesystem::is_existing_directory(base_directory) {87 return Err(anyhow!(88 "The '--base-directory' path '{}' is not a directory.",89 base_directory.to_string_lossy()90 ));91 }92 env::set_current_dir(base_directory).with_context(|| {93 format!(94 "Could not set '{}' as the current working directory",95 base_directory.to_string_lossy()96 )97 })?;98 }99 Ok(())100}101102fn ensure_current_directory_exists(current_directory: &Path) -> Result<()> {103 if filesystem::is_existing_directory(current_directory) {104 Ok(())105 } else {106 Err(anyhow!(107 "Could not retrieve current directory (has it been deleted?)."108 ))109 }110}111112fn extract_search_pattern<'a>(matches: &'a clap::ArgMatches) -> Result<&'a str> {113 let pattern = matches114 .value_of_os("pattern")115 .map(|p| {116 p.to_str()117 .ok_or_else(|| anyhow!("The search pattern includes invalid UTF-8 sequences."))118 })119 .transpose()?120 .unwrap_or("");121 Ok(pattern)122}123124fn extract_search_paths(125 matches: &clap::ArgMatches,126 current_directory: &Path,127) -> Result<Vec<PathBuf>> {128 let mut search_paths = matches129 .values_of_os("path")130 .or_else(|| matches.values_of_os("search-path"))131 .map_or_else(132 || vec![current_directory.to_path_buf()],133 |paths| {134 paths135 .filter_map(|path| {136 let path_buffer = PathBuf::from(path);137 if filesystem::is_existing_directory(&path_buffer) {138 Some(path_buffer)139 } else {140 print_error(format!(141 "Search path '{}' is not a directory.",142 path_buffer.to_string_lossy()143 ));144 None145 }146 })147 .collect()148 },149 );150 if search_paths.is_empty() {151 return Err(anyhow!("No valid search paths given."));152 }153 if matches.is_present("absolute-path") {154 update_to_absolute_paths(&mut search_paths);155 }156 Ok(search_paths)157}158159fn update_to_absolute_paths(search_paths: &mut [PathBuf]) {160 for buffer in search_paths.iter_mut() {161 *buffer = filesystem::absolute_path(buffer.normalize().unwrap().as_path()).unwrap();162 }163}164165/// Detect if the user accidentally supplied a path instead of a search pattern166fn ensure_search_pattern_is_not_a_path(matches: &clap::ArgMatches, pattern: &str) -> Result<()> {167 if !matches.is_present("full-path")168 && pattern.contains(std::path::MAIN_SEPARATOR)169 && Path::new(pattern).is_dir()170 {171 Err(anyhow!(172 "The search pattern '{pattern}' contains a path-separation character ('{sep}') \173 and will not lead to any search results.\n\n\174 If you want to search for all files inside the '{pattern}' directory, use a match-all pattern:\n\n \175 fd . '{pattern}'\n\n\176 Instead, if you want your pattern to match the full file path, use:\n\n \177 fd --full-path '{pattern}'",178 pattern = pattern,179 sep = std::path::MAIN_SEPARATOR,180 ))181 } else {182 Ok(())183 }184}185186fn build_pattern_regex(matches: &clap::ArgMatches, pattern: &str) -> Result<String> {187 Ok(if matches.is_present("glob") && !pattern.is_empty() {188 let glob = GlobBuilder::new(pattern).literal_separator(true).build()?;189 glob.regex().to_owned()190 } else if matches.is_present("fixed-strings") {191 // Treat pattern as literal string if '--fixed-strings' is used192 regex::escape(pattern)193 } else {194 String::from(pattern)195 })196}197198fn check_path_separator_length(path_separator: Option<&str>) -> Result<()> {199 match (cfg!(windows), path_separator) {200 (true, Some(sep)) if sep.len() > 1 => Err(anyhow!(201 "A path separator must be exactly one byte, but \202 the given separator is {} bytes: '{}'.\n\203 In some shells on Windows, '/' is automatically \204 expanded. Try to use '//' instead.",205 sep.len(),206 sep207 )),208 _ => Ok(()),209 }210}211212fn construct_config(matches: clap::ArgMatches, pattern_regex: &str) -> Result<Config> {213 // The search will be case-sensitive if the command line flag is set or214 // if the pattern has an uppercase character (smart case).215 let case_sensitive = !matches.is_present("ignore-case")216 && (matches.is_present("case-sensitive") || pattern_has_uppercase_char(pattern_regex));217218 let path_separator = matches219 .value_of("path-separator")220 .map_or_else(filesystem::default_path_separator, |s| Some(s.to_owned()));221 check_path_separator_length(path_separator.as_deref())?;222223 let size_limits = extract_size_limits(&matches)?;224 let time_constraints = extract_time_constraints(&matches)?;225 #[cfg(unix)]226 let owner_constraint = matches227 .value_of("owner")228 .map(OwnerFilter::from_string)229 .transpose()?230 .flatten();231232 #[cfg(windows)]233 let ansi_colors_support =234 ansi_term::enable_ansi_support().is_ok() || std::env::var_os("TERM").is_some();235 #[cfg(not(windows))]236 let ansi_colors_support = true;237238 let interactive_terminal = atty::is(Stream::Stdout);239 let colored_output = match matches.value_of("color") {240 Some("always") => true,241 Some("never") => false,242 _ => ansi_colors_support && env::var_os("NO_COLOR").is_none() && interactive_terminal,243 };244245 let ls_colors = if colored_output {246 Some(LsColors::from_env().unwrap_or_else(|| LsColors::from_string(DEFAULT_LS_COLORS)))247 } else {248 None249 };250 let command = extract_command(&matches, path_separator.as_deref(), colored_output)?;251252 Ok(Config {253 case_sensitive,254 search_full_path: matches.is_present("full-path"),255 ignore_hidden: !(matches.is_present("hidden")256 || matches.occurrences_of("rg-alias-hidden-ignore") >= 2),257 read_fdignore: !(matches.is_present("no-ignore")258 || matches.is_present("rg-alias-hidden-ignore")),259 read_vcsignore: !(matches.is_present("no-ignore")260 || matches.is_present("rg-alias-hidden-ignore")261 || matches.is_present("no-ignore-vcs")),262 read_parent_ignore: !(matches.is_present("no-ignore")263 || matches.is_present("rg-alias-hidden-ignore")264 || matches.is_present("no-ignore-vcs")265 || matches.is_present("no-ignore-parent")),266 read_global_ignore: !(matches.is_present("no-ignore")267 || matches.is_present("rg-alias-hidden-ignore")268 || matches.is_present("no-global-ignore-file")),269 follow_links: matches.is_present("follow"),270 one_file_system: matches.is_present("one-file-system"),271 null_separator: matches.is_present("null_separator"),272 quiet: matches.is_present("quiet"),273 max_depth: matches274 .value_of("max-depth")275 .or_else(|| matches.value_of("rg-depth"))276 .or_else(|| matches.value_of("exact-depth"))277 .map(|n| n.parse::<usize>())278 .transpose()279 .context("Failed to parse argument to --max-depth/--exact-depth")?,280 min_depth: matches281 .value_of("min-depth")282 .or_else(|| matches.value_of("exact-depth"))283 .map(|n| n.parse::<usize>())284 .transpose()285 .context("Failed to parse argument to --min-depth/--exact-depth")?,286 prune: matches.is_present("prune"),287 threads: std::cmp::max(288 matches289 .value_of("threads")290 .map(|n| n.parse::<usize>())291 .transpose()292 .context("Failed to parse number of threads")?293 .map(|n| {294 if n > 0 {295 Ok(n)296 } else {297 Err(anyhow!("Number of threads must be positive."))298 }299 })300 .transpose()?301 .unwrap_or_else(num_cpus::get),302 1,303 ),304 max_buffer_time: matches305 .value_of("max-buffer-time")306 .map(|n| n.parse::<u64>())307 .transpose()308 .context("Failed to parse max. buffer time argument")?309 .map(time::Duration::from_millis),310 ls_colors,311 interactive_terminal,312 file_types: matches.values_of("file-type").map(|values| {313 let mut file_types = FileTypes::default();314 for value in values {315 match value {316 "f" | "file" => file_types.files = true,317 "d" | "directory" => file_types.directories = true,318 "l" | "symlink" => file_types.symlinks = true,319 "x" | "executable" => {320 file_types.executables_only = true;321 file_types.files = true;322 }323 "e" | "empty" => file_types.empty_only = true,324 "s" | "socket" => file_types.sockets = true,325 "p" | "pipe" => file_types.pipes = true,326 _ => unreachable!(),327 }328 }329330 // If only 'empty' was specified, search for both files and directories:331 if file_types.empty_only && !(file_types.files || file_types.directories) {332 file_types.files = true;333 file_types.directories = true;334 }335336 file_types337 }),338 extensions: matches339 .values_of("extension")340 .map(|exts| {341 let patterns = exts342 .map(|e| e.trim_start_matches('.'))343 .map(|e| format!(r".\.{}$", regex::escape(e)));344 RegexSetBuilder::new(patterns)345 .case_insensitive(true)346 .build()347 })348 .transpose()?,349 command: command.map(Arc::new),350 batch_size: matches351 .value_of("batch-size")352 .map(|n| n.parse::<usize>())353 .transpose()354 .context("Failed to parse --batch-size argument")?355 .unwrap_or_default(),356 exclude_patterns: matches357 .values_of("exclude")358 .map(|v| v.map(|p| String::from("!") + p).collect())359 .unwrap_or_else(Vec::new),360 ignore_files: matches361 .values_of("ignore-file")362 .map(|vs| vs.map(PathBuf::from).collect())363 .unwrap_or_else(Vec::new),364 size_constraints: size_limits,365 time_constraints,366 #[cfg(unix)]367 owner_constraint,368 show_filesystem_errors: matches.is_present("show-errors"),369 path_separator,370 max_results: matches371 .value_of("max-results")372 .map(|n| n.parse::<usize>())373 .transpose()374 .context("Failed to parse --max-results argument")?375 .filter(|&n| n > 0)376 .or_else(|| {377 if matches.is_present("max-one-result") {378 Some(1)379 } else {380 None381 }382 }),383 strip_cwd_prefix: (!matches.is_present("path")384 && !matches.is_present("search-path")385 && (interactive_terminal || matches.is_present("strip-cwd-prefix"))),386 })387}388389fn extract_command(390 matches: &clap::ArgMatches,391 path_separator: Option<&str>,392 colored_output: bool,393) -> Result<Option<CommandTemplate>> {394 None.or_else(|| {395 matches.values_of("exec").map(|args| {396 Ok(CommandTemplate::new(397 args,398 path_separator.map(str::to_string),399 ))400 })401 })402 .or_else(|| {403 matches404 .values_of("exec-batch")405 .map(|args| CommandTemplate::new_batch(args, path_separator.map(str::to_string)))406 })407 .or_else(|| {408 if !matches.is_present("list-details") {409 return None;410 }411412 let color = matches.value_of("color").unwrap_or("auto");413 let color_arg = format!("--color={}", color);414415 let res = determine_ls_command(&color_arg, colored_output).map(|cmd| {416 CommandTemplate::new_batch(cmd, path_separator.map(str::to_string)).unwrap()417 });418419 Some(res)420 })421 .transpose()422}423424fn determine_ls_command(color_arg: &str, colored_output: bool) -> Result<Vec<&str>> {425 #[allow(unused)]426 let gnu_ls = |command_name| {427 // Note: we use short options here (instead of --long-options) to support more428 // platforms (like BusyBox).429 vec![430 command_name,431 "-l", // long listing format432 "-h", // human readable file sizes433 "-d", // list directories themselves, not their contents434 color_arg,435 ]436 };437 let cmd: Vec<&str> = if cfg!(unix) {438 if !cfg!(any(439 target_os = "macos",440 target_os = "dragonfly",441 target_os = "freebsd",442 target_os = "netbsd",443 target_os = "openbsd"444 )) {445 // Assume ls is GNU ls446 gnu_ls("ls")447 } else {448 // MacOS, DragonFlyBSD, FreeBSD449 use std::process::{Command, Stdio};450451 // Use GNU ls, if available (support for --color=auto, better LS_COLORS support)452 let gnu_ls_exists = Command::new("gls")453 .arg("--version")454 .stdout(Stdio::null())455 .stderr(Stdio::null())456 .status()457 .is_ok();458459 if gnu_ls_exists {460 gnu_ls("gls")461 } else {462 let mut cmd = vec![463 "ls", // BSD version of ls464 "-l", // long listing format465 "-h", // '--human-readable' is not available, '-h' is466 "-d", // '--directory' is not available, but '-d' is467 ];468469 if !cfg!(any(target_os = "netbsd", target_os = "openbsd")) && colored_output {470 // -G is not available in NetBSD's and OpenBSD's ls471 cmd.push("-G");472 }473474 cmd475 }476 }477 } else if cfg!(windows) {478 use std::process::{Command, Stdio};479480 // Use GNU ls, if available481 let gnu_ls_exists = Command::new("ls")482 .arg("--version")483 .stdout(Stdio::null())484 .stderr(Stdio::null())485 .status()486 .is_ok();487488 if gnu_ls_exists {489 gnu_ls("ls")490 } else {491 return Err(anyhow!(492 "'fd --list-details' is not supported on Windows unless GNU 'ls' is installed."493 ));494 }495 } else {496 return Err(anyhow!(497 "'fd --list-details' is not supported on this platform."498 ));499 };500 Ok(cmd)501}502503fn extract_size_limits(matches: &clap::ArgMatches) -> Result<Vec<SizeFilter>> {504 matches.values_of("size").map_or(Ok(Vec::new()), |vs| {505 vs.map(|sf| {506 SizeFilter::from_string(sf)507 .ok_or_else(|| anyhow!("'{}' is not a valid size constraint. See 'fd --help'.", sf))508 })509 .collect::<Result<Vec<_>>>()510 })511}512513fn extract_time_constraints(matches: &clap::ArgMatches) -> Result<Vec<TimeFilter>> {514 let now = time::SystemTime::now();515 let mut time_constraints: Vec<TimeFilter> = Vec::new();516 if let Some(t) = matches.value_of("changed-within") {517 if let Some(f) = TimeFilter::after(&now, t) {518 time_constraints.push(f);519 } else {520 return Err(anyhow!(521 "'{}' is not a valid date or duration. See 'fd --help'.",522 t523 ));524 }525 }526 if let Some(t) = matches.value_of("changed-before") {527 if let Some(f) = TimeFilter::before(&now, t) {528 time_constraints.push(f);529 } else {530 return Err(anyhow!(531 "'{}' is not a valid date or duration. See 'fd --help'.",532 t533 ));534 }535 }536 Ok(time_constraints)537}538539fn ensure_use_hidden_option_for_leading_dot_pattern(540 config: &Config,541 pattern_regex: &str,542) -> Result<()> {543 if cfg!(unix) && config.ignore_hidden && pattern_matches_strings_with_leading_dot(pattern_regex)544 {545 Err(anyhow!(546 "The pattern seems to only match files with a leading dot, but hidden files are \547 filtered by default. Consider adding -H/--hidden to search hidden files as well \548 or adjust your search pattern."549 ))550 } else {551 Ok(())552 }553}554555fn build_regex(pattern_regex: String, config: &Config) -> Result<regex::bytes::Regex> {556 RegexBuilder::new(&pattern_regex)557 .case_insensitive(!config.case_sensitive)558 .dot_matches_new_line(true)559 .build()560 .map_err(|e| {561 anyhow!(562 "{}\n\nNote: You can use the '--fixed-strings' option to search for a \563 literal string instead of a regular expression. Alternatively, you can \564 also use the '--glob' option to match on a glob pattern.",565 e.to_string()566 )567 })568}