Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

839 lines · 29.3 KiB · Rust

Last changed by

update: Update to clap 4.1Thayne McCombsbefore adoption10ba34f

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    /// Show search results from files and directories that would otherwise be78    /// ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories.79    #[arg(80        long,81        hide_short_help = true,82        help = "Do not respect .(git|fd)ignore files in parent directories",83        long_help84    )]85    pub no_ignore_parent: bool,8687    /// Do not respect the global ignore file88    #[arg(long, hide = true)]89    pub no_global_ignore_file: bool,9091    /// Perform an unrestricted search, including ignored and hidden files. This is92    /// an alias for '--no-ignore --hidden'.93    #[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,94    help = "Unrestricted search, alias for '--no-ignore --hidden'",95        long_help,96        )]97    rg_alias_hidden_ignore: u8,9899    /// Case-sensitive search (default: smart case)100    #[arg(101        long,102        short = 's',103        overrides_with("ignore_case"),104        long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \105                     searches, unless the pattern contains an uppercase character (smart \106                     case)."107    )]108    pub case_sensitive: bool,109110    /// Perform a case-insensitive search. By default, fd uses case-insensitive111    /// searches, unless the pattern contains an uppercase character (smart112    /// case).113    #[arg(114        long,115        short = 'i',116        overrides_with("case_sensitive"),117        help = "Case-insensitive search (default: smart case)",118        long_help119    )]120    pub ignore_case: bool,121122    /// Perform a glob-based search instead of a regular expression search.123    #[arg(124        long,125        short = 'g',126        conflicts_with("fixed_strings"),127        help = "Glob-based search (default: regular expression)",128        long_help129    )]130    pub glob: bool,131132    /// Perform a regular-expression based search (default). This can be used to133    /// override --glob.134    #[arg(135        long,136        overrides_with("glob"),137        hide_short_help = true,138        help = "Regular-expression based search (default)",139        long_help140    )]141    pub regex: bool,142143    /// Treat the pattern as a literal string instead of a regular expression. Note144    /// that this also performs substring comparison. If you want to match on an145    /// exact filename, consider using '--glob'.146    #[arg(147        long,148        short = 'F',149        alias = "literal",150        hide_short_help = true,151        help = "Treat pattern as literal string stead of regex",152        long_help153    )]154    pub fixed_strings: bool,155156    /// Add additional required search patterns, all of which must be matched. Multiple157    /// additional patterns can be specified. The patterns are regular158    /// expressions, unless '--glob' or '--fixed-strings' is used.159    #[arg(160        long = "and",161        value_name = "pattern",162        help = "Additional search patterns that need to be matched",163        long_help,164        hide_short_help = true,165        allow_hyphen_values = true166    )]167    pub exprs: Option<Vec<String>>,168169    /// Shows the full path starting from the root as opposed to relative paths.170    /// The flag can be overridden with --relative-path.171    #[arg(172        long,173        short = 'a',174        help = "Show absolute instead of relative paths",175        long_help176    )]177    pub absolute_path: bool,178179    /// Overrides --absolute-path180    #[arg(long, overrides_with = "absolute_path", hide = true, action = ArgAction::SetTrue)]181    relative_path: (),182183    /// Use a detailed listing format like 'ls -l'. This is basically an alias184    /// for '--exec-batch ls -l' with some additional 'ls' options. This can be185    /// used to see more metadata, to show symlink targets and to achieve a186    /// deterministic sort order.187    #[arg(188        long,189        short = 'l',190        conflicts_with("absolute_path"),191        help = "Use a long listing format with file metadata",192        long_help193    )]194    pub list_details: bool,195196    /// Follow symbolic links197    #[arg(198        long,199        short = 'L',200        alias = "dereference",201        long_help = "By default, fd does not descend into symlinked directories. Using this \202                     flag, symbolic links are also traversed. \203                     Flag can be overriden with --no-follow."204    )]205    pub follow: bool,206207    /// Overrides --follow208    #[arg(long, overrides_with = "follow", hide = true, action = ArgAction::SetTrue)]209    no_follow: (),210211    /// 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:212    ///   fd --glob -p '**/.git/config'213    #[arg(214        long,215        short = 'p',216        help = "Search full abs. path (default: filename only)",217        long_help,218        verbatim_doc_comment219    )]220    pub full_path: bool,221222    /// Separate search results by the null character (instead of newlines).223    /// Useful for piping results to 'xargs'.224    #[arg(225        long = "print0",226        short = '0',227        conflicts_with("list_details"),228        hide_short_help = true,229        help = "Separate search results by the null character",230        long_help231    )]232    pub null_separator: bool,233234    /// Limit the directory traversal to a given depth. By default, there is no235    /// limit on the search depth.236    #[arg(237        long,238        short = 'd',239        value_name = "depth",240        alias("maxdepth"),241        help = "Set maximum search depth (default: none)",242        long_help243    )]244    max_depth: Option<usize>,245246    /// Only show search results starting at the given depth.247    /// See also: '--max-depth' and '--exact-depth'248    #[arg(249        long,250        value_name = "depth",251        hide_short_help = true,252        help = "Only show search results starting at the given depth.",253        long_help254    )]255    min_depth: Option<usize>,256257    /// Only show search results at the exact given depth. This is an alias for258    /// '--min-depth <depth> --max-depth <depth>'.259    #[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),260    help = "Only show search results at the exact given depth",261        long_help,262        )]263    exact_depth: Option<usize>,264265    /// Exclude files/directories that match the given glob pattern. This266    /// overrides any other ignore logic. Multiple exclude patterns can be267    /// specified.268    ///269    /// Examples:270    /// {n}  --exclude '*.pyc'271    /// {n}  --exclude node_modules272    #[arg(273        long,274        short = 'E',275        value_name = "pattern",276        help = "Exclude entries that match the given glob pattern",277        long_help278    )]279    pub exclude: Vec<String>,280281    /// Do not traverse into directories that match the search criteria. If282    /// you want to exclude specific directories, use the '--exclude=…' option.283    #[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),284        long_help,285        )]286    pub prune: bool,287288    /// Filter the search by type:289    /// {n}  'f' or 'file':         regular files290    /// {n}  'd' or 'directory':    directories291    /// {n}  'l' or 'symlink':      symbolic links292    /// {n}  's' or 'socket':       socket293    /// {n}  'p' or 'pipe':         named pipe (FIFO)294    /// {n}{n}  'x' or 'executable':   executables295    /// {n}  'e' or 'empty':        empty files or directories296    ///297    /// This option can be specified more than once to include multiple file types.298    /// Searching for '--type file --type symlink' will show both regular files as299    /// well as symlinks. Note that the 'executable' and 'empty' filters work differently:300    /// '--type executable' implies '--type file' by default. And '--type empty' searches301    /// for empty files and directories, unless either '--type file' or '--type directory'302    /// is specified in addition.303    ///304    /// Examples:305    /// {n}  - Only search for files:306    /// {n}      fd --type file …307    /// {n}      fd -tf …308    /// {n}  - Find both files and symlinks309    /// {n}      fd --type file --type symlink …310    /// {n}      fd -tf -tl …311    /// {n}  - Find executable files:312    /// {n}      fd --type executable313    /// {n}      fd -tx314    /// {n}  - Find empty files:315    /// {n}      fd --type empty --type file316    /// {n}      fd -te -tf317    /// {n}  - Find empty directories:318    /// {n}      fd --type empty --type directory319    /// {n}      fd -te -td320    #[arg(321        long = "type",322        short = 't',323        value_name = "filetype",324        hide_possible_values = true,325        value_enum,326        help = "Filter by type: file (f), directory (d), symlink (l), \327                executable (x), empty (e), socket (s), pipe (p)",328        long_help329    )]330    pub filetype: Option<Vec<FileType>>,331332    /// (Additionally) filter search results by their file extension. Multiple333    /// allowable file extensions can be specified.334    ///335    /// If you want to search for files without extension,336    /// you can use the regex '^[^.]+$' as a normal search pattern.337    #[arg(338        long = "extension",339        short = 'e',340        value_name = "ext",341        help = "Filter by file extension",342        long_help343    )]344    pub extensions: Option<Vec<String>>,345346    /// Limit results based on the size of files using the format <+-><NUM><UNIT>.347    ///    '+': file size must be greater than or equal to this348    ///    '-': file size must be less than or equal to this349    ///350    /// If neither '+' nor '-' is specified, file size must be exactly equal to this.351    ///    'NUM':  The numeric size (e.g. 500)352    ///    'UNIT': The units for NUM. They are not case-sensitive.353    /// Allowed unit values:354    ///     'b':  bytes355    ///     'k':  kilobytes (base ten, 10^3 = 1000 bytes)356    ///     'm':  megabytes357    ///     'g':  gigabytes358    ///     't':  terabytes359    ///     'ki': kibibytes (base two, 2^10 = 1024 bytes)360    ///     'mi': mebibytes361    ///     'gi': gibibytes362    ///     'ti': tebibytes363    #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",364        help = "Limit results based on the size of files",365        long_help,366        verbatim_doc_comment,367        )]368    pub size: Vec<SizeFilter>,369370    /// Filter results based on the file modification time. Files with modification times371    /// greater than the argument are returned. The argument can be provided372    /// as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min).373    /// If the time is not specified, it defaults to 00:00:00.374    /// '--change-newer-than', '--newer', or '--changed-after' can be used as aliases.375    ///376    /// Examples:377    /// {n}    --changed-within 2weeks378    /// {n}    --change-newer-than '2018-10-27 10:00:00'379    /// {n}    --newer 2018-10-27380    /// {n}    --changed-after 1day381    #[arg(382        long,383        alias("change-newer-than"),384        alias("newer"),385        alias("changed-after"),386        value_name = "date|dur",387        help = "Filter by file modification time (newer than)",388        long_help389    )]390    pub changed_within: Option<String>,391392    /// Filter results based on the file modification time. Files with modification times393    /// less 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    /// '--change-older-than' or '--older' can be used as aliases.396    ///397    /// Examples:398    /// {n}    --changed-before '2018-10-27 10:00:00'399    /// {n}    --change-older-than 2weeks400    /// {n}    --older 2018-10-27401    #[arg(402        long,403        alias("change-older-than"),404        alias("older"),405        value_name = "date|dur",406        help = "Filter by file modification time (older than)",407        long_help408    )]409    pub changed_before: Option<String>,410411    /// Filter files by their user and/or group.412    /// Format: [(user|uid)][:(group|gid)]. Either side is optional.413    /// Precede either side with a '!' to exclude files instead.414    ///415    /// Examples:416    /// {n}    --owner john417    /// {n}    --owner :students418    /// {n}    --owner '!john:students'419    #[cfg(unix)]420    #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",421        help = "Filter by owning user and/or group",422        long_help,423        )]424    pub owner: Option<OwnerFilter>,425426    #[command(flatten)]427    pub exec: Exec,428429    /// Maximum number of arguments to pass to the command given with -X.430    /// If the number of results is greater than the given size,431    /// the command given with -X is run again with remaining arguments.432    /// A batch size of zero means there is no limit (default), but note433    /// that batching might still happen due to OS restrictions on the434    /// maximum length of command lines.435    #[arg(436        long,437        value_name = "size",438        hide_short_help = true,439        requires("exec_batch"),440        value_parser = value_parser!(usize),441        default_value_t,442        help = "Max number of arguments to run as a batch size with -X",443        long_help,444    )]445    pub batch_size: usize,446447    /// Add a custom ignore-file in '.gitignore' format. These files have a low precedence.448    #[arg(449        long,450        value_name = "path",451        hide_short_help = true,452        help = "Add a custom ignore-file in '.gitignore' format",453        long_help454    )]455    pub ignore_file: Vec<PathBuf>,456457    /// Declare when to use color for the pattern match output458    #[arg(459        long,460        short = 'c',461        value_enum,462        default_value_t = ColorWhen::Auto,463        value_name = "when",464        help = "When to use colors",465        long_help,466    )]467    pub color: ColorWhen,468469    /// Set number of threads to use for searching & executing (default: number470    /// of available CPU cores)471    #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = clap::value_parser!(u32).range(1..))]472    pub threads: Option<u32>,473474    /// Milliseconds to buffer before streaming search results to console475    ///476    /// Amount of time in milliseconds to buffer, before streaming the search477    /// results to the console.478    #[arg(long, hide = true, value_parser = parse_millis)]479    pub max_buffer_time: Option<Duration>,480481    ///Limit the number of search results to 'count' and quit immediately.482    #[arg(483        long,484        value_name = "count",485        hide_short_help = true,486        help = "Limit the number of search results",487        long_help488    )]489    max_results: Option<usize>,490491    /// Limit the search to a single result and quit immediately.492    /// This is an alias for '--max-results=1'.493    #[arg(494        short = '1',495        hide_short_help = true,496        overrides_with("max_results"),497        help = "Limit search to a single result",498        long_help499    )]500    max_one_result: bool,501502    /// When the flag is present, the program does not print anything and will503    /// return with an exit code of 0 if there is at least one match. Otherwise, the504    /// exit code will be 1.505    /// '--has-results' can be used as an alias.506    #[arg(507        long,508        short = 'q',509        alias = "has-results",510        hide_short_help = true,511        conflicts_with("max_results"),512        help = "Print nothing, exit code 0 if match found, 1 otherwise",513        long_help514    )]515    pub quiet: bool,516517    /// Enable the display of filesystem errors for situations such as518    /// insufficient permissions or dead symlinks.519    #[arg(520        long,521        hide_short_help = true,522        help = "Show filesystem errors",523        long_help524    )]525    pub show_errors: bool,526527    /// Change the current working directory of fd to the provided path. This528    /// means that search results will be shown with respect to the given base529    /// path. Note that relative paths which are passed to fd via the positional530    /// <path> argument or the '--search-path' option will also be resolved531    /// relative to this directory.532    #[arg(533        long,534        value_name = "path",535        hide_short_help = true,536        help = "Change current working directory",537        long_help538    )]539    pub base_directory: Option<PathBuf>,540541    /// the search pattern which is either a regular expression (default) or a glob542    /// pattern (if --glob is used). If no pattern has been specified, every entry543    /// is considered a match. If your pattern starts with a dash (-), make sure to544    /// pass '--' first, or it will be considered as a flag (fd -- '-foo').545    #[arg(546        default_value = "",547        hide_default_value = true,548        value_name = "pattern",549        help = "the search pattern (a regular expression, unless '--glob' is used; optional)",550        long_help551    )]552    pub pattern: String,553554    /// Set the path separator to use when printing file paths. The default is555    /// the OS-specific separator ('/' on Unix, '\' on Windows).556    #[arg(557        long,558        value_name = "separator",559        hide_short_help = true,560        help = "Set path separator when printing file paths",561        long_help562    )]563    pub path_separator: Option<String>,564565    /// The directory where the filesystem search is rooted (optional). If566    /// omitted, search the current working directory.567    #[arg(action = ArgAction::Append,568        value_name = "path",569        help = "the root directories for the filesystem search (optional)",570        long_help,571        )]572    path: Vec<PathBuf>,573574    /// Provide paths to search as an alternative to the positional <path>575    /// argument. Changes the usage to `fd [OPTIONS] --search-path <path>576    /// --search-path <path2> [<pattern>]`577    #[arg(578        long,579        conflicts_with("path"),580        value_name = "search-path",581        hide_short_help = true,582        help = "Provides paths to search as an alternative to the positional <path> argument",583        long_help584    )]585    search_path: Vec<PathBuf>,586587    /// By default, relative paths are prefixed with './' when -x/--exec,588    /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a589    /// path starting with '-' being treated as a command line option. Use590    /// this flag to disable this behaviour.591    #[arg(long, conflicts_with_all(&["path", "search_path"]), hide_short_help = true, long_help)]592    pub strip_cwd_prefix: bool,593594    /// By default, fd will traverse the file system tree as far as other options595    /// dictate. With this flag, fd ensures that it does not descend into a596    /// different file system than the one it started in. Comparable to the -mount597    /// or -xdev filters of find(1).598    #[cfg(any(unix, windows))]599    #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]600    pub one_file_system: bool,601602    #[cfg(feature = "completions")]603    #[arg(long, hide = true, exclusive = true)]604    gen_completions: Option<Option<Shell>>,605}606607impl Opts {608    pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {609        // would it make sense to concatenate these?610        let paths = if !self.path.is_empty() {611            &self.path612        } else if !self.search_path.is_empty() {613            &self.search_path614        } else {615            let current_directory = Path::new(".");616            ensure_current_directory_exists(current_directory)?;617            return Ok(vec![self.normalize_path(current_directory)]);618        };619        Ok(paths620            .iter()621            .filter_map(|path| {622                if filesystem::is_existing_directory(path) {623                    Some(self.normalize_path(path))624                } else {625                    print_error(format!(626                        "Search path '{}' is not a directory.",627                        path.to_string_lossy()628                    ));629                    None630                }631            })632            .collect())633    }634635    fn normalize_path(&self, path: &Path) -> PathBuf {636        if self.absolute_path {637            filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()638        } else {639            path.to_path_buf()640        }641    }642643    pub fn no_search_paths(&self) -> bool {644        self.path.is_empty() && self.search_path.is_empty()645    }646647    #[inline]648    pub fn rg_alias_ignore(&self) -> bool {649        self.rg_alias_hidden_ignore > 0650    }651652    pub fn max_depth(&self) -> Option<usize> {653        self.max_depth.or(self.exact_depth)654    }655656    pub fn min_depth(&self) -> Option<usize> {657        self.min_depth.or(self.exact_depth)658    }659660    pub fn threads(&self) -> usize {661        // This will panic if the number of threads passed in is more than usize::MAX in an environment662        // where usize is less than 32 bits (for example 16-bit architectures). It's pretty663        // unlikely fd will be running in such an environment, and even more unlikely someone would664        // be trying to use that many threads on such an environment, so I think panicing is an665        // appropriate way to handle that.666        std::cmp::max(667            self.threads668                .map_or_else(num_cpus::get, |n| n.try_into().expect("too many threads")),669            1,670        )671    }672673    pub fn max_results(&self) -> Option<usize> {674        self.max_results675            .filter(|&m| m > 0)676            .or_else(|| self.max_one_result.then(|| 1))677    }678679    #[cfg(feature = "completions")]680    pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {681        self.gen_completions682            .map(|maybe_shell| match maybe_shell {683                Some(sh) => Ok(sh),684                None => {685                    Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))686                }687            })688            .transpose()689    }690}691692#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]693pub enum FileType {694    #[value(alias = "f")]695    File,696    #[value(alias = "d")]697    Directory,698    #[value(alias = "l")]699    Symlink,700    /// A file which is executable by the current effective user701    #[value(alias = "x")]702    Executable,703    #[value(alias = "e")]704    Empty,705    #[value(alias = "s")]706    Socket,707    #[value(alias = "p")]708    Pipe,709}710711#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]712pub enum ColorWhen {713    /// show colors if the output goes to an interactive console (default)714    Auto,715    /// always use colorized output716    Always,717    /// do not use colorized output718    Never,719}720721impl ColorWhen {722    pub fn as_str(&self) -> &'static str {723        use ColorWhen::*;724        match *self {725            Auto => "auto",726            Never => "never",727            Always => "always",728        }729    }730}731732// there isn't a derive api for getting grouped values yet,733// so we have to use hand-rolled parsing for exec and exec-batch734pub struct Exec {735    pub command: Option<CommandSet>,736}737738impl clap::FromArgMatches for Exec {739    fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {740        let command = matches741            .get_occurrences::<String>("exec")742            .map(CommandSet::new)743            .or_else(|| {744                matches745                    .get_occurrences::<String>("exec_batch")746                    .map(CommandSet::new_batch)747            })748            .transpose()749            .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;750        Ok(Exec { command })751    }752753    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {754        *self = Self::from_arg_matches(matches)?;755        Ok(())756    }757}758759impl clap::Args for Exec {760    fn augment_args(cmd: Command) -> Command {761        cmd.arg(Arg::new("exec")762            .action(ArgAction::Append)763            .long("exec")764            .short('x')765            .num_args(1..)766                .allow_hyphen_values(true)767                .value_terminator(";")768                .value_name("cmd")769                .conflicts_with("list_details")770                .help("Execute a command for each search result")771                .long_help(772                    "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \773                     All positional arguments following --exec are considered to be arguments to the command - not to fd. \774                     It is therefore recommended to place the '-x'/'--exec' option last.\n\775                     The following placeholders are substituted before the command is executed:\n  \776                       '{}':   path (of the current search result)\n  \777                       '{/}':  basename\n  \778                       '{//}': parent directory\n  \779                       '{.}':  path without file extension\n  \780                       '{/.}': basename without file extension\n\n\781                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\782                     Examples:\n\n  \783                       - find all *.zip files and unzip them:\n\n      \784                           fd -e zip -x unzip\n\n  \785                       - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n      \786                           fd -e h -e cpp -x clang-format -i\n\n  \787                       - Convert all *.jpg files to *.png files:\n\n      \788                           fd -e jpg -x convert {} {.}.png\789                    ",790                ),791        )792        .arg(793            Arg::new("exec_batch")794                .action(ArgAction::Append)795                .long("exec-batch")796                .short('X')797                .num_args(1..)798                .allow_hyphen_values(true)799                .value_terminator(";")800                .value_name("cmd")801                .conflicts_with_all(["exec", "list_details"])802                .help("Execute a command with all search results at once")803                .long_help(804                    "Execute the given command once, with all search results as arguments.\n\805                     One of the following placeholders is substituted before the command is executed:\n  \806                       '{}':   path (of all search results)\n  \807                       '{/}':  basename\n  \808                       '{//}': parent directory\n  \809                       '{.}':  path without file extension\n  \810                       '{/.}': basename without file extension\n\n\811                     If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\812                     Examples:\n\n  \813                       - Find all test_*.py files and open them in your favorite editor:\n\n      \814                           fd -g 'test_*.py' -X vim\n\n  \815                       - Find all *.rs files and count the lines with \"wc -l ...\":\n\n      \816                           fd -e rs -X wc -l\817                     "818                ),819        )820    }821822    fn augment_args_for_update(cmd: Command) -> Command {823        Self::augment_args(cmd)824    }825}826827fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {828    Ok(Duration::from_millis(arg.parse()?))829}830831fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {832    if filesystem::is_existing_directory(current_directory) {833        Ok(())834    } else {835        Err(anyhow!(836            "Could not retrieve current directory (has it been deleted?)."837        ))838    }839}