cli.rs
This file
Path
src/cli.rs
979 lines · 35.5 KiB · Rust
Last changed by
docs(help): pattern is mandatory for pathThayne McCombsbefore adoption19a55aa
History of this fileTake it
The walk stopped after 200 commits: lines older than 86d6e2d point at it.
Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 1–6why, one step back1use std::num::NonZeroUsize;2use std::path::{Path, PathBuf};3use std::time::Duration;45use anyhow::anyhow;6use clap::{Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06
lines 7–8why, one step back7 Arg, ArgAction, ArgGroup, ArgMatches, Command, Parser, ValueEnum, error::ErrorKind,8 value_parser,Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 9–23why, one step back9};10#[cfg(feature = "completions")]11use clap_complete::Shell;12use normpath::PathExt;1314use crate::exec::CommandSet;15use crate::filesystem;16#[cfg(unix)]17use crate::filter::OwnerFilter;18use crate::filter::SizeFilter;1920#[derive(Parser)]21#[command(22 name = "fd",23 version,Merge pull request #2011 from stevenwalton/masterThayne McCombsbefore adoptionfebc1b6
line 24why, one step back24 about = "A program to find entries in your filesystem with regex and glob based matching. By default, fd respects gitignore rules, ignores hidden directories, and is case insensitive.",Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 25–103why, one step back25 after_long_help = "Bugs can be reported on GitHub: https://github.com/sharkdp/fd/issues",26 max_term_width = 98,27 args_override_self = true,28 group(ArgGroup::new("execs").args(&["exec", "exec_batch", "list_details"]).conflicts_with_all(&[29 "max_results", "quiet", "max_one_result"])),30)]31pub struct Opts {32 /// Include hidden directories and files in the search results (default:33 /// hidden files and directories are skipped). Files and directories are34 /// considered to be hidden if their name starts with a `.` sign (dot).35 /// Any files or directories that are ignored due to the rules described by36 /// --no-ignore are still ignored unless otherwise specified.37 /// The flag can be overridden with --no-hidden.38 #[arg(39 long,40 short = 'H',41 help = "Search hidden files and directories",42 long_help43 )]44 pub hidden: bool,4546 /// Overrides --hidden47 #[arg(long, overrides_with = "hidden", hide = true, action = ArgAction::SetTrue)]48 no_hidden: (),4950 /// Show search results from files and directories that would otherwise be51 /// ignored by '.gitignore', '.ignore', '.fdignore', or the global ignore file,52 /// The flag can be overridden with --ignore.53 #[arg(54 long,55 short = 'I',56 help = "Do not respect .(git|fd)ignore files",57 long_help58 )]59 pub no_ignore: bool,6061 /// Overrides --no-ignore62 #[arg(long, overrides_with = "no_ignore", hide = true, action = ArgAction::SetTrue)]63 ignore: (),6465 ///Show search results from files and directories that66 ///would otherwise be ignored by '.gitignore' files.67 ///The flag can be overridden with --ignore-vcs.68 #[arg(69 long,70 hide_short_help = true,71 help = "Do not respect .gitignore files",72 long_help73 )]74 pub no_ignore_vcs: bool,7576 /// Overrides --no-ignore-vcs77 #[arg(long, overrides_with = "no_ignore_vcs", hide = true, action = ArgAction::SetTrue)]78 ignore_vcs: (),7980 /// Do not require a git repository to respect gitignores.81 /// By default, fd will only respect global gitignore rules, .gitignore rules,82 /// and local exclude rules if fd detects that you are searching inside a83 /// git repository. This flag allows you to relax this restriction such that84 /// fd will respect all git related ignore rules regardless of whether you're85 /// searching in a git repository or not.86 ///87 ///88 /// This flag can be disabled with --require-git.89 #[arg(90 long,91 overrides_with = "require_git",92 hide_short_help = true,93 // same description as ripgrep's flag: ripgrep/crates/core/app.rs94 long_help95 )]96 pub no_require_git: bool,9798 /// Overrides --no-require-git99 #[arg(long, overrides_with = "no_require_git", hide = true, action = ArgAction::SetTrue)]100 require_git: (),101102 /// Show search results from files and directories that would otherwise be103 /// ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories.Merge pull request #1959 from tmchow/osc/1958-ignore-parentThayne McCombsbefore adoption90e73d7
line 104why, one step back104 /// The flag can be overridden with --ignore-parent.Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 105–111why, one step back105 #[arg(106 long,107 hide_short_help = true,108 help = "Do not respect .(git|fd)ignore files in parent directories",109 long_help110 )]111 pub no_ignore_parent: bool,Merge pull request #1959 from tmchow/osc/1958-ignore-parentThayne McCombsbefore adoption90e73d7
lines 112–115why, one step back112113 /// Overrides --no-ignore-parent114 #[arg(long, overrides_with = "no_ignore_parent", hide = true, action = ArgAction::SetTrue)]115 ignore_parent: (),Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 116–174why, one step back116117 /// Do not respect the global ignore file118 #[arg(long, hide = true)]119 pub no_global_ignore_file: bool,120121 /// Perform an unrestricted search, including ignored and hidden files. This is122 /// an alias for '--no-ignore --hidden'.123 #[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,124 help = "Unrestricted search, alias for '--no-ignore --hidden'",125 long_help,126 )]127 rg_alias_hidden_ignore: u8,128129 /// Case-sensitive search (default: smart case)130 #[arg(131 long,132 short = 's',133 overrides_with("ignore_case"),134 long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \135 searches, unless the pattern contains an uppercase character (smart \136 case)."137 )]138 pub case_sensitive: bool,139140 /// Perform a case-insensitive search. By default, fd uses case-insensitive141 /// searches, unless the pattern contains an uppercase character (smart142 /// case).143 #[arg(144 long,145 short = 'i',146 overrides_with("case_sensitive"),147 help = "Case-insensitive search (default: smart case)",148 long_help149 )]150 pub ignore_case: bool,151152 /// Perform a glob-based search instead of a regular expression search.153 #[arg(154 long,155 short = 'g',156 conflicts_with("fixed_strings"),157 help = "Glob-based search (default: regular expression)",158 long_help159 )]160 pub glob: bool,161162 /// Perform a regular-expression based search (default). This can be used to163 /// override --glob.164 #[arg(165 long,166 overrides_with("glob"),167 hide_short_help = true,168 help = "Regular-expression based search (default)",169 long_help170 )]171 pub regex: bool,172173 /// Treat the pattern as a literal string instead of a regular expression. Note174 /// that this also performs substring comparison. If you want to match on anMerge pull request #1983 from DeflateAwning/feat-exact-i1963Thayne McCombsbefore adoption42b2ab8
line 175why, one step back175 /// exact filename, consider using '--glob' or '--exact' instead.Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 176–180why, one step back176 #[arg(177 long,178 short = 'F',179 alias = "literal",180 hide_short_help = true,Merge pull request #1983 from DeflateAwning/feat-exact-i1963Thayne McCombsbefore adoption42b2ab8
line 181why, one step back181 help = "Treat pattern as literal string instead of regex",Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 182–184why, one step back182 long_help183 )]184 pub fixed_strings: bool,Merge pull request #1983 from DeflateAwning/feat-exact-i1963Thayne McCombsbefore adoption42b2ab8
lines 185–197why, one step back185186 /// Perform an exact match. This is equivalent to '--fixed-strings' but requires187 /// the pattern to match the entire filename (or path if '--full-path' is used),188 /// rather than a substring. Special regex characters in the pattern are treated189 /// as literal characters.190 #[arg(191 long,192 conflicts_with_all(["glob", "fixed_strings"]),193 hide_short_help = true,194 help = "Match the entire filename exactly (literal, non-substring)",195 long_help196 )]197 pub exact: bool,Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 198–318why, one step back198199 /// Add additional required search patterns, all of which must be matched. Multiple200 /// additional patterns can be specified. The patterns are regular201 /// expressions, unless '--glob' or '--fixed-strings' is used.202 #[arg(203 long = "and",204 value_name = "pattern",205 help = "Additional search patterns that need to be matched",206 long_help,207 hide_short_help = true,208 allow_hyphen_values = true209 )]210 pub exprs: Option<Vec<String>>,211212 /// Shows the full path starting from the root as opposed to relative paths.213 /// The flag can be overridden with --relative-path.214 #[arg(215 long,216 short = 'a',217 help = "Show absolute instead of relative paths",218 long_help219 )]220 pub absolute_path: bool,221222 /// Overrides --absolute-path223 #[arg(long, overrides_with = "absolute_path", hide = true, action = ArgAction::SetTrue)]224 relative_path: (),225226 /// Use a detailed listing format like 'ls -l'. This is basically an alias227 /// for '--exec-batch ls -l' with some additional 'ls' options. This can be228 /// used to see more metadata, to show symlink targets and to achieve a229 /// deterministic sort order.230 #[arg(231 long,232 short = 'l',233 conflicts_with("absolute_path"),234 help = "Use a long listing format with file metadata",235 long_help236 )]237 pub list_details: bool,238239 /// Follow symbolic links240 #[arg(241 long,242 short = 'L',243 alias = "dereference",244 long_help = "By default, fd does not descend into symlinked directories. Using this \245 flag, symbolic links are also traversed. \246 Flag can be overridden with --no-follow."247 )]248 pub follow: bool,249250 /// Overrides --follow251 #[arg(long, overrides_with = "follow", hide = true, action = ArgAction::SetTrue)]252 no_follow: (),253254 /// By default, the search pattern is only matched against the filename (or directory name). Using this flag, the pattern is matched against the full (absolute) path. Example:255 /// fd --glob -p '**/.git/config'256 #[arg(257 long,258 short = 'p',259 help = "Search full abs. path (default: filename only)",260 long_help,261 verbatim_doc_comment262 )]263 pub full_path: bool,264265 /// Separate search results by the null character (instead of newlines).266 /// Useful for piping results to 'xargs'.267 #[arg(268 long = "print0",269 short = '0',270 conflicts_with("list_details"),271 hide_short_help = true,272 help = "Separate search results by the null character",273 long_help274 )]275 pub null_separator: bool,276277 /// Limit the directory traversal to a given depth. By default, there is no278 /// limit on the search depth.279 #[arg(280 long,281 short = 'd',282 value_name = "depth",283 alias("maxdepth"),284 help = "Set maximum search depth (default: none)",285 long_help286 )]287 max_depth: Option<usize>,288289 /// Only show search results starting at the given depth.290 /// See also: '--max-depth' and '--exact-depth'291 #[arg(292 long,293 value_name = "depth",294 hide_short_help = true,295 alias("mindepth"),296 help = "Only show search results starting at the given depth.",297 long_help298 )]299 min_depth: Option<usize>,300301 /// Only show search results at the exact given depth. This is an alias for302 /// '--min-depth <depth> --max-depth <depth>'.303 #[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),304 help = "Only show search results at the exact given depth",305 long_help,306 )]307 exact_depth: Option<usize>,308309 /// Exclude files/directories that match the given glob pattern. This310 /// overrides any other ignore logic. Multiple exclude patterns can be311 /// specified.312 ///313 /// Examples:314 /// {n} --exclude '*.pyc'315 /// {n} --exclude node_modules316 #[arg(317 long,318 short = 'E',Merge pull request #1921 from rexkirshner/fix-exclude-value-name-globThayne McCombsbefore adoptionfcd8466
line 319why, one step back319 value_name = "glob",Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 320–378why, one step back320 help = "Exclude entries that match the given glob pattern",321 long_help322 )]323 pub exclude: Vec<String>,324325 /// Do not traverse into directories that match the search criteria. If326 /// you want to exclude specific directories, use the '--exclude=…' option.327 #[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),328 long_help,329 )]330 pub prune: bool,331332 /// Filter the search by type:333 /// {n} 'f' or 'file': regular files334 /// {n} 'd' or 'dir' or 'directory': directories335 /// {n} 'l' or 'symlink': symbolic links336 /// {n} 's' or 'socket': socket337 /// {n} 'p' or 'pipe': named pipe (FIFO)338 /// {n} 'b' or 'block-device': block device339 /// {n} 'c' or 'char-device': character device340 /// {n}{n} 'x' or 'executable': executables341 /// {n} 'e' or 'empty': empty files or directories342 ///343 /// This option can be specified more than once to include multiple file types.344 /// Searching for '--type file --type symlink' will show both regular files as345 /// well as symlinks. Note that the 'executable' and 'empty' filters work differently:346 /// '--type executable' implies '--type file' by default. And '--type empty' searches347 /// for empty files and directories, unless either '--type file' or '--type directory'348 /// is specified in addition.349 ///350 /// Examples:351 /// {n} - Only search for files:352 /// {n} fd --type file …353 /// {n} fd -tf …354 /// {n} - Find both files and symlinks355 /// {n} fd --type file --type symlink …356 /// {n} fd -tf -tl …357 /// {n} - Find executable files:358 /// {n} fd --type executable359 /// {n} fd -tx360 /// {n} - Find empty files:361 /// {n} fd --type empty --type file362 /// {n} fd -te -tf363 /// {n} - Find empty directories:364 /// {n} fd --type empty --type directory365 /// {n} fd -te -td366 #[arg(367 long = "type",368 short = 't',369 value_name = "filetype",370 hide_possible_values = true,371 value_enum,372 help = "Filter by type: file (f), directory (d/dir), symlink (l), \373 executable (x), empty (e), socket (s), pipe (p), \374 char-device (c), block-device (b)",375 long_help376 )]377 pub filetype: Option<Vec<FileType>>,378Merge pull request #2001 from leno23/docs/extension-help-1693Thayne McCombsbefore adoption0944460
lines 379–381why, one step back379 /// Filter results by extension. By default, this matches all entry types380 /// (including directories whose names end with the extension). Use `--type`381 /// to restrict the search to specific types. Multiple extensions can be specified.Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 382–388why, one step back382 ///383 /// If you want to search for files without extension,384 /// you can use the regex '^[^.]+$' as a normal search pattern.385 #[arg(386 long = "extension",387 short = 'e',388 value_name = "ext",Merge pull request #2001 from leno23/docs/extension-help-1693Thayne McCombsbefore adoption0944460
line 389why, one step back389 help = "Filter by extension",Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 390–483why, one step back390 long_help391 )]392 pub extensions: Option<Vec<String>>,393394 /// Limit results based on the size of files using the format <+-><NUM><UNIT>.395 /// '+': file size must be greater than or equal to this396 /// '-': file size must be less than or equal to this397 ///398 /// If neither '+' nor '-' is specified, file size must be exactly equal to this.399 /// 'NUM': The numeric size (e.g. 500)400 /// 'UNIT': The units for NUM. They are not case-sensitive.401 /// Allowed unit values:402 /// 'b': bytes403 /// 'k': kilobytes (base ten, 10^3 = 1000 bytes)404 /// 'm': megabytes405 /// 'g': gigabytes406 /// 't': terabytes407 /// 'ki': kibibytes (base two, 2^10 = 1024 bytes)408 /// 'mi': mebibytes409 /// 'gi': gibibytes410 /// 'ti': tebibytes411 #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",412 help = "Limit results based on the size of files",413 long_help,414 verbatim_doc_comment,415 )]416 pub size: Vec<SizeFilter>,417418 /// Filter results based on the file modification time. Files with modification times419 /// greater than the argument are returned. The argument can be provided420 /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).421 /// If the time is not specified, it defaults to 00:00:00.422 /// '--change-newer-than', '--newer', or '--changed-after' can be used as aliases.423 ///424 /// Examples:425 /// {n} --changed-within 2weeks426 /// {n} --change-newer-than '2018-10-27 10:00:00'427 /// {n} --newer 2018-10-27428 /// {n} --changed-after 1day429 #[arg(430 long,431 alias("change-newer-than"),432 alias("newer"),433 alias("changed-after"),434 value_name = "date|dur",435 help = "Filter by file modification time (newer than)",436 long_help437 )]438 pub changed_within: Option<String>,439440 /// Filter results based on the file modification time. Files with modification times441 /// less than the argument are returned. The argument can be provided442 /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).443 /// '--change-older-than' or '--older' can be used as aliases.444 ///445 /// Examples:446 /// {n} --changed-before '2018-10-27 10:00:00'447 /// {n} --change-older-than 2weeks448 /// {n} --older 2018-10-27449 #[arg(450 long,451 alias("change-older-than"),452 alias("older"),453 value_name = "date|dur",454 help = "Filter by file modification time (older than)",455 long_help456 )]457 pub changed_before: Option<String>,458459 /// Filter files by their user and/or group.460 /// Format: [(user|uid)][:(group|gid)]. Either side is optional.461 /// Precede either side with a '!' to exclude files instead.462 ///463 /// Examples:464 /// {n} --owner john465 /// {n} --owner :students466 /// {n} --owner '!john:students'467 #[cfg(unix)]468 #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",469 help = "Filter by owning user and/or group",470 long_help,471 )]472 pub owner: Option<OwnerFilter>,473474 /// Instead of printing the file normally, print the format string with the following placeholders replaced:475 /// '{}': path (of the current search result)476 /// '{/}': basename477 /// '{//}': parent directory478 /// '{.}': path without file extension479 /// '{/.}': basename without file extension480 #[arg(481 long,482 value_name = "fmt",483 help = "Print results according to template",fix: allow hyphen-leading --format templatesJason Wangbefore adoptionb422e5d
lines 484–485why, one step back484 conflicts_with = "list_details",485 allow_hyphen_values = trueMerge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 486–549why, one step back486 )]487 pub format: Option<String>,488489 #[command(flatten)]490 pub exec: Exec,491492 /// Maximum number of arguments to pass to the command given with -X.493 /// If the number of results is greater than the given size,494 /// the command given with -X is run again with remaining arguments.495 /// A batch size of zero means there is no limit (default), but note496 /// that batching might still happen due to OS restrictions on the497 /// maximum length of command lines.498 #[arg(499 long,500 value_name = "size",501 hide_short_help = true,502 requires("exec_batch"),503 value_parser = value_parser!(usize),504 default_value_t,505 help = "Max number of arguments to run as a batch size with -X",506 long_help,507 )]508 pub batch_size: usize,509510 /// Add a custom ignore-file in '.gitignore' format. These files have a low precedence.511 #[arg(512 long,513 value_name = "path",514 hide_short_help = true,515 help = "Add a custom ignore-file in '.gitignore' format",516 long_help517 )]518 pub ignore_file: Vec<PathBuf>,519520 /// Declare when to use color for the pattern match output521 #[arg(522 long,523 short = 'c',524 value_enum,525 default_value_t = ColorWhen::Auto,526 value_name = "when",527 help = "When to use colors",528 long_help,529 )]530 pub color: ColorWhen,531532 /// Add a terminal hyperlink to a file:// url for each path in the output.533 ///534 /// Auto mode is used if no argument is given to this option.535 ///536 /// This doesn't do anything for --exec and --exec-batch.537 #[arg(538 long,539 alias = "hyper",540 value_name = "when",541 require_equals = true,542 value_enum,543 default_value_t = HyperlinkWhen::Never,544 default_missing_value = "auto",545 num_args = 0..=1,546 help = "Add hyperlinks to output paths"547 )]548 pub hyperlink: HyperlinkWhen,549Merge pull request #1852 from fischman/1727-ignore-containThayne McCombsbefore adoptionbf81fb9
lines 550–553why, one step back550 /// Ignore directories containing the named entry.551 #[arg(long, value_name = "name")]552 pub ignore_contain: Vec<String>,553Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 554–619why, one step back554 /// Set number of threads to use for searching & executing (default: number555 /// of available CPU cores)556 #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = str::parse::<NonZeroUsize>)]557 pub threads: Option<NonZeroUsize>,558559 /// Milliseconds to buffer before streaming search results to console560 ///561 /// Amount of time in milliseconds to buffer, before streaming the search562 /// results to the console.563 #[arg(long, hide = true, value_parser = parse_millis)]564 pub max_buffer_time: Option<Duration>,565566 ///Limit the number of search results to 'count' and quit immediately.567 #[arg(568 long,569 value_name = "count",570 hide_short_help = true,571 overrides_with("max_one_result"),572 help = "Limit the number of search results",573 long_help574 )]575 max_results: Option<usize>,576577 /// Limit the search to a single result and quit immediately.578 /// This is an alias for '--max-results=1'.579 #[arg(580 short = '1',581 hide_short_help = true,582 overrides_with("max_results"),583 help = "Limit search to a single result",584 long_help585 )]586 max_one_result: bool,587588 /// When the flag is present, the program does not print anything and will589 /// return with an exit code of 0 if there is at least one match. Otherwise, the590 /// exit code will be 1.591 /// '--has-results' can be used as an alias.592 #[arg(593 long,594 short = 'q',595 alias = "has-results",596 hide_short_help = true,597 conflicts_with("max_results"),598 help = "Print nothing, exit code 0 if match found, 1 otherwise",599 long_help600 )]601 pub quiet: bool,602603 /// Enable the display of filesystem errors for situations such as604 /// insufficient permissions or dead symlinks.605 #[arg(606 long,607 hide_short_help = true,608 help = "Show filesystem errors",609 long_help610 )]611 pub show_errors: bool,612613 /// Change the current working directory of fd to the provided path. This614 /// means that search results will be shown with respect to the given base615 /// path. Note that relative paths which are passed to fd via the positional616 /// <path> argument or the '--search-path' option will also be resolved617 /// relative to this directory.618 #[arg(619 long,Merge pull request #1808 from sivaramsk/masterThayne McCombsbefore adoption54fa011
line 620why, one step back620 short = 'C',Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 621–653why, one step back621 value_name = "path",622 hide_short_help = true,623 help = "Change current working directory",624 long_help625 )]626 pub base_directory: Option<PathBuf>,627628 /// the search pattern which is either a regular expression (default) or a glob629 /// pattern (if --glob is used). If no pattern has been specified, every entry630 /// is considered a match. If your pattern starts with a dash (-), make sure to631 /// pass '--' first, or it will be considered as a flag (fd -- '-foo').632 #[arg(633 default_value = "",634 hide_default_value = true,635 value_name = "pattern",636 help = "the search pattern (a regular expression, unless '--glob' is used; optional)",637 long_help638 )]639 pub pattern: String,640641 /// Set the path separator to use when printing file paths. The default is642 /// the OS-specific separator ('/' on Unix, '\' on Windows).643 #[arg(644 long,645 value_name = "separator",646 hide_short_help = true,647 help = "Set path separator when printing file paths",648 long_help649 )]650 pub path_separator: Option<String>,651652 /// The directory where the filesystem search is rooted (optional). If653 /// omitted, search the current working directory.docs(help): pattern is mandatory for pathThayne McCombsbefore adoption19a55aa
line 654why, one step back654 /// If supplied, the pattern must come first.Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 655–656why, one step back655 #[arg(action = ArgAction::Append,656 value_name = "path",docs(help): pattern is mandatory for pathThayne McCombsbefore adoption19a55aa
line 657why, one step back657 help = "the root directories for the filesystem search (optional, requires pattern first)",Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 658–713why, one step back658 long_help,659 )]660 path: Vec<PathBuf>,661662 /// Provide paths to search as an alternative to the positional <path>663 /// argument. Changes the usage to `fd [OPTIONS] --search-path <path>664 /// --search-path <path2> [<pattern>]`665 #[arg(666 long,667 conflicts_with("path"),668 value_name = "search-path",669 hide_short_help = true,670 help = "Provides paths to search as an alternative to the positional <path> argument",671 long_help672 )]673 search_path: Vec<PathBuf>,674675 /// By default, relative paths are prefixed with './' when -x/--exec,676 /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a677 /// path starting with '-' being treated as a command line option. Use678 /// this flag to change this behavior. If this flag is used without a value,679 /// it is equivalent to passing "always".680 #[arg(long, conflicts_with_all(&["path", "search_path"]), value_name = "when", hide_short_help = true, require_equals = true, long_help)]681 strip_cwd_prefix: Option<Option<StripCwdWhen>>,682683 /// By default, fd will traverse the file system tree as far as other options684 /// dictate. With this flag, fd ensures that it does not descend into a685 /// different file system than the one it started in. Comparable to the -mount686 /// or -xdev filters of find(1).687 #[cfg(any(unix, windows))]688 #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]689 pub one_file_system: bool,690691 #[cfg(feature = "completions")]692 #[arg(long, hide = true, exclusive = true)]693 gen_completions: Option<Option<Shell>>,694}695696impl Opts {697 pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {698 // would it make sense to concatenate these?699 let paths = if !self.path.is_empty() {700 &self.path701 } else if !self.search_path.is_empty() {702 &self.search_path703 } else {704 let current_directory = Path::new("./");705 ensure_current_directory_exists(current_directory)?;706 return Ok(vec![self.normalize_path(current_directory)]);707 };708 Ok(paths709 .iter()710 .filter_map(|path| {711 if filesystem::is_existing_directory(path) {712 Some(self.normalize_path(path))713 } else {fix: Better sanitizingThayne McCombsbefore adoption24198d9
lines 714–719why, one step back714 // We use debug for the path to make it more readable if it has special characters715 // Should we use a more reliable escape?716 print_error!(717 "Search path {:?} is not a directory.",718 path.to_string_lossy().as_ref()719 );Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 720–731why, one step back720 None721 }722 })723 .collect())724 }725726 fn normalize_path(&self, path: &Path) -> PathBuf {727 if self.absolute_path {728 filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()729 } else if path == Path::new(".") {730 // Change "." to "./" as a workaround for https://github.com/BurntSushi/ripgrep/pull/2711731 PathBuf::from("./")Merge pull request #2006 from Sean-Kenneth-Doherty/codex/single-dash-search-pathThayne McCombsbefore adoptiond491003
lines 732–735why, one step back732 } else if path == Path::new("-") {733 // Prefix "-" so the underlying walker treats it as a path.734 // See sharkdp/fd#849.735 Path::new(".").join(path)Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 736–898why, one step back736 } else {737 path.to_path_buf()738 }739 }740741 pub fn no_search_paths(&self) -> bool {742 self.path.is_empty() && self.search_path.is_empty()743 }744745 #[inline]746 pub fn rg_alias_ignore(&self) -> bool {747 self.rg_alias_hidden_ignore > 0748 }749750 pub fn max_depth(&self) -> Option<usize> {751 self.max_depth.or(self.exact_depth)752 }753754 pub fn min_depth(&self) -> Option<usize> {755 self.min_depth.or(self.exact_depth)756 }757758 pub fn threads(&self) -> NonZeroUsize {759 self.threads.unwrap_or_else(default_num_threads)760 }761762 pub fn max_results(&self) -> Option<usize> {763 self.max_results764 .filter(|&m| m > 0)765 .or_else(|| self.max_one_result.then_some(1))766 }767768 pub fn strip_cwd_prefix<P: FnOnce() -> bool>(&self, auto_pred: P) -> bool {769 use self::StripCwdWhen::*;770 self.no_search_paths()771 && match self.strip_cwd_prefix.map_or(Auto, |o| o.unwrap_or(Always)) {772 Auto => auto_pred(),773 Always => true,774 Never => false,775 }776 }777778 #[cfg(feature = "completions")]779 pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {780 self.gen_completions781 .map(|maybe_shell| match maybe_shell {782 Some(sh) => Ok(sh),783 None => {784 Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))785 }786 })787 .transpose()788 }789}790791/// Get the default number of threads to use, if not explicitly specified.792fn default_num_threads() -> NonZeroUsize {793 // If we can't get the amount of parallelism for some reason, then794 // default to a single thread, because that is safe.795 let fallback = NonZeroUsize::MIN;796 // To limit startup overhead on massively parallel machines, don't use more797 // than 64 threads.798 let limit = NonZeroUsize::new(64).unwrap();799800 std::thread::available_parallelism()801 .unwrap_or(fallback)802 .min(limit)803}804805#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]806pub enum FileType {807 #[value(alias = "f")]808 File,809 #[value(alias = "d", alias = "dir")]810 Directory,811 #[value(alias = "l")]812 Symlink,813 #[value(alias = "b")]814 BlockDevice,815 #[value(alias = "c")]816 CharDevice,817 /// A file which is executable by the current effective user818 #[value(alias = "x")]819 Executable,820 #[value(alias = "e")]821 Empty,822 #[value(alias = "s")]823 Socket,824 #[value(alias = "p")]825 Pipe,826}827828#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]829pub enum ColorWhen {830 /// show colors if the output goes to an interactive console (default)831 Auto,832 /// always use colorized output833 Always,834 /// do not use colorized output835 Never,836}837838#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]839pub enum StripCwdWhen {840 /// Use the default behavior841 Auto,842 /// Always strip the ./ at the beginning of paths843 Always,844 /// Never strip the ./845 Never,846}847848#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]849pub enum HyperlinkWhen {850 /// Use hyperlinks only if color is enabled851 Auto,852 /// Always use hyperlinks when printing file paths853 Always,854 /// Never use hyperlinks855 Never,856}857858// there isn't a derive api for getting grouped values yet,859// so we have to use hand-rolled parsing for exec and exec-batch860pub struct Exec {861 pub command: Option<CommandSet>,862}863864impl clap::FromArgMatches for Exec {865 fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {866 let command = matches867 .get_occurrences::<String>("exec")868 .map(CommandSet::new)869 .or_else(|| {870 matches871 .get_occurrences::<String>("exec_batch")872 .map(CommandSet::new_batch)873 })874 .transpose()875 .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;876 Ok(Exec { command })877 }878879 fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {880 *self = Self::from_arg_matches(matches)?;881 Ok(())882 }883}884885impl clap::Args for Exec {886 fn augment_args(cmd: Command) -> Command {887 cmd.arg(Arg::new("exec")888 .action(ArgAction::Append)889 .long("exec")890 .short('x')891 .num_args(1..)892 .allow_hyphen_values(true)893 .value_terminator(";")894 .value_name("cmd")895 .conflicts_with("list_details")896 .help("Execute a command for each search result")897 .long_help(898 "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \docs(exec): clarify command ordering and output grouping for -x/--execpederbebefore adoption468cd43
line 899why, one step back899 The order in which different search results are processed and their output is printed is not guaranteed, even with --threads=1. \Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
line 900why, one step back900 All positional arguments following --exec are considered to be arguments to the command - not to fd. \Merge pull request #1924 from liruiluo/docs/clarify-exec-arg-boundaryThayne McCombsbefore adoptiondb7d448
line 901why, one step back901 It is therefore recommended to place the '-x'/'--exec' option last. \docs(exec): clarify command ordering and output grouping for -x/--execpederbebefore adoption468cd43
line 902why, one step back902 Use '\\;' to terminate the command template if you need to continue passing fd arguments afterwards.\n\n\docs(exec): explain repeated commands for each filePeder Berganbefore adoption5bbfa3e
lines 903–904why, one step back903 Specify this option multiple times to run several commands for each file or directory found. \904 For each file or directory, fd runs these commands one after another in the order they appear on the command line. \docs(exec): clarify command ordering and output grouping for -x/--execpederbebefore adoption468cd43
lines 905–907why, one step back905 Terminate each command except the last with '\\;'. \906 When running in parallel, fd buffers command output and prints it together for each search result, \907 without interleaving it with command output for other results.\n\n\Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 908–921why, one step back908 The following placeholders are substituted before the command is executed:\n \909 '{}': path (of the current search result)\n \910 '{/}': basename\n \911 '{//}': parent directory\n \912 '{.}': path without file extension\n \913 '{/.}': basename without file extension\n \914 '{{': literal '{' (for escaping)\n \915 '}}': literal '}' (for escaping)\n\n\916 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\917 Examples:\n\n \918 - find all *.zip files and unzip them:\n\n \919 fd -e zip -x unzip\n\n \920 - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n \921 fd -e h -e cpp -x clang-format -i\n\n \Merge pull request #1924 from liruiluo/docs/clarify-exec-arg-boundaryThayne McCombsbefore adoptiondb7d448
lines 922–923why, one step back922 - search within `src/` and echo each match (place `-x` last):\n\n \923 fd . src -x echo\n\n \Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d
lines 924–979why, one step back924 - Convert all *.jpg files to *.png files:\n\n \925 fd -e jpg -x convert {} {.}.png\926 ",927 ),928 )929 .arg(930 Arg::new("exec_batch")931 .action(ArgAction::Append)932 .long("exec-batch")933 .short('X')934 .num_args(1..)935 .allow_hyphen_values(true)936 .value_terminator(";")937 .value_name("cmd")938 .conflicts_with_all(["exec", "list_details"])939 .help("Execute a command with all search results at once")940 .long_help(941 "Execute the given command once, with all search results as arguments.\n\942 The order of the arguments is non-deterministic, and should not be relied upon.\n\943 One of the following placeholders is substituted before the command is executed:\n \944 '{}': path (of all search results)\n \945 '{/}': basename\n \946 '{//}': parent directory\n \947 '{.}': path without file extension\n \948 '{/.}': basename without file extension\n \949 '{{': literal '{' (for escaping)\n \950 '}}': literal '}' (for escaping)\n\n\951 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\952 Examples:\n\n \953 - Find all test_*.py files and open them in your favorite editor:\n\n \954 fd -g 'test_*.py' -X vim\n\n \955 - Find all *.rs files and count the lines with \"wc -l ...\":\n\n \956 fd -e rs -X wc -l\957 "958 ),959 )960 }961962 fn augment_args_for_update(cmd: Command) -> Command {963 Self::augment_args(cmd)964 }965}966967fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {968 Ok(Duration::from_millis(arg.parse()?))969}970971fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {972 if filesystem::is_existing_directory(current_directory) {973 Ok(())974 } else {975 Err(anyhow!(976 "Could not retrieve current directory (has it been deleted?)."977 ))978 }979}