cli.rs
This file
Path
src/cli.rs
802 lines · 31.0 KiB · Rust
Last changed by
Merge pull request #1139 from Uthar/masterDavid Peterbefore adoptionc9d3968
History of this fileTake it
Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 1–21why, one step back1use std::path::{Path, PathBuf};2use std::time::Duration;34use anyhow::anyhow;5use clap::{6 error::ErrorKind, value_parser, Arg, ArgAction, ArgGroup, ArgMatches, Command, Parser,7 ValueEnum,8};9#[cfg(feature = "completions")]10use clap_complete::Shell;11use normpath::PathExt;1213use crate::error::print_error;14use crate::exec::CommandSet;15use crate::filesystem;16#[cfg(unix)]17use crate::filter::OwnerFilter;18use crate::filter::SizeFilter;1920#[derive(Parser)]21#[command(Change clap CLI binary name to 'fd'David Peterbefore adoptionac35b11
line 22why, one step back22 name = "fd",Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 23why, one step back23 version,Add simple 'about' textDavid Peterbefore adoption7f5bc98
line 24why, one step back24 about = "A program to find entries in your filesystem",Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 25why, one step back25 after_long_help = "Bugs can be reported on GitHub: https://github.com/sharkdp/fd/issues",Set max. term width to make help texts easier to readDavid Peterbefore adoption70c4865
line 26why, one step back26 max_term_width = 98,Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 27–42why, one step back27 args_override_self = true,28 group(ArgGroup::new("execs").args(&["exec", "exec_batch", "list_details"]).conflicts_with_all(&[29 "max_results", "has_results", "count"])),30)]31pub struct Opts {32 /// Search hidden files and directories33 #[arg(34 long,35 short = 'H',36 long_help = "Include hidden directories and files in the search results (default: \37 hidden files and directories are skipped). Files and directories are \38 considered to be hidden if their name starts with a `.` sign (dot). \39 The flag can be overridden with --no-hidden."40 )]41 pub hidden: bool,42Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada
lines 43–46why, one step back43 /// Overrides --hidden44 #[arg(long, overrides_with = "hidden", hide = true, action = ArgAction::SetTrue)]45 no_hidden: (),46Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 47–56why, one step back47 /// Do not respect .(git|fd)ignore files48 #[arg(49 long,50 short = 'I',51 long_help = "Show search results from files and directories that would otherwise be \52 ignored by '.gitignore', '.ignore', '.fdignore', or the global ignore file. \53 The flag can be overridden with --ignore."54 )]55 pub no_ignore: bool,56Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada
lines 57–60why, one step back57 /// Overrides --no-ignore58 #[arg(long, overrides_with = "no_ignore", hide = true, action = ArgAction::SetTrue)]59 ignore: (),60Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 61–69why, one step back61 /// Do not respect .gitignore files62 #[arg(63 long,64 hide_short_help = true,65 long_help = "Show search results from files and directories that would otherwise be \66 ignored by '.gitignore' files. The flag can be overridden with --ignore-vcs."67 )]68 pub no_ignore_vcs: bool,69Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada
lines 70–73why, one step back70 /// Overrides --no-ignore-vcs71 #[arg(long, overrides_with = "no_ignore_vcs", hide = true, action = ArgAction::SetTrue)]72 ignore_vcs: (),73Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 74–146why, one step back74 /// Do not respect .(git|fd)ignore files in parent directories75 #[arg(76 long,77 hide_short_help = true,78 long_help = "Show search results from files and directories that would otherwise be \79 ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories."80 )]81 pub no_ignore_parent: bool,8283 /// Do not respect the global ignore file84 #[arg(long, hide = true)]85 pub no_global_ignore_file: bool,8687 /// Unrestricted search, alias for '--no-ignore --hidden'88 #[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,89 long_help = "Perform an unrestricted search, including ignored and hidden files. This is \90 an alias for '--no-ignore --hidden'."91 )]92 rg_alias_hidden_ignore: u8,9394 /// Case-sensitive search (default: smart case)95 #[arg(96 long,97 short = 's',98 overrides_with("ignore_case"),99 long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \100 searches, unless the pattern contains an uppercase character (smart \101 case)."102 )]103 pub case_sensitive: bool,104105 /// Case-insensitive search (default: smart case)106 #[arg(107 long,108 short = 'i',109 overrides_with("case_sensitive"),110 long_help = "Perform a case-insensitive search. By default, fd uses case-insensitive \111 searches, unless the pattern contains an uppercase character (smart \112 case)."113 )]114 pub ignore_case: bool,115116 /// Glob-based search (default: regular expression)117 #[arg(118 long,119 short = 'g',120 conflicts_with("fixed_strings"),121 long_help = "Perform a glob-based search instead of a regular expression search."122 )]123 pub glob: bool,124125 /// Regular-expression based search (default)126 #[arg(127 long,128 overrides_with("glob"),129 hide_short_help = true,130 long_help = "Perform a regular-expression based search (default). This can be used to \131 override --glob."132 )]133 pub regex: bool,134135 /// Treat pattern as literal string stead of regex136 #[arg(137 long,138 short = 'F',139 alias = "literal",140 hide_short_help = true,141 long_help = "Treat the pattern as a literal string instead of a regular expression. Note \142 that this also performs substring comparison. If you want to match on an \143 exact filename, consider using '--glob'."144 )]145 pub fixed_strings: bool,146Merge pull request #1139 from Uthar/masterDavid Peterbefore adoptionc9d3968
lines 147–158why, one step back147 /// Additional search patterns that need to be matched148 #[arg(149 long = "and",150 value_name = "pattern",151 long_help = "Add additional required search patterns, all of which must be matched. Multiple \152 additional patterns can be specified. The patterns are regular expressions, \153 unless '--glob' or '--fixed-strings' is used.",154 hide_short_help = true,155 allow_hyphen_values = true156 )]157 pub exprs: Option<Vec<String>>,158Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 159–167why, one step back159 /// Show absolute instead of relative paths160 #[arg(161 long,162 short = 'a',163 long_help = "Shows the full path starting from the root as opposed to relative paths. \164 The flag can be overridden with --relative-path."165 )]166 pub absolute_path: bool,167Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada
lines 168–171why, one step back168 /// Overrides --absolute-path169 #[arg(long, overrides_with = "absolute_path", hide = true, action = ArgAction::SetTrue)]170 relative_path: (),171Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 172–194why, one step back172 /// Use a long listing format with file metadata173 #[arg(174 long,175 short = 'l',176 conflicts_with("absolute_path"),177 long_help = "Use a detailed listing format like 'ls -l'. This is basically an alias \178 for '--exec-batch ls -l' with some additional 'ls' options. This can be \179 used to see more metadata, to show symlink targets and to achieve a \180 deterministic sort order."181 )]182 pub list_details: bool,183184 /// Follow symbolic links185 #[arg(186 long,187 short = 'L',188 alias = "dereference",189 long_help = "By default, fd does not descend into symlinked directories. Using this \190 flag, symbolic links are also traversed. \191 Flag can be overriden with --no-follow."192 )]193 pub follow: bool,194Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada
lines 195–198why, one step back195 /// Overrides --follow196 #[arg(long, overrides_with = "follow", hide = true, action = ArgAction::SetTrue)]197 no_follow: (),198Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 199–248why, one step back199 /// Search full abs. path (default: filename only)200 #[arg(201 long,202 short = 'p',203 long_help = "By default, the search pattern is only matched against the filename (or \204 directory name). Using this flag, the pattern is matched against the full \205 (absolute) path. Example:\n \206 fd --glob -p '**/.git/config'"207 )]208 pub full_path: bool,209210 /// Separate search results by the null character211 #[arg(212 long = "print0",213 short = '0',214 conflicts_with("list_details"),215 hide_short_help = true,216 long_help = "Separate search results by the null character (instead of newlines). \217 Useful for piping results to 'xargs'."218 )]219 pub null_separator: bool,220221 /// Set maximum search depth (default: none)222 #[arg(223 long,224 short = 'd',225 value_name = "depth",226 alias("maxdepth"),227 long_help = "Limit the directory traversal to a given depth. By default, there is no \228 limit on the search depth."229 )]230 max_depth: Option<usize>,231232 /// Only show search results starting at the given depth.233 #[arg(234 long,235 value_name = "depth",236 hide_short_help = true,237 long_help = "Only show search results starting at the given depth. \238 See also: '--max-depth' and '--exact-depth'"239 )]240 min_depth: Option<usize>,241242 /// Only show search results at the exact given depth243 #[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),244 long_help = "Only show search results at the exact given depth. This is an alias for \245 '--min-depth <depth> --max-depth <depth>'.",246 )]247 exact_depth: Option<usize>,248Reorder command line optionsDavid Peterbefore adoption12165c7
lines 249–262why, one step back249 /// Exclude entries that match the given glob pattern250 #[arg(251 long,252 short = 'E',253 value_name = "pattern",254 long_help = "Exclude files/directories that match the given glob pattern. This \255 overrides any other ignore logic. Multiple exclude patterns can be \256 specified.\n\n\257 Examples:\n \258 --exclude '*.pyc'\n \259 --exclude node_modules"260 )]261 pub exclude: Vec<String>,262Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 263–349why, one step back263 /// Do not traverse into directories that match the search criteria. If264 /// you want to exclude specific directories, use the '--exclude=…' option.265 #[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),266 long_help = "Do not traverse into directories that match the search criteria. If \267 you want to exclude specific directories, use the '--exclude=…' option.",268 )]269 pub prune: bool,270271 /// Filter by type: file (f), directory (d), symlink (l),272 /// executable (x), empty (e), socket (s), pipe (p)273 #[arg(274 long = "type",275 short = 't',276 value_name = "filetype",277 hide_possible_values = true,278 value_enum,279 long_help = "Filter the search by type:\n \280 'f' or 'file': regular files\n \281 'd' or 'directory': directories\n \282 'l' or 'symlink': symbolic links\n \283 's' or 'socket': socket\n \284 'p' or 'pipe': named pipe (FIFO)\n\n \285 'x' or 'executable': executables\n \286 'e' or 'empty': empty files or directories\n\n\287 This option can be specified more than once to include multiple file types. \288 Searching for '--type file --type symlink' will show both regular files as \289 well as symlinks. Note that the 'executable' and 'empty' filters work differently: \290 '--type executable' implies '--type file' by default. And '--type empty' searches \291 for empty files and directories, unless either '--type file' or '--type directory' \292 is specified in addition.\n\n\293 Examples:\n \294 - Only search for files:\n \295 fd --type file …\n \296 fd -tf …\n \297 - Find both files and symlinks\n \298 fd --type file --type symlink …\n \299 fd -tf -tl …\n \300 - Find executable files:\n \301 fd --type executable\n \302 fd -tx\n \303 - Find empty files:\n \304 fd --type empty --type file\n \305 fd -te -tf\n \306 - Find empty directories:\n \307 fd --type empty --type directory\n \308 fd -te -td"309 )]310 pub filetype: Option<Vec<FileType>>,311312 /// Filter by file extension313 #[arg(314 long = "extension",315 short = 'e',316 value_name = "ext",317 long_help = "(Additionally) filter search results by their file extension. Multiple \318 allowable file extensions can be specified.\n\319 If you want to search for files without extension, \320 you can use the regex '^[^.]+$' as a normal search pattern."321 )]322 pub extensions: Option<Vec<String>>,323324 /// Limit results based on the size of files325 #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",326 long_help = "Limit results based on the size of files using the format <+-><NUM><UNIT>.\n \327 '+': file size must be greater than or equal to this\n \328 '-': file size must be less than or equal to this\n\329 If neither '+' nor '-' is specified, file size must be exactly equal to this.\n \330 'NUM': The numeric size (e.g. 500)\n \331 'UNIT': The units for NUM. They are not case-sensitive.\n\332 Allowed unit values:\n \333 'b': bytes\n \334 'k': kilobytes (base ten, 10^3 = 1000 bytes)\n \335 'm': megabytes\n \336 'g': gigabytes\n \337 't': terabytes\n \338 'ki': kibibytes (base two, 2^10 = 1024 bytes)\n \339 'mi': mebibytes\n \340 'gi': gibibytes\n \341 'ti': tebibytes",342 )]343 pub size: Vec<SizeFilter>,344345 /// Filter by file modification time (newer than)346 #[arg(347 long,348 alias("change-newer-than"),349 alias("newer"),Merge pull request #1176 from tmccombs/changed-afterDavid Peterbefore adoption8dda499
line 350why, one step back350 alias("changed-after"),Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 351why, one step back351 value_name = "date|dur",Merge pull request #1176 from tmccombs/changed-afterDavid Peterbefore adoption8dda499
lines 352–354why, one step back352 long_help = "Filter results based on the file modification time. \353 Files with modification times greater than the argument are returned. \354 The argument can be provided \Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 355–370why, one step back355 as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \356 If the time is not specified, it defaults to 00:00:00. \357 '--change-newer-than' or '--newer' can be used as aliases.\n\358 Examples:\n \359 --changed-within 2weeks\n \360 --change-newer-than '2018-10-27 10:00:00'\n \361 --newer 2018-10-27"362 )]363 pub changed_within: Option<String>,364365 /// Filter by file modification time (older than)366 #[arg(367 long,368 alias("change-older-than"),369 alias("older"),370 value_name = "date|dur",Merge pull request #1176 from tmccombs/changed-afterDavid Peterbefore adoption8dda499
lines 371–373why, one step back371 long_help = "Filter results based on the file modification time. \372 Files with modification times less than the argument are returned. \373 The argument can be provided \Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 374–382why, one step back374 as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \375 '--change-older-than' or '--older' can be used as aliases.\n\376 Examples:\n \377 --changed-before '2018-10-27 10:00:00'\n \378 --change-older-than 2weeks\n \379 --older 2018-10-27"380 )]381 pub changed_before: Option<String>,382Reorder command line optionsDavid Peterbefore adoption12165c7
lines 383–437why, one step back383 /// Filter by owning user and/or group384 #[cfg(unix)]385 #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",386 long_help = "Filter files by their user and/or group. \387 Format: [(user|uid)][:(group|gid)]. Either side is optional. \388 Precede either side with a '!' to exclude files instead.\n\389 Examples:\n \390 --owner john\n \391 --owner :students\n \392 --owner '!john:students'"393 )]394 pub owner: Option<OwnerFilter>,395396 #[command(flatten)]397 pub exec: Exec,398399 /// Max number of arguments to run as a batch size with -X400 #[arg(401 long,402 value_name = "size",403 hide_short_help = true,404 requires("exec_batch"),405 value_parser = value_parser!(usize),406 default_value_t,407 long_help = "Maximum number of arguments to pass to the command given with -X. \408 If the number of results is greater than the given size, \409 the command given with -X is run again with remaining arguments. \410 A batch size of zero means there is no limit (default), but note \411 that batching might still happen due to OS restrictions on the \412 maximum length of command lines.",413 )]414 pub batch_size: usize,415416 /// Add a custom ignore-file in '.gitignore' format417 #[arg(418 long,419 value_name = "path",420 hide_short_help = true,421 long_help = "Add a custom ignore-file in '.gitignore' format. These files have a low precedence."422 )]423 pub ignore_file: Vec<PathBuf>,424425 /// When to use colors426 #[arg(427 long,428 short = 'c',429 value_enum,430 default_value_t = ColorWhen::Auto,431 value_name = "when",432 long_help = "Declare when to use color for the pattern match output",433 )]434 pub color: ColorWhen,435436 /// Set number of threads to use for searching & executing (default: number437 /// of available CPU cores)Merge pull request #1162 from sharkdp/fix-threads-optionDavid Peterbefore adoption0a7b51a
line 438why, one step back438 #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = clap::value_parser!(u32).range(1..))]Reorder command line optionsDavid Peterbefore adoption12165c7
lines 439–447why, one step back439 pub threads: Option<u32>,440441 /// Milliseconds to buffer before streaming search results to console442 ///443 /// Amount of time in milliseconds to buffer, before streaming the search444 /// results to the console.445 #[arg(long, hide = true, value_parser = parse_millis)]446 pub max_buffer_time: Option<Duration>,447Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 448–646why, one step back448 /// Limit number of search results449 #[arg(450 long,451 value_name = "count",452 hide_short_help = true,453 long_help = "Limit the number of search results to 'count' and quit immediately."454 )]455 max_results: Option<usize>,456457 /// Limit search to a single result458 #[arg(459 short = '1',460 hide_short_help = true,461 overrides_with("max_results"),462 long_help = "Limit the search to a single result and quit immediately. \463 This is an alias for '--max-results=1'."464 )]465 max_one_result: bool,466467 /// Print nothing, exit code 0 if match found, 1 otherwise468 #[arg(469 long,470 short = 'q',471 alias = "has-results",472 hide_short_help = true,473 conflicts_with("max_results"),474 long_help = "When the flag is present, the program does not print anything and will \475 return with an exit code of 0 if there is at least one match. Otherwise, the \476 exit code will be 1. \477 '--has-results' can be used as an alias."478 )]479 pub quiet: bool,480481 /// Show filesystem errors482 #[arg(483 long,484 hide_short_help = true,485 long_help = "Enable the display of filesystem errors for situations such as \486 insufficient permissions or dead symlinks."487 )]488 pub show_errors: bool,489490 /// Change current working directory491 #[arg(492 long,493 value_name = "path",494 hide_short_help = true,495 long_help = "Change the current working directory of fd to the provided path. This \496 means that search results will be shown with respect to the given base \497 path. Note that relative paths which are passed to fd via the positional \498 <path> argument or the '--search-path' option will also be resolved \499 relative to this directory."500 )]501 pub base_directory: Option<PathBuf>,502503 /// the search pattern (a regular expression, unless '--glob' is used; optional)504 #[arg(505 default_value = "",506 hide_default_value = true,507 value_name = "pattern",508 long_help = "the search pattern which is either a regular expression (default) or a glob \509 pattern (if --glob is used). If no pattern has been specified, every entry \510 is considered a match. If your pattern starts with a dash (-), make sure to \511 pass '--' first, or it will be considered as a flag (fd -- '-foo')."512 )]513 pub pattern: String,514515 /// Set path separator when printing file paths516 #[arg(517 long,518 value_name = "separator",519 hide_short_help = true,520 long_help = "Set the path separator to use when printing file paths. The default is \521 the OS-specific separator ('/' on Unix, '\\' on Windows)."522 )]523 pub path_separator: Option<String>,524525 /// the root directories for the filesystem search (optional)526 #[arg(action = ArgAction::Append,527 value_name = "path",528 long_help = "The directory where the filesystem search is rooted (optional). If \529 omitted, search the current working directory.",530 )]531 path: Vec<PathBuf>,532533 /// Provides paths to search as an alternative to the positional <path> argument534 #[arg(535 long,536 conflicts_with("path"),537 value_name = "search-path",538 hide_short_help = true,539 long_help = "Provide paths to search as an alternative to the positional <path> \540 argument. Changes the usage to `fd [OPTIONS] --search-path <path> \541 --search-path <path2> [<pattern>]`"542 )]543 search_path: Vec<PathBuf>,544545 /// By default, relative paths are prefixed with './' when -x/--exec,546 /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a547 /// path starting with '-' being treated as a command line option. Use548 /// this flag to disable this behaviour.549 #[arg(long, conflicts_with_all(&["path", "search_path"]), hide_short_help = true,550 long_help = "By default, relative paths are prefixed with './' when -x/--exec, \551 -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a \552 path starting with '-' being treated as a command line option. Use \553 this flag to disable this behaviour.",554 )]555 pub strip_cwd_prefix: bool,556557 #[cfg(any(unix, windows))]558 #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true,559 long_help = "By default, fd will traverse the file system tree as far as other options \560 dictate. With this flag, fd ensures that it does not descend into a \561 different file system than the one it started in. Comparable to the -mount \562 or -xdev filters of find(1).")]563 pub one_file_system: bool,564565 #[cfg(feature = "completions")]566 #[arg(long, hide = true, exclusive = true)]567 gen_completions: Option<Option<Shell>>,568}569570impl Opts {571 pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {572 // would it make sense to concatenate these?573 let paths = if !self.path.is_empty() {574 &self.path575 } else if !self.search_path.is_empty() {576 &self.search_path577 } else {578 let current_directory = Path::new(".");579 ensure_current_directory_exists(current_directory)?;580 return Ok(vec![self.normalize_path(current_directory)]);581 };582 Ok(paths583 .iter()584 .filter_map(|path| {585 if filesystem::is_existing_directory(path) {586 Some(self.normalize_path(path))587 } else {588 print_error(format!(589 "Search path '{}' is not a directory.",590 path.to_string_lossy()591 ));592 None593 }594 })595 .collect())596 }597598 fn normalize_path(&self, path: &Path) -> PathBuf {599 if self.absolute_path {600 filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()601 } else {602 path.to_path_buf()603 }604 }605606 pub fn no_search_paths(&self) -> bool {607 self.path.is_empty() && self.search_path.is_empty()608 }609610 #[inline]611 pub fn rg_alias_ignore(&self) -> bool {612 self.rg_alias_hidden_ignore > 0613 }614615 pub fn max_depth(&self) -> Option<usize> {616 self.max_depth.or(self.exact_depth)617 }618619 pub fn min_depth(&self) -> Option<usize> {620 self.min_depth.or(self.exact_depth)621 }622623 pub fn threads(&self) -> usize {624 // This will panic if the number of threads passed in is more than usize::MAX in an environment625 // where usize is less than 32 bits (for example 16-bit architectures). It's pretty626 // unlikely fd will be running in such an environment, and even more unlikely someone would627 // be trying to use that many threads on such an environment, so I think panicing is an628 // appropriate way to handle that.629 std::cmp::max(630 self.threads631 .map_or_else(num_cpus::get, |n| n.try_into().expect("too many threads")),632 1,633 )634 }635636 pub fn max_results(&self) -> Option<usize> {637 self.max_results638 .filter(|&m| m > 0)639 .or_else(|| self.max_one_result.then(|| 1))640 }641642 #[cfg(feature = "completions")]643 pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {644 self.gen_completions645 .map(|maybe_shell| match maybe_shell {646 Some(sh) => Ok(sh),Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada
lines 647–649why, one step back647 None => {648 Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))649 }Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 650–662why, one step back650 })651 .transpose()652 }653}654655#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]656pub enum FileType {657 #[value(alias = "f")]658 File,659 #[value(alias = "d")]660 Directory,661 #[value(alias = "l")]662 Symlink,Merge pull request #1169 from Ptipiak/mention-executable-detectionDavid Peterbefore adoption38cdeb0
line 663why, one step back663 /// A file which is executable by the current effective userMerge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 664–763why, one step back664 #[value(alias = "x")]665 Executable,666 #[value(alias = "e")]667 Empty,668 #[value(alias = "s")]669 Socket,670 #[value(alias = "p")]671 Pipe,672}673674#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]675pub enum ColorWhen {676 /// show colors if the output goes to an interactive console (default)677 Auto,678 /// always use colorized output679 Always,680 /// do not use colorized output681 Never,682}683684impl ColorWhen {685 pub fn as_str(&self) -> &'static str {686 use ColorWhen::*;687 match *self {688 Auto => "auto",689 Never => "never",690 Always => "always",691 }692 }693}694695// there isn't a derive api for getting grouped values yet,696// so we have to use hand-rolled parsing for exec and exec-batch697pub struct Exec {698 pub command: Option<CommandSet>,699}700701impl clap::FromArgMatches for Exec {702 fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {703 let command = matches704 .grouped_values_of("exec")705 .map(CommandSet::new)706 .or_else(|| {707 matches708 .grouped_values_of("exec_batch")709 .map(CommandSet::new_batch)710 })711 .transpose()712 .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;713 Ok(Exec { command })714 }715716 fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {717 *self = Self::from_arg_matches(matches)?;718 Ok(())719 }720}721722impl clap::Args for Exec {723 fn augment_args(cmd: Command) -> Command {724 cmd.arg(Arg::new("exec")725 .action(ArgAction::Append)726 .long("exec")727 .short('x')728 .num_args(1..)729 .allow_hyphen_values(true)730 .value_terminator(";")731 .value_name("cmd")732 .conflicts_with("list_details")733 .help("Execute a command for each search result")734 .long_help(735 "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \736 All positional arguments following --exec are considered to be arguments to the command - not to fd. \737 It is therefore recommended to place the '-x'/'--exec' option last.\n\738 The following placeholders are substituted before the command is executed:\n \739 '{}': path (of the current search result)\n \740 '{/}': basename\n \741 '{//}': parent directory\n \742 '{.}': path without file extension\n \743 '{/.}': basename without file extension\n\n\744 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\745 Examples:\n\n \746 - find all *.zip files and unzip them:\n\n \747 fd -e zip -x unzip\n\n \748 - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n \749 fd -e h -e cpp -x clang-format -i\n\n \750 - Convert all *.jpg files to *.png files:\n\n \751 fd -e jpg -x convert {} {.}.png\752 ",753 ),754 )755 .arg(756 Arg::new("exec_batch")757 .action(ArgAction::Append)758 .long("exec-batch")759 .short('X')760 .num_args(1..)761 .allow_hyphen_values(true)762 .value_terminator(";")763 .value_name("cmd")Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91
line 764why, one step back764 .conflicts_with_all(["exec", "list_details"])Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 765–802why, one step back765 .help("Execute a command with all search results at once")766 .long_help(767 "Execute the given command once, with all search results as arguments.\n\768 One of the following placeholders is substituted before the command is executed:\n \769 '{}': path (of all search results)\n \770 '{/}': basename\n \771 '{//}': parent directory\n \772 '{.}': path without file extension\n \773 '{/.}': basename without file extension\n\n\774 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\775 Examples:\n\n \776 - Find all test_*.py files and open them in your favorite editor:\n\n \777 fd -g 'test_*.py' -X vim\n\n \778 - Find all *.rs files and count the lines with \"wc -l ...\":\n\n \779 fd -e rs -X wc -l\780 "781 ),782 )783 }784785 fn augment_args_for_update(cmd: Command) -> Command {786 Self::augment_args(cmd)787 }788}789790fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {791 Ok(Duration::from_millis(arg.parse()?))792}793794fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {795 if filesystem::is_existing_directory(current_directory) {796 Ok(())797 } else {798 Err(anyhow!(799 "Could not retrieve current directory (has it been deleted?)."800 ))801 }802}