Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

861 lines · 30.1 KiB · Rust

Last changed by

Merge pull request #1244 from tmccombs/grouped-occurrencesDavid Peterbefore adoption73a693e

History of this file

Take it

1use std::path::{Path, PathBuf};2use std::time::Duration;34use anyhow::anyhow;5use clap::{6    error::ErrorKind, value_parser, Arg, ArgAction, ArgGroup, ArgMatches, Command, Parser,7    ValueEnum,8};9#[cfg(feature = "completions")]10use clap_complete::Shell;11use normpath::PathExt;1213use crate::error::print_error;14use crate::exec::CommandSet;15use crate::filesystem;16#[cfg(unix)]17use crate::filter::OwnerFilter;18use crate::filter::SizeFilter;1920#[derive(Parser)]21#[command(22    name = "fd",23    version,24    about = "A program to find entries in your filesystem",25    after_long_help = "Bugs can be reported on GitHub: https://github.com/sharkdp/fd/issues",26    max_term_width = 98,27    args_override_self = true,28    group(ArgGroup::new("execs").args(&["exec", "exec_batch", "list_details"]).conflicts_with_all(&[29            "max_results", "has_results", "count"])),30)]31pub struct Opts {32    /// Include hidden directories and files in the search results (default:33    /// hidden files and directories are skipped). Files and directories are34    /// considered to be hidden if their name starts with a `.` sign (dot).35    /// The flag can be overridden with --no-hidden.36    #[arg(37        long,38        short = 'H',39        help = "Search hidden files and directories",40        long_help41    )]42    pub hidden: bool,4344    /// Overrides --hidden45    #[arg(long, overrides_with = "hidden", hide = true, action = ArgAction::SetTrue)]46    no_hidden: (),4748    /// Show search results from files and directories that would otherwise be49    /// ignored by '.gitignore', '.ignore', '.fdignore', or the global ignore file.50    /// The flag can be overridden with --ignore.51    #[arg(52        long,53        short = 'I',54        help = "Do not respect .(git|fd)ignore files",55        long_help56    )]57    pub no_ignore: bool,5859    /// Overrides --no-ignore60    #[arg(long, overrides_with = "no_ignore", hide = true, action = ArgAction::SetTrue)]61    ignore: (),6263    ///Show search results from files and directories that would otherwise be64    /// ignored by '.gitignore' files. The flag can be overridden with --ignore-vcs.65    #[arg(66        long,67        hide_short_help = true,68        help = "Do not respect .gitignore files",69        long_help70    )]71    pub no_ignore_vcs: bool,7273    /// Overrides --no-ignore-vcs74    #[arg(long, overrides_with = "no_ignore_vcs", hide = true, action = ArgAction::SetTrue)]75    ignore_vcs: (),7677    /// Do not require a git repository to respect gitignores.78    /// By default, fd will only respect global gitignore rules, .gitignore rules,79    /// and local exclude rules if fd detects that you are searching inside a80    /// git repository. This flag allows you to relax this restriction such that81    /// fd will respect all git related ignore rules regardless of whether you're82    /// searching in a git repository or not.83    ///84    ///85    /// This flag can be disabled with --require-git.86    #[arg(87        long,88        overrides_with = "require_git",89        hide_short_help = true,90        // same description as ripgrep's flag: ripgrep/crates/core/app.rs91        long_help92    )]93    pub no_require_git: bool,9495    /// Overrides --no-require-git96    #[arg(long, overrides_with = "no_require_git", hide = true, action = ArgAction::SetTrue)]97    require_git: (),9899    /// Show search results from files and directories that would otherwise be100    /// ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories.101    #[arg(102        long,103        hide_short_help = true,104        help = "Do not respect .(git|fd)ignore files in parent directories",105        long_help106    )]107    pub no_ignore_parent: bool,108109    /// Do not respect the global ignore file110    #[arg(long, hide = true)]111    pub no_global_ignore_file: bool,112113    /// Perform an unrestricted search, including ignored and hidden files. This is114    /// an alias for '--no-ignore --hidden'.115    #[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,116    help = "Unrestricted search, alias for '--no-ignore --hidden'",117        long_help,118        )]119    rg_alias_hidden_ignore: u8,120121    /// Case-sensitive search (default: smart case)122    #[arg(123        long,124        short = 's',125        overrides_with("ignore_case"),126        long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \127                     searches, unless the pattern contains an uppercase character (smart \128                     case)."129    )]130    pub case_sensitive: bool,131132    /// Perform a case-insensitive search. By default, fd uses case-insensitive133    /// searches, unless the pattern contains an uppercase character (smart134    /// case).135    #[arg(136        long,137        short = 'i',138        overrides_with("case_sensitive"),139        help = "Case-insensitive search (default: smart case)",140        long_help141    )]142    pub ignore_case: bool,143144    /// Perform a glob-based search instead of a regular expression search.145    #[arg(146        long,147        short = 'g',148        conflicts_with("fixed_strings"),149        help = "Glob-based search (default: regular expression)",150        long_help151    )]152    pub glob: bool,153154    /// Perform a regular-expression based search (default). This can be used to155    /// override --glob.156    #[arg(157        long,158        overrides_with("glob"),159        hide_short_help = true,160        help = "Regular-expression based search (default)",161        long_help162    )]163    pub regex: bool,164165    /// Treat the pattern as a literal string instead of a regular expression. Note166    /// that this also performs substring comparison. If you want to match on an167    /// exact filename, consider using '--glob'.168    #[arg(169        long,170        short = 'F',171        alias = "literal",172        hide_short_help = true,173        help = "Treat pattern as literal string stead of regex",174        long_help175    )]176    pub fixed_strings: bool,177178    /// Add additional required search patterns, all of which must be matched. Multiple179    /// additional patterns can be specified. The patterns are regular180    /// expressions, unless '--glob' or '--fixed-strings' is used.181    #[arg(182        long = "and",183        value_name = "pattern",184        help = "Additional search patterns that need to be matched",185        long_help,186        hide_short_help = true,187        allow_hyphen_values = true188    )]189    pub exprs: Option<Vec<String>>,190191    /// Shows the full path starting from the root as opposed to relative paths.192    /// The flag can be overridden with --relative-path.193    #[arg(194        long,195        short = 'a',196        help = "Show absolute instead of relative paths",197        long_help198    )]199    pub absolute_path: bool,200201    /// Overrides --absolute-path202    #[arg(long, overrides_with = "absolute_path", hide = true, action = ArgAction::SetTrue)]203    relative_path: (),204205    /// Use a detailed listing format like 'ls -l'. This is basically an alias206    /// for '--exec-batch ls -l' with some additional 'ls' options. This can be207    /// used to see more metadata, to show symlink targets and to achieve a208    /// deterministic sort order.209    #[arg(210        long,211        short = 'l',212        conflicts_with("absolute_path"),213        help = "Use a long listing format with file metadata",214        long_help215    )]216    pub list_details: bool,217218    /// Follow symbolic links219    #[arg(220        long,221        short = 'L',222        alias = "dereference",223        long_help = "By default, fd does not descend into symlinked directories. Using this \224                     flag, symbolic links are also traversed. \225                     Flag can be overriden with --no-follow."226    )]227    pub follow: bool,228229    /// Overrides --follow230    #[arg(long, overrides_with = "follow", hide = true, action = ArgAction::SetTrue)]231    no_follow: (),232233    /// 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:234    ///   fd --glob -p '**/.git/config'235    #[arg(236        long,237        short = 'p',238        help = "Search full abs. path (default: filename only)",239        long_help,240        verbatim_doc_comment241    )]242    pub full_path: bool,243244    /// Separate search results by the null character (instead of newlines).245    /// Useful for piping results to 'xargs'.246    #[arg(247        long = "print0",248        short = '0',249        conflicts_with("list_details"),250        hide_short_help = true,251        help = "Separate search results by the null character",252        long_help253    )]254    pub null_separator: bool,255256    /// Limit the directory traversal to a given depth. By default, there is no257    /// limit on the search depth.258    #[arg(259        long,260        short = 'd',261        value_name = "depth",262        alias("maxdepth"),263        help = "Set maximum search depth (default: none)",264        long_help265    )]266    max_depth: Option<usize>,267268    /// Only show search results starting at the given depth.269    /// See also: '--max-depth' and '--exact-depth'270    #[arg(271        long,272        value_name = "depth",273        hide_short_help = true,274        help = "Only show search results starting at the given depth.",275        long_help276    )]277    min_depth: Option<usize>,278279    /// Only show search results at the exact given depth. This is an alias for280    /// '--min-depth <depth> --max-depth <depth>'.281    #[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),282    help = "Only show search results at the exact given depth",283        long_help,284        )]285    exact_depth: Option<usize>,286287    /// Exclude files/directories that match the given glob pattern. This288    /// overrides any other ignore logic. Multiple exclude patterns can be289    /// specified.290    ///291    /// Examples:292    /// {n}  --exclude '*.pyc'293    /// {n}  --exclude node_modules294    #[arg(295        long,296        short = 'E',297        value_name = "pattern",298        help = "Exclude entries that match the given glob pattern",299        long_help300    )]301    pub exclude: Vec<String>,302303    /// Do not traverse into directories that match the search criteria. If304    /// you want to exclude specific directories, use the '--exclude=…' option.305    #[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),306        long_help,307        )]308    pub prune: bool,309310    /// Filter the search by type:311    /// {n}  'f' or 'file':         regular files312    /// {n}  'd' or 'directory':    directories313    /// {n}  'l' or 'symlink':      symbolic links314    /// {n}  's' or 'socket':       socket315    /// {n}  'p' or 'pipe':         named pipe (FIFO)316    /// {n}{n}  'x' or 'executable':   executables317    /// {n}  'e' or 'empty':        empty files or directories318    ///319    /// This option can be specified more than once to include multiple file types.320    /// Searching for '--type file --type symlink' will show both regular files as321    /// well as symlinks. Note that the 'executable' and 'empty' filters work differently:322    /// '--type executable' implies '--type file' by default. And '--type empty' searches323    /// for empty files and directories, unless either '--type file' or '--type directory'324    /// is specified in addition.325    ///326    /// Examples:327    /// {n}  - Only search for files:328    /// {n}      fd --type file …329    /// {n}      fd -tf …330    /// {n}  - Find both files and symlinks331    /// {n}      fd --type file --type symlink …332    /// {n}      fd -tf -tl …333    /// {n}  - Find executable files:334    /// {n}      fd --type executable335    /// {n}      fd -tx336    /// {n}  - Find empty files:337    /// {n}      fd --type empty --type file338    /// {n}      fd -te -tf339    /// {n}  - Find empty directories:340    /// {n}      fd --type empty --type directory341    /// {n}      fd -te -td342    #[arg(343        long = "type",344        short = 't',345        value_name = "filetype",346        hide_possible_values = true,347        value_enum,348        help = "Filter by type: file (f), directory (d), symlink (l), \349                executable (x), empty (e), socket (s), pipe (p)",350        long_help351    )]352    pub filetype: Option<Vec<FileType>>,353354    /// (Additionally) filter search results by their file extension. Multiple355    /// allowable file extensions can be specified.356    ///357    /// If you want to search for files without extension,358    /// you can use the regex '^[^.]+$' as a normal search pattern.359    #[arg(360        long = "extension",361        short = 'e',362        value_name = "ext",363        help = "Filter by file extension",364        long_help365    )]366    pub extensions: Option<Vec<String>>,367368    /// Limit results based on the size of files using the format <+-><NUM><UNIT>.369    ///    '+': file size must be greater than or equal to this370    ///    '-': file size must be less than or equal to this371    ///372    /// If neither '+' nor '-' is specified, file size must be exactly equal to this.373    ///    'NUM':  The numeric size (e.g. 500)374    ///    'UNIT': The units for NUM. They are not case-sensitive.375    /// Allowed unit values:376    ///     'b':  bytes377    ///     'k':  kilobytes (base ten, 10^3 = 1000 bytes)378    ///     'm':  megabytes379    ///     'g':  gigabytes380    ///     't':  terabytes381    ///     'ki': kibibytes (base two, 2^10 = 1024 bytes)382    ///     'mi': mebibytes383    ///     'gi': gibibytes384    ///     'ti': tebibytes385    #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",386        help = "Limit results based on the size of files",387        long_help,388        verbatim_doc_comment,389        )]390    pub size: Vec<SizeFilter>,391392    /// Filter results based on the file modification time. Files with modification times393    /// greater than the argument are returned. The argument can be provided394    /// as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min).395    /// If the time is not specified, it defaults to 00:00:00.396    /// '--change-newer-than', '--newer', or '--changed-after' can be used as aliases.397    ///398    /// Examples:399    /// {n}    --changed-within 2weeks400    /// {n}    --change-newer-than '2018-10-27 10:00:00'401    /// {n}    --newer 2018-10-27402    /// {n}    --changed-after 1day403    #[arg(404        long,405        alias("change-newer-than"),406        alias("newer"),407        alias("changed-after"),408        value_name = "date|dur",409        help = "Filter by file modification time (newer than)",410        long_help411    )]412    pub changed_within: Option<String>,413414    /// Filter results based on the file modification time. Files with modification times415    /// less than the argument are returned. The argument can be provided416    /// as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min).417    /// '--change-older-than' or '--older' can be used as aliases.418    ///419    /// Examples:420    /// {n}    --changed-before '2018-10-27 10:00:00'421    /// {n}    --change-older-than 2weeks422    /// {n}    --older 2018-10-27423    #[arg(424        long,425        alias("change-older-than"),426        alias("older"),427        value_name = "date|dur",428        help = "Filter by file modification time (older than)",429        long_help430    )]431    pub changed_before: Option<String>,432433    /// Filter files by their user and/or group.434    /// Format: [(user|uid)][:(group|gid)]. Either side is optional.435    /// Precede either side with a '!' to exclude files instead.436    ///437    /// Examples:438    /// {n}    --owner john439    /// {n}    --owner :students440    /// {n}    --owner '!john:students'441    #[cfg(unix)]442    #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",443        help = "Filter by owning user and/or group",444        long_help,445        )]446    pub owner: Option<OwnerFilter>,447448    #[command(flatten)]449    pub exec: Exec,450451    /// Maximum number of arguments to pass to the command given with -X.452    /// If the number of results is greater than the given size,453    /// the command given with -X is run again with remaining arguments.454    /// A batch size of zero means there is no limit (default), but note455    /// that batching might still happen due to OS restrictions on the456    /// maximum length of command lines.457    #[arg(458        long,459        value_name = "size",460        hide_short_help = true,461        requires("exec_batch"),462        value_parser = value_parser!(usize),463        default_value_t,464        help = "Max number of arguments to run as a batch size with -X",465        long_help,466    )]467    pub batch_size: usize,468469    /// Add a custom ignore-file in '.gitignore' format. These files have a low precedence.470    #[arg(471        long,472        value_name = "path",473        hide_short_help = true,474        help = "Add a custom ignore-file in '.gitignore' format",475        long_help476    )]477    pub ignore_file: Vec<PathBuf>,478479    /// Declare when to use color for the pattern match output480    #[arg(481        long,482        short = 'c',483        value_enum,484        default_value_t = ColorWhen::Auto,485        value_name = "when",486        help = "When to use colors",487        long_help,488    )]489    pub color: ColorWhen,490491    /// Set number of threads to use for searching & executing (default: number492    /// of available CPU cores)493    #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = clap::value_parser!(u32).range(1..))]494    pub threads: Option<u32>,495496    /// Milliseconds to buffer before streaming search results to console497    ///498    /// Amount of time in milliseconds to buffer, before streaming the search499    /// results to the console.500    #[arg(long, hide = true, value_parser = parse_millis)]501    pub max_buffer_time: Option<Duration>,502503    ///Limit the number of search results to 'count' and quit immediately.504    #[arg(505        long,506        value_name = "count",507        hide_short_help = true,508        help = "Limit the number of search results",509        long_help510    )]511    max_results: Option<usize>,512513    /// Limit the search to a single result and quit immediately.514    /// This is an alias for '--max-results=1'.515    #[arg(516        short = '1',517        hide_short_help = true,518        overrides_with("max_results"),519        help = "Limit search to a single result",520        long_help521    )]522    max_one_result: bool,523524    /// When the flag is present, the program does not print anything and will525    /// return with an exit code of 0 if there is at least one match. Otherwise, the526    /// exit code will be 1.527    /// '--has-results' can be used as an alias.528    #[arg(529        long,530        short = 'q',531        alias = "has-results",532        hide_short_help = true,533        conflicts_with("max_results"),534        help = "Print nothing, exit code 0 if match found, 1 otherwise",535        long_help536    )]537    pub quiet: bool,538539    /// Enable the display of filesystem errors for situations such as540    /// insufficient permissions or dead symlinks.541    #[arg(542        long,543        hide_short_help = true,544        help = "Show filesystem errors",545        long_help546    )]547    pub show_errors: bool,548549    /// Change the current working directory of fd to the provided path. This550    /// means that search results will be shown with respect to the given base551    /// path. Note that relative paths which are passed to fd via the positional552    /// <path> argument or the '--search-path' option will also be resolved553    /// relative to this directory.554    #[arg(555        long,556        value_name = "path",557        hide_short_help = true,558        help = "Change current working directory",559        long_help560    )]561    pub base_directory: Option<PathBuf>,562563    /// the search pattern which is either a regular expression (default) or a glob564    /// pattern (if --glob is used). If no pattern has been specified, every entry565    /// is considered a match. If your pattern starts with a dash (-), make sure to566    /// pass '--' first, or it will be considered as a flag (fd -- '-foo').567    #[arg(568        default_value = "",569        hide_default_value = true,570        value_name = "pattern",571        help = "the search pattern (a regular expression, unless '--glob' is used; optional)",572        long_help573    )]574    pub pattern: String,575576    /// Set the path separator to use when printing file paths. The default is577    /// the OS-specific separator ('/' on Unix, '\' on Windows).578    #[arg(579        long,580        value_name = "separator",581        hide_short_help = true,582        help = "Set path separator when printing file paths",583        long_help584    )]585    pub path_separator: Option<String>,586587    /// The directory where the filesystem search is rooted (optional). If588    /// omitted, search the current working directory.589    #[arg(action = ArgAction::Append,590        value_name = "path",591        help = "the root directories for the filesystem search (optional)",592        long_help,593        )]594    path: Vec<PathBuf>,595596    /// Provide paths to search as an alternative to the positional <path>597    /// argument. Changes the usage to `fd [OPTIONS] --search-path <path>598    /// --search-path <path2> [<pattern>]`599    #[arg(600        long,601        conflicts_with("path"),602        value_name = "search-path",603        hide_short_help = true,604        help = "Provides paths to search as an alternative to the positional <path> argument",605        long_help606    )]607    search_path: Vec<PathBuf>,608609    /// By default, relative paths are prefixed with './' when -x/--exec,610    /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a611    /// path starting with '-' being treated as a command line option. Use612    /// this flag to disable this behaviour.613    #[arg(long, conflicts_with_all(&["path", "search_path"]), hide_short_help = true, long_help)]614    pub strip_cwd_prefix: bool,615616    /// By default, fd will traverse the file system tree as far as other options617    /// dictate. With this flag, fd ensures that it does not descend into a618    /// different file system than the one it started in. Comparable to the -mount619    /// or -xdev filters of find(1).620    #[cfg(any(unix, windows))]621    #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]622    pub one_file_system: bool,623624    #[cfg(feature = "completions")]625    #[arg(long, hide = true, exclusive = true)]626    gen_completions: Option<Option<Shell>>,627}628629impl Opts {630    pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {631        // would it make sense to concatenate these?632        let paths = if !self.path.is_empty() {633            &self.path634        } else if !self.search_path.is_empty() {635            &self.search_path636        } else {637            let current_directory = Path::new(".");638            ensure_current_directory_exists(current_directory)?;639            return Ok(vec![self.normalize_path(current_directory)]);640        };641        Ok(paths642            .iter()643            .filter_map(|path| {644                if filesystem::is_existing_directory(path) {645                    Some(self.normalize_path(path))646                } else {647                    print_error(format!(648                        "Search path '{}' is not a directory.",649                        path.to_string_lossy()650                    ));651                    None652                }653            })654            .collect())655    }656657    fn normalize_path(&self, path: &Path) -> PathBuf {658        if self.absolute_path {659            filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()660        } else {661            path.to_path_buf()662        }663    }664665    pub fn no_search_paths(&self) -> bool {666        self.path.is_empty() && self.search_path.is_empty()667    }668669    #[inline]670    pub fn rg_alias_ignore(&self) -> bool {671        self.rg_alias_hidden_ignore > 0672    }673674    pub fn max_depth(&self) -> Option<usize> {675        self.max_depth.or(self.exact_depth)676    }677678    pub fn min_depth(&self) -> Option<usize> {679        self.min_depth.or(self.exact_depth)680    }681682    pub fn threads(&self) -> usize {683        // This will panic if the number of threads passed in is more than usize::MAX in an environment684        // where usize is less than 32 bits (for example 16-bit architectures). It's pretty685        // unlikely fd will be running in such an environment, and even more unlikely someone would686        // be trying to use that many threads on such an environment, so I think panicing is an687        // appropriate way to handle that.688        std::cmp::max(689            self.threads690                .map_or_else(num_cpus::get, |n| n.try_into().expect("too many threads")),691            1,692        )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(|| 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#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]715pub enum FileType {716    #[value(alias = "f")]717    File,718    #[value(alias = "d")]719    Directory,720    #[value(alias = "l")]721    Symlink,722    /// A file which is executable by the current effective user723    #[value(alias = "x")]724    Executable,725    #[value(alias = "e")]726    Empty,727    #[value(alias = "s")]728    Socket,729    #[value(alias = "p")]730    Pipe,731}732733#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]734pub enum ColorWhen {735    /// show colors if the output goes to an interactive console (default)736    Auto,737    /// always use colorized output738    Always,739    /// do not use colorized output740    Never,741}742743impl ColorWhen {744    pub fn as_str(&self) -> &'static str {745        use ColorWhen::*;746        match *self {747            Auto => "auto",748            Never => "never",749            Always => "always",750        }751    }752}753754// there isn't a derive api for getting grouped values yet,755// so we have to use hand-rolled parsing for exec and exec-batch756pub struct Exec {757    pub command: Option<CommandSet>,758}759760impl clap::FromArgMatches for Exec {761    fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {762        let command = matches763            .get_occurrences::<String>("exec")764            .map(CommandSet::new)765            .or_else(|| {766                matches767                    .get_occurrences::<String>("exec_batch")768                    .map(CommandSet::new_batch)769            })770            .transpose()771            .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;772        Ok(Exec { command })773    }774775    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {776        *self = Self::from_arg_matches(matches)?;777        Ok(())778    }779}780781impl clap::Args for Exec {782    fn augment_args(cmd: Command) -> Command {783        cmd.arg(Arg::new("exec")784            .action(ArgAction::Append)785            .long("exec")786            .short('x')787            .num_args(1..)788                .allow_hyphen_values(true)789                .value_terminator(";")790                .value_name("cmd")791                .conflicts_with("list_details")792                .help("Execute a command for each search result")793                .long_help(794                    "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \795                     All positional arguments following --exec are considered to be arguments to the command - not to fd. \796                     It is therefore recommended to place the '-x'/'--exec' option last.\n\797                     The following placeholders are substituted before the command is executed:\n  \798                       '{}':   path (of the current search result)\n  \799                       '{/}':  basename\n  \800                       '{//}': parent directory\n  \801                       '{.}':  path without file extension\n  \802                       '{/.}': basename without file extension\n\n\803                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\804                     Examples:\n\n  \805                       - find all *.zip files and unzip them:\n\n      \806                           fd -e zip -x unzip\n\n  \807                       - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n      \808                           fd -e h -e cpp -x clang-format -i\n\n  \809                       - Convert all *.jpg files to *.png files:\n\n      \810                           fd -e jpg -x convert {} {.}.png\811                    ",812                ),813        )814        .arg(815            Arg::new("exec_batch")816                .action(ArgAction::Append)817                .long("exec-batch")818                .short('X')819                .num_args(1..)820                .allow_hyphen_values(true)821                .value_terminator(";")822                .value_name("cmd")823                .conflicts_with_all(["exec", "list_details"])824                .help("Execute a command with all search results at once")825                .long_help(826                    "Execute the given command once, with all search results as arguments.\n\827                     One of the following placeholders is substituted before the command is executed:\n  \828                       '{}':   path (of all search results)\n  \829                       '{/}':  basename\n  \830                       '{//}': parent directory\n  \831                       '{.}':  path without file extension\n  \832                       '{/.}': basename without file extension\n\n\833                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\834                     Examples:\n\n  \835                       - Find all test_*.py files and open them in your favorite editor:\n\n      \836                           fd -g 'test_*.py' -X vim\n\n  \837                       - Find all *.rs files and count the lines with \"wc -l ...\":\n\n      \838                           fd -e rs -X wc -l\839                     "840                ),841        )842    }843844    fn augment_args_for_update(cmd: Command) -> Command {845        Self::augment_args(cmd)846    }847}848849fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {850    Ok(Duration::from_millis(arg.parse()?))851}852853fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {854    if filesystem::is_existing_directory(current_directory) {855        Ok(())856    } else {857        Err(anyhow!(858            "Could not retrieve current directory (has it been deleted?)."859        ))860    }861}