cli.rs
This file
Path
src/cli.rs
849 lines · 31.9 KiB · Rust
Last changed by
Reorder command line optionsDavid Peterbefore adoption12165c7
History of this fileTake it
1use std::path::{Path, PathBuf};2use std::time::Duration;34#[cfg(feature = "completions")]5use anyhow::anyhow;6use clap::{7 error::ErrorKind, value_parser, Arg, ArgAction, ArgGroup, ArgMatches, Command, Parser,8 ValueEnum,9};10#[cfg(feature = "completions")]11use clap_complete::Shell;12use normpath::PathExt;1314use crate::error::print_error;15use crate::exec::CommandSet;16use crate::filesystem;17#[cfg(unix)]18use crate::filter::OwnerFilter;19use crate::filter::SizeFilter;2021// Type for options that don't have any values, but are used to negate22// earlier options23struct Negations;2425impl clap::FromArgMatches for Negations {26 fn from_arg_matches(_: &ArgMatches) -> clap::error::Result<Self> {27 Ok(Negations)28 }2930 fn update_from_arg_matches(&mut self, _: &ArgMatches) -> clap::error::Result<()> {31 Ok(())32 }33}3435impl clap::Args for Negations {36 fn augment_args(cmd: Command) -> Command {37 Self::augment_args_for_update(cmd)38 }3940 fn augment_args_for_update(cmd: Command) -> Command {41 cmd.arg(42 Arg::new("no_hidden")43 .action(ArgAction::Count)44 .long("no-hidden")45 .overrides_with("hidden")46 .hide(true)47 .long_help("Overrides --hidden."),48 )49 .arg(50 Arg::new("ignore")51 .action(ArgAction::Count)52 .long("ignore")53 .overrides_with("no_ignore")54 .hide(true)55 .long_help("Overrides --no-ignore."),56 )57 .arg(58 Arg::new("ignore_vcs")59 .action(ArgAction::Count)60 .long("ignore-vcs")61 .overrides_with("no_ignore_vcs")62 .hide(true)63 .long_help("Overrides --no-ignore-vcs."),64 )65 .arg(66 Arg::new("relative_path")67 .action(ArgAction::Count)68 .long("relative-path")69 .overrides_with("absolute_path")70 .hide(true)71 .long_help("Overrides --absolute-path."),72 )73 .arg(74 Arg::new("no_follow")75 .action(ArgAction::Count)76 .long("no-follow")77 .overrides_with("follow")78 .hide(true)79 .long_help("Overrides --follow."),80 )81 }82}8384#[derive(Parser)]85#[command(86 name = "fd",87 version,88 about = "A program to find entries in your filesystem",89 after_long_help = "Bugs can be reported on GitHub: https://github.com/sharkdp/fd/issues",90 max_term_width = 98,91 args_override_self = true,92 group(ArgGroup::new("execs").args(&["exec", "exec_batch", "list_details"]).conflicts_with_all(&[93 "max_results", "has_results", "count"])),94)]95pub struct Opts {96 /// Search hidden files and directories97 #[arg(98 long,99 short = 'H',100 long_help = "Include hidden directories and files in the search results (default: \101 hidden files and directories are skipped). Files and directories are \102 considered to be hidden if their name starts with a `.` sign (dot). \103 The flag can be overridden with --no-hidden."104 )]105 pub hidden: bool,106107 /// Do not respect .(git|fd)ignore files108 #[arg(109 long,110 short = 'I',111 long_help = "Show search results from files and directories that would otherwise be \112 ignored by '.gitignore', '.ignore', '.fdignore', or the global ignore file. \113 The flag can be overridden with --ignore."114 )]115 pub no_ignore: bool,116117 /// Do not respect .gitignore files118 #[arg(119 long,120 hide_short_help = true,121 long_help = "Show search results from files and directories that would otherwise be \122 ignored by '.gitignore' files. The flag can be overridden with --ignore-vcs."123 )]124 pub no_ignore_vcs: bool,125126 /// Do not respect .(git|fd)ignore files in parent directories127 #[arg(128 long,129 hide_short_help = true,130 long_help = "Show search results from files and directories that would otherwise be \131 ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories."132 )]133 pub no_ignore_parent: bool,134135 /// Do not respect the global ignore file136 #[arg(long, hide = true)]137 pub no_global_ignore_file: bool,138139 /// Unrestricted search, alias for '--no-ignore --hidden'140 #[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,141 long_help = "Perform an unrestricted search, including ignored and hidden files. This is \142 an alias for '--no-ignore --hidden'."143 )]144 rg_alias_hidden_ignore: u8,145146 /// Case-sensitive search (default: smart case)147 #[arg(148 long,149 short = 's',150 overrides_with("ignore_case"),151 long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \152 searches, unless the pattern contains an uppercase character (smart \153 case)."154 )]155 pub case_sensitive: bool,156157 /// Case-insensitive search (default: smart case)158 #[arg(159 long,160 short = 'i',161 overrides_with("case_sensitive"),162 long_help = "Perform a case-insensitive search. By default, fd uses case-insensitive \163 searches, unless the pattern contains an uppercase character (smart \164 case)."165 )]166 pub ignore_case: bool,167168 /// Glob-based search (default: regular expression)169 #[arg(170 long,171 short = 'g',172 conflicts_with("fixed_strings"),173 long_help = "Perform a glob-based search instead of a regular expression search."174 )]175 pub glob: bool,176177 /// Regular-expression based search (default)178 #[arg(179 long,180 overrides_with("glob"),181 hide_short_help = true,182 long_help = "Perform a regular-expression based search (default). This can be used to \183 override --glob."184 )]185 pub regex: bool,186187 /// Treat pattern as literal string stead of regex188 #[arg(189 long,190 short = 'F',191 alias = "literal",192 hide_short_help = true,193 long_help = "Treat the pattern as a literal string instead of a regular expression. Note \194 that this also performs substring comparison. If you want to match on an \195 exact filename, consider using '--glob'."196 )]197 pub fixed_strings: bool,198199 /// Show absolute instead of relative paths200 #[arg(201 long,202 short = 'a',203 long_help = "Shows the full path starting from the root as opposed to relative paths. \204 The flag can be overridden with --relative-path."205 )]206 pub absolute_path: bool,207208 /// Use a long listing format with file metadata209 #[arg(210 long,211 short = 'l',212 conflicts_with("absolute_path"),213 long_help = "Use a detailed listing format like 'ls -l'. This is basically an alias \214 for '--exec-batch ls -l' with some additional 'ls' options. This can be \215 used to see more metadata, to show symlink targets and to achieve a \216 deterministic sort order."217 )]218 pub list_details: bool,219220 /// Follow symbolic links221 #[arg(222 long,223 short = 'L',224 alias = "dereference",225 long_help = "By default, fd does not descend into symlinked directories. Using this \226 flag, symbolic links are also traversed. \227 Flag can be overriden with --no-follow."228 )]229 pub follow: bool,230231 /// Search full abs. path (default: filename only)232 #[arg(233 long,234 short = 'p',235 long_help = "By default, the search pattern is only matched against the filename (or \236 directory name). Using this flag, the pattern is matched against the full \237 (absolute) path. Example:\n \238 fd --glob -p '**/.git/config'"239 )]240 pub full_path: bool,241242 /// Separate search results by the null character243 #[arg(244 long = "print0",245 short = '0',246 conflicts_with("list_details"),247 hide_short_help = true,248 long_help = "Separate search results by the null character (instead of newlines). \249 Useful for piping results to 'xargs'."250 )]251 pub null_separator: bool,252253 /// Set maximum search depth (default: none)254 #[arg(255 long,256 short = 'd',257 value_name = "depth",258 alias("maxdepth"),259 long_help = "Limit the directory traversal to a given depth. By default, there is no \260 limit on the search depth."261 )]262 max_depth: Option<usize>,263264 /// Only show search results starting at the given depth.265 #[arg(266 long,267 value_name = "depth",268 hide_short_help = true,269 long_help = "Only show search results starting at the given depth. \270 See also: '--max-depth' and '--exact-depth'"271 )]272 min_depth: Option<usize>,273274 /// Only show search results at the exact given depth275 #[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),276 long_help = "Only show search results at the exact given depth. This is an alias for \277 '--min-depth <depth> --max-depth <depth>'.",278 )]279 exact_depth: Option<usize>,280281 /// Exclude entries that match the given glob pattern282 #[arg(283 long,284 short = 'E',285 value_name = "pattern",286 long_help = "Exclude files/directories that match the given glob pattern. This \287 overrides any other ignore logic. Multiple exclude patterns can be \288 specified.\n\n\289 Examples:\n \290 --exclude '*.pyc'\n \291 --exclude node_modules"292 )]293 pub exclude: Vec<String>,294295 /// Do not traverse into directories that match the search criteria. If296 /// you want to exclude specific directories, use the '--exclude=…' option.297 #[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),298 long_help = "Do not traverse into directories that match the search criteria. If \299 you want to exclude specific directories, use the '--exclude=…' option.",300 )]301 pub prune: bool,302303 /// Filter by type: file (f), directory (d), symlink (l),304 /// executable (x), empty (e), socket (s), pipe (p)305 #[arg(306 long = "type",307 short = 't',308 value_name = "filetype",309 hide_possible_values = true,310 value_enum,311 long_help = "Filter the search by type:\n \312 'f' or 'file': regular files\n \313 'd' or 'directory': directories\n \314 'l' or 'symlink': symbolic links\n \315 's' or 'socket': socket\n \316 'p' or 'pipe': named pipe (FIFO)\n\n \317 'x' or 'executable': executables\n \318 'e' or 'empty': empty files or directories\n\n\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 as \321 well as symlinks. Note that the 'executable' and 'empty' filters work differently: \322 '--type executable' implies '--type file' by default. And '--type empty' searches \323 for empty files and directories, unless either '--type file' or '--type directory' \324 is specified in addition.\n\n\325 Examples:\n \326 - Only search for files:\n \327 fd --type file …\n \328 fd -tf …\n \329 - Find both files and symlinks\n \330 fd --type file --type symlink …\n \331 fd -tf -tl …\n \332 - Find executable files:\n \333 fd --type executable\n \334 fd -tx\n \335 - Find empty files:\n \336 fd --type empty --type file\n \337 fd -te -tf\n \338 - Find empty directories:\n \339 fd --type empty --type directory\n \340 fd -te -td"341 )]342 pub filetype: Option<Vec<FileType>>,343344 /// Filter by file extension345 #[arg(346 long = "extension",347 short = 'e',348 value_name = "ext",349 long_help = "(Additionally) filter search results by their file extension. Multiple \350 allowable file extensions can be specified.\n\351 If you want to search for files without extension, \352 you can use the regex '^[^.]+$' as a normal search pattern."353 )]354 pub extensions: Option<Vec<String>>,355356 /// Limit results based on the size of files357 #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",358 long_help = "Limit results based on the size of files using the format <+-><NUM><UNIT>.\n \359 '+': file size must be greater than or equal to this\n \360 '-': file size must be less than or equal to this\n\361 If neither '+' nor '-' is specified, file size must be exactly equal to this.\n \362 'NUM': The numeric size (e.g. 500)\n \363 'UNIT': The units for NUM. They are not case-sensitive.\n\364 Allowed unit values:\n \365 'b': bytes\n \366 'k': kilobytes (base ten, 10^3 = 1000 bytes)\n \367 'm': megabytes\n \368 'g': gigabytes\n \369 't': terabytes\n \370 'ki': kibibytes (base two, 2^10 = 1024 bytes)\n \371 'mi': mebibytes\n \372 'gi': gibibytes\n \373 'ti': tebibytes",374 )]375 pub size: Vec<SizeFilter>,376377 /// Filter by file modification time (newer than)378 #[arg(379 long,380 alias("change-newer-than"),381 alias("newer"),382 value_name = "date|dur",383 long_help = "Filter results based on the file modification time. The argument can be provided \384 as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \385 If the time is not specified, it defaults to 00:00:00. \386 '--change-newer-than' or '--newer' can be used as aliases.\n\387 Examples:\n \388 --changed-within 2weeks\n \389 --change-newer-than '2018-10-27 10:00:00'\n \390 --newer 2018-10-27"391 )]392 pub changed_within: Option<String>,393394 /// Filter by file modification time (older than)395 #[arg(396 long,397 alias("change-older-than"),398 alias("older"),399 value_name = "date|dur",400 long_help = "Filter results based on the file modification time. The argument can be provided \401 as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \402 '--change-older-than' or '--older' can be used as aliases.\n\403 Examples:\n \404 --changed-before '2018-10-27 10:00:00'\n \405 --change-older-than 2weeks\n \406 --older 2018-10-27"407 )]408 pub changed_before: Option<String>,409410 /// Filter by owning user and/or group411 #[cfg(unix)]412 #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",413 long_help = "Filter files by their user and/or group. \414 Format: [(user|uid)][:(group|gid)]. Either side is optional. \415 Precede either side with a '!' to exclude files instead.\n\416 Examples:\n \417 --owner john\n \418 --owner :students\n \419 --owner '!john:students'"420 )]421 pub owner: Option<OwnerFilter>,422423 #[command(flatten)]424 pub exec: Exec,425426 /// Max number of arguments to run as a batch size with -X427 #[arg(428 long,429 value_name = "size",430 hide_short_help = true,431 requires("exec_batch"),432 value_parser = value_parser!(usize),433 default_value_t,434 long_help = "Maximum number of arguments to pass to the command given with -X. \435 If the number of results is greater than the given size, \436 the command given with -X is run again with remaining arguments. \437 A batch size of zero means there is no limit (default), but note \438 that batching might still happen due to OS restrictions on the \439 maximum length of command lines.",440 )]441 pub batch_size: usize,442443 /// Add a custom ignore-file in '.gitignore' format444 #[arg(445 long,446 value_name = "path",447 hide_short_help = true,448 long_help = "Add a custom ignore-file in '.gitignore' format. These files have a low precedence."449 )]450 pub ignore_file: Vec<PathBuf>,451452 /// When to use colors453 #[arg(454 long,455 short = 'c',456 value_enum,457 default_value_t = ColorWhen::Auto,458 value_name = "when",459 long_help = "Declare when to use color for the pattern match output",460 )]461 pub color: ColorWhen,462463 /// Set number of threads to use for searching & executing (default: number464 /// of available CPU cores)465 #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = 1..)]466 pub threads: Option<u32>,467468 /// Milliseconds to buffer before streaming search results to console469 ///470 /// Amount of time in milliseconds to buffer, before streaming the search471 /// results to the console.472 #[arg(long, hide = true, value_parser = parse_millis)]473 pub max_buffer_time: Option<Duration>,474475 /// Limit number of search results476 #[arg(477 long,478 value_name = "count",479 hide_short_help = true,480 long_help = "Limit the number of search results to 'count' and quit immediately."481 )]482 max_results: Option<usize>,483484 /// Limit search to a single result485 #[arg(486 short = '1',487 hide_short_help = true,488 overrides_with("max_results"),489 long_help = "Limit the search to a single result and quit immediately. \490 This is an alias for '--max-results=1'."491 )]492 max_one_result: bool,493494 /// Print nothing, exit code 0 if match found, 1 otherwise495 #[arg(496 long,497 short = 'q',498 alias = "has-results",499 hide_short_help = true,500 conflicts_with("max_results"),501 long_help = "When the flag is present, the program does not print anything and will \502 return with an exit code of 0 if there is at least one match. Otherwise, the \503 exit code will be 1. \504 '--has-results' can be used as an alias."505 )]506 pub quiet: bool,507508 /// Show filesystem errors509 #[arg(510 long,511 hide_short_help = true,512 long_help = "Enable the display of filesystem errors for situations such as \513 insufficient permissions or dead symlinks."514 )]515 pub show_errors: bool,516517 /// Change current working directory518 #[arg(519 long,520 value_name = "path",521 hide_short_help = true,522 long_help = "Change the current working directory of fd to the provided path. This \523 means that search results will be shown with respect to the given base \524 path. Note that relative paths which are passed to fd via the positional \525 <path> argument or the '--search-path' option will also be resolved \526 relative to this directory."527 )]528 pub base_directory: Option<PathBuf>,529530 /// the search pattern (a regular expression, unless '--glob' is used; optional)531 #[arg(532 default_value = "",533 hide_default_value = true,534 value_name = "pattern",535 long_help = "the search pattern which is either a regular expression (default) or a glob \536 pattern (if --glob is used). If no pattern has been specified, every entry \537 is considered a match. If your pattern starts with a dash (-), make sure to \538 pass '--' first, or it will be considered as a flag (fd -- '-foo')."539 )]540 pub pattern: String,541542 /// Set path separator when printing file paths543 #[arg(544 long,545 value_name = "separator",546 hide_short_help = true,547 long_help = "Set the path separator to use when printing file paths. The default is \548 the OS-specific separator ('/' on Unix, '\\' on Windows)."549 )]550 pub path_separator: Option<String>,551552 /// the root directories for the filesystem search (optional)553 #[arg(action = ArgAction::Append,554 value_name = "path",555 long_help = "The directory where the filesystem search is rooted (optional). If \556 omitted, search the current working directory.",557 )]558 path: Vec<PathBuf>,559560 /// Provides paths to search as an alternative to the positional <path> argument561 #[arg(562 long,563 conflicts_with("path"),564 value_name = "search-path",565 hide_short_help = true,566 long_help = "Provide paths to search as an alternative to the positional <path> \567 argument. Changes the usage to `fd [OPTIONS] --search-path <path> \568 --search-path <path2> [<pattern>]`"569 )]570 search_path: Vec<PathBuf>,571572 /// By default, relative paths are prefixed with './' when -x/--exec,573 /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a574 /// path starting with '-' being treated as a command line option. Use575 /// this flag to disable this behaviour.576 #[arg(long, conflicts_with_all(&["path", "search_path"]), hide_short_help = true,577 long_help = "By default, relative paths are prefixed with './' when -x/--exec, \578 -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a \579 path starting with '-' being treated as a command line option. Use \580 this flag to disable this behaviour.",581 )]582 pub strip_cwd_prefix: bool,583584 #[cfg(any(unix, windows))]585 #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true,586 long_help = "By default, fd will traverse the file system tree as far as other options \587 dictate. With this flag, fd ensures that it does not descend into a \588 different file system than the one it started in. Comparable to the -mount \589 or -xdev filters of find(1).")]590 pub one_file_system: bool,591592 #[cfg(feature = "completions")]593 #[arg(long, hide = true, exclusive = true)]594 gen_completions: Option<Option<Shell>>,595596 #[clap(flatten)]597 _negations: Negations,598}599600impl Opts {601 pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {602 // would it make sense to concatenate these?603 let paths = if !self.path.is_empty() {604 &self.path605 } else if !self.search_path.is_empty() {606 &self.search_path607 } else {608 let current_directory = Path::new(".");609 ensure_current_directory_exists(current_directory)?;610 return Ok(vec![self.normalize_path(current_directory)]);611 };612 Ok(paths613 .iter()614 .filter_map(|path| {615 if filesystem::is_existing_directory(path) {616 Some(self.normalize_path(path))617 } else {618 print_error(format!(619 "Search path '{}' is not a directory.",620 path.to_string_lossy()621 ));622 None623 }624 })625 .collect())626 }627628 fn normalize_path(&self, path: &Path) -> PathBuf {629 if self.absolute_path {630 filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()631 } else {632 path.to_path_buf()633 }634 }635636 pub fn no_search_paths(&self) -> bool {637 self.path.is_empty() && self.search_path.is_empty()638 }639640 #[inline]641 pub fn rg_alias_ignore(&self) -> bool {642 self.rg_alias_hidden_ignore > 0643 }644645 pub fn max_depth(&self) -> Option<usize> {646 self.max_depth.or(self.exact_depth)647 }648649 pub fn min_depth(&self) -> Option<usize> {650 self.min_depth.or(self.exact_depth)651 }652653 pub fn threads(&self) -> usize {654 // This will panic if the number of threads passed in is more than usize::MAX in an environment655 // where usize is less than 32 bits (for example 16-bit architectures). It's pretty656 // unlikely fd will be running in such an environment, and even more unlikely someone would657 // be trying to use that many threads on such an environment, so I think panicing is an658 // appropriate way to handle that.659 std::cmp::max(660 self.threads661 .map_or_else(num_cpus::get, |n| n.try_into().expect("too many threads")),662 1,663 )664 }665666 pub fn max_results(&self) -> Option<usize> {667 self.max_results668 .filter(|&m| m > 0)669 .or_else(|| self.max_one_result.then(|| 1))670 }671672 #[cfg(feature = "completions")]673 pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {674 self.gen_completions675 .map(|maybe_shell| match maybe_shell {676 Some(sh) => Ok(sh),677 None => guess_shell(),678 })679 .transpose()680 }681}682683#[cfg(feature = "completions")]684fn guess_shell() -> anyhow::Result<Shell> {685 let env_shell = std::env::var_os("SHELL").map(PathBuf::from);686 if let Some(shell) = env_shell687 .as_ref()688 .and_then(|s| s.file_name())689 .and_then(|s| s.to_str())690 {691 shell692 .parse::<Shell>()693 .map_err(|_| anyhow!("Unknown shell {}", shell))694 } else {695 // Assume powershell on windows696 #[cfg(windows)]697 return Ok(Shell::PowerShell);698 #[cfg(not(windows))]699 return Err(anyhow!("Unable to get shell from environment"));700 }701}702703#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]704pub enum FileType {705 #[value(alias = "f")]706 File,707 #[value(alias = "d")]708 Directory,709 #[value(alias = "l")]710 Symlink,711 #[value(alias = "x")]712 Executable,713 #[value(alias = "e")]714 Empty,715 #[value(alias = "s")]716 Socket,717 #[value(alias = "p")]718 Pipe,719}720721#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]722pub enum ColorWhen {723 /// show colors if the output goes to an interactive console (default)724 Auto,725 /// always use colorized output726 Always,727 /// do not use colorized output728 Never,729}730731impl ColorWhen {732 pub fn as_str(&self) -> &'static str {733 use ColorWhen::*;734 match *self {735 Auto => "auto",736 Never => "never",737 Always => "always",738 }739 }740}741742// there isn't a derive api for getting grouped values yet,743// so we have to use hand-rolled parsing for exec and exec-batch744pub struct Exec {745 pub command: Option<CommandSet>,746}747748impl clap::FromArgMatches for Exec {749 fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {750 let command = matches751 .grouped_values_of("exec")752 .map(CommandSet::new)753 .or_else(|| {754 matches755 .grouped_values_of("exec_batch")756 .map(CommandSet::new_batch)757 })758 .transpose()759 .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;760 Ok(Exec { command })761 }762763 fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {764 *self = Self::from_arg_matches(matches)?;765 Ok(())766 }767}768769impl clap::Args for Exec {770 fn augment_args(cmd: Command) -> Command {771 cmd.arg(Arg::new("exec")772 .action(ArgAction::Append)773 .long("exec")774 .short('x')775 .num_args(1..)776 .allow_hyphen_values(true)777 .value_terminator(";")778 .value_name("cmd")779 .conflicts_with("list_details")780 .help("Execute a command for each search result")781 .long_help(782 "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \783 All positional arguments following --exec are considered to be arguments to the command - not to fd. \784 It is therefore recommended to place the '-x'/'--exec' option last.\n\785 The following placeholders are substituted before the command is executed:\n \786 '{}': path (of the current search result)\n \787 '{/}': basename\n \788 '{//}': parent directory\n \789 '{.}': path without file extension\n \790 '{/.}': basename without file extension\n\n\791 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\792 Examples:\n\n \793 - find all *.zip files and unzip them:\n\n \794 fd -e zip -x unzip\n\n \795 - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n \796 fd -e h -e cpp -x clang-format -i\n\n \797 - Convert all *.jpg files to *.png files:\n\n \798 fd -e jpg -x convert {} {.}.png\799 ",800 ),801 )802 .arg(803 Arg::new("exec_batch")804 .action(ArgAction::Append)805 .long("exec-batch")806 .short('X')807 .num_args(1..)808 .allow_hyphen_values(true)809 .value_terminator(";")810 .value_name("cmd")811 .conflicts_with_all(&["exec", "list_details"])812 .help("Execute a command with all search results at once")813 .long_help(814 "Execute the given command once, with all search results as arguments.\n\815 One of the following placeholders is substituted before the command is executed:\n \816 '{}': path (of all search results)\n \817 '{/}': basename\n \818 '{//}': parent directory\n \819 '{.}': path without file extension\n \820 '{/.}': basename without file extension\n\n\821 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\822 Examples:\n\n \823 - Find all test_*.py files and open them in your favorite editor:\n\n \824 fd -g 'test_*.py' -X vim\n\n \825 - Find all *.rs files and count the lines with \"wc -l ...\":\n\n \826 fd -e rs -X wc -l\827 "828 ),829 )830 }831832 fn augment_args_for_update(cmd: Command) -> Command {833 Self::augment_args(cmd)834 }835}836837fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {838 Ok(Duration::from_millis(arg.parse()?))839}840841fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {842 if filesystem::is_existing_directory(current_directory) {843 Ok(())844 } else {845 Err(anyhow!(846 "Could not retrieve current directory (has it been deleted?)."847 ))848 }849}