cli.rs
This file
Path
src/cli.rs
953 lines · 33.7 KiB · Rust
Last changed by
Merge pull request #1959 from tmchow/osc/1958-ignore-parentThayne McCombsbefore adoption90e73d7
History of this fileTake it
1use std::num::NonZeroUsize;2use std::path::{Path, PathBuf};3use std::time::Duration;45use anyhow::anyhow;6use clap::{7 Arg, ArgAction, ArgGroup, ArgMatches, Command, Parser, ValueEnum, error::ErrorKind,8 value_parser,9};10#[cfg(feature = "completions")]11use clap_complete::Shell;12use normpath::PathExt;1314use crate::error::print_error;15use crate::exec::CommandSet;16use crate::filesystem;17#[cfg(unix)]18use crate::filter::OwnerFilter;19use crate::filter::SizeFilter;2021#[derive(Parser)]22#[command(23 name = "fd",24 version,25 about = "A program to find entries in your filesystem",26 after_long_help = "Bugs can be reported on GitHub: https://github.com/sharkdp/fd/issues",27 max_term_width = 98,28 args_override_self = true,29 group(ArgGroup::new("execs").args(&["exec", "exec_batch", "list_details"]).conflicts_with_all(&[30 "max_results", "quiet", "max_one_result"])),31)]32pub struct Opts {33 /// Include hidden directories and files in the search results (default:34 /// hidden files and directories are skipped). Files and directories are35 /// considered to be hidden if their name starts with a `.` sign (dot).36 /// Any files or directories that are ignored due to the rules described by37 /// --no-ignore are still ignored unless otherwise specified.38 /// The flag can be overridden with --no-hidden.39 #[arg(40 long,41 short = 'H',42 help = "Search hidden files and directories",43 long_help44 )]45 pub hidden: bool,4647 /// Overrides --hidden48 #[arg(long, overrides_with = "hidden", hide = true, action = ArgAction::SetTrue)]49 no_hidden: (),5051 /// Show search results from files and directories that would otherwise be52 /// ignored by '.gitignore', '.ignore', '.fdignore', or the global ignore file,53 /// The flag can be overridden with --ignore.54 #[arg(55 long,56 short = 'I',57 help = "Do not respect .(git|fd)ignore files",58 long_help59 )]60 pub no_ignore: bool,6162 /// Overrides --no-ignore63 #[arg(long, overrides_with = "no_ignore", hide = true, action = ArgAction::SetTrue)]64 ignore: (),6566 ///Show search results from files and directories that67 ///would otherwise be ignored by '.gitignore' files.68 ///The flag can be overridden with --ignore-vcs.69 #[arg(70 long,71 hide_short_help = true,72 help = "Do not respect .gitignore files",73 long_help74 )]75 pub no_ignore_vcs: bool,7677 /// Overrides --no-ignore-vcs78 #[arg(long, overrides_with = "no_ignore_vcs", hide = true, action = ArgAction::SetTrue)]79 ignore_vcs: (),8081 /// Do not require a git repository to respect gitignores.82 /// By default, fd will only respect global gitignore rules, .gitignore rules,83 /// and local exclude rules if fd detects that you are searching inside a84 /// git repository. This flag allows you to relax this restriction such that85 /// fd will respect all git related ignore rules regardless of whether you're86 /// searching in a git repository or not.87 ///88 ///89 /// This flag can be disabled with --require-git.90 #[arg(91 long,92 overrides_with = "require_git",93 hide_short_help = true,94 // same description as ripgrep's flag: ripgrep/crates/core/app.rs95 long_help96 )]97 pub no_require_git: bool,9899 /// Overrides --no-require-git100 #[arg(long, overrides_with = "no_require_git", hide = true, action = ArgAction::SetTrue)]101 require_git: (),102103 /// Show search results from files and directories that would otherwise be104 /// ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories.105 /// The flag can be overridden with --ignore-parent.106 #[arg(107 long,108 hide_short_help = true,109 help = "Do not respect .(git|fd)ignore files in parent directories",110 long_help111 )]112 pub no_ignore_parent: bool,113114 /// Overrides --no-ignore-parent115 #[arg(long, overrides_with = "no_ignore_parent", hide = true, action = ArgAction::SetTrue)]116 ignore_parent: (),117118 /// Do not respect the global ignore file119 #[arg(long, hide = true)]120 pub no_global_ignore_file: bool,121122 /// Perform an unrestricted search, including ignored and hidden files. This is123 /// an alias for '--no-ignore --hidden'.124 #[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,125 help = "Unrestricted search, alias for '--no-ignore --hidden'",126 long_help,127 )]128 rg_alias_hidden_ignore: u8,129130 /// Case-sensitive search (default: smart case)131 #[arg(132 long,133 short = 's',134 overrides_with("ignore_case"),135 long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \136 searches, unless the pattern contains an uppercase character (smart \137 case)."138 )]139 pub case_sensitive: bool,140141 /// Perform a case-insensitive search. By default, fd uses case-insensitive142 /// searches, unless the pattern contains an uppercase character (smart143 /// case).144 #[arg(145 long,146 short = 'i',147 overrides_with("case_sensitive"),148 help = "Case-insensitive search (default: smart case)",149 long_help150 )]151 pub ignore_case: bool,152153 /// Perform a glob-based search instead of a regular expression search.154 #[arg(155 long,156 short = 'g',157 conflicts_with("fixed_strings"),158 help = "Glob-based search (default: regular expression)",159 long_help160 )]161 pub glob: bool,162163 /// Perform a regular-expression based search (default). This can be used to164 /// override --glob.165 #[arg(166 long,167 overrides_with("glob"),168 hide_short_help = true,169 help = "Regular-expression based search (default)",170 long_help171 )]172 pub regex: bool,173174 /// Treat the pattern as a literal string instead of a regular expression. Note175 /// that this also performs substring comparison. If you want to match on an176 /// exact filename, consider using '--glob'.177 #[arg(178 long,179 short = 'F',180 alias = "literal",181 hide_short_help = true,182 help = "Treat pattern as literal string stead of regex",183 long_help184 )]185 pub fixed_strings: bool,186187 /// Add additional required search patterns, all of which must be matched. Multiple188 /// additional patterns can be specified. The patterns are regular189 /// expressions, unless '--glob' or '--fixed-strings' is used.190 #[arg(191 long = "and",192 value_name = "pattern",193 help = "Additional search patterns that need to be matched",194 long_help,195 hide_short_help = true,196 allow_hyphen_values = true197 )]198 pub exprs: Option<Vec<String>>,199200 /// Shows the full path starting from the root as opposed to relative paths.201 /// The flag can be overridden with --relative-path.202 #[arg(203 long,204 short = 'a',205 help = "Show absolute instead of relative paths",206 long_help207 )]208 pub absolute_path: bool,209210 /// Overrides --absolute-path211 #[arg(long, overrides_with = "absolute_path", hide = true, action = ArgAction::SetTrue)]212 relative_path: (),213214 /// Use a detailed listing format like 'ls -l'. This is basically an alias215 /// for '--exec-batch ls -l' with some additional 'ls' options. This can be216 /// used to see more metadata, to show symlink targets and to achieve a217 /// deterministic sort order.218 #[arg(219 long,220 short = 'l',221 conflicts_with("absolute_path"),222 help = "Use a long listing format with file metadata",223 long_help224 )]225 pub list_details: bool,226227 /// Follow symbolic links228 #[arg(229 long,230 short = 'L',231 alias = "dereference",232 long_help = "By default, fd does not descend into symlinked directories. Using this \233 flag, symbolic links are also traversed. \234 Flag can be overridden with --no-follow."235 )]236 pub follow: bool,237238 /// Overrides --follow239 #[arg(long, overrides_with = "follow", hide = true, action = ArgAction::SetTrue)]240 no_follow: (),241242 /// 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:243 /// fd --glob -p '**/.git/config'244 #[arg(245 long,246 short = 'p',247 help = "Search full abs. path (default: filename only)",248 long_help,249 verbatim_doc_comment250 )]251 pub full_path: bool,252253 /// Separate search results by the null character (instead of newlines).254 /// Useful for piping results to 'xargs'.255 #[arg(256 long = "print0",257 short = '0',258 conflicts_with("list_details"),259 hide_short_help = true,260 help = "Separate search results by the null character",261 long_help262 )]263 pub null_separator: bool,264265 /// Limit the directory traversal to a given depth. By default, there is no266 /// limit on the search depth.267 #[arg(268 long,269 short = 'd',270 value_name = "depth",271 alias("maxdepth"),272 help = "Set maximum search depth (default: none)",273 long_help274 )]275 max_depth: Option<usize>,276277 /// Only show search results starting at the given depth.278 /// See also: '--max-depth' and '--exact-depth'279 #[arg(280 long,281 value_name = "depth",282 hide_short_help = true,283 alias("mindepth"),284 help = "Only show search results starting at the given depth.",285 long_help286 )]287 min_depth: Option<usize>,288289 /// Only show search results at the exact given depth. This is an alias for290 /// '--min-depth <depth> --max-depth <depth>'.291 #[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),292 help = "Only show search results at the exact given depth",293 long_help,294 )]295 exact_depth: Option<usize>,296297 /// Exclude files/directories that match the given glob pattern. This298 /// overrides any other ignore logic. Multiple exclude patterns can be299 /// specified.300 ///301 /// Examples:302 /// {n} --exclude '*.pyc'303 /// {n} --exclude node_modules304 #[arg(305 long,306 short = 'E',307 value_name = "glob",308 help = "Exclude entries that match the given glob pattern",309 long_help310 )]311 pub exclude: Vec<String>,312313 /// Do not traverse into directories that match the search criteria. If314 /// you want to exclude specific directories, use the '--exclude=…' option.315 #[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),316 long_help,317 )]318 pub prune: bool,319320 /// Filter the search by type:321 /// {n} 'f' or 'file': regular files322 /// {n} 'd' or 'dir' or 'directory': directories323 /// {n} 'l' or 'symlink': symbolic links324 /// {n} 's' or 'socket': socket325 /// {n} 'p' or 'pipe': named pipe (FIFO)326 /// {n} 'b' or 'block-device': block device327 /// {n} 'c' or 'char-device': character device328 /// {n}{n} 'x' or 'executable': executables329 /// {n} 'e' or 'empty': empty files or directories330 ///331 /// This option can be specified more than once to include multiple file types.332 /// Searching for '--type file --type symlink' will show both regular files as333 /// well as symlinks. Note that the 'executable' and 'empty' filters work differently:334 /// '--type executable' implies '--type file' by default. And '--type empty' searches335 /// for empty files and directories, unless either '--type file' or '--type directory'336 /// is specified in addition.337 ///338 /// Examples:339 /// {n} - Only search for files:340 /// {n} fd --type file …341 /// {n} fd -tf …342 /// {n} - Find both files and symlinks343 /// {n} fd --type file --type symlink …344 /// {n} fd -tf -tl …345 /// {n} - Find executable files:346 /// {n} fd --type executable347 /// {n} fd -tx348 /// {n} - Find empty files:349 /// {n} fd --type empty --type file350 /// {n} fd -te -tf351 /// {n} - Find empty directories:352 /// {n} fd --type empty --type directory353 /// {n} fd -te -td354 #[arg(355 long = "type",356 short = 't',357 value_name = "filetype",358 hide_possible_values = true,359 value_enum,360 help = "Filter by type: file (f), directory (d/dir), symlink (l), \361 executable (x), empty (e), socket (s), pipe (p), \362 char-device (c), block-device (b)",363 long_help364 )]365 pub filetype: Option<Vec<FileType>>,366367 /// (Additionally) filter search results by their file extension. Multiple368 /// allowable file extensions can be specified.369 ///370 /// If you want to search for files without extension,371 /// you can use the regex '^[^.]+$' as a normal search pattern.372 #[arg(373 long = "extension",374 short = 'e',375 value_name = "ext",376 help = "Filter by file extension",377 long_help378 )]379 pub extensions: Option<Vec<String>>,380381 /// Limit results based on the size of files using the format <+-><NUM><UNIT>.382 /// '+': file size must be greater than or equal to this383 /// '-': file size must be less than or equal to this384 ///385 /// If neither '+' nor '-' is specified, file size must be exactly equal to this.386 /// 'NUM': The numeric size (e.g. 500)387 /// 'UNIT': The units for NUM. They are not case-sensitive.388 /// Allowed unit values:389 /// 'b': bytes390 /// 'k': kilobytes (base ten, 10^3 = 1000 bytes)391 /// 'm': megabytes392 /// 'g': gigabytes393 /// 't': terabytes394 /// 'ki': kibibytes (base two, 2^10 = 1024 bytes)395 /// 'mi': mebibytes396 /// 'gi': gibibytes397 /// 'ti': tebibytes398 #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",399 help = "Limit results based on the size of files",400 long_help,401 verbatim_doc_comment,402 )]403 pub size: Vec<SizeFilter>,404405 /// Filter results based on the file modification time. Files with modification times406 /// greater than the argument are returned. The argument can be provided407 /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).408 /// If the time is not specified, it defaults to 00:00:00.409 /// '--change-newer-than', '--newer', or '--changed-after' can be used as aliases.410 ///411 /// Examples:412 /// {n} --changed-within 2weeks413 /// {n} --change-newer-than '2018-10-27 10:00:00'414 /// {n} --newer 2018-10-27415 /// {n} --changed-after 1day416 #[arg(417 long,418 alias("change-newer-than"),419 alias("newer"),420 alias("changed-after"),421 value_name = "date|dur",422 help = "Filter by file modification time (newer than)",423 long_help424 )]425 pub changed_within: Option<String>,426427 /// Filter results based on the file modification time. Files with modification times428 /// less than the argument are returned. The argument can be provided429 /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).430 /// '--change-older-than' or '--older' can be used as aliases.431 ///432 /// Examples:433 /// {n} --changed-before '2018-10-27 10:00:00'434 /// {n} --change-older-than 2weeks435 /// {n} --older 2018-10-27436 #[arg(437 long,438 alias("change-older-than"),439 alias("older"),440 value_name = "date|dur",441 help = "Filter by file modification time (older than)",442 long_help443 )]444 pub changed_before: Option<String>,445446 /// Filter files by their user and/or group.447 /// Format: [(user|uid)][:(group|gid)]. Either side is optional.448 /// Precede either side with a '!' to exclude files instead.449 ///450 /// Examples:451 /// {n} --owner john452 /// {n} --owner :students453 /// {n} --owner '!john:students'454 #[cfg(unix)]455 #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",456 help = "Filter by owning user and/or group",457 long_help,458 )]459 pub owner: Option<OwnerFilter>,460461 /// Instead of printing the file normally, print the format string with the following placeholders replaced:462 /// '{}': path (of the current search result)463 /// '{/}': basename464 /// '{//}': parent directory465 /// '{.}': path without file extension466 /// '{/.}': basename without file extension467 #[arg(468 long,469 value_name = "fmt",470 help = "Print results according to template",471 conflicts_with = "list_details"472 )]473 pub format: Option<String>,474475 #[command(flatten)]476 pub exec: Exec,477478 /// Maximum number of arguments to pass to the command given with -X.479 /// If the number of results is greater than the given size,480 /// the command given with -X is run again with remaining arguments.481 /// A batch size of zero means there is no limit (default), but note482 /// that batching might still happen due to OS restrictions on the483 /// maximum length of command lines.484 #[arg(485 long,486 value_name = "size",487 hide_short_help = true,488 requires("exec_batch"),489 value_parser = value_parser!(usize),490 default_value_t,491 help = "Max number of arguments to run as a batch size with -X",492 long_help,493 )]494 pub batch_size: usize,495496 /// Add a custom ignore-file in '.gitignore' format. These files have a low precedence.497 #[arg(498 long,499 value_name = "path",500 hide_short_help = true,501 help = "Add a custom ignore-file in '.gitignore' format",502 long_help503 )]504 pub ignore_file: Vec<PathBuf>,505506 /// Declare when to use color for the pattern match output507 #[arg(508 long,509 short = 'c',510 value_enum,511 default_value_t = ColorWhen::Auto,512 value_name = "when",513 help = "When to use colors",514 long_help,515 )]516 pub color: ColorWhen,517518 /// Add a terminal hyperlink to a file:// url for each path in the output.519 ///520 /// Auto mode is used if no argument is given to this option.521 ///522 /// This doesn't do anything for --exec and --exec-batch.523 #[arg(524 long,525 alias = "hyper",526 value_name = "when",527 require_equals = true,528 value_enum,529 default_value_t = HyperlinkWhen::Never,530 default_missing_value = "auto",531 num_args = 0..=1,532 help = "Add hyperlinks to output paths"533 )]534 pub hyperlink: HyperlinkWhen,535536 /// Ignore directories containing the named entry.537 #[arg(long, value_name = "name")]538 pub ignore_contain: Vec<String>,539540 /// Set number of threads to use for searching & executing (default: number541 /// of available CPU cores)542 #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = str::parse::<NonZeroUsize>)]543 pub threads: Option<NonZeroUsize>,544545 /// Milliseconds to buffer before streaming search results to console546 ///547 /// Amount of time in milliseconds to buffer, before streaming the search548 /// results to the console.549 #[arg(long, hide = true, value_parser = parse_millis)]550 pub max_buffer_time: Option<Duration>,551552 ///Limit the number of search results to 'count' and quit immediately.553 #[arg(554 long,555 value_name = "count",556 hide_short_help = true,557 overrides_with("max_one_result"),558 help = "Limit the number of search results",559 long_help560 )]561 max_results: Option<usize>,562563 /// Limit the search to a single result and quit immediately.564 /// This is an alias for '--max-results=1'.565 #[arg(566 short = '1',567 hide_short_help = true,568 overrides_with("max_results"),569 help = "Limit search to a single result",570 long_help571 )]572 max_one_result: bool,573574 /// When the flag is present, the program does not print anything and will575 /// return with an exit code of 0 if there is at least one match. Otherwise, the576 /// exit code will be 1.577 /// '--has-results' can be used as an alias.578 #[arg(579 long,580 short = 'q',581 alias = "has-results",582 hide_short_help = true,583 conflicts_with("max_results"),584 help = "Print nothing, exit code 0 if match found, 1 otherwise",585 long_help586 )]587 pub quiet: bool,588589 /// Enable the display of filesystem errors for situations such as590 /// insufficient permissions or dead symlinks.591 #[arg(592 long,593 hide_short_help = true,594 help = "Show filesystem errors",595 long_help596 )]597 pub show_errors: bool,598599 /// Change the current working directory of fd to the provided path. This600 /// means that search results will be shown with respect to the given base601 /// path. Note that relative paths which are passed to fd via the positional602 /// <path> argument or the '--search-path' option will also be resolved603 /// relative to this directory.604 #[arg(605 long,606 short = 'C',607 value_name = "path",608 hide_short_help = true,609 help = "Change current working directory",610 long_help611 )]612 pub base_directory: Option<PathBuf>,613614 /// the search pattern which is either a regular expression (default) or a glob615 /// pattern (if --glob is used). If no pattern has been specified, every entry616 /// is considered a match. If your pattern starts with a dash (-), make sure to617 /// pass '--' first, or it will be considered as a flag (fd -- '-foo').618 #[arg(619 default_value = "",620 hide_default_value = true,621 value_name = "pattern",622 help = "the search pattern (a regular expression, unless '--glob' is used; optional)",623 long_help624 )]625 pub pattern: String,626627 /// Set the path separator to use when printing file paths. The default is628 /// the OS-specific separator ('/' on Unix, '\' on Windows).629 #[arg(630 long,631 value_name = "separator",632 hide_short_help = true,633 help = "Set path separator when printing file paths",634 long_help635 )]636 pub path_separator: Option<String>,637638 /// The directory where the filesystem search is rooted (optional). If639 /// omitted, search the current working directory.640 #[arg(action = ArgAction::Append,641 value_name = "path",642 help = "the root directories for the filesystem search (optional)",643 long_help,644 )]645 path: Vec<PathBuf>,646647 /// Provide paths to search as an alternative to the positional <path>648 /// argument. Changes the usage to `fd [OPTIONS] --search-path <path>649 /// --search-path <path2> [<pattern>]`650 #[arg(651 long,652 conflicts_with("path"),653 value_name = "search-path",654 hide_short_help = true,655 help = "Provides paths to search as an alternative to the positional <path> argument",656 long_help657 )]658 search_path: Vec<PathBuf>,659660 /// By default, relative paths are prefixed with './' when -x/--exec,661 /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a662 /// path starting with '-' being treated as a command line option. Use663 /// this flag to change this behavior. If this flag is used without a value,664 /// it is equivalent to passing "always".665 #[arg(long, conflicts_with_all(&["path", "search_path"]), value_name = "when", hide_short_help = true, require_equals = true, long_help)]666 strip_cwd_prefix: Option<Option<StripCwdWhen>>,667668 /// By default, fd will traverse the file system tree as far as other options669 /// dictate. With this flag, fd ensures that it does not descend into a670 /// different file system than the one it started in. Comparable to the -mount671 /// or -xdev filters of find(1).672 #[cfg(any(unix, windows))]673 #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]674 pub one_file_system: bool,675676 #[cfg(feature = "completions")]677 #[arg(long, hide = true, exclusive = true)]678 gen_completions: Option<Option<Shell>>,679}680681impl Opts {682 pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {683 // would it make sense to concatenate these?684 let paths = if !self.path.is_empty() {685 &self.path686 } else if !self.search_path.is_empty() {687 &self.search_path688 } else {689 let current_directory = Path::new("./");690 ensure_current_directory_exists(current_directory)?;691 return Ok(vec![self.normalize_path(current_directory)]);692 };693 Ok(paths694 .iter()695 .filter_map(|path| {696 if filesystem::is_existing_directory(path) {697 Some(self.normalize_path(path))698 } else {699 print_error(format!(700 "Search path '{}' is not a directory.",701 path.to_string_lossy()702 ));703 None704 }705 })706 .collect())707 }708709 fn normalize_path(&self, path: &Path) -> PathBuf {710 if self.absolute_path {711 filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()712 } else if path == Path::new(".") {713 // Change "." to "./" as a workaround for https://github.com/BurntSushi/ripgrep/pull/2711714 PathBuf::from("./")715 } else {716 path.to_path_buf()717 }718 }719720 pub fn no_search_paths(&self) -> bool {721 self.path.is_empty() && self.search_path.is_empty()722 }723724 #[inline]725 pub fn rg_alias_ignore(&self) -> bool {726 self.rg_alias_hidden_ignore > 0727 }728729 pub fn max_depth(&self) -> Option<usize> {730 self.max_depth.or(self.exact_depth)731 }732733 pub fn min_depth(&self) -> Option<usize> {734 self.min_depth.or(self.exact_depth)735 }736737 pub fn threads(&self) -> NonZeroUsize {738 self.threads.unwrap_or_else(default_num_threads)739 }740741 pub fn max_results(&self) -> Option<usize> {742 self.max_results743 .filter(|&m| m > 0)744 .or_else(|| self.max_one_result.then_some(1))745 }746747 pub fn strip_cwd_prefix<P: FnOnce() -> bool>(&self, auto_pred: P) -> bool {748 use self::StripCwdWhen::*;749 self.no_search_paths()750 && match self.strip_cwd_prefix.map_or(Auto, |o| o.unwrap_or(Always)) {751 Auto => auto_pred(),752 Always => true,753 Never => false,754 }755 }756757 #[cfg(feature = "completions")]758 pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {759 self.gen_completions760 .map(|maybe_shell| match maybe_shell {761 Some(sh) => Ok(sh),762 None => {763 Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))764 }765 })766 .transpose()767 }768}769770/// Get the default number of threads to use, if not explicitly specified.771fn default_num_threads() -> NonZeroUsize {772 // If we can't get the amount of parallelism for some reason, then773 // default to a single thread, because that is safe.774 let fallback = NonZeroUsize::MIN;775 // To limit startup overhead on massively parallel machines, don't use more776 // than 64 threads.777 let limit = NonZeroUsize::new(64).unwrap();778779 std::thread::available_parallelism()780 .unwrap_or(fallback)781 .min(limit)782}783784#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]785pub enum FileType {786 #[value(alias = "f")]787 File,788 #[value(alias = "d", alias = "dir")]789 Directory,790 #[value(alias = "l")]791 Symlink,792 #[value(alias = "b")]793 BlockDevice,794 #[value(alias = "c")]795 CharDevice,796 /// A file which is executable by the current effective user797 #[value(alias = "x")]798 Executable,799 #[value(alias = "e")]800 Empty,801 #[value(alias = "s")]802 Socket,803 #[value(alias = "p")]804 Pipe,805}806807#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]808pub enum ColorWhen {809 /// show colors if the output goes to an interactive console (default)810 Auto,811 /// always use colorized output812 Always,813 /// do not use colorized output814 Never,815}816817#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]818pub enum StripCwdWhen {819 /// Use the default behavior820 Auto,821 /// Always strip the ./ at the beginning of paths822 Always,823 /// Never strip the ./824 Never,825}826827#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]828pub enum HyperlinkWhen {829 /// Use hyperlinks only if color is enabled830 Auto,831 /// Always use hyperlinks when printing file paths832 Always,833 /// Never use hyperlinks834 Never,835}836837// there isn't a derive api for getting grouped values yet,838// so we have to use hand-rolled parsing for exec and exec-batch839pub struct Exec {840 pub command: Option<CommandSet>,841}842843impl clap::FromArgMatches for Exec {844 fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {845 let command = matches846 .get_occurrences::<String>("exec")847 .map(CommandSet::new)848 .or_else(|| {849 matches850 .get_occurrences::<String>("exec_batch")851 .map(CommandSet::new_batch)852 })853 .transpose()854 .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;855 Ok(Exec { command })856 }857858 fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {859 *self = Self::from_arg_matches(matches)?;860 Ok(())861 }862}863864impl clap::Args for Exec {865 fn augment_args(cmd: Command) -> Command {866 cmd.arg(Arg::new("exec")867 .action(ArgAction::Append)868 .long("exec")869 .short('x')870 .num_args(1..)871 .allow_hyphen_values(true)872 .value_terminator(";")873 .value_name("cmd")874 .conflicts_with("list_details")875 .help("Execute a command for each search result")876 .long_help(877 "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \878 There is no guarantee of the order commands are executed in, and the order should not be depended upon. \879 All positional arguments following --exec are considered to be arguments to the command - not to fd. \880 It is therefore recommended to place the '-x'/'--exec' option last. \881 Use '\\;' to terminate the command template if you need to continue passing fd arguments afterwards.\n\882 The following placeholders are substituted before the command is executed:\n \883 '{}': path (of the current search result)\n \884 '{/}': basename\n \885 '{//}': parent directory\n \886 '{.}': path without file extension\n \887 '{/.}': basename without file extension\n \888 '{{': literal '{' (for escaping)\n \889 '}}': literal '}' (for escaping)\n\n\890 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\891 Examples:\n\n \892 - find all *.zip files and unzip them:\n\n \893 fd -e zip -x unzip\n\n \894 - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n \895 fd -e h -e cpp -x clang-format -i\n\n \896 - search within `src/` and echo each match (place `-x` last):\n\n \897 fd . src -x echo\n\n \898 - Convert all *.jpg files to *.png files:\n\n \899 fd -e jpg -x convert {} {.}.png\900 ",901 ),902 )903 .arg(904 Arg::new("exec_batch")905 .action(ArgAction::Append)906 .long("exec-batch")907 .short('X')908 .num_args(1..)909 .allow_hyphen_values(true)910 .value_terminator(";")911 .value_name("cmd")912 .conflicts_with_all(["exec", "list_details"])913 .help("Execute a command with all search results at once")914 .long_help(915 "Execute the given command once, with all search results as arguments.\n\916 The order of the arguments is non-deterministic, and should not be relied upon.\n\917 One of the following placeholders is substituted before the command is executed:\n \918 '{}': path (of all search results)\n \919 '{/}': basename\n \920 '{//}': parent directory\n \921 '{.}': path without file extension\n \922 '{/.}': basename without file extension\n \923 '{{': literal '{' (for escaping)\n \924 '}}': literal '}' (for escaping)\n\n\925 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\926 Examples:\n\n \927 - Find all test_*.py files and open them in your favorite editor:\n\n \928 fd -g 'test_*.py' -X vim\n\n \929 - Find all *.rs files and count the lines with \"wc -l ...\":\n\n \930 fd -e rs -X wc -l\931 "932 ),933 )934 }935936 fn augment_args_for_update(cmd: Command) -> Command {937 Self::augment_args(cmd)938 }939}940941fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {942 Ok(Duration::from_millis(arg.parse()?))943}944945fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {946 if filesystem::is_existing_directory(current_directory) {947 Ok(())948 } else {949 Err(anyhow!(950 "Could not retrieve current directory (has it been deleted?)."951 ))952 }953}