Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

941 lines · 33.1 KiB · Rust

Last changed by

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

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",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    #[arg(106        long,107        hide_short_help = true,108        help = "Do not respect .(git|fd)ignore files in parent directories",109        long_help110    )]111    pub no_ignore_parent: bool,112113    /// Do not respect the global ignore file114    #[arg(long, hide = true)]115    pub no_global_ignore_file: bool,116117    /// Perform an unrestricted search, including ignored and hidden files. This is118    /// an alias for '--no-ignore --hidden'.119    #[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,120    help = "Unrestricted search, alias for '--no-ignore --hidden'",121        long_help,122        )]123    rg_alias_hidden_ignore: u8,124125    /// Case-sensitive search (default: smart case)126    #[arg(127        long,128        short = 's',129        overrides_with("ignore_case"),130        long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \131                     searches, unless the pattern contains an uppercase character (smart \132                     case)."133    )]134    pub case_sensitive: bool,135136    /// Perform a case-insensitive search. By default, fd uses case-insensitive137    /// searches, unless the pattern contains an uppercase character (smart138    /// case).139    #[arg(140        long,141        short = 'i',142        overrides_with("case_sensitive"),143        help = "Case-insensitive search (default: smart case)",144        long_help145    )]146    pub ignore_case: bool,147148    /// Perform a glob-based search instead of a regular expression search.149    #[arg(150        long,151        short = 'g',152        conflicts_with("fixed_strings"),153        help = "Glob-based search (default: regular expression)",154        long_help155    )]156    pub glob: bool,157158    /// Perform a regular-expression based search (default). This can be used to159    /// override --glob.160    #[arg(161        long,162        overrides_with("glob"),163        hide_short_help = true,164        help = "Regular-expression based search (default)",165        long_help166    )]167    pub regex: bool,168169    /// Treat the pattern as a literal string instead of a regular expression. Note170    /// that this also performs substring comparison. If you want to match on an171    /// exact filename, consider using '--glob'.172    #[arg(173        long,174        short = 'F',175        alias = "literal",176        hide_short_help = true,177        help = "Treat pattern as literal string stead of regex",178        long_help179    )]180    pub fixed_strings: bool,181182    /// Add additional required search patterns, all of which must be matched. Multiple183    /// additional patterns can be specified. The patterns are regular184    /// expressions, unless '--glob' or '--fixed-strings' is used.185    #[arg(186        long = "and",187        value_name = "pattern",188        help = "Additional search patterns that need to be matched",189        long_help,190        hide_short_help = true,191        allow_hyphen_values = true192    )]193    pub exprs: Option<Vec<String>>,194195    /// Shows the full path starting from the root as opposed to relative paths.196    /// The flag can be overridden with --relative-path.197    #[arg(198        long,199        short = 'a',200        help = "Show absolute instead of relative paths",201        long_help202    )]203    pub absolute_path: bool,204205    /// Overrides --absolute-path206    #[arg(long, overrides_with = "absolute_path", hide = true, action = ArgAction::SetTrue)]207    relative_path: (),208209    /// Use a detailed listing format like 'ls -l'. This is basically an alias210    /// for '--exec-batch ls -l' with some additional 'ls' options. This can be211    /// used to see more metadata, to show symlink targets and to achieve a212    /// deterministic sort order.213    #[arg(214        long,215        short = 'l',216        conflicts_with("absolute_path"),217        help = "Use a long listing format with file metadata",218        long_help219    )]220    pub list_details: bool,221222    /// Follow symbolic links223    #[arg(224        long,225        short = 'L',226        alias = "dereference",227        long_help = "By default, fd does not descend into symlinked directories. Using this \228                     flag, symbolic links are also traversed. \229                     Flag can be overridden with --no-follow."230    )]231    pub follow: bool,232233    /// Overrides --follow234    #[arg(long, overrides_with = "follow", hide = true, action = ArgAction::SetTrue)]235    no_follow: (),236237    /// 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:238    ///   fd --glob -p '**/.git/config'239    #[arg(240        long,241        short = 'p',242        help = "Search full abs. path (default: filename only)",243        long_help,244        verbatim_doc_comment245    )]246    pub full_path: bool,247248    /// Separate search results by the null character (instead of newlines).249    /// Useful for piping results to 'xargs'.250    #[arg(251        long = "print0",252        short = '0',253        conflicts_with("list_details"),254        hide_short_help = true,255        help = "Separate search results by the null character",256        long_help257    )]258    pub null_separator: bool,259260    /// Limit the directory traversal to a given depth. By default, there is no261    /// limit on the search depth.262    #[arg(263        long,264        short = 'd',265        value_name = "depth",266        alias("maxdepth"),267        help = "Set maximum search depth (default: none)",268        long_help269    )]270    max_depth: Option<usize>,271272    /// Only show search results starting at the given depth.273    /// See also: '--max-depth' and '--exact-depth'274    #[arg(275        long,276        value_name = "depth",277        hide_short_help = true,278        alias("mindepth"),279        help = "Only show search results starting at the given depth.",280        long_help281    )]282    min_depth: Option<usize>,283284    /// Only show search results at the exact given depth. This is an alias for285    /// '--min-depth <depth> --max-depth <depth>'.286    #[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),287    help = "Only show search results at the exact given depth",288        long_help,289        )]290    exact_depth: Option<usize>,291292    /// Exclude files/directories that match the given glob pattern. This293    /// overrides any other ignore logic. Multiple exclude patterns can be294    /// specified.295    ///296    /// Examples:297    /// {n}  --exclude '*.pyc'298    /// {n}  --exclude node_modules299    #[arg(300        long,301        short = 'E',302        value_name = "pattern",303        help = "Exclude entries that match the given glob pattern",304        long_help305    )]306    pub exclude: Vec<String>,307308    /// Do not traverse into directories that match the search criteria. If309    /// you want to exclude specific directories, use the '--exclude=…' option.310    #[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),311        long_help,312        )]313    pub prune: bool,314315    /// Filter the search by type:316    /// {n}  'f' or 'file':         regular files317    /// {n}  'd' or 'dir' or 'directory':    directories318    /// {n}  'l' or 'symlink':      symbolic links319    /// {n}  's' or 'socket':       socket320    /// {n}  'p' or 'pipe':         named pipe (FIFO)321    /// {n}  'b' or 'block-device': block device322    /// {n}  'c' or 'char-device':  character device323    /// {n}{n}  'x' or 'executable':   executables324    /// {n}  'e' or 'empty':        empty files or directories325    ///326    /// This option can be specified more than once to include multiple file types.327    /// Searching for '--type file --type symlink' will show both regular files as328    /// well as symlinks. Note that the 'executable' and 'empty' filters work differently:329    /// '--type executable' implies '--type file' by default. And '--type empty' searches330    /// for empty files and directories, unless either '--type file' or '--type directory'331    /// is specified in addition.332    ///333    /// Examples:334    /// {n}  - Only search for files:335    /// {n}      fd --type file …336    /// {n}      fd -tf …337    /// {n}  - Find both files and symlinks338    /// {n}      fd --type file --type symlink …339    /// {n}      fd -tf -tl …340    /// {n}  - Find executable files:341    /// {n}      fd --type executable342    /// {n}      fd -tx343    /// {n}  - Find empty files:344    /// {n}      fd --type empty --type file345    /// {n}      fd -te -tf346    /// {n}  - Find empty directories:347    /// {n}      fd --type empty --type directory348    /// {n}      fd -te -td349    #[arg(350        long = "type",351        short = 't',352        value_name = "filetype",353        hide_possible_values = true,354        value_enum,355        help = "Filter by type: file (f), directory (d/dir), symlink (l), \356                executable (x), empty (e), socket (s), pipe (p), \357                char-device (c), block-device (b)",358        long_help359    )]360    pub filetype: Option<Vec<FileType>>,361362    /// (Additionally) filter search results by their file extension. Multiple363    /// allowable file extensions can be specified.364    ///365    /// If you want to search for files without extension,366    /// you can use the regex '^[^.]+$' as a normal search pattern.367    #[arg(368        long = "extension",369        short = 'e',370        value_name = "ext",371        help = "Filter by file extension",372        long_help373    )]374    pub extensions: Option<Vec<String>>,375376    /// Limit results based on the size of files using the format <+-><NUM><UNIT>.377    ///    '+': file size must be greater than or equal to this378    ///    '-': file size must be less than or equal to this379    ///380    /// If neither '+' nor '-' is specified, file size must be exactly equal to this.381    ///    'NUM':  The numeric size (e.g. 500)382    ///    'UNIT': The units for NUM. They are not case-sensitive.383    /// Allowed unit values:384    ///     'b':  bytes385    ///     'k':  kilobytes (base ten, 10^3 = 1000 bytes)386    ///     'm':  megabytes387    ///     'g':  gigabytes388    ///     't':  terabytes389    ///     'ki': kibibytes (base two, 2^10 = 1024 bytes)390    ///     'mi': mebibytes391    ///     'gi': gibibytes392    ///     'ti': tebibytes393    #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",394        help = "Limit results based on the size of files",395        long_help,396        verbatim_doc_comment,397        )]398    pub size: Vec<SizeFilter>,399400    /// Filter results based on the file modification time. Files with modification times401    /// greater than the argument are returned. The argument can be provided402    /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).403    /// If the time is not specified, it defaults to 00:00:00.404    /// '--change-newer-than', '--newer', or '--changed-after' can be used as aliases.405    ///406    /// Examples:407    /// {n}    --changed-within 2weeks408    /// {n}    --change-newer-than '2018-10-27 10:00:00'409    /// {n}    --newer 2018-10-27410    /// {n}    --changed-after 1day411    #[arg(412        long,413        alias("change-newer-than"),414        alias("newer"),415        alias("changed-after"),416        value_name = "date|dur",417        help = "Filter by file modification time (newer than)",418        long_help419    )]420    pub changed_within: Option<String>,421422    /// Filter results based on the file modification time. Files with modification times423    /// less than the argument are returned. The argument can be provided424    /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).425    /// '--change-older-than' or '--older' can be used as aliases.426    ///427    /// Examples:428    /// {n}    --changed-before '2018-10-27 10:00:00'429    /// {n}    --change-older-than 2weeks430    /// {n}    --older 2018-10-27431    #[arg(432        long,433        alias("change-older-than"),434        alias("older"),435        value_name = "date|dur",436        help = "Filter by file modification time (older than)",437        long_help438    )]439    pub changed_before: Option<String>,440441    /// Filter files by their user and/or group.442    /// Format: [(user|uid)][:(group|gid)]. Either side is optional.443    /// Precede either side with a '!' to exclude files instead.444    ///445    /// Examples:446    /// {n}    --owner john447    /// {n}    --owner :students448    /// {n}    --owner '!john:students'449    #[cfg(unix)]450    #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",451        help = "Filter by owning user and/or group",452        long_help,453        )]454    pub owner: Option<OwnerFilter>,455456    /// Instead of printing the file normally, print the format string with the following placeholders replaced:457    ///   '{}': path (of the current search result)458    ///   '{/}': basename459    ///   '{//}': parent directory460    ///   '{.}': path without file extension461    ///   '{/.}': basename without file extension462    #[arg(463        long,464        value_name = "fmt",465        help = "Print results according to template",466        conflicts_with = "list_details"467    )]468    pub format: Option<String>,469470    #[command(flatten)]471    pub exec: Exec,472473    /// Maximum number of arguments to pass to the command given with -X.474    /// If the number of results is greater than the given size,475    /// the command given with -X is run again with remaining arguments.476    /// A batch size of zero means there is no limit (default), but note477    /// that batching might still happen due to OS restrictions on the478    /// maximum length of command lines.479    #[arg(480        long,481        value_name = "size",482        hide_short_help = true,483        requires("exec_batch"),484        value_parser = value_parser!(usize),485        default_value_t,486        help = "Max number of arguments to run as a batch size with -X",487        long_help,488    )]489    pub batch_size: usize,490491    /// Add a custom ignore-file in '.gitignore' format. These files have a low precedence.492    #[arg(493        long,494        value_name = "path",495        hide_short_help = true,496        help = "Add a custom ignore-file in '.gitignore' format",497        long_help498    )]499    pub ignore_file: Vec<PathBuf>,500501    /// Declare when to use color for the pattern match output502    #[arg(503        long,504        short = 'c',505        value_enum,506        default_value_t = ColorWhen::Auto,507        value_name = "when",508        help = "When to use colors",509        long_help,510    )]511    pub color: ColorWhen,512513    /// Add a terminal hyperlink to a file:// url for each path in the output.514    ///515    /// Auto mode  is used if no argument is given to this option.516    ///517    /// This doesn't do anything for --exec and --exec-batch.518    #[arg(519        long,520        alias = "hyper",521        value_name = "when",522        require_equals = true,523        value_enum,524        default_value_t = HyperlinkWhen::Never,525        default_missing_value = "auto",526        num_args = 0..=1,527        help = "Add hyperlinks to output paths"528    )]529    pub hyperlink: HyperlinkWhen,530531    /// Set number of threads to use for searching & executing (default: number532    /// of available CPU cores)533    #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = str::parse::<NonZeroUsize>)]534    pub threads: Option<NonZeroUsize>,535536    /// Milliseconds to buffer before streaming search results to console537    ///538    /// Amount of time in milliseconds to buffer, before streaming the search539    /// results to the console.540    #[arg(long, hide = true, value_parser = parse_millis)]541    pub max_buffer_time: Option<Duration>,542543    ///Limit the number of search results to 'count' and quit immediately.544    #[arg(545        long,546        value_name = "count",547        hide_short_help = true,548        overrides_with("max_one_result"),549        help = "Limit the number of search results",550        long_help551    )]552    max_results: Option<usize>,553554    /// Limit the search to a single result and quit immediately.555    /// This is an alias for '--max-results=1'.556    #[arg(557        short = '1',558        hide_short_help = true,559        overrides_with("max_results"),560        help = "Limit search to a single result",561        long_help562    )]563    max_one_result: bool,564565    /// When the flag is present, the program does not print anything and will566    /// return with an exit code of 0 if there is at least one match. Otherwise, the567    /// exit code will be 1.568    /// '--has-results' can be used as an alias.569    #[arg(570        long,571        short = 'q',572        alias = "has-results",573        hide_short_help = true,574        conflicts_with("max_results"),575        help = "Print nothing, exit code 0 if match found, 1 otherwise",576        long_help577    )]578    pub quiet: bool,579580    /// Enable the display of filesystem errors for situations such as581    /// insufficient permissions or dead symlinks.582    #[arg(583        long,584        hide_short_help = true,585        help = "Show filesystem errors",586        long_help587    )]588    pub show_errors: bool,589590    /// Change the current working directory of fd to the provided path. This591    /// means that search results will be shown with respect to the given base592    /// path. Note that relative paths which are passed to fd via the positional593    /// <path> argument or the '--search-path' option will also be resolved594    /// relative to this directory.595    #[arg(596        long,597        short = 'C',598        value_name = "path",599        hide_short_help = true,600        help = "Change current working directory",601        long_help602    )]603    pub base_directory: Option<PathBuf>,604605    /// the search pattern which is either a regular expression (default) or a glob606    /// pattern (if --glob is used). If no pattern has been specified, every entry607    /// is considered a match. If your pattern starts with a dash (-), make sure to608    /// pass '--' first, or it will be considered as a flag (fd -- '-foo').609    #[arg(610        default_value = "",611        hide_default_value = true,612        value_name = "pattern",613        help = "the search pattern (a regular expression, unless '--glob' is used; optional)",614        long_help615    )]616    pub pattern: String,617618    /// Set the path separator to use when printing file paths. The default is619    /// the OS-specific separator ('/' on Unix, '\' on Windows).620    #[arg(621        long,622        value_name = "separator",623        hide_short_help = true,624        help = "Set path separator when printing file paths",625        long_help626    )]627    pub path_separator: Option<String>,628629    /// The directory where the filesystem search is rooted (optional). If630    /// omitted, search the current working directory.631    #[arg(action = ArgAction::Append,632        value_name = "path",633        help = "the root directories for the filesystem search (optional)",634        long_help,635        )]636    path: Vec<PathBuf>,637638    /// Provide paths to search as an alternative to the positional <path>639    /// argument. Changes the usage to `fd [OPTIONS] --search-path <path>640    /// --search-path <path2> [<pattern>]`641    #[arg(642        long,643        conflicts_with("path"),644        value_name = "search-path",645        hide_short_help = true,646        help = "Provides paths to search as an alternative to the positional <path> argument",647        long_help648    )]649    search_path: Vec<PathBuf>,650651    /// By default, relative paths are prefixed with './' when -x/--exec,652    /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a653    /// path starting with '-' being treated as a command line option. Use654    /// this flag to change this behavior. If this flag is used without a value,655    /// it is equivalent to passing "always".656    #[arg(long, conflicts_with_all(&["path", "search_path"]), value_name = "when", hide_short_help = true, require_equals = true, long_help)]657    strip_cwd_prefix: Option<Option<StripCwdWhen>>,658659    /// By default, fd will traverse the file system tree as far as other options660    /// dictate. With this flag, fd ensures that it does not descend into a661    /// different file system than the one it started in. Comparable to the -mount662    /// or -xdev filters of find(1).663    #[cfg(any(unix, windows))]664    #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]665    pub one_file_system: bool,666667    #[cfg(feature = "completions")]668    #[arg(long, hide = true, exclusive = true)]669    gen_completions: Option<Option<Shell>>,670}671672impl Opts {673    pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {674        // would it make sense to concatenate these?675        let paths = if !self.path.is_empty() {676            &self.path677        } else if !self.search_path.is_empty() {678            &self.search_path679        } else {680            let current_directory = Path::new("./");681            ensure_current_directory_exists(current_directory)?;682            return Ok(vec![self.normalize_path(current_directory)]);683        };684        Ok(paths685            .iter()686            .filter_map(|path| {687                if filesystem::is_existing_directory(path) {688                    Some(self.normalize_path(path))689                } else {690                    print_error(format!(691                        "Search path '{}' is not a directory.",692                        path.to_string_lossy()693                    ));694                    None695                }696            })697            .collect())698    }699700    fn normalize_path(&self, path: &Path) -> PathBuf {701        if self.absolute_path {702            filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()703        } else if path == Path::new(".") {704            // Change "." to "./" as a workaround for https://github.com/BurntSushi/ripgrep/pull/2711705            PathBuf::from("./")706        } else {707            path.to_path_buf()708        }709    }710711    pub fn no_search_paths(&self) -> bool {712        self.path.is_empty() && self.search_path.is_empty()713    }714715    #[inline]716    pub fn rg_alias_ignore(&self) -> bool {717        self.rg_alias_hidden_ignore > 0718    }719720    pub fn max_depth(&self) -> Option<usize> {721        self.max_depth.or(self.exact_depth)722    }723724    pub fn min_depth(&self) -> Option<usize> {725        self.min_depth.or(self.exact_depth)726    }727728    pub fn threads(&self) -> NonZeroUsize {729        self.threads.unwrap_or_else(default_num_threads)730    }731732    pub fn max_results(&self) -> Option<usize> {733        self.max_results734            .filter(|&m| m > 0)735            .or_else(|| self.max_one_result.then_some(1))736    }737738    pub fn strip_cwd_prefix<P: FnOnce() -> bool>(&self, auto_pred: P) -> bool {739        use self::StripCwdWhen::*;740        self.no_search_paths()741            && match self.strip_cwd_prefix.map_or(Auto, |o| o.unwrap_or(Always)) {742                Auto => auto_pred(),743                Always => true,744                Never => false,745            }746    }747748    #[cfg(feature = "completions")]749    pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {750        self.gen_completions751            .map(|maybe_shell| match maybe_shell {752                Some(sh) => Ok(sh),753                None => {754                    Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))755                }756            })757            .transpose()758    }759}760761/// Get the default number of threads to use, if not explicitly specified.762fn default_num_threads() -> NonZeroUsize {763    // If we can't get the amount of parallelism for some reason, then764    // default to a single thread, because that is safe.765    let fallback = NonZeroUsize::MIN;766    // To limit startup overhead on massively parallel machines, don't use more767    // than 64 threads.768    let limit = NonZeroUsize::new(64).unwrap();769770    std::thread::available_parallelism()771        .unwrap_or(fallback)772        .min(limit)773}774775#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]776pub enum FileType {777    #[value(alias = "f")]778    File,779    #[value(alias = "d", alias = "dir")]780    Directory,781    #[value(alias = "l")]782    Symlink,783    #[value(alias = "b")]784    BlockDevice,785    #[value(alias = "c")]786    CharDevice,787    /// A file which is executable by the current effective user788    #[value(alias = "x")]789    Executable,790    #[value(alias = "e")]791    Empty,792    #[value(alias = "s")]793    Socket,794    #[value(alias = "p")]795    Pipe,796}797798#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]799pub enum ColorWhen {800    /// show colors if the output goes to an interactive console (default)801    Auto,802    /// always use colorized output803    Always,804    /// do not use colorized output805    Never,806}807808#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]809pub enum StripCwdWhen {810    /// Use the default behavior811    Auto,812    /// Always strip the ./ at the beginning of paths813    Always,814    /// Never strip the ./815    Never,816}817818#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]819pub enum HyperlinkWhen {820    /// Use hyperlinks only if color is enabled821    Auto,822    /// Always use hyperlinks when printing file paths823    Always,824    /// Never use hyperlinks825    Never,826}827828// there isn't a derive api for getting grouped values yet,829// so we have to use hand-rolled parsing for exec and exec-batch830pub struct Exec {831    pub command: Option<CommandSet>,832}833834impl clap::FromArgMatches for Exec {835    fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {836        let command = matches837            .get_occurrences::<String>("exec")838            .map(CommandSet::new)839            .or_else(|| {840                matches841                    .get_occurrences::<String>("exec_batch")842                    .map(CommandSet::new_batch)843            })844            .transpose()845            .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;846        Ok(Exec { command })847    }848849    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {850        *self = Self::from_arg_matches(matches)?;851        Ok(())852    }853}854855impl clap::Args for Exec {856    fn augment_args(cmd: Command) -> Command {857        cmd.arg(Arg::new("exec")858            .action(ArgAction::Append)859            .long("exec")860            .short('x')861            .num_args(1..)862                .allow_hyphen_values(true)863                .value_terminator(";")864                .value_name("cmd")865                .conflicts_with("list_details")866                .help("Execute a command for each search result")867                .long_help(868                    "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \869                     There is no guarantee of the order commands are executed in, and the order should not be depended upon. \870                     All positional arguments following --exec are considered to be arguments to the command - not to fd. \871                     It is therefore recommended to place the '-x'/'--exec' option last.\n\872                     The following placeholders are substituted before the command is executed:\n  \873                       '{}':   path (of the current search result)\n  \874                       '{/}':  basename\n  \875                       '{//}': parent directory\n  \876                       '{.}':  path without file extension\n  \877                       '{/.}': basename without file extension\n  \878                       '{{':   literal '{' (for escaping)\n  \879                       '}}':   literal '}' (for escaping)\n\n\880                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\881                     Examples:\n\n  \882                       - find all *.zip files and unzip them:\n\n      \883                           fd -e zip -x unzip\n\n  \884                       - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n      \885                           fd -e h -e cpp -x clang-format -i\n\n  \886                       - Convert all *.jpg files to *.png files:\n\n      \887                           fd -e jpg -x convert {} {.}.png\888                    ",889                ),890        )891        .arg(892            Arg::new("exec_batch")893                .action(ArgAction::Append)894                .long("exec-batch")895                .short('X')896                .num_args(1..)897                .allow_hyphen_values(true)898                .value_terminator(";")899                .value_name("cmd")900                .conflicts_with_all(["exec", "list_details"])901                .help("Execute a command with all search results at once")902                .long_help(903                    "Execute the given command once, with all search results as arguments.\n\904                     The order of the arguments is non-deterministic, and should not be relied upon.\n\905                     One of the following placeholders is substituted before the command is executed:\n  \906                       '{}':   path (of all search results)\n  \907                       '{/}':  basename\n  \908                       '{//}': parent directory\n  \909                       '{.}':  path without file extension\n  \910                       '{/.}': basename without file extension\n  \911                       '{{':   literal '{' (for escaping)\n  \912                       '}}':   literal '}' (for escaping)\n\n\913                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\914                     Examples:\n\n  \915                       - Find all test_*.py files and open them in your favorite editor:\n\n      \916                           fd -g 'test_*.py' -X vim\n\n  \917                       - Find all *.rs files and count the lines with \"wc -l ...\":\n\n      \918                           fd -e rs -X wc -l\919                     "920                ),921        )922    }923924    fn augment_args_for_update(cmd: Command) -> Command {925        Self::augment_args(cmd)926    }927}928929fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {930    Ok(Duration::from_millis(arg.parse()?))931}932933fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {934    if filesystem::is_existing_directory(current_directory) {935        Ok(())936    } else {937        Err(anyhow!(938            "Could not retrieve current directory (has it been deleted?)."939        ))940    }941}