Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

785 lines · 30.3 KiB · Rust

Last changed by

Merge pull request #1169 from Ptipiak/mention-executable-detectionDavid Peterbefore adoption38cdeb0

History of this file

Take it

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 1–21why, one step back
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(

Change clap CLI binary name to 'fd'David Peterbefore adoptionac35b11

line 22why, one step back
22 name = "fd",

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 23why, one step back
23 version,

Add simple 'about' textDavid Peterbefore adoption7f5bc98

line 24why, one step back
24 about = "A program to find entries in your filesystem",

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

line 25why, one step back
25 after_long_help = "Bugs can be reported on GitHub: https://github.com/sharkdp/fd/issues",

Set max. term width to make help texts easier to readDavid Peterbefore adoption70c4865

line 26why, one step back
26 max_term_width = 98,

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 27–42why, one step back
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 /// Search hidden files and directories33 #[arg(34 long,35 short = 'H',36 long_help = "Include hidden directories and files in the search results (default: \37 hidden files and directories are skipped). Files and directories are \38 considered to be hidden if their name starts with a `.` sign (dot). \39 The flag can be overridden with --no-hidden."40 )]41 pub hidden: bool,42

Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada

lines 43–46why, one step back
43 /// Overrides --hidden
44 #[arg(long, overrides_with = "hidden", hide = true, action = ArgAction::SetTrue)]45 no_hidden: (),46

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 47–56why, one step back
47 /// Do not respect .(git|fd)ignore files
48 #[arg(49 long,50 short = 'I',51 long_help = "Show search results from files and directories that would otherwise be \52 ignored by '.gitignore', '.ignore', '.fdignore', or the global ignore file. \53 The flag can be overridden with --ignore."54 )]55 pub no_ignore: bool,56

Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada

lines 57–60why, one step back
57 /// Overrides --no-ignore
58 #[arg(long, overrides_with = "no_ignore", hide = true, action = ArgAction::SetTrue)]59 ignore: (),60

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 61–69why, one step back
61 /// Do not respect .gitignore files
62 #[arg(63 long,64 hide_short_help = true,65 long_help = "Show search results from files and directories that would otherwise be \66 ignored by '.gitignore' files. The flag can be overridden with --ignore-vcs."67 )]68 pub no_ignore_vcs: bool,69

Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada

lines 70–73why, one step back
70 /// Overrides --no-ignore-vcs
71 #[arg(long, overrides_with = "no_ignore_vcs", hide = true, action = ArgAction::SetTrue)]72 ignore_vcs: (),73

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 74–155why, one step back
74 /// Do not respect .(git|fd)ignore files in parent directories
75 #[arg(76 long,77 hide_short_help = true,78 long_help = "Show search results from files and directories that would otherwise be \79 ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories."80 )]81 pub no_ignore_parent: bool,8283 /// Do not respect the global ignore file84 #[arg(long, hide = true)]85 pub no_global_ignore_file: bool,8687 /// Unrestricted search, alias for '--no-ignore --hidden'88 #[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,89 long_help = "Perform an unrestricted search, including ignored and hidden files. This is \90 an alias for '--no-ignore --hidden'."91 )]92 rg_alias_hidden_ignore: u8,9394 /// Case-sensitive search (default: smart case)95 #[arg(96 long,97 short = 's',98 overrides_with("ignore_case"),99 long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \100 searches, unless the pattern contains an uppercase character (smart \101 case)."102 )]103 pub case_sensitive: bool,104105 /// Case-insensitive search (default: smart case)106 #[arg(107 long,108 short = 'i',109 overrides_with("case_sensitive"),110 long_help = "Perform a case-insensitive search. By default, fd uses case-insensitive \111 searches, unless the pattern contains an uppercase character (smart \112 case)."113 )]114 pub ignore_case: bool,115116 /// Glob-based search (default: regular expression)117 #[arg(118 long,119 short = 'g',120 conflicts_with("fixed_strings"),121 long_help = "Perform a glob-based search instead of a regular expression search."122 )]123 pub glob: bool,124125 /// Regular-expression based search (default)126 #[arg(127 long,128 overrides_with("glob"),129 hide_short_help = true,130 long_help = "Perform a regular-expression based search (default). This can be used to \131 override --glob."132 )]133 pub regex: bool,134135 /// Treat pattern as literal string stead of regex136 #[arg(137 long,138 short = 'F',139 alias = "literal",140 hide_short_help = true,141 long_help = "Treat the pattern as a literal string instead of a regular expression. Note \142 that this also performs substring comparison. If you want to match on an \143 exact filename, consider using '--glob'."144 )]145 pub fixed_strings: bool,146147 /// Show absolute instead of relative paths148 #[arg(149 long,150 short = 'a',151 long_help = "Shows the full path starting from the root as opposed to relative paths. \152 The flag can be overridden with --relative-path."153 )]154 pub absolute_path: bool,155

Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada

lines 156–159why, one step back
156 /// Overrides --absolute-path
157 #[arg(long, overrides_with = "absolute_path", hide = true, action = ArgAction::SetTrue)]158 relative_path: (),159

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 160–182why, one step back
160 /// Use a long listing format with file metadata
161 #[arg(162 long,163 short = 'l',164 conflicts_with("absolute_path"),165 long_help = "Use a detailed listing format like 'ls -l'. This is basically an alias \166 for '--exec-batch ls -l' with some additional 'ls' options. This can be \167 used to see more metadata, to show symlink targets and to achieve a \168 deterministic sort order."169 )]170 pub list_details: bool,171172 /// Follow symbolic links173 #[arg(174 long,175 short = 'L',176 alias = "dereference",177 long_help = "By default, fd does not descend into symlinked directories. Using this \178 flag, symbolic links are also traversed. \179 Flag can be overriden with --no-follow."180 )]181 pub follow: bool,182

Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada

lines 183–186why, one step back
183 /// Overrides --follow
184 #[arg(long, overrides_with = "follow", hide = true, action = ArgAction::SetTrue)]185 no_follow: (),186

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 187–236why, one step back
187 /// Search full abs. path (default: filename only)
188 #[arg(189 long,190 short = 'p',191 long_help = "By default, the search pattern is only matched against the filename (or \192 directory name). Using this flag, the pattern is matched against the full \193 (absolute) path. Example:\n \194 fd --glob -p '**/.git/config'"195 )]196 pub full_path: bool,197198 /// Separate search results by the null character199 #[arg(200 long = "print0",201 short = '0',202 conflicts_with("list_details"),203 hide_short_help = true,204 long_help = "Separate search results by the null character (instead of newlines). \205 Useful for piping results to 'xargs'."206 )]207 pub null_separator: bool,208209 /// Set maximum search depth (default: none)210 #[arg(211 long,212 short = 'd',213 value_name = "depth",214 alias("maxdepth"),215 long_help = "Limit the directory traversal to a given depth. By default, there is no \216 limit on the search depth."217 )]218 max_depth: Option<usize>,219220 /// Only show search results starting at the given depth.221 #[arg(222 long,223 value_name = "depth",224 hide_short_help = true,225 long_help = "Only show search results starting at the given depth. \226 See also: '--max-depth' and '--exact-depth'"227 )]228 min_depth: Option<usize>,229230 /// Only show search results at the exact given depth231 #[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),232 long_help = "Only show search results at the exact given depth. This is an alias for \233 '--min-depth <depth> --max-depth <depth>'.",234 )]235 exact_depth: Option<usize>,236

Reorder command line optionsDavid Peterbefore adoption12165c7

lines 237–250why, one step back
237 /// Exclude entries that match the given glob pattern
238 #[arg(239 long,240 short = 'E',241 value_name = "pattern",242 long_help = "Exclude files/directories that match the given glob pattern. This \243 overrides any other ignore logic. Multiple exclude patterns can be \244 specified.\n\n\245 Examples:\n \246 --exclude '*.pyc'\n \247 --exclude node_modules"248 )]249 pub exclude: Vec<String>,250

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 251–365why, one step back
251 /// Do not traverse into directories that match the search criteria. If
252 /// you want to exclude specific directories, use the '--exclude=…' option.253 #[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),254 long_help = "Do not traverse into directories that match the search criteria. If \255 you want to exclude specific directories, use the '--exclude=…' option.",256 )]257 pub prune: bool,258259 /// Filter by type: file (f), directory (d), symlink (l),260 /// executable (x), empty (e), socket (s), pipe (p)261 #[arg(262 long = "type",263 short = 't',264 value_name = "filetype",265 hide_possible_values = true,266 value_enum,267 long_help = "Filter the search by type:\n \268 'f' or 'file': regular files\n \269 'd' or 'directory': directories\n \270 'l' or 'symlink': symbolic links\n \271 's' or 'socket': socket\n \272 'p' or 'pipe': named pipe (FIFO)\n\n \273 'x' or 'executable': executables\n \274 'e' or 'empty': empty files or directories\n\n\275 This option can be specified more than once to include multiple file types. \276 Searching for '--type file --type symlink' will show both regular files as \277 well as symlinks. Note that the 'executable' and 'empty' filters work differently: \278 '--type executable' implies '--type file' by default. And '--type empty' searches \279 for empty files and directories, unless either '--type file' or '--type directory' \280 is specified in addition.\n\n\281 Examples:\n \282 - Only search for files:\n \283 fd --type file …\n \284 fd -tf …\n \285 - Find both files and symlinks\n \286 fd --type file --type symlink …\n \287 fd -tf -tl …\n \288 - Find executable files:\n \289 fd --type executable\n \290 fd -tx\n \291 - Find empty files:\n \292 fd --type empty --type file\n \293 fd -te -tf\n \294 - Find empty directories:\n \295 fd --type empty --type directory\n \296 fd -te -td"297 )]298 pub filetype: Option<Vec<FileType>>,299300 /// Filter by file extension301 #[arg(302 long = "extension",303 short = 'e',304 value_name = "ext",305 long_help = "(Additionally) filter search results by their file extension. Multiple \306 allowable file extensions can be specified.\n\307 If you want to search for files without extension, \308 you can use the regex '^[^.]+$' as a normal search pattern."309 )]310 pub extensions: Option<Vec<String>>,311312 /// Limit results based on the size of files313 #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",314 long_help = "Limit results based on the size of files using the format <+-><NUM><UNIT>.\n \315 '+': file size must be greater than or equal to this\n \316 '-': file size must be less than or equal to this\n\317 If neither '+' nor '-' is specified, file size must be exactly equal to this.\n \318 'NUM': The numeric size (e.g. 500)\n \319 'UNIT': The units for NUM. They are not case-sensitive.\n\320 Allowed unit values:\n \321 'b': bytes\n \322 'k': kilobytes (base ten, 10^3 = 1000 bytes)\n \323 'm': megabytes\n \324 'g': gigabytes\n \325 't': terabytes\n \326 'ki': kibibytes (base two, 2^10 = 1024 bytes)\n \327 'mi': mebibytes\n \328 'gi': gibibytes\n \329 'ti': tebibytes",330 )]331 pub size: Vec<SizeFilter>,332333 /// Filter by file modification time (newer than)334 #[arg(335 long,336 alias("change-newer-than"),337 alias("newer"),338 value_name = "date|dur",339 long_help = "Filter results based on the file modification time. The argument can be provided \340 as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \341 If the time is not specified, it defaults to 00:00:00. \342 '--change-newer-than' or '--newer' can be used as aliases.\n\343 Examples:\n \344 --changed-within 2weeks\n \345 --change-newer-than '2018-10-27 10:00:00'\n \346 --newer 2018-10-27"347 )]348 pub changed_within: Option<String>,349350 /// Filter by file modification time (older than)351 #[arg(352 long,353 alias("change-older-than"),354 alias("older"),355 value_name = "date|dur",356 long_help = "Filter results based on the file modification time. The argument can be provided \357 as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \358 '--change-older-than' or '--older' can be used as aliases.\n\359 Examples:\n \360 --changed-before '2018-10-27 10:00:00'\n \361 --change-older-than 2weeks\n \362 --older 2018-10-27"363 )]364 pub changed_before: Option<String>,365

Reorder command line optionsDavid Peterbefore adoption12165c7

lines 366–420why, one step back
366 /// Filter by owning user and/or group
367 #[cfg(unix)]368 #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",369 long_help = "Filter files by their user and/or group. \370 Format: [(user|uid)][:(group|gid)]. Either side is optional. \371 Precede either side with a '!' to exclude files instead.\n\372 Examples:\n \373 --owner john\n \374 --owner :students\n \375 --owner '!john:students'"376 )]377 pub owner: Option<OwnerFilter>,378379 #[command(flatten)]380 pub exec: Exec,381382 /// Max number of arguments to run as a batch size with -X383 #[arg(384 long,385 value_name = "size",386 hide_short_help = true,387 requires("exec_batch"),388 value_parser = value_parser!(usize),389 default_value_t,390 long_help = "Maximum number of arguments to pass to the command given with -X. \391 If the number of results is greater than the given size, \392 the command given with -X is run again with remaining arguments. \393 A batch size of zero means there is no limit (default), but note \394 that batching might still happen due to OS restrictions on the \395 maximum length of command lines.",396 )]397 pub batch_size: usize,398399 /// Add a custom ignore-file in '.gitignore' format400 #[arg(401 long,402 value_name = "path",403 hide_short_help = true,404 long_help = "Add a custom ignore-file in '.gitignore' format. These files have a low precedence."405 )]406 pub ignore_file: Vec<PathBuf>,407408 /// When to use colors409 #[arg(410 long,411 short = 'c',412 value_enum,413 default_value_t = ColorWhen::Auto,414 value_name = "when",415 long_help = "Declare when to use color for the pattern match output",416 )]417 pub color: ColorWhen,418419 /// Set number of threads to use for searching & executing (default: number420 /// of available CPU cores)

Merge pull request #1162 from sharkdp/fix-threads-optionDavid Peterbefore adoption0a7b51a

line 421why, one step back
421 #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = clap::value_parser!(u32).range(1..))]

Reorder command line optionsDavid Peterbefore adoption12165c7

lines 422–430why, one step back
422 pub threads: Option<u32>,
423424 /// Milliseconds to buffer before streaming search results to console425 ///426 /// Amount of time in milliseconds to buffer, before streaming the search427 /// results to the console.428 #[arg(long, hide = true, value_parser = parse_millis)]429 pub max_buffer_time: Option<Duration>,430

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 431–629why, one step back
431 /// Limit number of search results
432 #[arg(433 long,434 value_name = "count",435 hide_short_help = true,436 long_help = "Limit the number of search results to 'count' and quit immediately."437 )]438 max_results: Option<usize>,439440 /// Limit search to a single result441 #[arg(442 short = '1',443 hide_short_help = true,444 overrides_with("max_results"),445 long_help = "Limit the search to a single result and quit immediately. \446 This is an alias for '--max-results=1'."447 )]448 max_one_result: bool,449450 /// Print nothing, exit code 0 if match found, 1 otherwise451 #[arg(452 long,453 short = 'q',454 alias = "has-results",455 hide_short_help = true,456 conflicts_with("max_results"),457 long_help = "When the flag is present, the program does not print anything and will \458 return with an exit code of 0 if there is at least one match. Otherwise, the \459 exit code will be 1. \460 '--has-results' can be used as an alias."461 )]462 pub quiet: bool,463464 /// Show filesystem errors465 #[arg(466 long,467 hide_short_help = true,468 long_help = "Enable the display of filesystem errors for situations such as \469 insufficient permissions or dead symlinks."470 )]471 pub show_errors: bool,472473 /// Change current working directory474 #[arg(475 long,476 value_name = "path",477 hide_short_help = true,478 long_help = "Change the current working directory of fd to the provided path. This \479 means that search results will be shown with respect to the given base \480 path. Note that relative paths which are passed to fd via the positional \481 <path> argument or the '--search-path' option will also be resolved \482 relative to this directory."483 )]484 pub base_directory: Option<PathBuf>,485486 /// the search pattern (a regular expression, unless '--glob' is used; optional)487 #[arg(488 default_value = "",489 hide_default_value = true,490 value_name = "pattern",491 long_help = "the search pattern which is either a regular expression (default) or a glob \492 pattern (if --glob is used). If no pattern has been specified, every entry \493 is considered a match. If your pattern starts with a dash (-), make sure to \494 pass '--' first, or it will be considered as a flag (fd -- '-foo')."495 )]496 pub pattern: String,497498 /// Set path separator when printing file paths499 #[arg(500 long,501 value_name = "separator",502 hide_short_help = true,503 long_help = "Set the path separator to use when printing file paths. The default is \504 the OS-specific separator ('/' on Unix, '\\' on Windows)."505 )]506 pub path_separator: Option<String>,507508 /// the root directories for the filesystem search (optional)509 #[arg(action = ArgAction::Append,510 value_name = "path",511 long_help = "The directory where the filesystem search is rooted (optional). If \512 omitted, search the current working directory.",513 )]514 path: Vec<PathBuf>,515516 /// Provides paths to search as an alternative to the positional <path> argument517 #[arg(518 long,519 conflicts_with("path"),520 value_name = "search-path",521 hide_short_help = true,522 long_help = "Provide paths to search as an alternative to the positional <path> \523 argument. Changes the usage to `fd [OPTIONS] --search-path <path> \524 --search-path <path2> [<pattern>]`"525 )]526 search_path: Vec<PathBuf>,527528 /// By default, relative paths are prefixed with './' when -x/--exec,529 /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a530 /// path starting with '-' being treated as a command line option. Use531 /// this flag to disable this behaviour.532 #[arg(long, conflicts_with_all(&["path", "search_path"]), hide_short_help = true,533 long_help = "By default, relative paths are prefixed with './' when -x/--exec, \534 -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a \535 path starting with '-' being treated as a command line option. Use \536 this flag to disable this behaviour.",537 )]538 pub strip_cwd_prefix: bool,539540 #[cfg(any(unix, windows))]541 #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true,542 long_help = "By default, fd will traverse the file system tree as far as other options \543 dictate. With this flag, fd ensures that it does not descend into a \544 different file system than the one it started in. Comparable to the -mount \545 or -xdev filters of find(1).")]546 pub one_file_system: bool,547548 #[cfg(feature = "completions")]549 #[arg(long, hide = true, exclusive = true)]550 gen_completions: Option<Option<Shell>>,551}552553impl Opts {554 pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {555 // would it make sense to concatenate these?556 let paths = if !self.path.is_empty() {557 &self.path558 } else if !self.search_path.is_empty() {559 &self.search_path560 } else {561 let current_directory = Path::new(".");562 ensure_current_directory_exists(current_directory)?;563 return Ok(vec![self.normalize_path(current_directory)]);564 };565 Ok(paths566 .iter()567 .filter_map(|path| {568 if filesystem::is_existing_directory(path) {569 Some(self.normalize_path(path))570 } else {571 print_error(format!(572 "Search path '{}' is not a directory.",573 path.to_string_lossy()574 ));575 None576 }577 })578 .collect())579 }580581 fn normalize_path(&self, path: &Path) -> PathBuf {582 if self.absolute_path {583 filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()584 } else {585 path.to_path_buf()586 }587 }588589 pub fn no_search_paths(&self) -> bool {590 self.path.is_empty() && self.search_path.is_empty()591 }592593 #[inline]594 pub fn rg_alias_ignore(&self) -> bool {595 self.rg_alias_hidden_ignore > 0596 }597598 pub fn max_depth(&self) -> Option<usize> {599 self.max_depth.or(self.exact_depth)600 }601602 pub fn min_depth(&self) -> Option<usize> {603 self.min_depth.or(self.exact_depth)604 }605606 pub fn threads(&self) -> usize {607 // This will panic if the number of threads passed in is more than usize::MAX in an environment608 // where usize is less than 32 bits (for example 16-bit architectures). It's pretty609 // unlikely fd will be running in such an environment, and even more unlikely someone would610 // be trying to use that many threads on such an environment, so I think panicing is an611 // appropriate way to handle that.612 std::cmp::max(613 self.threads614 .map_or_else(num_cpus::get, |n| n.try_into().expect("too many threads")),615 1,616 )617 }618619 pub fn max_results(&self) -> Option<usize> {620 self.max_results621 .filter(|&m| m > 0)622 .or_else(|| self.max_one_result.then(|| 1))623 }624625 #[cfg(feature = "completions")]626 pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {627 self.gen_completions628 .map(|maybe_shell| match maybe_shell {629 Some(sh) => Ok(sh),

Merge pull request #1170 from tmccombs/clap-improvements-2Thayne McCombsbefore adoption85e3ada

lines 630–632why, one step back
630 None => {
631 Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))632 }

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 633–645why, one step back
633 })
634 .transpose()635 }636}637638#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]639pub enum FileType {640 #[value(alias = "f")]641 File,642 #[value(alias = "d")]643 Directory,644 #[value(alias = "l")]645 Symlink,

