Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

948 lines · 33.5 KiB · Rust

Last changed by

Merge pull request #1921 from rexkirshner/fix-exclude-value-name-globThayne McCombsbefore adoptionfcd8466

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 = "glob",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    /// Ignore directories containing the named entry.532    #[arg(long, value_name = "name")]533    pub ignore_contain: Vec<String>,534535    /// Set number of threads to use for searching & executing (default: number536    /// of available CPU cores)537    #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = str::parse::<NonZeroUsize>)]538    pub threads: Option<NonZeroUsize>,539540    /// Milliseconds to buffer before streaming search results to console541    ///542    /// Amount of time in milliseconds to buffer, before streaming the search543    /// results to the console.544    #[arg(long, hide = true, value_parser = parse_millis)]545    pub max_buffer_time: Option<Duration>,546547    ///Limit the number of search results to 'count' and quit immediately.548    #[arg(549        long,550        value_name = "count",551        hide_short_help = true,552        overrides_with("max_one_result"),553        help = "Limit the number of search results",554        long_help555    )]556    max_results: Option<usize>,557558    /// Limit the search to a single result and quit immediately.559    /// This is an alias for '--max-results=1'.560    #[arg(561        short = '1',562        hide_short_help = true,563        overrides_with("max_results"),564        help = "Limit search to a single result",565        long_help566    )]567    max_one_result: bool,568569    /// When the flag is present, the program does not print anything and will570    /// return with an exit code of 0 if there is at least one match. Otherwise, the571    /// exit code will be 1.572    /// '--has-results' can be used as an alias.573    #[arg(574        long,575        short = 'q',576        alias = "has-results",577        hide_short_help = true,578        conflicts_with("max_results"),579        help = "Print nothing, exit code 0 if match found, 1 otherwise",580        long_help581    )]582    pub quiet: bool,583584    /// Enable the display of filesystem errors for situations such as585    /// insufficient permissions or dead symlinks.586    #[arg(587        long,588        hide_short_help = true,589        help = "Show filesystem errors",590        long_help591    )]592    pub show_errors: bool,593594    /// Change the current working directory of fd to the provided path. This595    /// means that search results will be shown with respect to the given base596    /// path. Note that relative paths which are passed to fd via the positional597    /// <path> argument or the '--search-path' option will also be resolved598    /// relative to this directory.599    #[arg(600        long,601        short = 'C',602        value_name = "path",603        hide_short_help = true,604        help = "Change current working directory",605        long_help606    )]607    pub base_directory: Option<PathBuf>,608609    /// the search pattern which is either a regular expression (default) or a glob610    /// pattern (if --glob is used). If no pattern has been specified, every entry611    /// is considered a match. If your pattern starts with a dash (-), make sure to612    /// pass '--' first, or it will be considered as a flag (fd -- '-foo').613    #[arg(614        default_value = "",615        hide_default_value = true,616        value_name = "pattern",617        help = "the search pattern (a regular expression, unless '--glob' is used; optional)",618        long_help619    )]620    pub pattern: String,621622    /// Set the path separator to use when printing file paths. The default is623    /// the OS-specific separator ('/' on Unix, '\' on Windows).624    #[arg(625        long,626        value_name = "separator",627        hide_short_help = true,628        help = "Set path separator when printing file paths",629        long_help630    )]631    pub path_separator: Option<String>,632633    /// The directory where the filesystem search is rooted (optional). If634    /// omitted, search the current working directory.635    #[arg(action = ArgAction::Append,636        value_name = "path",637        help = "the root directories for the filesystem search (optional)",638        long_help,639        )]640    path: Vec<PathBuf>,641642    /// Provide paths to search as an alternative to the positional <path>643    /// argument. Changes the usage to `fd [OPTIONS] --search-path <path>644    /// --search-path <path2> [<pattern>]`645    #[arg(646        long,647        conflicts_with("path"),648        value_name = "search-path",649        hide_short_help = true,650        help = "Provides paths to search as an alternative to the positional <path> argument",651        long_help652    )]653    search_path: Vec<PathBuf>,654655    /// By default, relative paths are prefixed with './' when -x/--exec,656    /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a657    /// path starting with '-' being treated as a command line option. Use658    /// this flag to change this behavior. If this flag is used without a value,659    /// it is equivalent to passing "always".660    #[arg(long, conflicts_with_all(&["path", "search_path"]), value_name = "when", hide_short_help = true, require_equals = true, long_help)]661    strip_cwd_prefix: Option<Option<StripCwdWhen>>,662663    /// By default, fd will traverse the file system tree as far as other options664    /// dictate. With this flag, fd ensures that it does not descend into a665    /// different file system than the one it started in. Comparable to the -mount666    /// or -xdev filters of find(1).667    #[cfg(any(unix, windows))]668    #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]669    pub one_file_system: bool,670671    #[cfg(feature = "completions")]672    #[arg(long, hide = true, exclusive = true)]673    gen_completions: Option<Option<Shell>>,674}675676impl Opts {677    pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {678        // would it make sense to concatenate these?679        let paths = if !self.path.is_empty() {680            &self.path681        } else if !self.search_path.is_empty() {682            &self.search_path683        } else {684            let current_directory = Path::new("./");685            ensure_current_directory_exists(current_directory)?;686            return Ok(vec![self.normalize_path(current_directory)]);687        };688        Ok(paths689            .iter()690            .filter_map(|path| {691                if filesystem::is_existing_directory(path) {692                    Some(self.normalize_path(path))693                } else {694                    print_error(format!(695                        "Search path '{}' is not a directory.",696                        path.to_string_lossy()697                    ));698                    None699                }700            })701            .collect())702    }703704    fn normalize_path(&self, path: &Path) -> PathBuf {705        if self.absolute_path {706            filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()707        } else if path == Path::new(".") {708            // Change "." to "./" as a workaround for https://github.com/BurntSushi/ripgrep/pull/2711709            PathBuf::from("./")710        } else {711            path.to_path_buf()712        }713    }714715    pub fn no_search_paths(&self) -> bool {716        self.path.is_empty() && self.search_path.is_empty()717    }718719    #[inline]720    pub fn rg_alias_ignore(&self) -> bool {721        self.rg_alias_hidden_ignore > 0722    }723724    pub fn max_depth(&self) -> Option<usize> {725        self.max_depth.or(self.exact_depth)726    }727728    pub fn min_depth(&self) -> Option<usize> {729        self.min_depth.or(self.exact_depth)730    }731732    pub fn threads(&self) -> NonZeroUsize {733        self.threads.unwrap_or_else(default_num_threads)734    }735736    pub fn max_results(&self) -> Option<usize> {737        self.max_results738            .filter(|&m| m > 0)739            .or_else(|| self.max_one_result.then_some(1))740    }741742    pub fn strip_cwd_prefix<P: FnOnce() -> bool>(&self, auto_pred: P) -> bool {743        use self::StripCwdWhen::*;744        self.no_search_paths()745            && match self.strip_cwd_prefix.map_or(Auto, |o| o.unwrap_or(Always)) {746                Auto => auto_pred(),747                Always => true,748                Never => false,749            }750    }751752    #[cfg(feature = "completions")]753    pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {754        self.gen_completions755            .map(|maybe_shell| match maybe_shell {756                Some(sh) => Ok(sh),757                None => {758                    Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))759                }760            })761            .transpose()762    }763}764765/// Get the default number of threads to use, if not explicitly specified.766fn default_num_threads() -> NonZeroUsize {767    // If we can't get the amount of parallelism for some reason, then768    // default to a single thread, because that is safe.769    let fallback = NonZeroUsize::MIN;770    // To limit startup overhead on massively parallel machines, don't use more771    // than 64 threads.772    let limit = NonZeroUsize::new(64).unwrap();773774    std::thread::available_parallelism()775        .unwrap_or(fallback)776        .min(limit)777}778779#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]780pub enum FileType {781    #[value(alias = "f")]782    File,783    #[value(alias = "d", alias = "dir")]784    Directory,785    #[value(alias = "l")]786    Symlink,787    #[value(alias = "b")]788    BlockDevice,789    #[value(alias = "c")]790    CharDevice,791    /// A file which is executable by the current effective user792    #[value(alias = "x")]793    Executable,794    #[value(alias = "e")]795    Empty,796    #[value(alias = "s")]797    Socket,798    #[value(alias = "p")]799    Pipe,800}801802#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]803pub enum ColorWhen {804    /// show colors if the output goes to an interactive console (default)805    Auto,806    /// always use colorized output807    Always,808    /// do not use colorized output809    Never,810}811812#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]813pub enum StripCwdWhen {814    /// Use the default behavior815    Auto,816    /// Always strip the ./ at the beginning of paths817    Always,818    /// Never strip the ./819    Never,820}821822#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]823pub enum HyperlinkWhen {824    /// Use hyperlinks only if color is enabled825    Auto,826    /// Always use hyperlinks when printing file paths827    Always,828    /// Never use hyperlinks829    Never,830}831832// there isn't a derive api for getting grouped values yet,833// so we have to use hand-rolled parsing for exec and exec-batch834pub struct Exec {835    pub command: Option<CommandSet>,836}837838impl clap::FromArgMatches for Exec {839    fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {840        let command = matches841            .get_occurrences::<String>("exec")842            .map(CommandSet::new)843            .or_else(|| {844                matches845                    .get_occurrences::<String>("exec_batch")846                    .map(CommandSet::new_batch)847            })848            .transpose()849            .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;850        Ok(Exec { command })851    }852853    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {854        *self = Self::from_arg_matches(matches)?;855        Ok(())856    }857}858859impl clap::Args for Exec {860    fn augment_args(cmd: Command) -> Command {861        cmd.arg(Arg::new("exec")862            .action(ArgAction::Append)863            .long("exec")864            .short('x')865            .num_args(1..)866                .allow_hyphen_values(true)867                .value_terminator(";")868                .value_name("cmd")869                .conflicts_with("list_details")870                .help("Execute a command for each search result")871                .long_help(872                    "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \873                     There is no guarantee of the order commands are executed in, and the order should not be depended upon. \874                     All positional arguments following --exec are considered to be arguments to the command - not to fd. \875                     It is therefore recommended to place the '-x'/'--exec' option last. \876                     Use '\\;' to terminate the command template if you need to continue passing fd arguments afterwards.\n\877                     The following placeholders are substituted before the command is executed:\n  \878                       '{}':   path (of the current search result)\n  \879                       '{/}':  basename\n  \880                       '{//}': parent directory\n  \881                       '{.}':  path without file extension\n  \882                       '{/.}': basename without file extension\n  \883                       '{{':   literal '{' (for escaping)\n  \884                       '}}':   literal '}' (for escaping)\n\n\885                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\886                     Examples:\n\n  \887                       - find all *.zip files and unzip them:\n\n      \888                           fd -e zip -x unzip\n\n  \889                       - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n      \890                           fd -e h -e cpp -x clang-format -i\n\n  \891                       - search within `src/` and echo each match (place `-x` last):\n\n      \892                           fd . src -x echo\n\n  \893                       - Convert all *.jpg files to *.png files:\n\n      \894                           fd -e jpg -x convert {} {.}.png\895                    ",896                ),897        )898        .arg(899            Arg::new("exec_batch")900                .action(ArgAction::Append)901                .long("exec-batch")902                .short('X')903                .num_args(1..)904                .allow_hyphen_values(true)905                .value_terminator(";")906                .value_name("cmd")907                .conflicts_with_all(["exec", "list_details"])908                .help("Execute a command with all search results at once")909                .long_help(910                    "Execute the given command once, with all search results as arguments.\n\911                     The order of the arguments is non-deterministic, and should not be relied upon.\n\912                     One of the following placeholders is substituted before the command is executed:\n  \913                       '{}':   path (of all search results)\n  \914                       '{/}':  basename\n  \915                       '{//}': parent directory\n  \916                       '{.}':  path without file extension\n  \917                       '{/.}': basename without file extension\n  \918                       '{{':   literal '{' (for escaping)\n  \919                       '}}':   literal '}' (for escaping)\n\n\920                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\921                     Examples:\n\n  \922                       - Find all test_*.py files and open them in your favorite editor:\n\n      \923                           fd -g 'test_*.py' -X vim\n\n  \924                       - Find all *.rs files and count the lines with \"wc -l ...\":\n\n      \925                           fd -e rs -X wc -l\926                     "927                ),928        )929    }930931    fn augment_args_for_update(cmd: Command) -> Command {932        Self::augment_args(cmd)933    }934}935936fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {937    Ok(Duration::from_millis(arg.parse()?))938}939940fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {941    if filesystem::is_existing_directory(current_directory) {942        Ok(())943    } else {944        Err(anyhow!(945            "Could not retrieve current directory (has it been deleted?)."946        ))947    }948}