Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

970 lines · 34.6 KiB · Rust

Last changed by

Merge pull request #1983 from DeflateAwning/feat-exact-i1963Thayne McCombsbefore adoption42b2ab8

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    /// (Additionally) filter search results by their file extension. Multiple381    /// allowable file extensions can be specified.382    ///383    /// If you want to search for files without extension,384    /// you can use the regex '^[^.]+$' as a normal search pattern.385    #[arg(386        long = "extension",387        short = 'e',388        value_name = "ext",389        help = "Filter by file extension",390        long_help391    )]392    pub extensions: Option<Vec<String>>,393394    /// Limit results based on the size of files using the format <+-><NUM><UNIT>.395    ///    '+': file size must be greater than or equal to this396    ///    '-': file size must be less than or equal to this397    ///398    /// If neither '+' nor '-' is specified, file size must be exactly equal to this.399    ///    'NUM':  The numeric size (e.g. 500)400    ///    'UNIT': The units for NUM. They are not case-sensitive.401    /// Allowed unit values:402    ///     'b':  bytes403    ///     'k':  kilobytes (base ten, 10^3 = 1000 bytes)404    ///     'm':  megabytes405    ///     'g':  gigabytes406    ///     't':  terabytes407    ///     'ki': kibibytes (base two, 2^10 = 1024 bytes)408    ///     'mi': mebibytes409    ///     'gi': gibibytes410    ///     'ti': tebibytes411    #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",412        help = "Limit results based on the size of files",413        long_help,414        verbatim_doc_comment,415        )]416    pub size: Vec<SizeFilter>,417418    /// Filter results based on the file modification time. Files with modification times419    /// greater than the argument are returned. The argument can be provided420    /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).421    /// If the time is not specified, it defaults to 00:00:00.422    /// '--change-newer-than', '--newer', or '--changed-after' can be used as aliases.423    ///424    /// Examples:425    /// {n}    --changed-within 2weeks426    /// {n}    --change-newer-than '2018-10-27 10:00:00'427    /// {n}    --newer 2018-10-27428    /// {n}    --changed-after 1day429    #[arg(430        long,431        alias("change-newer-than"),432        alias("newer"),433        alias("changed-after"),434        value_name = "date|dur",435        help = "Filter by file modification time (newer than)",436        long_help437    )]438    pub changed_within: Option<String>,439440    /// Filter results based on the file modification time. Files with modification times441    /// less than the argument are returned. The argument can be provided442    /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).443    /// '--change-older-than' or '--older' can be used as aliases.444    ///445    /// Examples:446    /// {n}    --changed-before '2018-10-27 10:00:00'447    /// {n}    --change-older-than 2weeks448    /// {n}    --older 2018-10-27449    #[arg(450        long,451        alias("change-older-than"),452        alias("older"),453        value_name = "date|dur",454        help = "Filter by file modification time (older than)",455        long_help456    )]457    pub changed_before: Option<String>,458459    /// Filter files by their user and/or group.460    /// Format: [(user|uid)][:(group|gid)]. Either side is optional.461    /// Precede either side with a '!' to exclude files instead.462    ///463    /// Examples:464    /// {n}    --owner john465    /// {n}    --owner :students466    /// {n}    --owner '!john:students'467    #[cfg(unix)]468    #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",469        help = "Filter by owning user and/or group",470        long_help,471        )]472    pub owner: Option<OwnerFilter>,473474    /// Instead of printing the file normally, print the format string with the following placeholders replaced:475    ///   '{}': path (of the current search result)476    ///   '{/}': basename477    ///   '{//}': parent directory478    ///   '{.}': path without file extension479    ///   '{/.}': basename without file extension480    #[arg(481        long,482        value_name = "fmt",483        help = "Print results according to template",484        conflicts_with = "list_details"485    )]486    pub format: Option<String>,487488    #[command(flatten)]489    pub exec: Exec,490491    /// Maximum number of arguments to pass to the command given with -X.492    /// If the number of results is greater than the given size,493    /// the command given with -X is run again with remaining arguments.494    /// A batch size of zero means there is no limit (default), but note495    /// that batching might still happen due to OS restrictions on the496    /// maximum length of command lines.497    #[arg(498        long,499        value_name = "size",500        hide_short_help = true,501        requires("exec_batch"),502        value_parser = value_parser!(usize),503        default_value_t,504        help = "Max number of arguments to run as a batch size with -X",505        long_help,506    )]507    pub batch_size: usize,508509    /// Add a custom ignore-file in '.gitignore' format. These files have a low precedence.510    #[arg(511        long,512        value_name = "path",513        hide_short_help = true,514        help = "Add a custom ignore-file in '.gitignore' format",515        long_help516    )]517    pub ignore_file: Vec<PathBuf>,518519    /// Declare when to use color for the pattern match output520    #[arg(521        long,522        short = 'c',523        value_enum,524        default_value_t = ColorWhen::Auto,525        value_name = "when",526        help = "When to use colors",527        long_help,528    )]529    pub color: ColorWhen,530531    /// Add a terminal hyperlink to a file:// url for each path in the output.532    ///533    /// Auto mode  is used if no argument is given to this option.534    ///535    /// This doesn't do anything for --exec and --exec-batch.536    #[arg(537        long,538        alias = "hyper",539        value_name = "when",540        require_equals = true,541        value_enum,542        default_value_t = HyperlinkWhen::Never,543        default_missing_value = "auto",544        num_args = 0..=1,545        help = "Add hyperlinks to output paths"546    )]547    pub hyperlink: HyperlinkWhen,548549    /// Ignore directories containing the named entry.550    #[arg(long, value_name = "name")]551    pub ignore_contain: Vec<String>,552553    /// Set number of threads to use for searching & executing (default: number554    /// of available CPU cores)555    #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = str::parse::<NonZeroUsize>)]556    pub threads: Option<NonZeroUsize>,557558    /// Milliseconds to buffer before streaming search results to console559    ///560    /// Amount of time in milliseconds to buffer, before streaming the search561    /// results to the console.562    #[arg(long, hide = true, value_parser = parse_millis)]563    pub max_buffer_time: Option<Duration>,564565    ///Limit the number of search results to 'count' and quit immediately.566    #[arg(567        long,568        value_name = "count",569        hide_short_help = true,570        overrides_with("max_one_result"),571        help = "Limit the number of search results",572        long_help573    )]574    max_results: Option<usize>,575576    /// Limit the search to a single result and quit immediately.577    /// This is an alias for '--max-results=1'.578    #[arg(579        short = '1',580        hide_short_help = true,581        overrides_with("max_results"),582        help = "Limit search to a single result",583        long_help584    )]585    max_one_result: bool,586587    /// When the flag is present, the program does not print anything and will588    /// return with an exit code of 0 if there is at least one match. Otherwise, the589    /// exit code will be 1.590    /// '--has-results' can be used as an alias.591    #[arg(592        long,593        short = 'q',594        alias = "has-results",595        hide_short_help = true,596        conflicts_with("max_results"),597        help = "Print nothing, exit code 0 if match found, 1 otherwise",598        long_help599    )]600    pub quiet: bool,601602    /// Enable the display of filesystem errors for situations such as603    /// insufficient permissions or dead symlinks.604    #[arg(605        long,606        hide_short_help = true,607        help = "Show filesystem errors",608        long_help609    )]610    pub show_errors: bool,611612    /// Change the current working directory of fd to the provided path. This613    /// means that search results will be shown with respect to the given base614    /// path. Note that relative paths which are passed to fd via the positional615    /// <path> argument or the '--search-path' option will also be resolved616    /// relative to this directory.617    #[arg(618        long,619        short = 'C',620        value_name = "path",621        hide_short_help = true,622        help = "Change current working directory",623        long_help624    )]625    pub base_directory: Option<PathBuf>,626627    /// the search pattern which is either a regular expression (default) or a glob628    /// pattern (if --glob is used). If no pattern has been specified, every entry629    /// is considered a match. If your pattern starts with a dash (-), make sure to630    /// pass '--' first, or it will be considered as a flag (fd -- '-foo').631    #[arg(632        default_value = "",633        hide_default_value = true,634        value_name = "pattern",635        help = "the search pattern (a regular expression, unless '--glob' is used; optional)",636        long_help637    )]638    pub pattern: String,639640    /// Set the path separator to use when printing file paths. The default is641    /// the OS-specific separator ('/' on Unix, '\' on Windows).642    #[arg(643        long,644        value_name = "separator",645        hide_short_help = true,646        help = "Set path separator when printing file paths",647        long_help648    )]649    pub path_separator: Option<String>,650651    /// The directory where the filesystem search is rooted (optional). If652    /// omitted, search the current working directory.653    #[arg(action = ArgAction::Append,654        value_name = "path",655        help = "the root directories for the filesystem search (optional)",656        long_help,657        )]658    path: Vec<PathBuf>,659660    /// Provide paths to search as an alternative to the positional <path>661    /// argument. Changes the usage to `fd [OPTIONS] --search-path <path>662    /// --search-path <path2> [<pattern>]`663    #[arg(664        long,665        conflicts_with("path"),666        value_name = "search-path",667        hide_short_help = true,668        help = "Provides paths to search as an alternative to the positional <path> argument",669        long_help670    )]671    search_path: Vec<PathBuf>,672673    /// By default, relative paths are prefixed with './' when -x/--exec,674    /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a675    /// path starting with '-' being treated as a command line option. Use676    /// this flag to change this behavior. If this flag is used without a value,677    /// it is equivalent to passing "always".678    #[arg(long, conflicts_with_all(&["path", "search_path"]), value_name = "when", hide_short_help = true, require_equals = true, long_help)]679    strip_cwd_prefix: Option<Option<StripCwdWhen>>,680681    /// By default, fd will traverse the file system tree as far as other options682    /// dictate. With this flag, fd ensures that it does not descend into a683    /// different file system than the one it started in. Comparable to the -mount684    /// or -xdev filters of find(1).685    #[cfg(any(unix, windows))]686    #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]687    pub one_file_system: bool,688689    #[cfg(feature = "completions")]690    #[arg(long, hide = true, exclusive = true)]691    gen_completions: Option<Option<Shell>>,692}693694impl Opts {695    pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {696        // would it make sense to concatenate these?697        let paths = if !self.path.is_empty() {698            &self.path699        } else if !self.search_path.is_empty() {700            &self.search_path701        } else {702            let current_directory = Path::new("./");703            ensure_current_directory_exists(current_directory)?;704            return Ok(vec![self.normalize_path(current_directory)]);705        };706        Ok(paths707            .iter()708            .filter_map(|path| {709                if filesystem::is_existing_directory(path) {710                    Some(self.normalize_path(path))711                } else {712                    print_error(format!(713                        "Search path '{}' is not a directory.",714                        path.to_string_lossy()715                    ));716                    None717                }718            })719            .collect())720    }721722    fn normalize_path(&self, path: &Path) -> PathBuf {723        if self.absolute_path {724            filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()725        } else if path == Path::new(".") {726            // Change "." to "./" as a workaround for https://github.com/BurntSushi/ripgrep/pull/2711727            PathBuf::from("./")728        } else if path == Path::new("-") {729            // Prefix "-" so the underlying walker treats it as a path.730            // See sharkdp/fd#849.731            Path::new(".").join(path)732        } else {733            path.to_path_buf()734        }735    }736737    pub fn no_search_paths(&self) -> bool {738        self.path.is_empty() && self.search_path.is_empty()739    }740741    #[inline]742    pub fn rg_alias_ignore(&self) -> bool {743        self.rg_alias_hidden_ignore > 0744    }745746    pub fn max_depth(&self) -> Option<usize> {747        self.max_depth.or(self.exact_depth)748    }749750    pub fn min_depth(&self) -> Option<usize> {751        self.min_depth.or(self.exact_depth)752    }753754    pub fn threads(&self) -> NonZeroUsize {755        self.threads.unwrap_or_else(default_num_threads)756    }757758    pub fn max_results(&self) -> Option<usize> {759        self.max_results760            .filter(|&m| m > 0)761            .or_else(|| self.max_one_result.then_some(1))762    }763764    pub fn strip_cwd_prefix<P: FnOnce() -> bool>(&self, auto_pred: P) -> bool {765        use self::StripCwdWhen::*;766        self.no_search_paths()767            && match self.strip_cwd_prefix.map_or(Auto, |o| o.unwrap_or(Always)) {768                Auto => auto_pred(),769                Always => true,770                Never => false,771            }772    }773774    #[cfg(feature = "completions")]775    pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {776        self.gen_completions777            .map(|maybe_shell| match maybe_shell {778                Some(sh) => Ok(sh),779                None => {780                    Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))781                }782            })783            .transpose()784    }785}786787/// Get the default number of threads to use, if not explicitly specified.788fn default_num_threads() -> NonZeroUsize {789    // If we can't get the amount of parallelism for some reason, then790    // default to a single thread, because that is safe.791    let fallback = NonZeroUsize::MIN;792    // To limit startup overhead on massively parallel machines, don't use more793    // than 64 threads.794    let limit = NonZeroUsize::new(64).unwrap();795796    std::thread::available_parallelism()797        .unwrap_or(fallback)798        .min(limit)799}800801#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]802pub enum FileType {803    #[value(alias = "f")]804    File,805    #[value(alias = "d", alias = "dir")]806    Directory,807    #[value(alias = "l")]808    Symlink,809    #[value(alias = "b")]810    BlockDevice,811    #[value(alias = "c")]812    CharDevice,813    /// A file which is executable by the current effective user814    #[value(alias = "x")]815    Executable,816    #[value(alias = "e")]817    Empty,818    #[value(alias = "s")]819    Socket,820    #[value(alias = "p")]821    Pipe,822}823824#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]825pub enum ColorWhen {826    /// show colors if the output goes to an interactive console (default)827    Auto,828    /// always use colorized output829    Always,830    /// do not use colorized output831    Never,832}833834#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]835pub enum StripCwdWhen {836    /// Use the default behavior837    Auto,838    /// Always strip the ./ at the beginning of paths839    Always,840    /// Never strip the ./841    Never,842}843844#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]845pub enum HyperlinkWhen {846    /// Use hyperlinks only if color is enabled847    Auto,848    /// Always use hyperlinks when printing file paths849    Always,850    /// Never use hyperlinks851    Never,852}853854// there isn't a derive api for getting grouped values yet,855// so we have to use hand-rolled parsing for exec and exec-batch856pub struct Exec {857    pub command: Option<CommandSet>,858}859860impl clap::FromArgMatches for Exec {861    fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {862        let command = matches863            .get_occurrences::<String>("exec")864            .map(CommandSet::new)865            .or_else(|| {866                matches867                    .get_occurrences::<String>("exec_batch")868                    .map(CommandSet::new_batch)869            })870            .transpose()871            .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;872        Ok(Exec { command })873    }874875    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {876        *self = Self::from_arg_matches(matches)?;877        Ok(())878    }879}880881impl clap::Args for Exec {882    fn augment_args(cmd: Command) -> Command {883        cmd.arg(Arg::new("exec")884            .action(ArgAction::Append)885            .long("exec")886            .short('x')887            .num_args(1..)888                .allow_hyphen_values(true)889                .value_terminator(";")890                .value_name("cmd")891                .conflicts_with("list_details")892                .help("Execute a command for each search result")893                .long_help(894                    "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \895                     There is no guarantee of the order commands are executed in, and the order should not be depended upon. \896                     All positional arguments following --exec are considered to be arguments to the command - not to fd. \897                     It is therefore recommended to place the '-x'/'--exec' option last. \898                     Use '\\;' to terminate the command template if you need to continue passing fd arguments afterwards.\n\899                     The following placeholders are substituted before the command is executed:\n  \900                       '{}':   path (of the current search result)\n  \901                       '{/}':  basename\n  \902                       '{//}': parent directory\n  \903                       '{.}':  path without file extension\n  \904                       '{/.}': basename without file extension\n  \905                       '{{':   literal '{' (for escaping)\n  \906                       '}}':   literal '}' (for escaping)\n\n\907                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\908                     Examples:\n\n  \909                       - find all *.zip files and unzip them:\n\n      \910                           fd -e zip -x unzip\n\n  \911                       - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n      \912                           fd -e h -e cpp -x clang-format -i\n\n  \913                       - search within `src/` and echo each match (place `-x` last):\n\n      \914                           fd . src -x echo\n\n  \915                       - Convert all *.jpg files to *.png files:\n\n      \916                           fd -e jpg -x convert {} {.}.png\917                    ",918                ),919        )920        .arg(921            Arg::new("exec_batch")922                .action(ArgAction::Append)923                .long("exec-batch")924                .short('X')925                .num_args(1..)926                .allow_hyphen_values(true)927                .value_terminator(";")928                .value_name("cmd")929                .conflicts_with_all(["exec", "list_details"])930                .help("Execute a command with all search results at once")931                .long_help(932                    "Execute the given command once, with all search results as arguments.\n\933                     The order of the arguments is non-deterministic, and should not be relied upon.\n\934                     One of the following placeholders is substituted before the command is executed:\n  \935                       '{}':   path (of all search results)\n  \936                       '{/}':  basename\n  \937                       '{//}': parent directory\n  \938                       '{.}':  path without file extension\n  \939                       '{/.}': basename without file extension\n  \940                       '{{':   literal '{' (for escaping)\n  \941                       '}}':   literal '}' (for escaping)\n\n\942                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\943                     Examples:\n\n  \944                       - Find all test_*.py files and open them in your favorite editor:\n\n      \945                           fd -g 'test_*.py' -X vim\n\n  \946                       - Find all *.rs files and count the lines with \"wc -l ...\":\n\n      \947                           fd -e rs -X wc -l\948                     "949                ),950        )951    }952953    fn augment_args_for_update(cmd: Command) -> Command {954        Self::augment_args(cmd)955    }956}957958fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {959    Ok(Duration::from_millis(arg.parse()?))960}961962fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {963    if filesystem::is_existing_directory(current_directory) {964        Ok(())965    } else {966        Err(anyhow!(967            "Could not retrieve current directory (has it been deleted?)."968        ))969    }970}