Merge pull request #1169 from Ptipiak/mention-executable-detectionDavid Peterbefore adoption38cdeb0

line 646why, one step back
646 /// A file which is executable by the current effective user

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 647–746why, one step back
647 #[value(alias = "x")]
648 Executable,649 #[value(alias = "e")]650 Empty,651 #[value(alias = "s")]652 Socket,653 #[value(alias = "p")]654 Pipe,655}656657#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]658pub enum ColorWhen {659 /// show colors if the output goes to an interactive console (default)660 Auto,661 /// always use colorized output662 Always,663 /// do not use colorized output664 Never,665}666667impl ColorWhen {668 pub fn as_str(&self) -> &'static str {669 use ColorWhen::*;670 match *self {671 Auto => "auto",672 Never => "never",673 Always => "always",674 }675 }676}677678// there isn't a derive api for getting grouped values yet,679// so we have to use hand-rolled parsing for exec and exec-batch680pub struct Exec {681 pub command: Option<CommandSet>,682}683684impl clap::FromArgMatches for Exec {685 fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {686 let command = matches687 .grouped_values_of("exec")688 .map(CommandSet::new)689 .or_else(|| {690 matches691 .grouped_values_of("exec_batch")692 .map(CommandSet::new_batch)693 })694 .transpose()695 .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;696 Ok(Exec { command })697 }698699 fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {700 *self = Self::from_arg_matches(matches)?;701 Ok(())702 }703}704705impl clap::Args for Exec {706 fn augment_args(cmd: Command) -> Command {707 cmd.arg(Arg::new("exec")708 .action(ArgAction::Append)709 .long("exec")710 .short('x')711 .num_args(1..)712 .allow_hyphen_values(true)713 .value_terminator(";")714 .value_name("cmd")715 .conflicts_with("list_details")716 .help("Execute a command for each search result")717 .long_help(718 "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \719 All positional arguments following --exec are considered to be arguments to the command - not to fd. \720 It is therefore recommended to place the '-x'/'--exec' option last.\n\721 The following placeholders are substituted before the command is executed:\n \722 '{}': path (of the current search result)\n \723 '{/}': basename\n \724 '{//}': parent directory\n \725 '{.}': path without file extension\n \726 '{/.}': basename without file extension\n\n\727 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\728 Examples:\n\n \729 - find all *.zip files and unzip them:\n\n \730 fd -e zip -x unzip\n\n \731 - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n \732 fd -e h -e cpp -x clang-format -i\n\n \733 - Convert all *.jpg files to *.png files:\n\n \734 fd -e jpg -x convert {} {.}.png\735 ",736 ),737 )738 .arg(739 Arg::new("exec_batch")740 .action(ArgAction::Append)741 .long("exec-batch")742 .short('X')743 .num_args(1..)744 .allow_hyphen_values(true)745 .value_terminator(";")746 .value_name("cmd")

Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91

line 747why, one step back
747 .conflicts_with_all(["exec", "list_details"])

Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3

lines 748–785why, one step back
748 .help("Execute a command with all search results at once")
749 .long_help(750 "Execute the given command once, with all search results as arguments.\n\751 One of the following placeholders is substituted before the command is executed:\n \752 '{}': path (of all search results)\n \753 '{/}': basename\n \754 '{//}': parent directory\n \755 '{.}': path without file extension\n \756 '{/.}': basename without file extension\n\n\757 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\758 Examples:\n\n \759 - Find all test_*.py files and open them in your favorite editor:\n\n \760 fd -g 'test_*.py' -X vim\n\n \761 - Find all *.rs files and count the lines with \"wc -l ...\":\n\n \762 fd -e rs -X wc -l\763 "764 ),765 )766 }767768 fn augment_args_for_update(cmd: Command) -> Command {769 Self::augment_args(cmd)770 }771}772773fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {774 Ok(Duration::from_millis(arg.parse()?))775}776777fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {778 if filesystem::is_existing_directory(current_directory) {779 Ok(())780 } else {781 Err(anyhow!(782 "Could not retrieve current directory (has it been deleted?)."783 ))784 }785}