Skip to content
Myr

Refactor: extract some methods out of `run` and reorder `main.rs`

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

Now, the top method is `main`, then comes `run`, then the methods used in `run` follow. Generally, a method is always declared somewhere after its first use. This way, you can read the file from top to bottom with a decreasing level of abstraction (you start with very high-level processes like setting the current dir and logic for which ls command to use only comes furher down).

authored by Niklas Mohrin · committed by David Peter · parent 3de948a · Browse files · 1 file+282 added−220 removed
This commit

State

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

Diff stats

1 file+282 added−220 removed

  • other:+282 added−220 removed

1 file+282 added−220 removed

modified:src/main.rs+282 added-220 removed
48 unmodified lines
49ow=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;5038;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;24351";5253fn main() {54 let result = run();55 match result {56 Ok(exit_code) => {57 process::exit(exit_code.into());58 }59 Err(err) => {60 eprintln!("[fd error]: {:#}", err);61 process::exit(ExitCode::GeneralError.into());62 }63 }64}6566fn run() -> Result<ExitCode> {67 let matches = app::build_app().get_matches_from(env::args_os());6856 // Set the current working directory of the process69 set_working_dir(&matches)?;70 let current_directory = Path::new(".");71 ensure_current_directory_exists(current_directory)?;72 let search_paths = extract_search_paths(&matches, current_directory)?;7374 let pattern = extract_search_pattern(&matches)?;75 ensure_search_pattern_is_not_a_path(&matches, pattern)?;76 let pattern_regex = build_pattern_regex(&matches, pattern)?;7778 let config = construct_options(matches, &pattern_regex)?;79 ensure_use_hidden_option_for_leading_dot_pattern(&config, &pattern_regex)?;80 let re = build_regex(pattern_regex, &config)?;81 walk::scan(&search_paths, Arc::new(re), Arc::new(config))82}8384fn set_working_dir(matches: &clap::ArgMatches) -> Result<()> {85 if let Some(base_directory) = matches.value_of_os("base-directory") {86 let base_directory = Path::new(base_directory);87 if !filesystem::is_existing_directory(base_directory) {88 return Err(anyhow!(
7 unmodified lines
96 base_directory.to_string_lossy()97 )98 })?;99 }100 Ok(())101}10273 let current_directory = Path::new(".");74 if !filesystem::is_existing_directory(current_directory) {75 return Err(anyhow!(103fn ensure_current_directory_exists(current_directory: &Path) -> Result<()> {104 if filesystem::is_existing_directory(current_directory) {105 Ok(())106 } else {107 Err(anyhow!(108 "Could not retrieve current directory (has it been deleted?)."77 ));109 ))110 }111}11280 // Get the search pattern113fn extract_search_pattern<'a>(matches: &'a clap::ArgMatches) -> Result<&'a str> {114 let pattern = matches115 .value_of_os("pattern")116 .map(|p| {117 p.to_str()118 .ok_or_else(|| anyhow!("The search pattern includes invalid UTF-8 sequences."))119 })120 .transpose()?121 .unwrap_or("");122 Ok(pattern)123}12490 // Get one or more root directories to search.91 let passed_arguments = matches125fn extract_search_paths(126 matches: &clap::ArgMatches,127 current_directory: &Path,128) -> Result<Vec<PathBuf>> {129 let mut search_paths = matches130 .values_of_os("path")93 .or_else(|| matches.values_of_os("search-path"));9495 let mut search_paths = if let Some(paths) = passed_arguments {96 let mut directories = vec![];97 for path in paths {98 let path_buffer = PathBuf::from(path);99 if filesystem::is_existing_directory(&path_buffer) {100 directories.push(path_buffer);101 } else {102 print_error(format!(103 "Search path '{}' is not a directory.",104 path_buffer.to_string_lossy()105 ));106 }107 }108109 directories110 } else {111 vec![current_directory.to_path_buf()]112 };113114 // Check if we have no valid search paths.131 .or_else(|| matches.values_of_os("search-path"))132 .map_or_else(133 || vec![current_directory.to_path_buf()],134 |paths| {135 paths136 .filter_map(|path| {137 let path_buffer = PathBuf::from(path);138 if filesystem::is_existing_directory(&path_buffer) {139 Some(path_buffer)140 } else {141 print_error(format!(142 "Search path '{}' is not a directory.",143 path_buffer.to_string_lossy()144 ));145 None146 }147 })148 .collect()149 },150 );151 if search_paths.is_empty() {152 return Err(anyhow!("No valid search paths given."));153 }118154 if matches.is_present("absolute-path") {120 search_paths = search_paths121 .iter()122 .map(|path_buffer| {123 path_buffer124 .normalize()125 .and_then(|pb| filesystem::absolute_path(pb.as_path()))126 .unwrap()127 })128 .collect();155 update_to_absolute_paths(&mut search_paths);156 }157 Ok(search_paths)158}159160fn update_to_absolute_paths(search_paths: &mut [PathBuf]) {161 for buffer in search_paths.iter_mut() {162 *buffer = filesystem::absolute_path(buffer.normalize().unwrap().as_path()).unwrap();163 }164}165131 // Detect if the user accidentally supplied a path instead of a search pattern166/// Detect if the user accidentally supplied a path instead of a search pattern167fn ensure_search_pattern_is_not_a_path(matches: &clap::ArgMatches, pattern: &str) -> Result<()> {168 if !matches.is_present("full-path")169 && pattern.contains(std::path::MAIN_SEPARATOR)170 && Path::new(pattern).is_dir()171 {136 return Err(anyhow!(172 Err(anyhow!(173 "The search pattern '{pattern}' contains a path-separation character ('{sep}') \174 and will not lead to any search results.\n\n\175 If you want to search for all files inside the '{pattern}' directory, use a match-all pattern:\n\n \176 fd . '{pattern}'\n\n\177 Instead, if you want your pattern to match the full file path, use:\n\n \178 fd --full-path '{pattern}'",179 pattern = pattern,180 sep = std::path::MAIN_SEPARATOR,145 ));181 ))182 } else {183 Ok(())184 }185}186187fn build_pattern_regex(matches: &clap::ArgMatches, pattern: &str) -> Result<String> {148 let pattern_regex = if matches.is_present("glob") && !pattern.is_empty() {188 Ok(if matches.is_present("glob") && !pattern.is_empty() {189 let glob = GlobBuilder::new(pattern).literal_separator(true).build()?;190 glob.regex().to_owned()191 } else if matches.is_present("fixed-strings") {192 // Treat pattern as literal string if '--fixed-strings' is used193 regex::escape(pattern)194 } else {195 String::from(pattern)156 };196 })197}198199fn check_path_separator_length(path_separator: Option<&str>) -> Result<()> {200 match (cfg!(windows), path_separator) {201 (true, Some(sep)) if sep.len() > 1 => Err(anyhow!(202 "A path separator must be exactly one byte, but \203 the given separator is {} bytes: '{}'.\n\204 In some shells on Windows, '/' is automatically \205 expanded. Try to use '//' instead.",206 sep.len(),207 sep208 )),209 _ => Ok(()),210 }211}212213fn construct_options(matches: clap::ArgMatches, pattern_regex: &str) -> Result<Options> {214 // The search will be case-sensitive if the command line flag is set or215 // if the pattern has an uppercase character (smart case).216 let case_sensitive = !matches.is_present("ignore-case")161 && (matches.is_present("case-sensitive") || pattern_has_uppercase_char(&pattern_regex));217 && (matches.is_present("case-sensitive") || pattern_has_uppercase_char(pattern_regex));218219 let path_separator = matches220 .value_of("path-separator")221 .map_or_else(filesystem::default_path_separator, |s| Some(s.to_owned()));222 check_path_separator_length(path_separator.as_deref())?;223224 let size_limits = extract_size_limits(&matches)?;225 let time_constraints = extract_time_constraints(&matches)?;226 #[cfg(unix)]227 let owner_constraint = matches228 .value_of("owner")229 .map(OwnerFilter::from_string)230 .transpose()?231 .flatten();232233 #[cfg(windows)]234 let ansi_colors_support =235 ansi_term::enable_ansi_support().is_ok() || std::env::var_os("TERM").is_some();166236 #[cfg(not(windows))]237 let ansi_colors_support = true;238239 let interactive_terminal = atty::is(Stream::Stdout);
2 unmodified lines
242 Some("never") => false,243 _ => ansi_colors_support && env::var_os("NO_COLOR").is_none() && interactive_terminal,244 };245177 let path_separator = matches178 .value_of("path-separator")179 .map_or_else(filesystem::default_path_separator, |s| Some(s.to_owned()));180181 #[cfg(windows)]182 {183 if let Some(ref sep) = path_separator {184 if sep.len() > 1 {185 return Err(anyhow!(186 "A path separator must be exactly one byte, but \187 the given separator is {} bytes: '{}'.\n\188 In some shells on Windows, '/' is automatically \189 expanded. Try to use '//' instead.",190 sep.len(),191 sep192 ));193 };194 };195 }196246 let ls_colors = if colored_output {247 Some(LsColors::from_env().unwrap_or_else(|| LsColors::from_string(DEFAULT_LS_COLORS)))248 } else {249 None250 };251 let command = extract_command(&matches, path_separator.as_deref(), colored_output)?;252203 let command = if let Some(args) = matches.values_of("exec") {204 Some(CommandTemplate::new(args, path_separator.clone()))205 } else if let Some(args) = matches.values_of("exec-batch") {206 Some(CommandTemplate::new_batch(args, path_separator.clone())?)207 } else if matches.is_present("list-details") {208 let color = matches.value_of("color").unwrap_or("auto");209 let color_arg = ["--color=", color].concat();210211 #[allow(unused)]212 let gnu_ls = |command_name| {213 // Note: we use short options here (instead of --long-options) to support more214 // platforms (like BusyBox).215 vec![216 command_name,217 "-l", // long listing format218 "-h", // human readable file sizes219 "-d", // list directories themselves, not their contents220 &color_arg,221 ]222 };223224 let cmd: Vec<&str> = if cfg!(unix) {225 if !cfg!(any(226 target_os = "macos",227 target_os = "dragonfly",228 target_os = "freebsd",229 target_os = "netbsd",230 target_os = "openbsd"231 )) {232 // Assume ls is GNU ls233 gnu_ls("ls")234 } else {235 // MacOS, DragonFlyBSD, FreeBSD236 use std::process::{Command, Stdio};237238 // Use GNU ls, if available (support for --color=auto, better LS_COLORS support)239 let gnu_ls_exists = Command::new("gls")240 .arg("--version")241 .stdout(Stdio::null())242 .stderr(Stdio::null())243 .status()244 .is_ok();245246 if gnu_ls_exists {247 gnu_ls("gls")248 } else {249 let mut cmd = vec![250 "ls", // BSD version of ls251 "-l", // long listing format252 "-h", // '--human-readable' is not available, '-h' is253 "-d", // '--directory' is not available, but '-d' is254 ];255256 if !cfg!(any(target_os = "netbsd", target_os = "openbsd")) && colored_output {257 // -G is not available in NetBSD's and OpenBSD's ls258 cmd.push("-G");259 }260261 cmd262 }263 }264 } else if cfg!(windows) {265 use std::process::{Command, Stdio};266267 // Use GNU ls, if available268 let gnu_ls_exists = Command::new("ls")269 .arg("--version")270 .stdout(Stdio::null())271 .stderr(Stdio::null())272 .status()273 .is_ok();274275 if gnu_ls_exists {276 gnu_ls("ls")277 } else {278 return Err(anyhow!(279 "'fd --list-details' is not supported on Windows unless GNU 'ls' is installed."280 ));281 }282 } else {283 return Err(anyhow!(284 "'fd --list-details' is not supported on this platform."285 ));286 };287288 Some(CommandTemplate::new_batch(&cmd, path_separator.clone()).unwrap())289 } else {290 None291 };292293 let size_limits = if let Some(vs) = matches.values_of("size") {294 vs.map(|sf| {295 SizeFilter::from_string(sf)296 .ok_or_else(|| anyhow!("'{}' is not a valid size constraint. See 'fd --help'.", sf))297 })298 .collect::<Result<Vec<_>>>()?299 } else {300 vec![]301 };302303 let now = time::SystemTime::now();304 let mut time_constraints: Vec<TimeFilter> = Vec::new();305 if let Some(t) = matches.value_of("changed-within") {306 if let Some(f) = TimeFilter::after(&now, t) {307 time_constraints.push(f);308 } else {309 return Err(anyhow!(310 "'{}' is not a valid date or duration. See 'fd --help'.",311 t312 ));313 }314 }315 if let Some(t) = matches.value_of("changed-before") {316 if let Some(f) = TimeFilter::before(&now, t) {317 time_constraints.push(f);318 } else {319 return Err(anyhow!(320 "'{}' is not a valid date or duration. See 'fd --help'.",321 t322 ));323 }324 }325326 #[cfg(unix)]327 let owner_constraint = if let Some(s) = matches.value_of("owner") {328 OwnerFilter::from_string(s)?329 } else {330 None331 };332333 let config = Options {253 Ok(Options {254 case_sensitive,255 search_full_path: matches.is_present("full-path"),256 ignore_hidden: !(matches.is_present("hidden")257 || matches.occurrences_of("rg-alias-hidden-ignore") >= 2),
116 unmodified lines
374 } else {375 None376 }377 }),378 })379}380381fn extract_command(382 matches: &clap::ArgMatches,383 path_separator: Option<&str>,384 colored_output: bool,385) -> Result<Option<CommandTemplate>> {386 None.or_else(|| {387 matches.values_of("exec").map(|args| {388 Ok(CommandTemplate::new(389 args,390 path_separator.map(str::to_string),391 ))392 })393 })394 .or_else(|| {395 matches396 .values_of("exec-batch")397 .map(|args| CommandTemplate::new_batch(args, path_separator.map(str::to_string)))398 })399 .or_else(|| {400 if !matches.is_present("list-details") {401 return None;402 }403404 let color = matches.value_of("color").unwrap_or("auto");405 let color_arg = format!("--color={}", color);406407 let res = determine_ls_command(&color_arg, colored_output).map(|cmd| {408 CommandTemplate::new_batch(cmd, path_separator.map(str::to_string)).unwrap()409 });410411 Some(res)412 })413 .transpose()414}415416fn determine_ls_command(color_arg: &str, colored_output: bool) -> Result<Vec<&str>> {417 #[allow(unused)]418 let gnu_ls = |command_name| {419 // Note: we use short options here (instead of --long-options) to support more420 // platforms (like BusyBox).421 vec![422 command_name,423 "-l", // long listing format424 "-h", // human readable file sizes425 "-d", // list directories themselves, not their contents426 color_arg,427 ]428 };429 let cmd: Vec<&str> = if cfg!(unix) {430 if !cfg!(any(431 target_os = "macos",432 target_os = "dragonfly",433 target_os = "freebsd",434 target_os = "netbsd",435 target_os = "openbsd"436 )) {437 // Assume ls is GNU ls438 gnu_ls("ls")439 } else {440 // MacOS, DragonFlyBSD, FreeBSD441 use std::process::{Command, Stdio};442460 if cfg!(unix)461 && config.ignore_hidden462 && pattern_matches_strings_with_leading_dot(&pattern_regex)463 {443 // Use GNU ls, if available (support for --color=auto, better LS_COLORS support)444 let gnu_ls_exists = Command::new("gls")445 .arg("--version")446 .stdout(Stdio::null())447 .stderr(Stdio::null())448 .status()449 .is_ok();450451 if gnu_ls_exists {452 gnu_ls("gls")453 } else {454 let mut cmd = vec![455 "ls", // BSD version of ls456 "-l", // long listing format457 "-h", // '--human-readable' is not available, '-h' is458 "-d", // '--directory' is not available, but '-d' is459 ];460461 if !cfg!(any(target_os = "netbsd", target_os = "openbsd")) && colored_output {462 // -G is not available in NetBSD's and OpenBSD's ls463 cmd.push("-G");464 }465466 cmd467 }468 }469 } else if cfg!(windows) {470 use std::process::{Command, Stdio};471472 // Use GNU ls, if available473 let gnu_ls_exists = Command::new("ls")474 .arg("--version")475 .stdout(Stdio::null())476 .stderr(Stdio::null())477 .status()478 .is_ok();479480 if gnu_ls_exists {481 gnu_ls("ls")482 } else {483 return Err(anyhow!(484 "'fd --list-details' is not supported on Windows unless GNU 'ls' is installed."485 ));486 }487 } else {488 return Err(anyhow!(489 "'fd --list-details' is not supported on this platform."490 ));491 };492 Ok(cmd)493}494495fn extract_size_limits(matches: &clap::ArgMatches) -> Result<Vec<SizeFilter>> {496 matches.values_of("size").map_or(Ok(Vec::new()), |vs| {497 vs.map(|sf| {498 SizeFilter::from_string(sf)499 .ok_or_else(|| anyhow!("'{}' is not a valid size constraint. See 'fd --help'.", sf))500 })501 .collect::<Result<Vec<_>>>()502 })503}504505fn extract_time_constraints(matches: &clap::ArgMatches) -> Result<Vec<TimeFilter>> {506 let now = time::SystemTime::now();507 let mut time_constraints: Vec<TimeFilter> = Vec::new();508 if let Some(t) = matches.value_of("changed-within") {509 if let Some(f) = TimeFilter::after(&now, t) {510 time_constraints.push(f);511 } else {512 return Err(anyhow!(513 "'{}' is not a valid date or duration. See 'fd --help'.",514 t515 ));516 }517 }518 if let Some(t) = matches.value_of("changed-before") {519 if let Some(f) = TimeFilter::before(&now, t) {520 time_constraints.push(f);521 } else {522 return Err(anyhow!(523 "'{}' is not a valid date or duration. See 'fd --help'.",524 t525 ));526 }527 }528 Ok(time_constraints)529}530531fn ensure_use_hidden_option_for_leading_dot_pattern(532 config: &Options,533 pattern_regex: &str,534) -> Result<()> {535 if cfg!(unix) && config.ignore_hidden && pattern_matches_strings_with_leading_dot(pattern_regex)536 {537 Err(anyhow!(538 "The pattern seems to only match files with a leading dot, but hidden files are \539 filtered by default. Consider adding -H/--hidden to search hidden files as well \540 or adjust your search pattern."468 ));541 ))542 } else {543 Ok(())544 }545}546547fn build_regex(pattern_regex: String, config: &Options) -> Result<regex::bytes::Regex> {471 let re = RegexBuilder::new(&pattern_regex)548 RegexBuilder::new(&pattern_regex)549 .case_insensitive(!config.case_sensitive)550 .dot_matches_new_line(true)551 .build()552 .map_err(|e| {
2 unmodified lines
555 literal string instead of a regular expression. Alternatively, you can \556 also use the '--glob' option to match on a glob pattern.",557 e.to_string()558 )482 })?;483484 walk::scan(&search_paths, Arc::new(re), Arc::new(config))559 })560}486487fn main() {488 let result = run();489 match result {490 Ok(exit_code) => {491 process::exit(exit_code.into());492 }493 Err(err) => {494 eprintln!("[fd error]: {:#}", err);495 process::exit(ExitCode::GeneralError.into());496 }497 }498}