Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

862 lines · 30.2 KiB · Rust

Last changed by

bug: Update clap to 4.4.6Thayne McCombsbefore adoptione6b5a4e

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", "quiet", "max_one_result"])),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        overrides_with("max_one_result"),509        help = "Limit the number of search results",510        long_help511    )]512    max_results: Option<usize>,513514    /// Limit the search to a single result and quit immediately.515    /// This is an alias for '--max-results=1'.516    #[arg(517        short = '1',518        hide_short_help = true,519        overrides_with("max_results"),520        help = "Limit search to a single result",521        long_help522    )]523    max_one_result: bool,524525    /// When the flag is present, the program does not print anything and will526    /// return with an exit code of 0 if there is at least one match. Otherwise, the527    /// exit code will be 1.528    /// '--has-results' can be used as an alias.529    #[arg(530        long,531        short = 'q',532        alias = "has-results",533        hide_short_help = true,534        conflicts_with("max_results"),535        help = "Print nothing, exit code 0 if match found, 1 otherwise",536        long_help537    )]538    pub quiet: bool,539540    /// Enable the display of filesystem errors for situations such as541    /// insufficient permissions or dead symlinks.542    #[arg(543        long,544        hide_short_help = true,545        help = "Show filesystem errors",546        long_help547    )]548    pub show_errors: bool,549550    /// Change the current working directory of fd to the provided path. This551    /// means that search results will be shown with respect to the given base552    /// path. Note that relative paths which are passed to fd via the positional553    /// <path> argument or the '--search-path' option will also be resolved554    /// relative to this directory.555    #[arg(556        long,557        value_name = "path",558        hide_short_help = true,559        help = "Change current working directory",560        long_help561    )]562    pub base_directory: Option<PathBuf>,563564    /// the search pattern which is either a regular expression (default) or a glob565    /// pattern (if --glob is used). If no pattern has been specified, every entry566    /// is considered a match. If your pattern starts with a dash (-), make sure to567    /// pass '--' first, or it will be considered as a flag (fd -- '-foo').568    #[arg(569        default_value = "",570        hide_default_value = true,571        value_name = "pattern",572        help = "the search pattern (a regular expression, unless '--glob' is used; optional)",573        long_help574    )]575    pub pattern: String,576577    /// Set the path separator to use when printing file paths. The default is578    /// the OS-specific separator ('/' on Unix, '\' on Windows).579    #[arg(580        long,581        value_name = "separator",582        hide_short_help = true,583        help = "Set path separator when printing file paths",584        long_help585    )]586    pub path_separator: Option<String>,587588    /// The directory where the filesystem search is rooted (optional). If589    /// omitted, search the current working directory.590    #[arg(action = ArgAction::Append,591        value_name = "path",592        help = "the root directories for the filesystem search (optional)",593        long_help,594        )]595    path: Vec<PathBuf>,596597    /// Provide paths to search as an alternative to the positional <path>598    /// argument. Changes the usage to `fd [OPTIONS] --search-path <path>599    /// --search-path <path2> [<pattern>]`600    #[arg(601        long,602        conflicts_with("path"),603        value_name = "search-path",604        hide_short_help = true,605        help = "Provides paths to search as an alternative to the positional <path> argument",606        long_help607    )]608    search_path: Vec<PathBuf>,609610    /// By default, relative paths are prefixed with './' when -x/--exec,611    /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a612    /// path starting with '-' being treated as a command line option. Use613    /// this flag to disable this behaviour.614    #[arg(long, conflicts_with_all(&["path", "search_path"]), hide_short_help = true, long_help)]615    pub strip_cwd_prefix: bool,616617    /// By default, fd will traverse the file system tree as far as other options618    /// dictate. With this flag, fd ensures that it does not descend into a619    /// different file system than the one it started in. Comparable to the -mount620    /// or -xdev filters of find(1).621    #[cfg(any(unix, windows))]622    #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]623    pub one_file_system: bool,624625    #[cfg(feature = "completions")]626    #[arg(long, hide = true, exclusive = true)]627    gen_completions: Option<Option<Shell>>,628}629630impl Opts {631    pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {632        // would it make sense to concatenate these?633        let paths = if !self.path.is_empty() {634            &self.path635        } else if !self.search_path.is_empty() {636            &self.search_path637        } else {638            let current_directory = Path::new(".");639            ensure_current_directory_exists(current_directory)?;640            return Ok(vec![self.normalize_path(current_directory)]);641        };642        Ok(paths643            .iter()644            .filter_map(|path| {645                if filesystem::is_existing_directory(path) {646                    Some(self.normalize_path(path))647                } else {648                    print_error(format!(649                        "Search path '{}' is not a directory.",650                        path.to_string_lossy()651                    ));652                    None653                }654            })655            .collect())656    }657658    fn normalize_path(&self, path: &Path) -> PathBuf {659        if self.absolute_path {660            filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()661        } else {662            path.to_path_buf()663        }664    }665666    pub fn no_search_paths(&self) -> bool {667        self.path.is_empty() && self.search_path.is_empty()668    }669670    #[inline]671    pub fn rg_alias_ignore(&self) -> bool {672        self.rg_alias_hidden_ignore > 0673    }674675    pub fn max_depth(&self) -> Option<usize> {676        self.max_depth.or(self.exact_depth)677    }678679    pub fn min_depth(&self) -> Option<usize> {680        self.min_depth.or(self.exact_depth)681    }682683    pub fn threads(&self) -> usize {684        // This will panic if the number of threads passed in is more than usize::MAX in an environment685        // where usize is less than 32 bits (for example 16-bit architectures). It's pretty686        // unlikely fd will be running in such an environment, and even more unlikely someone would687        // be trying to use that many threads on such an environment, so I think panicing is an688        // appropriate way to handle that.689        std::cmp::max(690            self.threads691                .map_or_else(num_cpus::get, |n| n.try_into().expect("too many threads")),692            1,693        )694    }695696    pub fn max_results(&self) -> Option<usize> {697        self.max_results698            .filter(|&m| m > 0)699            .or_else(|| self.max_one_result.then_some(1))700    }701702    #[cfg(feature = "completions")]703    pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {704        self.gen_completions705            .map(|maybe_shell| match maybe_shell {706                Some(sh) => Ok(sh),707                None => {708                    Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))709                }710            })711            .transpose()712    }713}714715#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]716pub enum FileType {717    #[value(alias = "f")]718    File,719    #[value(alias = "d")]720    Directory,721    #[value(alias = "l")]722    Symlink,723    /// A file which is executable by the current effective user724    #[value(alias = "x")]725    Executable,726    #[value(alias = "e")]727    Empty,728    #[value(alias = "s")]729    Socket,730    #[value(alias = "p")]731    Pipe,732}733734#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]735pub enum ColorWhen {736    /// show colors if the output goes to an interactive console (default)737    Auto,738    /// always use colorized output739    Always,740    /// do not use colorized output741    Never,742}743744impl ColorWhen {745    pub fn as_str(&self) -> &'static str {746        use ColorWhen::*;747        match *self {748            Auto => "auto",749            Never => "never",750            Always => "always",751        }752    }753}754755// there isn't a derive api for getting grouped values yet,756// so we have to use hand-rolled parsing for exec and exec-batch757pub struct Exec {758    pub command: Option<CommandSet>,759}760761impl clap::FromArgMatches for Exec {762    fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {763        let command = matches764            .get_occurrences::<String>("exec")765            .map(CommandSet::new)766            .or_else(|| {767                matches768                    .get_occurrences::<String>("exec_batch")769                    .map(CommandSet::new_batch)770            })771            .transpose()772            .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;773        Ok(Exec { command })774    }775776    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {777        *self = Self::from_arg_matches(matches)?;778        Ok(())779    }780}781782impl clap::Args for Exec {783    fn augment_args(cmd: Command) -> Command {784        cmd.arg(Arg::new("exec")785            .action(ArgAction::Append)786            .long("exec")787            .short('x')788            .num_args(1..)789                .allow_hyphen_values(true)790                .value_terminator(";")791                .value_name("cmd")792                .conflicts_with("list_details")793                .help("Execute a command for each search result")794                .long_help(795                    "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \796                     All positional arguments following --exec are considered to be arguments to the command - not to fd. \797                     It is therefore recommended to place the '-x'/'--exec' option last.\n\798                     The following placeholders are substituted before the command is executed:\n  \799                       '{}':   path (of the current search result)\n  \800                       '{/}':  basename\n  \801                       '{//}': parent directory\n  \802                       '{.}':  path without file extension\n  \803                       '{/.}': basename without file extension\n\n\804                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\805                     Examples:\n\n  \806                       - find all *.zip files and unzip them:\n\n      \807                           fd -e zip -x unzip\n\n  \808                       - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n      \809                           fd -e h -e cpp -x clang-format -i\n\n  \810                       - Convert all *.jpg files to *.png files:\n\n      \811                           fd -e jpg -x convert {} {.}.png\812                    ",813                ),814        )815        .arg(816            Arg::new("exec_batch")817                .action(ArgAction::Append)818                .long("exec-batch")819                .short('X')820                .num_args(1..)821                .allow_hyphen_values(true)822                .value_terminator(";")823                .value_name("cmd")824                .conflicts_with_all(["exec", "list_details"])825                .help("Execute a command with all search results at once")826                .long_help(827                    "Execute the given command once, with all search results as arguments.\n\828                     One of the following placeholders is substituted before the command is executed:\n  \829                       '{}':   path (of all search results)\n  \830                       '{/}':  basename\n  \831                       '{//}': parent directory\n  \832                       '{.}':  path without file extension\n  \833                       '{/.}': basename without file extension\n\n\834                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\835                     Examples:\n\n  \836                       - Find all test_*.py files and open them in your favorite editor:\n\n      \837                           fd -g 'test_*.py' -X vim\n\n  \838                       - Find all *.rs files and count the lines with \"wc -l ...\":\n\n      \839                           fd -e rs -X wc -l\840                     "841                ),842        )843    }844845    fn augment_args_for_update(cmd: Command) -> Command {846        Self::augment_args(cmd)847    }848}849850fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {851    Ok(Duration::from_millis(arg.parse()?))852}853854fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {855    if filesystem::is_existing_directory(current_directory) {856        Ok(())857    } else {858        Err(anyhow!(859            "Could not retrieve current directory (has it been deleted?)."860        ))861    }862}