Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

954 lines · 33.8 KiB · Rust

Last changed by

docs: drop accidental --full-path edits from extension PRwuyangfanbefore adoption9f938be

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    /// The flag can be overridden with --ignore-parent.106    #[arg(107        long,108        hide_short_help = true,109        help = "Do not respect .(git|fd)ignore files in parent directories",110        long_help111    )]112    pub no_ignore_parent: bool,113114    /// Overrides --no-ignore-parent115    #[arg(long, overrides_with = "no_ignore_parent", hide = true, action = ArgAction::SetTrue)]116    ignore_parent: (),117118    /// Do not respect the global ignore file119    #[arg(long, hide = true)]120    pub no_global_ignore_file: bool,121122    /// Perform an unrestricted search, including ignored and hidden files. This is123    /// an alias for '--no-ignore --hidden'.124    #[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,125    help = "Unrestricted search, alias for '--no-ignore --hidden'",126        long_help,127        )]128    rg_alias_hidden_ignore: u8,129130    /// Case-sensitive search (default: smart case)131    #[arg(132        long,133        short = 's',134        overrides_with("ignore_case"),135        long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \136                     searches, unless the pattern contains an uppercase character (smart \137                     case)."138    )]139    pub case_sensitive: bool,140141    /// Perform a case-insensitive search. By default, fd uses case-insensitive142    /// searches, unless the pattern contains an uppercase character (smart143    /// case).144    #[arg(145        long,146        short = 'i',147        overrides_with("case_sensitive"),148        help = "Case-insensitive search (default: smart case)",149        long_help150    )]151    pub ignore_case: bool,152153    /// Perform a glob-based search instead of a regular expression search.154    #[arg(155        long,156        short = 'g',157        conflicts_with("fixed_strings"),158        help = "Glob-based search (default: regular expression)",159        long_help160    )]161    pub glob: bool,162163    /// Perform a regular-expression based search (default). This can be used to164    /// override --glob.165    #[arg(166        long,167        overrides_with("glob"),168        hide_short_help = true,169        help = "Regular-expression based search (default)",170        long_help171    )]172    pub regex: bool,173174    /// Treat the pattern as a literal string instead of a regular expression. Note175    /// that this also performs substring comparison. If you want to match on an176    /// exact filename, consider using '--glob'.177    #[arg(178        long,179        short = 'F',180        alias = "literal",181        hide_short_help = true,182        help = "Treat pattern as literal string stead of regex",183        long_help184    )]185    pub fixed_strings: bool,186187    /// Add additional required search patterns, all of which must be matched. Multiple188    /// additional patterns can be specified. The patterns are regular189    /// expressions, unless '--glob' or '--fixed-strings' is used.190    #[arg(191        long = "and",192        value_name = "pattern",193        help = "Additional search patterns that need to be matched",194        long_help,195        hide_short_help = true,196        allow_hyphen_values = true197    )]198    pub exprs: Option<Vec<String>>,199200    /// Shows the full path starting from the root as opposed to relative paths.201    /// The flag can be overridden with --relative-path.202    #[arg(203        long,204        short = 'a',205        help = "Show absolute instead of relative paths",206        long_help207    )]208    pub absolute_path: bool,209210    /// Overrides --absolute-path211    #[arg(long, overrides_with = "absolute_path", hide = true, action = ArgAction::SetTrue)]212    relative_path: (),213214    /// Use a detailed listing format like 'ls -l'. This is basically an alias215    /// for '--exec-batch ls -l' with some additional 'ls' options. This can be216    /// used to see more metadata, to show symlink targets and to achieve a217    /// deterministic sort order.218    #[arg(219        long,220        short = 'l',221        conflicts_with("absolute_path"),222        help = "Use a long listing format with file metadata",223        long_help224    )]225    pub list_details: bool,226227    /// Follow symbolic links228    #[arg(229        long,230        short = 'L',231        alias = "dereference",232        long_help = "By default, fd does not descend into symlinked directories. Using this \233                     flag, symbolic links are also traversed. \234                     Flag can be overridden with --no-follow."235    )]236    pub follow: bool,237238    /// Overrides --follow239    #[arg(long, overrides_with = "follow", hide = true, action = ArgAction::SetTrue)]240    no_follow: (),241242    /// By default, the search pattern is only matched against the filename (or directory name). Using this flag, the pattern is matched against the full (absolute) path. Example:243    ///   fd --glob -p '**/.git/config'244    #[arg(245        long,246        short = 'p',247        help = "Search full abs. path (default: filename only)",248        long_help,249        verbatim_doc_comment250    )]251    pub full_path: bool,252253    /// Separate search results by the null character (instead of newlines).254    /// Useful for piping results to 'xargs'.255    #[arg(256        long = "print0",257        short = '0',258        conflicts_with("list_details"),259        hide_short_help = true,260        help = "Separate search results by the null character",261        long_help262    )]263    pub null_separator: bool,264265    /// Limit the directory traversal to a given depth. By default, there is no266    /// limit on the search depth.267    #[arg(268        long,269        short = 'd',270        value_name = "depth",271        alias("maxdepth"),272        help = "Set maximum search depth (default: none)",273        long_help274    )]275    max_depth: Option<usize>,276277    /// Only show search results starting at the given depth.278    /// See also: '--max-depth' and '--exact-depth'279    #[arg(280        long,281        value_name = "depth",282        hide_short_help = true,283        alias("mindepth"),284        help = "Only show search results starting at the given depth.",285        long_help286    )]287    min_depth: Option<usize>,288289    /// Only show search results at the exact given depth. This is an alias for290    /// '--min-depth <depth> --max-depth <depth>'.291    #[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),292    help = "Only show search results at the exact given depth",293        long_help,294        )]295    exact_depth: Option<usize>,296297    /// Exclude files/directories that match the given glob pattern. This298    /// overrides any other ignore logic. Multiple exclude patterns can be299    /// specified.300    ///301    /// Examples:302    /// {n}  --exclude '*.pyc'303    /// {n}  --exclude node_modules304    #[arg(305        long,306        short = 'E',307        value_name = "glob",308        help = "Exclude entries that match the given glob pattern",309        long_help310    )]311    pub exclude: Vec<String>,312313    /// Do not traverse into directories that match the search criteria. If314    /// you want to exclude specific directories, use the '--exclude=…' option.315    #[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),316        long_help,317        )]318    pub prune: bool,319320    /// Filter the search by type:321    /// {n}  'f' or 'file':         regular files322    /// {n}  'd' or 'dir' or 'directory':    directories323    /// {n}  'l' or 'symlink':      symbolic links324    /// {n}  's' or 'socket':       socket325    /// {n}  'p' or 'pipe':         named pipe (FIFO)326    /// {n}  'b' or 'block-device': block device327    /// {n}  'c' or 'char-device':  character device328    /// {n}{n}  'x' or 'executable':   executables329    /// {n}  'e' or 'empty':        empty files or directories330    ///331    /// This option can be specified more than once to include multiple file types.332    /// Searching for '--type file --type symlink' will show both regular files as333    /// well as symlinks. Note that the 'executable' and 'empty' filters work differently:334    /// '--type executable' implies '--type file' by default. And '--type empty' searches335    /// for empty files and directories, unless either '--type file' or '--type directory'336    /// is specified in addition.337    ///338    /// Examples:339    /// {n}  - Only search for files:340    /// {n}      fd --type file …341    /// {n}      fd -tf …342    /// {n}  - Find both files and symlinks343    /// {n}      fd --type file --type symlink …344    /// {n}      fd -tf -tl …345    /// {n}  - Find executable files:346    /// {n}      fd --type executable347    /// {n}      fd -tx348    /// {n}  - Find empty files:349    /// {n}      fd --type empty --type file350    /// {n}      fd -te -tf351    /// {n}  - Find empty directories:352    /// {n}      fd --type empty --type directory353    /// {n}      fd -te -td354    #[arg(355        long = "type",356        short = 't',357        value_name = "filetype",358        hide_possible_values = true,359        value_enum,360        help = "Filter by type: file (f), directory (d/dir), symlink (l), \361                executable (x), empty (e), socket (s), pipe (p), \362                char-device (c), block-device (b)",363        long_help364    )]365    pub filetype: Option<Vec<FileType>>,366367    /// Filter results by extension. By default, this matches all entry types368    /// (including directories whose names end with the extension). Use `--type`369    /// to restrict the search to specific types. Multiple extensions can be specified.370    ///371    /// If you want to search for files without extension,372    /// you can use the regex '^[^.]+$' as a normal search pattern.373    #[arg(374        long = "extension",375        short = 'e',376        value_name = "ext",377        help = "Filter by extension",378        long_help379    )]380    pub extensions: Option<Vec<String>>,381382    /// Limit results based on the size of files using the format <+-><NUM><UNIT>.383    ///    '+': file size must be greater than or equal to this384    ///    '-': file size must be less than or equal to this385    ///386    /// If neither '+' nor '-' is specified, file size must be exactly equal to this.387    ///    'NUM':  The numeric size (e.g. 500)388    ///    'UNIT': The units for NUM. They are not case-sensitive.389    /// Allowed unit values:390    ///     'b':  bytes391    ///     'k':  kilobytes (base ten, 10^3 = 1000 bytes)392    ///     'm':  megabytes393    ///     'g':  gigabytes394    ///     't':  terabytes395    ///     'ki': kibibytes (base two, 2^10 = 1024 bytes)396    ///     'mi': mebibytes397    ///     'gi': gibibytes398    ///     'ti': tebibytes399    #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",400        help = "Limit results based on the size of files",401        long_help,402        verbatim_doc_comment,403        )]404    pub size: Vec<SizeFilter>,405406    /// Filter results based on the file modification time. Files with modification times407    /// greater than the argument are returned. The argument can be provided408    /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).409    /// If the time is not specified, it defaults to 00:00:00.410    /// '--change-newer-than', '--newer', or '--changed-after' can be used as aliases.411    ///412    /// Examples:413    /// {n}    --changed-within 2weeks414    /// {n}    --change-newer-than '2018-10-27 10:00:00'415    /// {n}    --newer 2018-10-27416    /// {n}    --changed-after 1day417    #[arg(418        long,419        alias("change-newer-than"),420        alias("newer"),421        alias("changed-after"),422        value_name = "date|dur",423        help = "Filter by file modification time (newer than)",424        long_help425    )]426    pub changed_within: Option<String>,427428    /// Filter results based on the file modification time. Files with modification times429    /// less than the argument are returned. The argument can be provided430    /// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).431    /// '--change-older-than' or '--older' can be used as aliases.432    ///433    /// Examples:434    /// {n}    --changed-before '2018-10-27 10:00:00'435    /// {n}    --change-older-than 2weeks436    /// {n}    --older 2018-10-27437    #[arg(438        long,439        alias("change-older-than"),440        alias("older"),441        value_name = "date|dur",442        help = "Filter by file modification time (older than)",443        long_help444    )]445    pub changed_before: Option<String>,446447    /// Filter files by their user and/or group.448    /// Format: [(user|uid)][:(group|gid)]. Either side is optional.449    /// Precede either side with a '!' to exclude files instead.450    ///451    /// Examples:452    /// {n}    --owner john453    /// {n}    --owner :students454    /// {n}    --owner '!john:students'455    #[cfg(unix)]456    #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",457        help = "Filter by owning user and/or group",458        long_help,459        )]460    pub owner: Option<OwnerFilter>,461462    /// Instead of printing the file normally, print the format string with the following placeholders replaced:463    ///   '{}': path (of the current search result)464    ///   '{/}': basename465    ///   '{//}': parent directory466    ///   '{.}': path without file extension467    ///   '{/.}': basename without file extension468    #[arg(469        long,470        value_name = "fmt",471        help = "Print results according to template",472        conflicts_with = "list_details"473    )]474    pub format: Option<String>,475476    #[command(flatten)]477    pub exec: Exec,478479    /// Maximum number of arguments to pass to the command given with -X.480    /// If the number of results is greater than the given size,481    /// the command given with -X is run again with remaining arguments.482    /// A batch size of zero means there is no limit (default), but note483    /// that batching might still happen due to OS restrictions on the484    /// maximum length of command lines.485    #[arg(486        long,487        value_name = "size",488        hide_short_help = true,489        requires("exec_batch"),490        value_parser = value_parser!(usize),491        default_value_t,492        help = "Max number of arguments to run as a batch size with -X",493        long_help,494    )]495    pub batch_size: usize,496497    /// Add a custom ignore-file in '.gitignore' format. These files have a low precedence.498    #[arg(499        long,500        value_name = "path",501        hide_short_help = true,502        help = "Add a custom ignore-file in '.gitignore' format",503        long_help504    )]505    pub ignore_file: Vec<PathBuf>,506507    /// Declare when to use color for the pattern match output508    #[arg(509        long,510        short = 'c',511        value_enum,512        default_value_t = ColorWhen::Auto,513        value_name = "when",514        help = "When to use colors",515        long_help,516    )]517    pub color: ColorWhen,518519    /// Add a terminal hyperlink to a file:// url for each path in the output.520    ///521    /// Auto mode  is used if no argument is given to this option.522    ///523    /// This doesn't do anything for --exec and --exec-batch.524    #[arg(525        long,526        alias = "hyper",527        value_name = "when",528        require_equals = true,529        value_enum,530        default_value_t = HyperlinkWhen::Never,531        default_missing_value = "auto",532        num_args = 0..=1,533        help = "Add hyperlinks to output paths"534    )]535    pub hyperlink: HyperlinkWhen,536537    /// Ignore directories containing the named entry.538    #[arg(long, value_name = "name")]539    pub ignore_contain: Vec<String>,540541    /// Set number of threads to use for searching & executing (default: number542    /// of available CPU cores)543    #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = str::parse::<NonZeroUsize>)]544    pub threads: Option<NonZeroUsize>,545546    /// Milliseconds to buffer before streaming search results to console547    ///548    /// Amount of time in milliseconds to buffer, before streaming the search549    /// results to the console.550    #[arg(long, hide = true, value_parser = parse_millis)]551    pub max_buffer_time: Option<Duration>,552553    ///Limit the number of search results to 'count' and quit immediately.554    #[arg(555        long,556        value_name = "count",557        hide_short_help = true,558        overrides_with("max_one_result"),559        help = "Limit the number of search results",560        long_help561    )]562    max_results: Option<usize>,563564    /// Limit the search to a single result and quit immediately.565    /// This is an alias for '--max-results=1'.566    #[arg(567        short = '1',568        hide_short_help = true,569        overrides_with("max_results"),570        help = "Limit search to a single result",571        long_help572    )]573    max_one_result: bool,574575    /// When the flag is present, the program does not print anything and will576    /// return with an exit code of 0 if there is at least one match. Otherwise, the577    /// exit code will be 1.578    /// '--has-results' can be used as an alias.579    #[arg(580        long,581        short = 'q',582        alias = "has-results",583        hide_short_help = true,584        conflicts_with("max_results"),585        help = "Print nothing, exit code 0 if match found, 1 otherwise",586        long_help587    )]588    pub quiet: bool,589590    /// Enable the display of filesystem errors for situations such as591    /// insufficient permissions or dead symlinks.592    #[arg(593        long,594        hide_short_help = true,595        help = "Show filesystem errors",596        long_help597    )]598    pub show_errors: bool,599600    /// Change the current working directory of fd to the provided path. This601    /// means that search results will be shown with respect to the given base602    /// path. Note that relative paths which are passed to fd via the positional603    /// <path> argument or the '--search-path' option will also be resolved604    /// relative to this directory.605    #[arg(606        long,607        short = 'C',608        value_name = "path",609        hide_short_help = true,610        help = "Change current working directory",611        long_help612    )]613    pub base_directory: Option<PathBuf>,614615    /// the search pattern which is either a regular expression (default) or a glob616    /// pattern (if --glob is used). If no pattern has been specified, every entry617    /// is considered a match. If your pattern starts with a dash (-), make sure to618    /// pass '--' first, or it will be considered as a flag (fd -- '-foo').619    #[arg(620        default_value = "",621        hide_default_value = true,622        value_name = "pattern",623        help = "the search pattern (a regular expression, unless '--glob' is used; optional)",624        long_help625    )]626    pub pattern: String,627628    /// Set the path separator to use when printing file paths. The default is629    /// the OS-specific separator ('/' on Unix, '\' on Windows).630    #[arg(631        long,632        value_name = "separator",633        hide_short_help = true,634        help = "Set path separator when printing file paths",635        long_help636    )]637    pub path_separator: Option<String>,638639    /// The directory where the filesystem search is rooted (optional). If640    /// omitted, search the current working directory.641    #[arg(action = ArgAction::Append,642        value_name = "path",643        help = "the root directories for the filesystem search (optional)",644        long_help,645        )]646    path: Vec<PathBuf>,647648    /// Provide paths to search as an alternative to the positional <path>649    /// argument. Changes the usage to `fd [OPTIONS] --search-path <path>650    /// --search-path <path2> [<pattern>]`651    #[arg(652        long,653        conflicts_with("path"),654        value_name = "search-path",655        hide_short_help = true,656        help = "Provides paths to search as an alternative to the positional <path> argument",657        long_help658    )]659    search_path: Vec<PathBuf>,660661    /// By default, relative paths are prefixed with './' when -x/--exec,662    /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a663    /// path starting with '-' being treated as a command line option. Use664    /// this flag to change this behavior. If this flag is used without a value,665    /// it is equivalent to passing "always".666    #[arg(long, conflicts_with_all(&["path", "search_path"]), value_name = "when", hide_short_help = true, require_equals = true, long_help)]667    strip_cwd_prefix: Option<Option<StripCwdWhen>>,668669    /// By default, fd will traverse the file system tree as far as other options670    /// dictate. With this flag, fd ensures that it does not descend into a671    /// different file system than the one it started in. Comparable to the -mount672    /// or -xdev filters of find(1).673    #[cfg(any(unix, windows))]674    #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]675    pub one_file_system: bool,676677    #[cfg(feature = "completions")]678    #[arg(long, hide = true, exclusive = true)]679    gen_completions: Option<Option<Shell>>,680}681682impl Opts {683    pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {684        // would it make sense to concatenate these?685        let paths = if !self.path.is_empty() {686            &self.path687        } else if !self.search_path.is_empty() {688            &self.search_path689        } else {690            let current_directory = Path::new("./");691            ensure_current_directory_exists(current_directory)?;692            return Ok(vec![self.normalize_path(current_directory)]);693        };694        Ok(paths695            .iter()696            .filter_map(|path| {697                if filesystem::is_existing_directory(path) {698                    Some(self.normalize_path(path))699                } else {700                    print_error(format!(701                        "Search path '{}' is not a directory.",702                        path.to_string_lossy()703                    ));704                    None705                }706            })707            .collect())708    }709710    fn normalize_path(&self, path: &Path) -> PathBuf {711        if self.absolute_path {712            filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()713        } else if path == Path::new(".") {714            // Change "." to "./" as a workaround for https://github.com/BurntSushi/ripgrep/pull/2711715            PathBuf::from("./")716        } else {717            path.to_path_buf()718        }719    }720721    pub fn no_search_paths(&self) -> bool {722        self.path.is_empty() && self.search_path.is_empty()723    }724725    #[inline]726    pub fn rg_alias_ignore(&self) -> bool {727        self.rg_alias_hidden_ignore > 0728    }729730    pub fn max_depth(&self) -> Option<usize> {731        self.max_depth.or(self.exact_depth)732    }733734    pub fn min_depth(&self) -> Option<usize> {735        self.min_depth.or(self.exact_depth)736    }737738    pub fn threads(&self) -> NonZeroUsize {739        self.threads.unwrap_or_else(default_num_threads)740    }741742    pub fn max_results(&self) -> Option<usize> {743        self.max_results744            .filter(|&m| m > 0)745            .or_else(|| self.max_one_result.then_some(1))746    }747748    pub fn strip_cwd_prefix<P: FnOnce() -> bool>(&self, auto_pred: P) -> bool {749        use self::StripCwdWhen::*;750        self.no_search_paths()751            && match self.strip_cwd_prefix.map_or(Auto, |o| o.unwrap_or(Always)) {752                Auto => auto_pred(),753                Always => true,754                Never => false,755            }756    }757758    #[cfg(feature = "completions")]759    pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {760        self.gen_completions761            .map(|maybe_shell| match maybe_shell {762                Some(sh) => Ok(sh),763                None => {764                    Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))765                }766            })767            .transpose()768    }769}770771/// Get the default number of threads to use, if not explicitly specified.772fn default_num_threads() -> NonZeroUsize {773    // If we can't get the amount of parallelism for some reason, then774    // default to a single thread, because that is safe.775    let fallback = NonZeroUsize::MIN;776    // To limit startup overhead on massively parallel machines, don't use more777    // than 64 threads.778    let limit = NonZeroUsize::new(64).unwrap();779780    std::thread::available_parallelism()781        .unwrap_or(fallback)782        .min(limit)783}784785#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]786pub enum FileType {787    #[value(alias = "f")]788    File,789    #[value(alias = "d", alias = "dir")]790    Directory,791    #[value(alias = "l")]792    Symlink,793    #[value(alias = "b")]794    BlockDevice,795    #[value(alias = "c")]796    CharDevice,797    /// A file which is executable by the current effective user798    #[value(alias = "x")]799    Executable,800    #[value(alias = "e")]801    Empty,802    #[value(alias = "s")]803    Socket,804    #[value(alias = "p")]805    Pipe,806}807808#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]809pub enum ColorWhen {810    /// show colors if the output goes to an interactive console (default)811    Auto,812    /// always use colorized output813    Always,814    /// do not use colorized output815    Never,816}817818#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]819pub enum StripCwdWhen {820    /// Use the default behavior821    Auto,822    /// Always strip the ./ at the beginning of paths823    Always,824    /// Never strip the ./825    Never,826}827828#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]829pub enum HyperlinkWhen {830    /// Use hyperlinks only if color is enabled831    Auto,832    /// Always use hyperlinks when printing file paths833    Always,834    /// Never use hyperlinks835    Never,836}837838// there isn't a derive api for getting grouped values yet,839// so we have to use hand-rolled parsing for exec and exec-batch840pub struct Exec {841    pub command: Option<CommandSet>,842}843844impl clap::FromArgMatches for Exec {845    fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {846        let command = matches847            .get_occurrences::<String>("exec")848            .map(CommandSet::new)849            .or_else(|| {850                matches851                    .get_occurrences::<String>("exec_batch")852                    .map(CommandSet::new_batch)853            })854            .transpose()855            .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;856        Ok(Exec { command })857    }858859    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {860        *self = Self::from_arg_matches(matches)?;861        Ok(())862    }863}864865impl clap::Args for Exec {866    fn augment_args(cmd: Command) -> Command {867        cmd.arg(Arg::new("exec")868            .action(ArgAction::Append)869            .long("exec")870            .short('x')871            .num_args(1..)872                .allow_hyphen_values(true)873                .value_terminator(";")874                .value_name("cmd")875                .conflicts_with("list_details")876                .help("Execute a command for each search result")877                .long_help(878                    "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \879                     There is no guarantee of the order commands are executed in, and the order should not be depended upon. \880                     All positional arguments following --exec are considered to be arguments to the command - not to fd. \881                     It is therefore recommended to place the '-x'/'--exec' option last. \882                     Use '\\;' to terminate the command template if you need to continue passing fd arguments afterwards.\n\883                     The following placeholders are substituted before the command is executed:\n  \884                       '{}':   path (of the current search result)\n  \885                       '{/}':  basename\n  \886                       '{//}': parent directory\n  \887                       '{.}':  path without file extension\n  \888                       '{/.}': basename without file extension\n  \889                       '{{':   literal '{' (for escaping)\n  \890                       '}}':   literal '}' (for escaping)\n\n\891                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\892                     Examples:\n\n  \893                       - find all *.zip files and unzip them:\n\n      \894                           fd -e zip -x unzip\n\n  \895                       - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n      \896                           fd -e h -e cpp -x clang-format -i\n\n  \897                       - search within `src/` and echo each match (place `-x` last):\n\n      \898                           fd . src -x echo\n\n  \899                       - Convert all *.jpg files to *.png files:\n\n      \900                           fd -e jpg -x convert {} {.}.png\901                    ",902                ),903        )904        .arg(905            Arg::new("exec_batch")906                .action(ArgAction::Append)907                .long("exec-batch")908                .short('X')909                .num_args(1..)910                .allow_hyphen_values(true)911                .value_terminator(";")912                .value_name("cmd")913                .conflicts_with_all(["exec", "list_details"])914                .help("Execute a command with all search results at once")915                .long_help(916                    "Execute the given command once, with all search results as arguments.\n\917                     The order of the arguments is non-deterministic, and should not be relied upon.\n\918                     One of the following placeholders is substituted before the command is executed:\n  \919                       '{}':   path (of all search results)\n  \920                       '{/}':  basename\n  \921                       '{//}': parent directory\n  \922                       '{.}':  path without file extension\n  \923                       '{/.}': basename without file extension\n  \924                       '{{':   literal '{' (for escaping)\n  \925                       '}}':   literal '}' (for escaping)\n\n\926                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\927                     Examples:\n\n  \928                       - Find all test_*.py files and open them in your favorite editor:\n\n      \929                           fd -g 'test_*.py' -X vim\n\n  \930                       - Find all *.rs files and count the lines with \"wc -l ...\":\n\n      \931                           fd -e rs -X wc -l\932                     "933                ),934        )935    }936937    fn augment_args_for_update(cmd: Command) -> Command {938        Self::augment_args(cmd)939    }940}941942fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {943    Ok(Duration::from_millis(arg.parse()?))944}945946fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {947    if filesystem::is_existing_directory(current_directory) {948        Ok(())949    } else {950        Err(anyhow!(951            "Could not retrieve current directory (has it been deleted?)."952        ))953    }954}