Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

971 lines · 34.7 KiB · Rust

Last changed by

Merge pull request #2001 from leno23/docs/extension-help-1693Thayne McCombsbefore adoption0944460

History of this file

Take 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 with regex and glob based matching. By default, fd respects gitignore rules, ignores hidden directories, and is case insensitive.",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' or '--exact' instead.177    #[arg(178        long,179        short = 'F',180        alias = "literal",181        hide_short_help = true,182        help = "Treat pattern as literal string instead of regex",183        long_help184    )]185    pub fixed_strings: bool,186187    /// Perform an exact match. This is equivalent to '--fixed-strings' but requires188    /// the pattern to match the entire filename (or path if '--full-path' is used),189    /// rather than a substring. Special regex characters in the pattern are treated190    /// as literal characters.191    #[arg(192        long,193        conflicts_with_all(["glob", "fixed_strings"]),194        hide_short_help = true,195        help = "Match the entire filename exactly (literal, non-substring)",196        long_help197    )]198    pub exact: bool,199200    /// Add additional required search patterns, all of which must be matched. Multiple201    /// additional patterns can be specified. The patterns are regular202    /// expressions, unless '--glob' or '--fixed-strings' is used.203    #[arg(204        long = "and",205        value_name = "pattern",206        help = "Additional search patterns that need to be matched",207        long_help,208        hide_short_help = true,209        allow_hyphen_values = true210    )]211    pub exprs: Option<Vec<String>>,212213    /// Shows the full path starting from the root as opposed to relative paths.214    /// The flag can be overridden with --relative-path.215    #[arg(216        long,217        short = 'a',218        help = "Show absolute instead of relative paths",219        long_help220    )]221    pub absolute_path: bool,222223    /// Overrides --absolute-path224    #[arg(long, overrides_with = "absolute_path", hide = true, action = ArgAction::SetTrue)]225    relative_path: (),226227    /// Use a detailed listing format like 'ls -l'. This is basically an alias228    /// for '--exec-batch ls -l' with some additional 'ls' options. This can be229    /// used to see more metadata, to show symlink targets and to achieve a230    /// deterministic sort order.231    #[arg(232        long,233        short = 'l',234        conflicts_with("absolute_path"),235        help = "Use a long listing format with file metadata",236        long_help237    )]238    pub list_details: bool,239240    /// Follow symbolic links241    #[arg(242        long,243        short = 'L',244        alias = "dereference",245        long_help = "By default, fd does not descend into symlinked directories. Using this \246                     flag, symbolic links are also traversed. \247                     Flag can be overridden with --no-follow."248    )]249    pub follow: bool,250251    /// Overrides --follow252    #[arg(long, overrides_with = "follow", hide = true, action = ArgAction::SetTrue)]253    no_follow: (),254255    /// 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:256    ///   fd --glob -p '**/.git/config'257    #[arg(258        long,259        short = 'p',260        help = "Search full abs. path (default: filename only)",261        long_help,262        verbatim_doc_comment263    )]264    pub full_path: bool,265266    /// Separate search results by the null character (instead of newlines).267    /// Useful for piping results to 'xargs'.268    #[arg(269        long = "print0",270        short = '0',271        conflicts_with("list_details"),272        hide_short_help = true,273        help = "Separate search results by the null character",274        long_help275    )]276    pub null_separator: bool,277278    /// Limit the directory traversal to a given depth. By default, there is no279    /// limit on the search depth.280    #[arg(281        long,282        short = 'd',283        value_name = "depth",284        alias("maxdepth"),285        help = "Set maximum search depth (default: none)",286        long_help287    )]288    max_depth: Option<usize>,289290    /// Only show search results starting at the given depth.291    /// See also: '--max-depth' and '--exact-depth'292    #[arg(293        long,294        value_name = "depth",295        hide_short_help = true,296        alias("mindepth"),297        help = "Only show search results starting at the given depth.",298        long_help299    )]300    min_depth: Option<usize>,301302    /// Only show search results at the exact given depth. This is an alias for303    /// '--min-depth <depth> --max-depth <depth>'.304    #[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),305    help = "Only show search results at the exact given depth",306        long_help,307        )]308    exact_depth: Option<usize>,309310    /// Exclude files/directories that match the given glob pattern. This311    /// overrides any other ignore logic. Multiple exclude patterns can be312    /// specified.313    ///314    /// Examples:315    /// {n}  --exclude '*.pyc'316    /// {n}  --exclude node_modules317    #[arg(318        long,319        short = 'E',320        value_name = "glob",321        help = "Exclude entries that match the given glob pattern",322        long_help323    )]324    pub exclude: Vec<String>,325326    /// Do not traverse into directories that match the search criteria. If327    /// you want to exclude specific directories, use the '--exclude=…' option.328    #[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),329        long_help,330        )]331    pub prune: bool,332333    /// Filter the search by type:334    /// {n}  'f' or 'file':         regular files335    /// {n}  'd' or 'dir' or 'directory':    directories336    /// {n}  'l' or 'symlink':      symbolic links337    /// {n}  's' or 'socket':       socket338    /// {n}  'p' or 'pipe':         named pipe (FIFO)339    /// {n}  'b' or 'block-device': block device340    /// {n}  'c' or 'char-device':  character device341    /// {n}{n}  'x' or 'executable':   executables342    /// {n}  'e' or 'empty':        empty files or directories343    ///344    /// This option can be specified more than once to include multiple file types.345    /// Searching for '--type file --type symlink' will show both regular files as346    /// well as symlinks. Note that the 'executable' and 'empty' filters work differently:347    /// '--type executable' implies '--type file' by default. And '--type empty' searches348    /// for empty files and directories, unless either '--type file' or '--type directory'349    /// is specified in addition.350    ///351    /// Examples:352    /// {n}  - Only search for files:353    /// {n}      fd --type file …354    /// {n}      fd -tf …355    /// {n}  - Find both files and symlinks356    /// {n}      fd --type file --type symlink …357    /// {n}      fd -tf -tl …358    /// {n}  - Find executable files:359    /// {n}      fd --type executable360    /// {n}      fd -tx361    /// {n}  - Find empty files:362    /// {n}      fd --type empty --type file363    /// {n}      fd -te -tf364    /// {n}  - Find empty directories:365    /// {n}      fd --type empty --type directory366    /// {n}      fd -te -td367    #[arg(368        long = "type",369        short = 't',370        value_name = "filetype",371        hide_possible_values = true,372        value_enum,373        help = "Filter by type: file (f), directory (d/dir), symlink (l), \374                executable (x), empty (e), socket (s), pipe (p), \375                char-device (c), block-device (b)",376        long_help377    )]378    pub filetype: Option<Vec<FileType>>,379380    /// Filter results by extension. By default, this matches all entry types381    /// (including directories whose names end with the extension). Use `--type`382    /// to restrict the search to specific types. Multiple extensions can be specified.383    ///384    /// If you want to search for files without extension,385    /// you can use the regex '^[^.]+$' as a normal search pattern.386    #[arg(387        long = "extension",388        short = 'e',389        value_name = "ext",390        help = "Filter by extension",391        long_help392    )]393    pub extensions: Option<Vec<String>>,394395    /// Limit results based on the size of files using the format <+-><NUM><UNIT>.396    ///    '+': file size must be greater than or equal to this397    ///    '-': file size must be less than or equal to this398    ///399    /// If neither '+' nor '-' is specified, file size must be exactly equal to this.400    ///    'NUM':  The numeric size (e.g. 500)401    ///    'UNIT': The units for NUM. They are not case-sensitive.402    /// Allowed unit values:403    ///     'b':  bytes404    ///     'k':  kilobytes (base ten, 10^3 = 1000 bytes)405    ///     'm':  megabytes406    ///     'g':  gigabytes407    ///     't':  terabytes408    ///     'ki': kibibytes (base two, 2^10 = 1024 bytes)409    ///     'mi': mebibytes410    ///     'gi': gibibytes411    ///     'ti': tebibytes412    #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",413        help = "Limit results based on the size of files",414        long_help,415        verbatim_doc_comment,416        )]417    pub size: Vec<SizeFilter>,418419    /// Filter results based on the file modification time. Files with modification times420    /// greater than the argument are returned. The argument can be provided421    /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).422    /// If the time is not specified, it defaults to 00:00:00.423    /// '--change-newer-than', '--newer', or '--changed-after' can be used as aliases.424    ///425    /// Examples:426    /// {n}    --changed-within 2weeks427    /// {n}    --change-newer-than '2018-10-27 10:00:00'428    /// {n}    --newer 2018-10-27429    /// {n}    --changed-after 1day430    #[arg(431        long,432        alias("change-newer-than"),433        alias("newer"),434        alias("changed-after"),435        value_name = "date|dur",436        help = "Filter by file modification time (newer than)",437        long_help438    )]439    pub changed_within: Option<String>,440441    /// Filter results based on the file modification time. Files with modification times442    /// less than the argument are returned. The argument can be provided443    /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).444    /// '--change-older-than' or '--older' can be used as aliases.445    ///446    /// Examples:447    /// {n}    --changed-before '2018-10-27 10:00:00'448    /// {n}    --change-older-than 2weeks449    /// {n}    --older 2018-10-27450    #[arg(451        long,452        alias("change-older-than"),453        alias("older"),454        value_name = "date|dur",455        help = "Filter by file modification time (older than)",456        long_help457    )]458    pub changed_before: Option<String>,459460    /// Filter files by their user and/or group.461    /// Format: [(user|uid)][:(group|gid)]. Either side is optional.462    /// Precede either side with a '!' to exclude files instead.463    ///464    /// Examples:465    /// {n}    --owner john466    /// {n}    --owner :students467    /// {n}    --owner '!john:students'468    #[cfg(unix)]469    #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",470        help = "Filter by owning user and/or group",471        long_help,472        )]473    pub owner: Option<OwnerFilter>,474475    /// Instead of printing the file normally, print the format string with the following placeholders replaced:476    ///   '{}': path (of the current search result)477    ///   '{/}': basename478    ///   '{//}': parent directory479    ///   '{.}': path without file extension480    ///   '{/.}': basename without file extension481    #[arg(482        long,483        value_name = "fmt",484        help = "Print results according to template",485        conflicts_with = "list_details"486    )]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,549550    /// Ignore directories containing the named entry.551    #[arg(long, value_name = "name")]552    pub ignore_contain: Vec<String>,553554    /// 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,620        short = 'C',621        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.654    #[arg(action = ArgAction::Append,655        value_name = "path",656        help = "the root directories for the filesystem search (optional)",657        long_help,658        )]659    path: Vec<PathBuf>,660661    /// Provide paths to search as an alternative to the positional <path>662    /// argument. Changes the usage to `fd [OPTIONS] --search-path <path>663    /// --search-path <path2> [<pattern>]`664    #[arg(665        long,666        conflicts_with("path"),667        value_name = "search-path",668        hide_short_help = true,669        help = "Provides paths to search as an alternative to the positional <path> argument",670        long_help671    )]672    search_path: Vec<PathBuf>,673674    /// By default, relative paths are prefixed with './' when -x/--exec,675    /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a676    /// path starting with '-' being treated as a command line option. Use677    /// this flag to change this behavior. If this flag is used without a value,678    /// it is equivalent to passing "always".679    #[arg(long, conflicts_with_all(&["path", "search_path"]), value_name = "when", hide_short_help = true, require_equals = true, long_help)]680    strip_cwd_prefix: Option<Option<StripCwdWhen>>,681682    /// By default, fd will traverse the file system tree as far as other options683    /// dictate. With this flag, fd ensures that it does not descend into a684    /// different file system than the one it started in. Comparable to the -mount685    /// or -xdev filters of find(1).686    #[cfg(any(unix, windows))]687    #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]688    pub one_file_system: bool,689690    #[cfg(feature = "completions")]691    #[arg(long, hide = true, exclusive = true)]692    gen_completions: Option<Option<Shell>>,693}694695impl Opts {696    pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {697        // would it make sense to concatenate these?698        let paths = if !self.path.is_empty() {699            &self.path700        } else if !self.search_path.is_empty() {701            &self.search_path702        } else {703            let current_directory = Path::new("./");704            ensure_current_directory_exists(current_directory)?;705            return Ok(vec![self.normalize_path(current_directory)]);706        };707        Ok(paths708            .iter()709            .filter_map(|path| {710                if filesystem::is_existing_directory(path) {711                    Some(self.normalize_path(path))712                } else {713                    print_error(format!(714                        "Search path '{}' is not a directory.",715                        path.to_string_lossy()716                    ));717                    None718                }719            })720            .collect())721    }722723    fn normalize_path(&self, path: &Path) -> PathBuf {724        if self.absolute_path {725            filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()726        } else if path == Path::new(".") {727            // Change "." to "./" as a workaround for https://github.com/BurntSushi/ripgrep/pull/2711728            PathBuf::from("./")729        } else if path == Path::new("-") {730            // Prefix "-" so the underlying walker treats it as a path.731            // See sharkdp/fd#849.732            Path::new(".").join(path)733        } else {734            path.to_path_buf()735        }736    }737738    pub fn no_search_paths(&self) -> bool {739        self.path.is_empty() && self.search_path.is_empty()740    }741742    #[inline]743    pub fn rg_alias_ignore(&self) -> bool {744        self.rg_alias_hidden_ignore > 0745    }746747    pub fn max_depth(&self) -> Option<usize> {748        self.max_depth.or(self.exact_depth)749    }750751    pub fn min_depth(&self) -> Option<usize> {752        self.min_depth.or(self.exact_depth)753    }754755    pub fn threads(&self) -> NonZeroUsize {756        self.threads.unwrap_or_else(default_num_threads)757    }758759    pub fn max_results(&self) -> Option<usize> {760        self.max_results761            .filter(|&m| m > 0)762            .or_else(|| self.max_one_result.then_some(1))763    }764765    pub fn strip_cwd_prefix<P: FnOnce() -> bool>(&self, auto_pred: P) -> bool {766        use self::StripCwdWhen::*;767        self.no_search_paths()768            && match self.strip_cwd_prefix.map_or(Auto, |o| o.unwrap_or(Always)) {769                Auto => auto_pred(),770                Always => true,771                Never => false,772            }773    }774775    #[cfg(feature = "completions")]776    pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {777        self.gen_completions778            .map(|maybe_shell| match maybe_shell {779                Some(sh) => Ok(sh),780                None => {781                    Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))782                }783            })784            .transpose()785    }786}787788/// Get the default number of threads to use, if not explicitly specified.789fn default_num_threads() -> NonZeroUsize {790    // If we can't get the amount of parallelism for some reason, then791    // default to a single thread, because that is safe.792    let fallback = NonZeroUsize::MIN;793    // To limit startup overhead on massively parallel machines, don't use more794    // than 64 threads.795    let limit = NonZeroUsize::new(64).unwrap();796797    std::thread::available_parallelism()798        .unwrap_or(fallback)799        .min(limit)800}801802#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]803pub enum FileType {804    #[value(alias = "f")]805    File,806    #[value(alias = "d", alias = "dir")]807    Directory,808    #[value(alias = "l")]809    Symlink,810    #[value(alias = "b")]811    BlockDevice,812    #[value(alias = "c")]813    CharDevice,814    /// A file which is executable by the current effective user815    #[value(alias = "x")]816    Executable,817    #[value(alias = "e")]818    Empty,819    #[value(alias = "s")]820    Socket,821    #[value(alias = "p")]822    Pipe,823}824825#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]826pub enum ColorWhen {827    /// show colors if the output goes to an interactive console (default)828    Auto,829    /// always use colorized output830    Always,831    /// do not use colorized output832    Never,833}834835#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]836pub enum StripCwdWhen {837    /// Use the default behavior838    Auto,839    /// Always strip the ./ at the beginning of paths840    Always,841    /// Never strip the ./842    Never,843}844845#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]846pub enum HyperlinkWhen {847    /// Use hyperlinks only if color is enabled848    Auto,849    /// Always use hyperlinks when printing file paths850    Always,851    /// Never use hyperlinks852    Never,853}854855// there isn't a derive api for getting grouped values yet,856// so we have to use hand-rolled parsing for exec and exec-batch857pub struct Exec {858    pub command: Option<CommandSet>,859}860861impl clap::FromArgMatches for Exec {862    fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {863        let command = matches864            .get_occurrences::<String>("exec")865            .map(CommandSet::new)866            .or_else(|| {867                matches868                    .get_occurrences::<String>("exec_batch")869                    .map(CommandSet::new_batch)870            })871            .transpose()872            .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;873        Ok(Exec { command })874    }875876    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {877        *self = Self::from_arg_matches(matches)?;878        Ok(())879    }880}881882impl clap::Args for Exec {883    fn augment_args(cmd: Command) -> Command {884        cmd.arg(Arg::new("exec")885            .action(ArgAction::Append)886            .long("exec")887            .short('x')888            .num_args(1..)889                .allow_hyphen_values(true)890                .value_terminator(";")891                .value_name("cmd")892                .conflicts_with("list_details")893                .help("Execute a command for each search result")894                .long_help(895                    "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \896                     There is no guarantee of the order commands are executed in, and the order should not be depended upon. \897                     All positional arguments following --exec are considered to be arguments to the command - not to fd. \898                     It is therefore recommended to place the '-x'/'--exec' option last. \899                     Use '\\;' to terminate the command template if you need to continue passing fd arguments afterwards.\n\900                     The following placeholders are substituted before the command is executed:\n  \901                       '{}':   path (of the current search result)\n  \902                       '{/}':  basename\n  \903                       '{//}': parent directory\n  \904                       '{.}':  path without file extension\n  \905                       '{/.}': basename without file extension\n  \906                       '{{':   literal '{' (for escaping)\n  \907                       '}}':   literal '}' (for escaping)\n\n\908                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\909                     Examples:\n\n  \910                       - find all *.zip files and unzip them:\n\n      \911                           fd -e zip -x unzip\n\n  \912                       - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n      \913                           fd -e h -e cpp -x clang-format -i\n\n  \914                       - search within `src/` and echo each match (place `-x` last):\n\n      \915                           fd . src -x echo\n\n  \916                       - Convert all *.jpg files to *.png files:\n\n      \917                           fd -e jpg -x convert {} {.}.png\918                    ",919                ),920        )921        .arg(922            Arg::new("exec_batch")923                .action(ArgAction::Append)924                .long("exec-batch")925                .short('X')926                .num_args(1..)927                .allow_hyphen_values(true)928                .value_terminator(";")929                .value_name("cmd")930                .conflicts_with_all(["exec", "list_details"])931                .help("Execute a command with all search results at once")932                .long_help(933                    "Execute the given command once, with all search results as arguments.\n\934                     The order of the arguments is non-deterministic, and should not be relied upon.\n\935                     One of the following placeholders is substituted before the command is executed:\n  \936                       '{}':   path (of all search results)\n  \937                       '{/}':  basename\n  \938                       '{//}': parent directory\n  \939                       '{.}':  path without file extension\n  \940                       '{/.}': basename without file extension\n  \941                       '{{':   literal '{' (for escaping)\n  \942                       '}}':   literal '}' (for escaping)\n\n\943                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\944                     Examples:\n\n  \945                       - Find all test_*.py files and open them in your favorite editor:\n\n      \946                           fd -g 'test_*.py' -X vim\n\n  \947                       - Find all *.rs files and count the lines with \"wc -l ...\":\n\n      \948                           fd -e rs -X wc -l\949                     "950                ),951        )952    }953954    fn augment_args_for_update(cmd: Command) -> Command {955        Self::augment_args(cmd)956    }957}958959fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {960    Ok(Duration::from_millis(arg.parse()?))961}962963fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {964    if filesystem::is_existing_directory(current_directory) {965        Ok(())966    } else {967        Err(anyhow!(968            "Could not retrieve current directory (has it been deleted?)."969        ))970    }971}