Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

895 lines · 31.7 KiB · Rust

Last changed by

Merge pull request #1412 from tmccombs/limit-default-threadsThayne McCombsbefore adoption95b4dff

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    error::ErrorKind, value_parser, Arg, ArgAction, ArgGroup, ArgMatches, Command, Parser,8    ValueEnum,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', the global ignore file,53    /// or the default rule that excludes .git/.54    /// The flag can be overridden with --ignore.55    #[arg(56        long,57        short = 'I',58        help = "Do not respect .(git|fd)ignore files",59        long_help60    )]61    pub no_ignore: bool,6263    /// Overrides --no-ignore64    #[arg(long, overrides_with = "no_ignore", hide = true, action = ArgAction::SetTrue)]65    ignore: (),6667    ///Show search results from '.git/' folders and files and directories that68    ///would otherwise be ignored by '.gitignore' files.69    ///The flag can be overridden with --ignore-vcs.70    #[arg(71        long,72        hide_short_help = true,73        help = "Do not respect .gitignore files",74        long_help75    )]76    pub no_ignore_vcs: bool,7778    /// Overrides --no-ignore-vcs79    #[arg(long, overrides_with = "no_ignore_vcs", hide = true, action = ArgAction::SetTrue)]80    ignore_vcs: (),8182    /// Do not require a git repository to respect gitignores.83    /// By default, fd will only respect global gitignore rules, .gitignore rules,84    /// and local exclude rules if fd detects that you are searching inside a85    /// git repository. This flag allows you to relax this restriction such that86    /// fd will respect all git related ignore rules regardless of whether you're87    /// searching in a git repository or not.88    ///89    ///90    /// This flag can be disabled with --require-git.91    #[arg(92        long,93        overrides_with = "require_git",94        hide_short_help = true,95        // same description as ripgrep's flag: ripgrep/crates/core/app.rs96        long_help97    )]98    pub no_require_git: bool,99100    /// Overrides --no-require-git101    #[arg(long, overrides_with = "no_require_git", hide = true, action = ArgAction::SetTrue)]102    require_git: (),103104    /// Show search results from files and directories that would otherwise be105    /// ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories.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    /// Do not respect the global ignore file115    #[arg(long, hide = true)]116    pub no_global_ignore_file: bool,117118    /// Perform an unrestricted search, including ignored and hidden files. This is119    /// an alias for '--no-ignore --hidden'.120    #[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,121    help = "Unrestricted search, alias for '--no-ignore --hidden'",122        long_help,123        )]124    rg_alias_hidden_ignore: u8,125126    /// Case-sensitive search (default: smart case)127    #[arg(128        long,129        short = 's',130        overrides_with("ignore_case"),131        long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \132                     searches, unless the pattern contains an uppercase character (smart \133                     case)."134    )]135    pub case_sensitive: bool,136137    /// Perform a case-insensitive search. By default, fd uses case-insensitive138    /// searches, unless the pattern contains an uppercase character (smart139    /// case).140    #[arg(141        long,142        short = 'i',143        overrides_with("case_sensitive"),144        help = "Case-insensitive search (default: smart case)",145        long_help146    )]147    pub ignore_case: bool,148149    /// Perform a glob-based search instead of a regular expression search.150    #[arg(151        long,152        short = 'g',153        conflicts_with("fixed_strings"),154        help = "Glob-based search (default: regular expression)",155        long_help156    )]157    pub glob: bool,158159    /// Perform a regular-expression based search (default). This can be used to160    /// override --glob.161    #[arg(162        long,163        overrides_with("glob"),164        hide_short_help = true,165        help = "Regular-expression based search (default)",166        long_help167    )]168    pub regex: bool,169170    /// Treat the pattern as a literal string instead of a regular expression. Note171    /// that this also performs substring comparison. If you want to match on an172    /// exact filename, consider using '--glob'.173    #[arg(174        long,175        short = 'F',176        alias = "literal",177        hide_short_help = true,178        help = "Treat pattern as literal string stead of regex",179        long_help180    )]181    pub fixed_strings: bool,182183    /// Add additional required search patterns, all of which must be matched. Multiple184    /// additional patterns can be specified. The patterns are regular185    /// expressions, unless '--glob' or '--fixed-strings' is used.186    #[arg(187        long = "and",188        value_name = "pattern",189        help = "Additional search patterns that need to be matched",190        long_help,191        hide_short_help = true,192        allow_hyphen_values = true193    )]194    pub exprs: Option<Vec<String>>,195196    /// Shows the full path starting from the root as opposed to relative paths.197    /// The flag can be overridden with --relative-path.198    #[arg(199        long,200        short = 'a',201        help = "Show absolute instead of relative paths",202        long_help203    )]204    pub absolute_path: bool,205206    /// Overrides --absolute-path207    #[arg(long, overrides_with = "absolute_path", hide = true, action = ArgAction::SetTrue)]208    relative_path: (),209210    /// Use a detailed listing format like 'ls -l'. This is basically an alias211    /// for '--exec-batch ls -l' with some additional 'ls' options. This can be212    /// used to see more metadata, to show symlink targets and to achieve a213    /// deterministic sort order.214    #[arg(215        long,216        short = 'l',217        conflicts_with("absolute_path"),218        help = "Use a long listing format with file metadata",219        long_help220    )]221    pub list_details: bool,222223    /// Follow symbolic links224    #[arg(225        long,226        short = 'L',227        alias = "dereference",228        long_help = "By default, fd does not descend into symlinked directories. Using this \229                     flag, symbolic links are also traversed. \230                     Flag can be overridden with --no-follow."231    )]232    pub follow: bool,233234    /// Overrides --follow235    #[arg(long, overrides_with = "follow", hide = true, action = ArgAction::SetTrue)]236    no_follow: (),237238    /// 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:239    ///   fd --glob -p '**/.git/config'240    #[arg(241        long,242        short = 'p',243        help = "Search full abs. path (default: filename only)",244        long_help,245        verbatim_doc_comment246    )]247    pub full_path: bool,248249    /// Separate search results by the null character (instead of newlines).250    /// Useful for piping results to 'xargs'.251    #[arg(252        long = "print0",253        short = '0',254        conflicts_with("list_details"),255        hide_short_help = true,256        help = "Separate search results by the null character",257        long_help258    )]259    pub null_separator: bool,260261    /// Limit the directory traversal to a given depth. By default, there is no262    /// limit on the search depth.263    #[arg(264        long,265        short = 'd',266        value_name = "depth",267        alias("maxdepth"),268        help = "Set maximum search depth (default: none)",269        long_help270    )]271    max_depth: Option<usize>,272273    /// Only show search results starting at the given depth.274    /// See also: '--max-depth' and '--exact-depth'275    #[arg(276        long,277        value_name = "depth",278        hide_short_help = true,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 '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), 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 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 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    #[command(flatten)]457    pub exec: Exec,458459    /// Maximum number of arguments to pass to the command given with -X.460    /// If the number of results is greater than the given size,461    /// the command given with -X is run again with remaining arguments.462    /// A batch size of zero means there is no limit (default), but note463    /// that batching might still happen due to OS restrictions on the464    /// maximum length of command lines.465    #[arg(466        long,467        value_name = "size",468        hide_short_help = true,469        requires("exec_batch"),470        value_parser = value_parser!(usize),471        default_value_t,472        help = "Max number of arguments to run as a batch size with -X",473        long_help,474    )]475    pub batch_size: usize,476477    /// Add a custom ignore-file in '.gitignore' format. These files have a low precedence.478    #[arg(479        long,480        value_name = "path",481        hide_short_help = true,482        help = "Add a custom ignore-file in '.gitignore' format",483        long_help484    )]485    pub ignore_file: Vec<PathBuf>,486487    /// Declare when to use color for the pattern match output488    #[arg(489        long,490        short = 'c',491        value_enum,492        default_value_t = ColorWhen::Auto,493        value_name = "when",494        help = "When to use colors",495        long_help,496    )]497    pub color: ColorWhen,498499    /// Set number of threads to use for searching & executing (default: number500    /// of available CPU cores)501    #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = str::parse::<NonZeroUsize>)]502    pub threads: Option<NonZeroUsize>,503504    /// Milliseconds to buffer before streaming search results to console505    ///506    /// Amount of time in milliseconds to buffer, before streaming the search507    /// results to the console.508    #[arg(long, hide = true, value_parser = parse_millis)]509    pub max_buffer_time: Option<Duration>,510511    ///Limit the number of search results to 'count' and quit immediately.512    #[arg(513        long,514        value_name = "count",515        hide_short_help = true,516        overrides_with("max_one_result"),517        help = "Limit the number of search results",518        long_help519    )]520    max_results: Option<usize>,521522    /// Limit the search to a single result and quit immediately.523    /// This is an alias for '--max-results=1'.524    #[arg(525        short = '1',526        hide_short_help = true,527        overrides_with("max_results"),528        help = "Limit search to a single result",529        long_help530    )]531    max_one_result: bool,532533    /// When the flag is present, the program does not print anything and will534    /// return with an exit code of 0 if there is at least one match. Otherwise, the535    /// exit code will be 1.536    /// '--has-results' can be used as an alias.537    #[arg(538        long,539        short = 'q',540        alias = "has-results",541        hide_short_help = true,542        conflicts_with("max_results"),543        help = "Print nothing, exit code 0 if match found, 1 otherwise",544        long_help545    )]546    pub quiet: bool,547548    /// Enable the display of filesystem errors for situations such as549    /// insufficient permissions or dead symlinks.550    #[arg(551        long,552        hide_short_help = true,553        help = "Show filesystem errors",554        long_help555    )]556    pub show_errors: bool,557558    /// Change the current working directory of fd to the provided path. This559    /// means that search results will be shown with respect to the given base560    /// path. Note that relative paths which are passed to fd via the positional561    /// <path> argument or the '--search-path' option will also be resolved562    /// relative to this directory.563    #[arg(564        long,565        value_name = "path",566        hide_short_help = true,567        help = "Change current working directory",568        long_help569    )]570    pub base_directory: Option<PathBuf>,571572    /// the search pattern which is either a regular expression (default) or a glob573    /// pattern (if --glob is used). If no pattern has been specified, every entry574    /// is considered a match. If your pattern starts with a dash (-), make sure to575    /// pass '--' first, or it will be considered as a flag (fd -- '-foo').576    #[arg(577        default_value = "",578        hide_default_value = true,579        value_name = "pattern",580        help = "the search pattern (a regular expression, unless '--glob' is used; optional)",581        long_help582    )]583    pub pattern: String,584585    /// Set the path separator to use when printing file paths. The default is586    /// the OS-specific separator ('/' on Unix, '\' on Windows).587    #[arg(588        long,589        value_name = "separator",590        hide_short_help = true,591        help = "Set path separator when printing file paths",592        long_help593    )]594    pub path_separator: Option<String>,595596    /// The directory where the filesystem search is rooted (optional). If597    /// omitted, search the current working directory.598    #[arg(action = ArgAction::Append,599        value_name = "path",600        help = "the root directories for the filesystem search (optional)",601        long_help,602        )]603    path: Vec<PathBuf>,604605    /// Provide paths to search as an alternative to the positional <path>606    /// argument. Changes the usage to `fd [OPTIONS] --search-path <path>607    /// --search-path <path2> [<pattern>]`608    #[arg(609        long,610        conflicts_with("path"),611        value_name = "search-path",612        hide_short_help = true,613        help = "Provides paths to search as an alternative to the positional <path> argument",614        long_help615    )]616    search_path: Vec<PathBuf>,617618    /// By default, relative paths are prefixed with './' when -x/--exec,619    /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a620    /// path starting with '-' being treated as a command line option. Use621    /// this flag to disable this behaviour.622    #[arg(long, conflicts_with_all(&["path", "search_path"]), hide_short_help = true, long_help)]623    pub strip_cwd_prefix: bool,624625    /// By default, fd will traverse the file system tree as far as other options626    /// dictate. With this flag, fd ensures that it does not descend into a627    /// different file system than the one it started in. Comparable to the -mount628    /// or -xdev filters of find(1).629    #[cfg(any(unix, windows))]630    #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]631    pub one_file_system: bool,632633    #[cfg(feature = "completions")]634    #[arg(long, hide = true, exclusive = true)]635    gen_completions: Option<Option<Shell>>,636}637638impl Opts {639    pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {640        // would it make sense to concatenate these?641        let paths = if !self.path.is_empty() {642            &self.path643        } else if !self.search_path.is_empty() {644            &self.search_path645        } else {646            let current_directory = Path::new(".");647            ensure_current_directory_exists(current_directory)?;648            return Ok(vec![self.normalize_path(current_directory)]);649        };650        Ok(paths651            .iter()652            .filter_map(|path| {653                if filesystem::is_existing_directory(path) {654                    Some(self.normalize_path(path))655                } else {656                    print_error(format!(657                        "Search path '{}' is not a directory.",658                        path.to_string_lossy()659                    ));660                    None661                }662            })663            .collect())664    }665666    fn normalize_path(&self, path: &Path) -> PathBuf {667        if self.absolute_path {668            filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()669        } else {670            path.to_path_buf()671        }672    }673674    pub fn no_search_paths(&self) -> bool {675        self.path.is_empty() && self.search_path.is_empty()676    }677678    #[inline]679    pub fn rg_alias_ignore(&self) -> bool {680        self.rg_alias_hidden_ignore > 0681    }682683    pub fn max_depth(&self) -> Option<usize> {684        self.max_depth.or(self.exact_depth)685    }686687    pub fn min_depth(&self) -> Option<usize> {688        self.min_depth.or(self.exact_depth)689    }690691    pub fn threads(&self) -> NonZeroUsize {692        self.threads.unwrap_or_else(default_num_threads)693    }694695    pub fn max_results(&self) -> Option<usize> {696        self.max_results697            .filter(|&m| m > 0)698            .or_else(|| self.max_one_result.then_some(1))699    }700701    #[cfg(feature = "completions")]702    pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {703        self.gen_completions704            .map(|maybe_shell| match maybe_shell {705                Some(sh) => Ok(sh),706                None => {707                    Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))708                }709            })710            .transpose()711    }712}713714/// Get the default number of threads to use, if not explicitly specified.715fn default_num_threads() -> NonZeroUsize {716    // If we can't get the amount of parallelism for some reason, then717    // default to a single thread, because that is safe.718    // Note that the minimum value for a NonZeroUsize is 1.719    // Unfortunately, we can't do `NonZeroUsize::new(1).unwrap()`720    // in a const context.721    const FALLBACK_PARALLELISM: NonZeroUsize = NonZeroUsize::MIN;722    // As the number of threads increases, the startup time suffers from723    // initializing the threads, and we get diminishing returns from additional724    // parallelism. So set a maximum number of threads to use by default.725    //726    // This value is based on some empirical observations, but the ideal value727    // probably depends on the exact hardware in use.728    //729    // Safety: The literal "20" is known not to be zero.730    const MAX_DEFAULT_THREADS: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(20) };731732    std::cmp::min(733        std::thread::available_parallelism().unwrap_or(FALLBACK_PARALLELISM),734        MAX_DEFAULT_THREADS,735    )736}737738#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]739pub enum FileType {740    #[value(alias = "f")]741    File,742    #[value(alias = "d")]743    Directory,744    #[value(alias = "l")]745    Symlink,746    #[value(alias = "b")]747    BlockDevice,748    #[value(alias = "c")]749    CharDevice,750    /// A file which is executable by the current effective user751    #[value(alias = "x")]752    Executable,753    #[value(alias = "e")]754    Empty,755    #[value(alias = "s")]756    Socket,757    #[value(alias = "p")]758    Pipe,759}760761#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]762pub enum ColorWhen {763    /// show colors if the output goes to an interactive console (default)764    Auto,765    /// always use colorized output766    Always,767    /// do not use colorized output768    Never,769}770771impl ColorWhen {772    pub fn as_str(&self) -> &'static str {773        use ColorWhen::*;774        match *self {775            Auto => "auto",776            Never => "never",777            Always => "always",778        }779    }780}781782// there isn't a derive api for getting grouped values yet,783// so we have to use hand-rolled parsing for exec and exec-batch784pub struct Exec {785    pub command: Option<CommandSet>,786}787788impl clap::FromArgMatches for Exec {789    fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {790        let command = matches791            .get_occurrences::<String>("exec")792            .map(CommandSet::new)793            .or_else(|| {794                matches795                    .get_occurrences::<String>("exec_batch")796                    .map(CommandSet::new_batch)797            })798            .transpose()799            .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;800        Ok(Exec { command })801    }802803    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {804        *self = Self::from_arg_matches(matches)?;805        Ok(())806    }807}808809impl clap::Args for Exec {810    fn augment_args(cmd: Command) -> Command {811        cmd.arg(Arg::new("exec")812            .action(ArgAction::Append)813            .long("exec")814            .short('x')815            .num_args(1..)816                .allow_hyphen_values(true)817                .value_terminator(";")818                .value_name("cmd")819                .conflicts_with("list_details")820                .help("Execute a command for each search result")821                .long_help(822                    "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \823                     There is no guarantee of the order commands are executed in, and the order should not be depended upon. \824                     All positional arguments following --exec are considered to be arguments to the command - not to fd. \825                     It is therefore recommended to place the '-x'/'--exec' option last.\n\826                     The following placeholders are substituted before the command is executed:\n  \827                       '{}':   path (of the current search result)\n  \828                       '{/}':  basename\n  \829                       '{//}': parent directory\n  \830                       '{.}':  path without file extension\n  \831                       '{/.}': basename without file extension\n  \832                       '{{':   literal '{' (for escaping)\n  \833                       '}}':   literal '}' (for escaping)\n\n\834                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\835                     Examples:\n\n  \836                       - find all *.zip files and unzip them:\n\n      \837                           fd -e zip -x unzip\n\n  \838                       - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n      \839                           fd -e h -e cpp -x clang-format -i\n\n  \840                       - Convert all *.jpg files to *.png files:\n\n      \841                           fd -e jpg -x convert {} {.}.png\842                    ",843                ),844        )845        .arg(846            Arg::new("exec_batch")847                .action(ArgAction::Append)848                .long("exec-batch")849                .short('X')850                .num_args(1..)851                .allow_hyphen_values(true)852                .value_terminator(";")853                .value_name("cmd")854                .conflicts_with_all(["exec", "list_details"])855                .help("Execute a command with all search results at once")856                .long_help(857                    "Execute the given command once, with all search results as arguments.\n\858                     The order of the arguments is non-deterministic, and should not be relied upon.\n\859                     One of the following placeholders is substituted before the command is executed:\n  \860                       '{}':   path (of all search results)\n  \861                       '{/}':  basename\n  \862                       '{//}': parent directory\n  \863                       '{.}':  path without file extension\n  \864                       '{/.}': basename without file extension\n  \865                       '{{':   literal '{' (for escaping)\n  \866                       '}}':   literal '}' (for escaping)\n\n\867                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\868                     Examples:\n\n  \869                       - Find all test_*.py files and open them in your favorite editor:\n\n      \870                           fd -g 'test_*.py' -X vim\n\n  \871                       - Find all *.rs files and count the lines with \"wc -l ...\":\n\n      \872                           fd -e rs -X wc -l\873                     "874                ),875        )876    }877878    fn augment_args_for_update(cmd: Command) -> Command {879        Self::augment_args(cmd)880    }881}882883fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {884    Ok(Duration::from_millis(arg.parse()?))885}886887fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {888    if filesystem::is_existing_directory(current_directory) {889        Ok(())890    } else {891        Err(anyhow!(892            "Could not retrieve current directory (has it been deleted?)."893        ))894    }895}