main.rs
This file
Path
src/main.rs
560 lines · 24.7 KiB · Rust
Last changed by
fix: Better sanitizingThayne McCombsbefore adoption24198d9
History of this fileTake it
The walk stopped after 200 commits: lines older than 86d6e2d point at it.
fix: Better sanitizingThayne McCombsbefore adoption24198d9
lines 1–4why, one step back1// needs to be first because it defines a macro2#[macro_use]3mod error;4Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 5–16why, one step back5mod cli;6mod config;7mod dir_entry;8mod exec;9mod exit_codes;10mod filesystem;11mod filetypes;12mod filter;13mod fmt;14mod hyperlink;15mod output;16mod regex_helper;Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064
line 17why, one step back17mod sanitize;Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 18–24why, one step back18mod walk;1920use std::env;21use std::io::IsTerminal;22use std::path::Path;23use std::sync::Arc;24Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06
line 25why, one step back25use anyhow::{Context, Result, anyhow, bail};Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 26–42why, one step back26use clap::{CommandFactory, Parser};27use globset::GlobBuilder;28use lscolors::LsColors;29use regex::bytes::{Regex, RegexBuilder, RegexSetBuilder};3031use crate::cli::{ColorWhen, HyperlinkWhen, Opts};32use crate::config::Config;33use crate::exec::CommandSet;34use crate::exit_codes::ExitCode;35use crate::filetypes::FileTypes;36#[cfg(unix)]37use crate::filter::OwnerFilter;38use crate::filter::TimeFilter;39use crate::regex_helper::{pattern_has_uppercase_char, pattern_matches_strings_with_leading_dot};4041// We use jemalloc for performance reasons, see https://github.com/sharkdp/fd/pull/48142// FIXME: re-enable jemalloc on macOS, see comment in Cargo.toml file for more infosMerge pull request #1742 from nealsid/remove-illumos-jemallocThayne McCombsbefore adoptionb7fe2ce
lines 43–44why, one step back43// This has to be kept in sync with the Cargo.toml file section that declares a44// dependency on tikv-jemallocator.Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 45–50why, one step back45#[cfg(all(46 not(windows),47 not(target_os = "android"),48 not(target_os = "macos"),49 not(target_os = "freebsd"),50 not(target_os = "openbsd"),Merge pull request #1742 from nealsid/remove-illumos-jemallocThayne McCombsbefore adoptionb7fe2ce
line 51why, one step back51 not(target_os = "illumos"),Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 52–56why, one step back52 not(all(target_env = "musl", target_pointer_width = "32")),53 not(target_arch = "riscv64"),54 feature = "use-jemalloc"55))]56#[global_allocator]Merge pull request #1722 from musicinmybrain/tikvThayne McCombsbefore adoption9bd1647
line 57why, one step back57static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 58–71why, one step back5859// vivid --color-mode 8-bit generate molokai60const DEFAULT_LS_COLORS: &str = "61ow=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;6238;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;24363";6465fn main() {66 let result = run();67 match result {68 Ok(exit_code) => {69 exit_code.exit();70 }71 Err(err) => {fix: Better sanitizingThayne McCombsbefore adoption24198d9
lines 72–74why, one step back72 // NB: we use eprintln directly instead of print_error!() because73 // we sanitize anyhow errors at the generation site74 eprintln!("[fd error]: {:#}", err);Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 75–139why, one step back75 ExitCode::GeneralError.exit();76 }77 }78}7980fn run() -> Result<ExitCode> {81 let opts = Opts::parse();8283 #[cfg(feature = "completions")]84 if let Some(shell) = opts.gen_completions()? {85 return print_completions(shell);86 }8788 set_working_dir(&opts)?;89 let search_paths = opts.search_paths()?;90 if search_paths.is_empty() {91 bail!("No valid search paths given.");92 }9394 ensure_search_pattern_is_not_a_path(&opts)?;95 let pattern = &opts.pattern;96 let exprs = &opts.exprs;97 let empty = Vec::new();9899 let pattern_regexps = exprs100 .as_ref()101 .unwrap_or(&empty)102 .iter()103 .chain([pattern])104 .map(|pat| build_pattern_regex(pat, &opts))105 .collect::<Result<Vec<String>>>()?;106107 let config = construct_config(opts, &pattern_regexps)?;108109 ensure_use_hidden_option_for_leading_dot_pattern(&config, &pattern_regexps)?;110111 let regexps = pattern_regexps112 .into_iter()113 .map(|pat| build_regex(pat, &config))114 .collect::<Result<Vec<Regex>>>()?;115116 walk::scan(&search_paths, regexps, config)117}118119#[cfg(feature = "completions")]120#[cold]121fn print_completions(shell: clap_complete::Shell) -> Result<ExitCode> {122 // The program name is the first argument.123 let first_arg = env::args().next();124 let program_name = first_arg125 .as_ref()126 .map(Path::new)127 .and_then(|path| path.file_stem())128 .and_then(|file| file.to_str())129 .unwrap_or("fd");130 let mut cmd = Opts::command();131 cmd.build();132 clap_complete::generate(shell, &mut cmd, program_name, &mut std::io::stdout());133 Ok(ExitCode::Success)134}135136fn set_working_dir(opts: &Opts) -> Result<()> {137 if let Some(ref base_directory) = opts.base_directory {138 if !filesystem::is_existing_directory(base_directory) {139 return Err(anyhow!(fix: Better sanitizingThayne McCombsbefore adoption24198d9
lines 140–141why, one step back140 "The '--base-directory' path {:?} is not a directory.",141 base_directory.to_string_lossy().as_ref()Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 142–145why, one step back142 ));143 }144 env::set_current_dir(base_directory).with_context(|| {145 format!(fix: Better sanitizingThayne McCombsbefore adoption24198d9
lines 146–147why, one step back146 "Could not set {:?} as the current working directory",147 base_directory.to_string_lossy().as_ref()Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 148–153why, one step back148 )149 })?;150 }151 Ok(())152}153Merge pull request #1975 from SAY-5/fix/pattern-path-separator-v2Thayne McCombsbefore adoption4e2c812
lines 154–156why, one step back154/// Detect if the user accidentally supplied a path instead of a search pattern.155///156/// Without `--full-path`, fd matches patterns against file names, so any patternMerge pull request #2036 from greymoth-jp/fix/and-pattern-path-separatorThayne McCombsbefore adoption61c5399
lines 157–160why, one step back157/// containing a path separator can never match. This applies to the primary158/// positional pattern *and* to every `--and` pattern, since all of them are159/// chained together and matched against the file name (see `run`). Two cases per160/// pattern are worth a friendly error rather than silent "no results":Merge pull request #1975 from SAY-5/fix/pattern-path-separator-v2Thayne McCombsbefore adoption4e2c812
lines 161–173why, one step back161///162/// 1. The pattern contains '/'. '/' is always a path separator (including on163/// Windows) and has no regex meaning, so flagging it is safe and catches the164/// common Linux/macOS mistake of pasting a full path as the pattern.165/// 2. On Windows only, the pattern contains the native `\` separator *and*166/// names an existing directory on disk. We can't treat `\` as a pure167/// path-separator signal there because it is also the regex escape char,168/// so valid regex patterns like `\Ac` or `\d+` must still run. Requiring169/// that the pattern resolves to a real directory avoids those false170/// positives while preserving the legacy diagnostic for operators who171/// literally typed a directory path.172///173/// See https://github.com/sharkdp/fd/issues/1873.Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
line 174why, one step back174fn ensure_search_pattern_is_not_a_path(opts: &Opts) -> Result<()> {Merge pull request #1975 from SAY-5/fix/pattern-path-separator-v2Thayne McCombsbefore adoption4e2c812
lines 175–178why, one step back175 if opts.full_path {176 return Ok(());177 }178Merge pull request #2036 from greymoth-jp/fix/and-pattern-path-separatorThayne McCombsbefore adoption61c5399
lines 179–190why, one step back179 // Check the primary pattern and every `--and` pattern. They are all matched180 // against the file name (see `run`), so a path separator in any of them is181 // the same silent "no results" footgun.182 for pattern in std::iter::once(&opts.pattern).chain(opts.exprs.iter().flatten()) {183 ensure_single_search_pattern_is_not_a_path(pattern)?;184 }185 Ok(())186}187188/// Apply the path-separator diagnostic to a single pattern. See189/// [`ensure_search_pattern_is_not_a_path`] for the rationale of each case.190fn ensure_single_search_pattern_is_not_a_path(pattern: &str) -> Result<()> {Merge pull request #1975 from SAY-5/fix/pattern-path-separator-v2Thayne McCombsbefore adoption4e2c812
lines 191–194why, one step back191 // Start with the cheap check: '/' is always a path separator, including on192 // Windows, and has no regex meaning, so flagging it is safe and catches the193 // Linux/macOS mistake of pasting a full path as the pattern.194 #[cfg_attr(not(windows), allow(unused_mut))]Merge pull request #2036 from greymoth-jp/fix/and-pattern-path-separatorThayne McCombsbefore adoption61c5399
line 195why, one step back195 let mut should_warn = pattern.contains('/');Merge pull request #1975 from SAY-5/fix/pattern-path-separator-v2Thayne McCombsbefore adoption4e2c812
lines 196–202why, one step back196197 // On Windows we additionally accept the native `\` separator, but only when198 // the pattern actually resolves to an existing directory - `\` is also the199 // regex escape char there, so valid patterns like `\Ac` or `\d+` must still200 // run. The is_dir syscall is only needed when `should_warn` is still false,201 // so short-circuit via `||` to avoid the stat call on the happy path.202 #[cfg(windows)]Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
line 203why, one step back203 {Merge pull request #1975 from SAY-5/fix/pattern-path-separator-v2Thayne McCombsbefore adoption4e2c812
line 204why, one step back204 should_warn = should_warnMerge pull request #2036 from greymoth-jp/fix/and-pattern-path-separatorThayne McCombsbefore adoption61c5399
line 205why, one step back205 || (pattern.contains(std::path::MAIN_SEPARATOR) && Path::new(pattern).is_dir());Merge pull request #1975 from SAY-5/fix/pattern-path-separator-v2Thayne McCombsbefore adoption4e2c812
lines 206–208why, one step back206 }207208 if should_warn {Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
line 209why, one step back209 Err(anyhow!(Merge pull request #1975 from SAY-5/fix/pattern-path-separator-v2Thayne McCombsbefore adoption4e2c812
line 210why, one step back210 "The search pattern '{pattern}' contains a path-separation character \Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 211–215why, one step back211 and will not lead to any search results.\n\n\212 If you want to search for all files inside the '{pattern}' directory, use a match-all pattern:\n\n \213 fd . '{pattern}'\n\n\214 Instead, if you want your pattern to match the full file path, use:\n\n \215 fd --full-path '{pattern}'",Merge pull request #2036 from greymoth-jp/fix/and-pattern-path-separatorThayne McCombsbefore adoption61c5399
line 216why, one step back216 pattern = pattern,Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 217–226why, one step back217 ))218 } else {219 Ok(())220 }221}222223fn build_pattern_regex(pattern: &str, opts: &Opts) -> Result<String> {224 Ok(if opts.glob && !pattern.is_empty() {225 let glob = GlobBuilder::new(pattern).literal_separator(true).build()?;226 glob.regex().to_owned()Merge pull request #1983 from DeflateAwning/feat-exact-i1963Thayne McCombsbefore adoption42b2ab8
lines 227–230why, one step back227 } else if opts.exact {228 // Anchor the escaped pattern so the full filename (or path) must match exactly.229 // Literal. No substring matching.230 format!("^{}$", regex::escape(pattern))Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 231–305why, one step back231 } else if opts.fixed_strings {232 // Treat pattern as literal string if '--fixed-strings' is used233 regex::escape(pattern)234 } else {235 String::from(pattern)236 })237}238239fn check_path_separator_length(path_separator: Option<&str>) -> Result<()> {240 match (cfg!(windows), path_separator) {241 (true, Some(sep)) if sep.len() > 1 => Err(anyhow!(242 "A path separator must be exactly one byte, but \243 the given separator is {} bytes: '{}'.\n\244 In some shells on Windows, '/' is automatically \245 expanded. Try to use '//' instead.",246 sep.len(),247 sep248 )),249 _ => Ok(()),250 }251}252253fn construct_config(mut opts: Opts, pattern_regexps: &[String]) -> Result<Config> {254 // The search will be case-sensitive if the command line flag is set or255 // if any of the patterns has an uppercase character (smart case).256 let case_sensitive = !opts.ignore_case257 && (opts.case_sensitive258 || pattern_regexps259 .iter()260 .any(|pat| pattern_has_uppercase_char(pat)));261262 let path_separator = opts263 .path_separator264 .take()265 .or_else(filesystem::default_path_separator);266 let actual_path_separator = path_separator267 .clone()268 .unwrap_or_else(|| std::path::MAIN_SEPARATOR.to_string());269 check_path_separator_length(path_separator.as_deref())?;270271 let size_limits = std::mem::take(&mut opts.size);272 let time_constraints = extract_time_constraints(&opts)?;273 #[cfg(unix)]274 let owner_constraint: Option<OwnerFilter> = opts.owner.and_then(OwnerFilter::filter_ignore);275276 #[cfg(windows)]277 let ansi_colors_support =278 nu_ansi_term::enable_ansi_support().is_ok() || std::env::var_os("TERM").is_some();279 #[cfg(not(windows))]280 let ansi_colors_support = true;281282 let interactive_terminal = std::io::stdout().is_terminal();283284 let colored_output = match opts.color {285 ColorWhen::Always => true,286 ColorWhen::Never => false,287 ColorWhen::Auto => {288 let no_color = env::var_os("NO_COLOR").is_some_and(|x| !x.is_empty());289 ansi_colors_support && !no_color && interactive_terminal290 }291 };292293 let ls_colors = if colored_output {294 Some(LsColors::from_env().unwrap_or_else(|| LsColors::from_string(DEFAULT_LS_COLORS)))295 } else {296 None297 };298 let hyperlink = match opts.hyperlink {299 HyperlinkWhen::Always => true,300 HyperlinkWhen::Never => false,301 HyperlinkWhen::Auto => colored_output,302 };303 let command = extract_command(&mut opts, colored_output)?;304 let has_command = command.is_some();305Merge pull request #1928 from tmccombs/full-path-fixesTavian Barnesbefore adoptiond6b44b8
line 306why, one step back306 let full_path_base = if opts.full_path {Merge pull request #1917 from Xavrir/issue-1900Thayne McCombsbefore adoption6d77799
lines 307–314why, one step back307 Some(env::current_dir().context(308 "Could not determine current directory. \309 This is required for --full-path.",310 )?)311 } else {312 None313 };314Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 315–316why, one step back315 Ok(Config {316 case_sensitive,Merge pull request #1928 from tmccombs/full-path-fixesTavian Barnesbefore adoptiond6b44b8
line 317why, one step back317 full_path_base,Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 318–395why, one step back318 ignore_hidden: !(opts.hidden || opts.rg_alias_ignore()),319 read_fdignore: !(opts.no_ignore || opts.rg_alias_ignore()),320 read_vcsignore: !(opts.no_ignore || opts.rg_alias_ignore() || opts.no_ignore_vcs),321 require_git_to_read_vcsignore: !opts.no_require_git,322 read_parent_ignore: !opts.no_ignore_parent,323 read_global_ignore: !(opts.no_ignore324 || opts.rg_alias_ignore()325 || opts.no_global_ignore_file),326 follow_links: opts.follow,327 one_file_system: opts.one_file_system,328 null_separator: opts.null_separator,329 quiet: opts.quiet,330 max_depth: opts.max_depth(),331 min_depth: opts.min_depth(),332 prune: opts.prune,333 threads: opts.threads().get(),334 max_buffer_time: opts.max_buffer_time,335 ls_colors,336 hyperlink,337 interactive_terminal,338 file_types: opts.filetype.as_ref().map(|values| {339 use crate::cli::FileType::*;340 let mut file_types = FileTypes::default();341 for value in values {342 match value {343 File => file_types.files = true,344 Directory => file_types.directories = true,345 Symlink => file_types.symlinks = true,346 Executable => {347 file_types.executables_only = true;348 file_types.files = true;349 }350 Empty => file_types.empty_only = true,351 BlockDevice => file_types.block_devices = true,352 CharDevice => file_types.char_devices = true,353 Socket => file_types.sockets = true,354 Pipe => file_types.pipes = true,355 }356 }357358 // If only 'empty' was specified, search for both files and directories:359 if file_types.empty_only && !(file_types.files || file_types.directories) {360 file_types.files = true;361 file_types.directories = true;362 }363364 file_types365 }),366 extensions: opts367 .extensions368 .as_ref()369 .map(|exts| {370 let patterns = exts371 .iter()372 .map(|e| e.trim_start_matches('.'))373 .map(|e| format!(r".\.{}$", regex::escape(e)));374 RegexSetBuilder::new(patterns)375 .case_insensitive(true)376 .build()377 })378 .transpose()?,379 format: opts380 .format381 .as_deref()382 .map(crate::fmt::FormatTemplate::parse),383 command: command.map(Arc::new),384 batch_size: opts.batch_size,385 exclude_patterns: opts.exclude.iter().map(|p| String::from("!") + p).collect(),386 ignore_files: std::mem::take(&mut opts.ignore_file),387 size_constraints: size_limits,388 time_constraints,389 #[cfg(unix)]390 owner_constraint,391 show_filesystem_errors: opts.show_errors,392 path_separator,393 actual_path_separator,394 max_results: opts.max_results(),395 strip_cwd_prefix: opts.strip_cwd_prefix(|| !(opts.null_separator || has_command)),Merge pull request #1852 from fischman/1727-ignore-containThayne McCombsbefore adoptionbf81fb9
line 396why, one step back396 ignore_contain: opts.ignore_contain,Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 397–445why, one step back397 })398}399400fn extract_command(opts: &mut Opts, colored_output: bool) -> Result<Option<CommandSet>> {401 opts.exec402 .command403 .take()404 .map(Ok)405 .or_else(|| {406 if !opts.list_details {407 return None;408 }409410 let res = determine_ls_command(colored_output)411 .map(|cmd| CommandSet::new_batch([cmd]).unwrap());412 Some(res)413 })414 .transpose()415}416417fn determine_ls_command(colored_output: bool) -> Result<Vec<&'static str>> {418 #[allow(unused)]419 let gnu_ls = |command_name| {420 let color_arg = if colored_output {421 "--color=always"422 } else {423 "--color=never"424 };425 // Note: we use short options here (instead of --long-options) to support more426 // platforms (like BusyBox).427 vec![428 command_name,429 "-l", // long listing format430 "-h", // human readable file sizes431 "-d", // list directories themselves, not their contents432 color_arg,433 ]434 };435 let cmd: Vec<&str> = if cfg!(unix) {436 if !cfg!(any(437 target_os = "macos",438 target_os = "dragonfly",439 target_os = "freebsd",440 target_os = "netbsd",441 target_os = "openbsd"442 )) {443 // Assume ls is GNU ls444 gnu_ls("ls")445 } else {Merge pull request #1953 from Rohan5commit/docs-macos-comment-20260404Thayne McCombsbefore adoptiona665a3b
line 446why, one step back446 // macOS, DragonFlyBSD, FreeBSDMerge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 447–503why, one step back447 use std::process::{Command, Stdio};448449 // Use GNU ls, if available (support for --color=auto, better LS_COLORS support)450 let gnu_ls_exists = Command::new("gls")451 .arg("--version")452 .stdout(Stdio::null())453 .stderr(Stdio::null())454 .status()455 .is_ok();456457 if gnu_ls_exists {458 gnu_ls("gls")459 } else {460 let mut cmd = vec![461 "ls", // BSD version of ls462 "-l", // long listing format463 "-h", // '--human-readable' is not available, '-h' is464 "-d", // '--directory' is not available, but '-d' is465 ];466467 if !cfg!(any(target_os = "netbsd", target_os = "openbsd")) && colored_output {468 // -G is not available in NetBSD's and OpenBSD's ls469 cmd.push("-G");470 }471472 cmd473 }474 }475 } else if cfg!(windows) {476 use std::process::{Command, Stdio};477478 // Use GNU ls, if available479 let gnu_ls_exists = Command::new("ls")480 .arg("--version")481 .stdout(Stdio::null())482 .stderr(Stdio::null())483 .status()484 .is_ok();485486 if gnu_ls_exists {487 gnu_ls("ls")488 } else {489 return Err(anyhow!(490 "'fd --list-details' is not supported on Windows unless GNU 'ls' is installed."491 ));492 }493 } else {494 return Err(anyhow!(495 "'fd --list-details' is not supported on this platform."496 ));497 };498 Ok(cmd)499}500501fn extract_time_constraints(opts: &Opts) -> Result<Vec<TimeFilter>> {502 let mut time_constraints: Vec<TimeFilter> = Vec::new();503 if let Some(ref t) = opts.changed_within {Merge pull request #1692 from tmccombs/jiff-moreThayne McCombsbefore adoption2b0f609
line 504why, one step back504 if let Some(f) = TimeFilter::after(t) {Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 505–513why, one step back505 time_constraints.push(f);506 } else {507 return Err(anyhow!(508 "'{}' is not a valid date or duration. See 'fd --help'.",509 t510 ));511 }512 }513 if let Some(ref t) = opts.changed_before {Merge pull request #1692 from tmccombs/jiff-moreThayne McCombsbefore adoption2b0f609
line 514why, one step back514 if let Some(f) = TimeFilter::before(t) {Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 515–552why, one step back515 time_constraints.push(f);516 } else {517 return Err(anyhow!(518 "'{}' is not a valid date or duration. See 'fd --help'.",519 t520 ));521 }522 }523 Ok(time_constraints)524}525526fn ensure_use_hidden_option_for_leading_dot_pattern(527 config: &Config,528 pattern_regexps: &[String],529) -> Result<()> {530 if cfg!(unix)531 && config.ignore_hidden532 && pattern_regexps533 .iter()534 .any(|pat| pattern_matches_strings_with_leading_dot(pat))535 {536 Err(anyhow!(537 "The pattern(s) seems to only match files with a leading dot, but hidden files are \538 filtered by default. Consider adding -H/--hidden to search hidden files as well \539 or adjust your search pattern(s)."540 ))541 } else {542 Ok(())543 }544}545546fn build_regex(pattern_regex: String, config: &Config) -> Result<regex::bytes::Regex> {547 RegexBuilder::new(&pattern_regex)548 .case_insensitive(!config.case_sensitive)549 .dot_matches_new_line(true)550 .build()551 .map_err(|e| {552 anyhow!(Merge pull request #1983 from DeflateAwning/feat-exact-i1963Thayne McCombsbefore adoption42b2ab8
lines 553–555why, one step back553 "{}\n\nNote: You can search for literal substrings with '--fixed-strings' \554 or literal strings with '--exact' options (instead of a regular expression). \555 Alternatively, you can \Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
line 556why, one step back556 also use the '--glob' option to match on a glob pattern.",Merge pull request #1802 from sharkdp/dependabot/cargo/anyhow-1.0.100Thayne McCombsbefore adoption8c9c6be
line 557why, one step back557 eMerge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 558–560why, one step back558 )559 })560}