Skip to content
Myr

Merge pull request #1067 from tmccombs/clap-derive

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Clap derive

authored by David Peter · committed by GitHub · parents c6f9595, 5771e74 · Browse files · 15 files+1081 added−1134 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+1081 added−1134 removed

  • tests:+12 added−2 removed
  • other:+1069 added−1132 removed

15 files+1081 added−1134 removed

modified:.github/workflows/CICD.yml+10 added-9 removed
1name: CICD23env:4 MIN_SUPPORTED_RUST_VERSION: "1.57.0"4 MIN_SUPPORTED_RUST_VERSION: "1.60.0"5 CICD_INTERMEDIATES_DIR: "_cicd-intermediates"67on:8 workflow_dispatch:
171 unmodified lines
180 use-cross: ${{ matrix.job.use-cross }}181 command: test182 args: --locked --target=${{ matrix.job.target }} ${{ steps.test-options.outputs.CARGO_TEST_OPTIONS}}183184 - name: Generate completions185 id: completions186 shell: bash187 run: make completions188189 - name: Create tarball190 id: package191 shell: bash192 run: |
4 unmodified lines
197198 PKG_STAGING="${{ env.CICD_INTERMEDIATES_DIR }}/package"199 ARCHIVE_DIR="${PKG_STAGING}/${PKG_BASENAME}/"200 mkdir -p "${ARCHIVE_DIR}"196 mkdir -p "${ARCHIVE_DIR}/autocomplete"201202 # Binary203 cp "${{ steps.strip.outputs.BIN_PATH }}" "$ARCHIVE_DIR"204
3 unmodified lines
208 # README, LICENSE and CHANGELOG files209 cp "README.md" "LICENSE-MIT" "LICENSE-APACHE" "CHANGELOG.md" "$ARCHIVE_DIR"210211 # Autocompletion files208 cp 'target/${{ matrix.job.target }}/release/build/${{ env.PROJECT_NAME }}'*/out/'${{ env.PROJECT_NAME }}.bash' "$ARCHIVE_DIR/autocomplete/"209 cp 'target/${{ matrix.job.target }}/release/build/${{ env.PROJECT_NAME }}'*/out/'${{ env.PROJECT_NAME }}.fish' "$ARCHIVE_DIR/autocomplete/"210 cp 'target/${{ matrix.job.target }}/release/build/${{ env.PROJECT_NAME }}'*/out/'_${{ env.PROJECT_NAME }}.ps1' "$ARCHIVE_DIR/autocomplete/"211 cp 'contrib/completion/_fd' "$ARCHIVE_DIR/autocomplete/"212 cp -r autocomplete "${ARCHIVE_DIR}"213214 # base compressed package215 pushd "${PKG_STAGING}/" >/dev/null216 case ${{ matrix.job.target }} in
39 unmodified lines
256 install -Dm644 'doc/${{ env.PROJECT_NAME }}.1' "${DPKG_DIR}/usr/share/man/man1/${{ env.PROJECT_NAME }}.1"257 gzip -n --best "${DPKG_DIR}/usr/share/man/man1/${{ env.PROJECT_NAME }}.1"258259 # Autocompletion files259 install -Dm644 'target/${{ matrix.job.target }}/release/build/${{ env.PROJECT_NAME }}'*/out/'${{ env.PROJECT_NAME }}.bash' "${DPKG_DIR}/usr/share/bash-completion/completions/${{ env.PROJECT_NAME }}"260 install -Dm644 'target/${{ matrix.job.target }}/release/build/${{ env.PROJECT_NAME }}'*/out/'${{ env.PROJECT_NAME }}.fish' "${DPKG_DIR}/usr/share/fish/vendor_completions.d/${{ env.PROJECT_NAME }}.fish"261 install -Dm644 'contrib/completion/_fd' "${DPKG_DIR}/usr/share/zsh/vendor-completions/_${{ env.PROJECT_NAME }}"260 install -Dm644 'autocomplete/fd.bash' "${DPKG_DIR}/usr/share/bash-completion/completions/${{ env.PROJECT_NAME }}"261 install -Dm644 'autocomplete/fd.fish' "${DPKG_DIR}/usr/share/fish/vendor_completions.d/${{ env.PROJECT_NAME }}.fish"262 install -Dm644 'autocomplete/_fd' "${DPKG_DIR}/usr/share/zsh/vendor-completions/_${{ env.PROJECT_NAME }}"263264 # README and LICENSE265 install -Dm644 "README.md" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/README.md"266 install -Dm644 "LICENSE-MIT" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/LICENSE-MIT"
99 unmodified lines
modified:src/exec/job.rs+2 added-1 removed
38 unmodified lines
3940 // Generate a command, execute it and store its exit code.41 results.push(cmd.execute(42 dir_entry.stripped_path(config),43 config.path_separator.as_deref(),44 Arc::clone(&out_perm),45 buffer_output,46 ))47 }
13 unmodified lines
61 None62 }63 });6464 cmd.execute_batch(paths, config.batch_size)65 cmd.execute_batch(paths, config.batch_size, config.path_separator.as_deref())66}
modified:src/exec/mod.rs+19 added-26 removed
33 unmodified lines
3435#[derive(Debug, Clone, PartialEq)]36pub struct CommandSet {37 mode: ExecutionMode,38 path_separator: Option<String>,38 commands: Vec<CommandTemplate>,39}4041impl CommandSet {43 pub fn new<I, S>(input: I, path_separator: Option<String>) -> Result<CommandSet>42 pub fn new<I, S>(input: I) -> Result<CommandSet>43 where44 I: IntoIterator<Item = Vec<S>>,45 S: AsRef<str>,46 {47 Ok(CommandSet {48 mode: ExecutionMode::OneByOne,50 path_separator,49 commands: input50 .into_iter()51 .map(CommandTemplate::new)52 .collect::<Result<_>>()?,53 })54 }5558 pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandSet>56 pub fn new_batch<I, S>(input: I) -> Result<CommandSet>57 where58 I: IntoIterator<Item = Vec<S>>,59 S: AsRef<str>,60 {61 Ok(CommandSet {62 mode: ExecutionMode::Batch,65 path_separator,63 commands: input64 .into_iter()65 .map(|args| {66 let cmd = CommandTemplate::new(args)?;
12 unmodified lines
79 pub fn in_batch_mode(&self) -> bool {80 self.mode == ExecutionMode::Batch81 }8286 pub fn execute(&self, input: &Path, out_perm: Arc<Mutex<()>>, buffer_output: bool) -> ExitCode {87 let path_separator = self.path_separator.as_deref();83 pub fn execute(84 &self,85 input: &Path,86 path_separator: Option<&str>,87 out_perm: Arc<Mutex<()>>,88 buffer_output: bool,89 ) -> ExitCode {90 let commands = self91 .commands92 .iter()93 .map(|c| c.generate(input, path_separator));94 execute_commands(commands, &out_perm, buffer_output)95 }9695 pub fn execute_batch<I>(&self, paths: I, limit: usize) -> ExitCode97 pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode98 where99 I: Iterator<Item = PathBuf>,100 {99 let path_separator = self.path_separator.as_deref();100101 let builders: io::Result<Vec<_>> = self102 .commands103 .iter()104 .map(|c| CommandBuilder::new(c, limit))
307 unmodified lines
412413 #[test]414 fn tokens_with_placeholder() {415 assert_eq!(416 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]], None).unwrap(),416 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),417 CommandSet {418 commands: vec![CommandTemplate {419 args: vec![420 ArgumentTemplate::Text("echo".into()),
1 unmodified line
422 ArgumentTemplate::Tokens(vec![Token::Placeholder]),423 ]424 }],425 mode: ExecutionMode::OneByOne,426 path_separator: None,426 }427 );428 }429430 #[test]431 fn tokens_with_no_extension() {432 assert_eq!(434 CommandSet::new(vec![vec!["echo", "{.}"]], None).unwrap(),433 CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),434 CommandSet {435 commands: vec![CommandTemplate {436 args: vec![437 ArgumentTemplate::Text("echo".into()),438 ArgumentTemplate::Tokens(vec![Token::NoExt]),439 ],440 }],441 mode: ExecutionMode::OneByOne,443 path_separator: None,442 }443 );444 }445446 #[test]447 fn tokens_with_basename() {448 assert_eq!(451 CommandSet::new(vec![vec!["echo", "{/}"]], None).unwrap(),449 CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),450 CommandSet {451 commands: vec![CommandTemplate {452 args: vec![453 ArgumentTemplate::Text("echo".into()),454 ArgumentTemplate::Tokens(vec![Token::Basename]),455 ],456 }],457 mode: ExecutionMode::OneByOne,460 path_separator: None,458 }459 );460 }461462 #[test]463 fn tokens_with_parent() {464 assert_eq!(468 CommandSet::new(vec![vec!["echo", "{//}"]], None).unwrap(),465 CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),466 CommandSet {467 commands: vec![CommandTemplate {468 args: vec![469 ArgumentTemplate::Text("echo".into()),470 ArgumentTemplate::Tokens(vec![Token::Parent]),471 ],472 }],473 mode: ExecutionMode::OneByOne,477 path_separator: None,474 }475 );476 }477478 #[test]479 fn tokens_with_basename_no_extension() {480 assert_eq!(485 CommandSet::new(vec![vec!["echo", "{/.}"]], None).unwrap(),481 CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),482 CommandSet {483 commands: vec![CommandTemplate {484 args: vec![485 ArgumentTemplate::Text("echo".into()),486 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),487 ],488 }],489 mode: ExecutionMode::OneByOne,494 path_separator: None,490 }491 );492 }493494 #[test]495 fn tokens_multiple() {496 assert_eq!(502 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]], None).unwrap(),497 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),498 CommandSet {499 commands: vec![CommandTemplate {500 args: vec![501 ArgumentTemplate::Text("cp".into()),
4 unmodified lines
506 ]),507 ],508 }],509 mode: ExecutionMode::OneByOne,515 path_separator: None,510 }511 );512 }513514 #[test]515 fn tokens_single_batch() {516 assert_eq!(523 CommandSet::new_batch(vec![vec!["echo", "{.}"]], None).unwrap(),517 CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),518 CommandSet {519 commands: vec![CommandTemplate {520 args: vec![521 ArgumentTemplate::Text("echo".into()),522 ArgumentTemplate::Tokens(vec![Token::NoExt]),523 ],524 }],525 mode: ExecutionMode::Batch,532 path_separator: None,526 }527 );528 }529530 #[test]531 fn tokens_multiple_batch() {539 assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]], None).is_err());532 assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());533 }534535 #[test]536 fn template_no_args() {
1 unmodified line
538 }539540 #[test]541 fn command_set_no_args() {549 assert!(CommandSet::new(vec![vec!["echo"], vec![]], None).is_err());542 assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());543 }544545 #[test]546 fn generate_custom_path_separator() {
40 unmodified lines
modified:src/filter/size.rs+8 added-2 removed
1use anyhow::anyhow;2use once_cell::sync::Lazy;3use regex::Regex;45static SIZE_CAPTURES: Lazy<Regex> =
18 unmodified lines
24const GIBI: u64 = MEBI * 1024;25const TEBI: u64 = GIBI * 1024;2627impl SizeFilter {27 pub fn from_string(s: &str) -> Option<Self> {28 pub fn from_string(s: &str) -> anyhow::Result<Self> {29 SizeFilter::parse_opt(s)30 .ok_or_else(|| anyhow!("'{}' is not a valid size constraint. See 'fd --help'.", s))31 }3233 fn parse_opt(s: &str) -> Option<Self> {34 if !SIZE_CAPTURES.is_match(s) {35 return None;36 }37
132 unmodified lines
170 $(171 #[test]172 fn $name() {173 let i = SizeFilter::from_string($value);168 assert!(i.is_none());174 assert!(i.is_err());175 }176 )*177 };178 }
39 unmodified lines
deleted:src/app.rs-779 removed
1use clap::{crate_version, AppSettings, Arg, ColorChoice, Command};23pub fn build_app() -> Command<'static> {4 let clap_color_choice = if std::env::var_os("NO_COLOR").is_none() {5 ColorChoice::Auto6 } else {7 ColorChoice::Never8 };910 let mut app = Command::new("fd")11 .version(crate_version!())12 .color(clap_color_choice)13 .setting(AppSettings::DeriveDisplayOrder)14 .dont_collapse_args_in_usage(true)15 .after_help(16 "Note: `fd -h` prints a short and concise overview while `fd --help` gives all \17 details.",18 )19 .after_long_help(20 "Bugs can be reported on GitHub: https://github.com/sharkdp/fd/issues"21 )22 .arg(23 Arg::new("hidden")24 .long("hidden")25 .short('H')26 .overrides_with("hidden")27 .help("Search hidden files and directories")28 .long_help(29 "Include hidden directories and files in the search results (default: \30 hidden files and directories are skipped). Files and directories are \31 considered to be hidden if their name starts with a `.` sign (dot). \32 The flag can be overridden with --no-hidden.",33 ),34 )35 .arg(36 Arg::new("no-hidden")37 .long("no-hidden")38 .overrides_with("hidden")39 .hide(true)40 .long_help(41 "Overrides --hidden.",42 ),43 )44 .arg(45 Arg::new("no-ignore")46 .long("no-ignore")47 .short('I')48 .overrides_with("no-ignore")49 .help("Do not respect .(git|fd)ignore files")50 .long_help(51 "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 )56 .arg(57 Arg::new("ignore")58 .long("ignore")59 .overrides_with("no-ignore")60 .hide(true)61 .long_help(62 "Overrides --no-ignore.",63 ),64 )65 .arg(66 Arg::new("no-ignore-vcs")67 .long("no-ignore-vcs")68 .overrides_with("no-ignore-vcs")69 .hide_short_help(true)70 .help("Do not respect .gitignore files")71 .long_help(72 "Show search results from files and directories that would otherwise be \73 ignored by '.gitignore' files. The flag can be overridden with --ignore-vcs.",74 ),75 )76 .arg(77 Arg::new("ignore-vcs")78 .long("ignore-vcs")79 .overrides_with("no-ignore-vcs")80 .hide(true)81 .long_help(82 "Overrides --no-ignore-vcs.",83 ),84 )85 .arg(86 Arg::new("no-ignore-parent")87 .long("no-ignore-parent")88 .overrides_with("no-ignore-parent")89 .hide_short_help(true)90 .help("Do not respect .(git|fd)ignore files in parent directories")91 .long_help(92 "Show search results from files and directories that would otherwise be \93 ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories.",94 ),95 )96 .arg(97 Arg::new("no-global-ignore-file")98 .long("no-global-ignore-file")99 .hide(true)100 .help("Do not respect the global ignore file")101 .long_help("Do not respect the global ignore file."),102 )103 .arg(104 Arg::new("rg-alias-hidden-ignore")105 .short('u')106 .long("unrestricted")107 .overrides_with_all(&["ignore", "no-hidden"])108 .multiple_occurrences(true) // Allowed for historical reasons109 .hide_short_help(true)110 .help("Unrestricted search, alias for '--no-ignore --hidden'")111 .long_help(112 "Perform an unrestricted search, including ignored and hidden files. This is \113 an alias for '--no-ignore --hidden'."114 ),115 )116 .arg(117 Arg::new("case-sensitive")118 .long("case-sensitive")119 .short('s')120 .overrides_with_all(&["ignore-case", "case-sensitive"])121 .help("Case-sensitive search (default: smart case)")122 .long_help(123 "Perform a case-sensitive search. By default, fd uses case-insensitive \124 searches, unless the pattern contains an uppercase character (smart \125 case).",126 ),127 )128 .arg(129 Arg::new("ignore-case")130 .long("ignore-case")131 .short('i')132 .overrides_with_all(&["case-sensitive", "ignore-case"])133 .help("Case-insensitive search (default: smart case)")134 .long_help(135 "Perform a case-insensitive search. By default, fd uses case-insensitive \136 searches, unless the pattern contains an uppercase character (smart \137 case).",138 ),139 )140 .arg(141 Arg::new("glob")142 .long("glob")143 .short('g')144 .conflicts_with("fixed-strings")145 .overrides_with("glob")146 .help("Glob-based search (default: regular expression)")147 .long_help("Perform a glob-based search instead of a regular expression search."),148 )149 .arg(150 Arg::new("regex")151 .long("regex")152 .overrides_with_all(&["glob", "regex"])153 .hide_short_help(true)154 .help("Regular-expression based search (default)")155 .long_help(156 "Perform a regular-expression based search (default). This can be used to \157 override --glob.",158 ),159 )160 .arg(161 Arg::new("fixed-strings")162 .long("fixed-strings")163 .short('F')164 .alias("literal")165 .overrides_with("fixed-strings")166 .hide_short_help(true)167 .help("Treat pattern as literal string instead of regex")168 .long_help(169 "Treat the pattern as a literal string instead of a regular expression. Note \170 that this also performs substring comparison. If you want to match on an \171 exact filename, consider using '--glob'.",172 ),173 )174 .arg(175 Arg::new("absolute-path")176 .long("absolute-path")177 .short('a')178 .overrides_with("absolute-path")179 .help("Show absolute instead of relative paths")180 .long_help(181 "Shows the full path starting from the root as opposed to relative paths. \182 The flag can be overridden with --relative-path.",183 ),184 )185 .arg(186 Arg::new("relative-path")187 .long("relative-path")188 .overrides_with("absolute-path")189 .hide(true)190 .long_help(191 "Overrides --absolute-path.",192 ),193 )194 .arg(195 Arg::new("list-details")196 .long("list-details")197 .short('l')198 .conflicts_with("absolute-path")199 .help("Use a long listing format with file metadata")200 .long_help(201 "Use a detailed listing format like 'ls -l'. This is basically an alias \202 for '--exec-batch ls -l' with some additional 'ls' options. This can be \203 used to see more metadata, to show symlink targets and to achieve a \204 deterministic sort order.",205 ),206 )207 .arg(208 Arg::new("follow")209 .long("follow")210 .short('L')211 .alias("dereference")212 .overrides_with("follow")213 .help("Follow symbolic links")214 .long_help(215 "By default, fd does not descend into symlinked directories. Using this \216 flag, symbolic links are also traversed. \217 Flag can be overriden with --no-follow.",218 ),219 )220 .arg(221 Arg::new("no-follow")222 .long("no-follow")223 .overrides_with("follow")224 .hide(true)225 .long_help(226 "Overrides --follow.",227 ),228 )229 .arg(230 Arg::new("full-path")231 .long("full-path")232 .short('p')233 .overrides_with("full-path")234 .help("Search full abs. path (default: filename only)")235 .long_help(236 "By default, the search pattern is only matched against the filename (or \237 directory name). Using this flag, the pattern is matched against the full \238 (absolute) path. Example:\n \239 fd --glob -p '**/.git/config'",240 ),241 )242 .arg(243 Arg::new("null_separator")244 .long("print0")245 .short('0')246 .overrides_with("print0")247 .conflicts_with("list-details")248 .hide_short_help(true)249 .help("Separate results by the null character")250 .long_help(251 "Separate search results by the null character (instead of newlines). \252 Useful for piping results to 'xargs'.",253 ),254 )255 .arg(256 Arg::new("max-depth")257 .long("max-depth")258 .short('d')259 .takes_value(true)260 .value_name("depth")261 .help("Set maximum search depth (default: none)")262 .long_help(263 "Limit the directory traversal to a given depth. By default, there is no \264 limit on the search depth.",265 ),266 )267 // support --maxdepth as well, for compatibility with rg268 .arg(269 Arg::new("rg-depth")270 .long("maxdepth")271 .hide(true)272 .takes_value(true)273 .help("Set maximum search depth (default: none)")274 )275 .arg(276 Arg::new("min-depth")277 .long("min-depth")278 .takes_value(true)279 .value_name("depth")280 .hide_short_help(true)281 .help("Only show results starting at given depth")282 .long_help(283 "Only show search results starting at the given depth. \284 See also: '--max-depth' and '--exact-depth'",285 ),286 )287 .arg(288 Arg::new("exact-depth")289 .long("exact-depth")290 .takes_value(true)291 .value_name("depth")292 .hide_short_help(true)293 .conflicts_with_all(&["max-depth", "min-depth"])294 .help("Only show results at exact given depth")295 .long_help(296 "Only show search results at the exact given depth. This is an alias for \297 '--min-depth <depth> --max-depth <depth>'.",298 ),299 )300 .arg(301 Arg::new("prune")302 .long("prune")303 .conflicts_with_all(&["size", "exact-depth"])304 .hide_short_help(true)305 .help("Do not traverse into matching directories")306 .long_help("Do not traverse into directories that match the search criteria. If \307 you want to exclude specific directories, use the '--exclude=…' option.")308 )309 .arg(310 Arg::new("file-type")311 .long("type")312 .short('t')313 .multiple_occurrences(true)314 .number_of_values(1)315 .takes_value(true)316 .value_name("filetype")317 .possible_values(&[318 "f",319 "file",320 "d",321 "directory",322 "l",323 "symlink",324 "x",325 "executable",326 "e",327 "empty",328 "s",329 "socket",330 "p",331 "pipe",332 ])333 .hide_possible_values(true)334 .help(335 "Filter by type: file (f), directory (d), symlink (l),\nexecutable (x), \336 empty (e), socket (s), pipe (p)",337 )338 .long_help(339 "Filter the search by type:\n \340 'f' or 'file': regular files\n \341 'd' or 'directory': directories\n \342 'l' or 'symlink': symbolic links\n \343 's' or 'socket': socket\n \344 'p' or 'pipe': named pipe (FIFO)\n\n \345 'x' or 'executable': executables\n \346 'e' or 'empty': empty files or directories\n\n\347 This option can be specified more than once to include multiple file types. \348 Searching for '--type file --type symlink' will show both regular files as \349 well as symlinks. Note that the 'executable' and 'empty' filters work differently: \350 '--type executable' implies '--type file' by default. And '--type empty' searches \351 for empty files and directories, unless either '--type file' or '--type directory' \352 is specified in addition.\n\n\353 Examples:\n \354 - Only search for files:\n \355 fd --type file …\n \356 fd -tf …\n \357 - Find both files and symlinks\n \358 fd --type file --type symlink …\n \359 fd -tf -tl …\n \360 - Find executable files:\n \361 fd --type executable\n \362 fd -tx\n \363 - Find empty files:\n \364 fd --type empty --type file\n \365 fd -te -tf\n \366 - Find empty directories:\n \367 fd --type empty --type directory\n \368 fd -te -td"369 ),370 )371 .arg(372 Arg::new("extension")373 .long("extension")374 .short('e')375 .multiple_occurrences(true)376 .number_of_values(1)377 .takes_value(true)378 .value_name("ext")379 .help("Filter by file extension")380 .long_help(381 "(Additionally) filter search results by their file extension. Multiple \382 allowable file extensions can be specified.\n\383 If you want to search for files without extension, \384 you can use the regex '^[^.]+$' as a normal search pattern.",385 ),386 )387 .arg(388 Arg::new("exec")389 .long("exec")390 .short('x')391 .min_values(1)392 .multiple_occurrences(true)393 .allow_hyphen_values(true)394 .value_terminator(";")395 .value_name("cmd")396 .conflicts_with("list-details")397 .help("Execute a command for each search result")398 .long_help(399 "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \400 All positional arguments following --exec are considered to be arguments to the command - not to fd. \401 It is therefore recommended to place the '-x'/'--exec' option last.\n\402 The following placeholders are substituted before the command is executed:\n \403 '{}': path (of the current search result)\n \404 '{/}': basename\n \405 '{//}': parent directory\n \406 '{.}': path without file extension\n \407 '{/.}': basename without file extension\n\n\408 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\409 Examples:\n\n \410 - find all *.zip files and unzip them:\n\n \411 fd -e zip -x unzip\n\n \412 - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n \413 fd -e h -e cpp -x clang-format -i\n\n \414 - Convert all *.jpg files to *.png files:\n\n \415 fd -e jpg -x convert {} {.}.png\416 ",417 ),418 )419 .arg(420 Arg::new("exec-batch")421 .long("exec-batch")422 .short('X')423 .min_values(1)424 .multiple_occurrences(true)425 .allow_hyphen_values(true)426 .value_terminator(";")427 .value_name("cmd")428 .conflicts_with_all(&["exec", "list-details"])429 .help("Execute a command with all search results at once")430 .long_help(431 "Execute the given command once, with all search results as arguments.\n\432 One of the following placeholders is substituted before the command is executed:\n \433 '{}': path (of all search results)\n \434 '{/}': basename\n \435 '{//}': parent directory\n \436 '{.}': path without file extension\n \437 '{/.}': basename without file extension\n\n\438 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\439 Examples:\n\n \440 - Find all test_*.py files and open them in your favorite editor:\n\n \441 fd -g 'test_*.py' -X vim\n\n \442 - Find all *.rs files and count the lines with \"wc -l ...\":\n\n \443 fd -e rs -X wc -l\444 "445 ),446 )447 .arg(448 Arg::new("batch-size")449 .long("batch-size")450 .takes_value(true)451 .value_name("size")452 .hide_short_help(true)453 .requires("exec-batch")454 .help("Max number of arguments to run as a batch with -X")455 .long_help(456 "Maximum number of arguments to pass to the command given with -X. \457 If the number of results is greater than the given size, \458 the command given with -X is run again with remaining arguments. \459 A batch size of zero means there is no limit (default), but note \460 that batching might still happen due to OS restrictions on the \461 maximum length of command lines.",462 ),463 )464 .arg(465 Arg::new("exclude")466 .long("exclude")467 .short('E')468 .takes_value(true)469 .value_name("pattern")470 .number_of_values(1)471 .multiple_occurrences(true)472 .help("Exclude entries that match the given glob pattern")473 .long_help(474 "Exclude files/directories that match the given glob pattern. This \475 overrides any other ignore logic. Multiple exclude patterns can be \476 specified.\n\n\477 Examples:\n \478 --exclude '*.pyc'\n \479 --exclude node_modules",480 ),481 )482 .arg(483 Arg::new("ignore-file")484 .long("ignore-file")485 .takes_value(true)486 .value_name("path")487 .number_of_values(1)488 .multiple_occurrences(true)489 .hide_short_help(true)490 .help("Add custom ignore-file in '.gitignore' format")491 .long_help(492 "Add a custom ignore-file in '.gitignore' format. These files have a low \493 precedence.",494 ),495 )496 .arg(497 Arg::new("color")498 .long("color")499 .short('c')500 .takes_value(true)501 .value_name("when")502 .possible_values(&["never", "auto", "always"])503 .hide_possible_values(true)504 .help("When to use colors: never, *auto*, always")505 .long_help(506 "Declare when to use color for the pattern match output:\n \507 'auto': show colors if the output goes to an interactive console (default)\n \508 'never': do not use colorized output\n \509 'always': always use colorized output",510 ),511 )512 .arg(513 Arg::new("threads")514 .long("threads")515 .short('j')516 .takes_value(true)517 .value_name("num")518 .hide_short_help(true)519 .help("Set number of threads")520 .long_help(521 "Set number of threads to use for searching & executing (default: number \522 of available CPU cores)",523 ),524 )525 .arg(526 Arg::new("size")527 .long("size")528 .short('S')529 .takes_value(true)530 .number_of_values(1)531 .allow_hyphen_values(true)532 .multiple_occurrences(true)533 .help("Limit results based on the size of files")534 .long_help(535 "Limit results based on the size of files using the format <+-><NUM><UNIT>.\n \536 '+': file size must be greater than or equal to this\n \537 '-': file size must be less than or equal to this\n\538 If neither '+' nor '-' is specified, file size must be exactly equal to this.\n \539 'NUM': The numeric size (e.g. 500)\n \540 'UNIT': The units for NUM. They are not case-sensitive.\n\541 Allowed unit values:\n \542 'b': bytes\n \543 'k': kilobytes (base ten, 10^3 = 1000 bytes)\n \544 'm': megabytes\n \545 'g': gigabytes\n \546 't': terabytes\n \547 'ki': kibibytes (base two, 2^10 = 1024 bytes)\n \548 'mi': mebibytes\n \549 'gi': gibibytes\n \550 'ti': tebibytes",551 ),552 )553 .arg(554 Arg::new("max-buffer-time")555 .long("max-buffer-time")556 .takes_value(true)557 .hide(true)558 .help("Milliseconds to buffer before streaming search results to console")559 .long_help(560 "Amount of time in milliseconds to buffer, before streaming the search \561 results to the console.",562 ),563 )564 .arg(565 Arg::new("changed-within")566 .long("changed-within")567 .alias("change-newer-than")568 .alias("newer")569 .takes_value(true)570 .value_name("date|dur")571 .number_of_values(1)572 .help("Filter by file modification time (newer than)")573 .long_help(574 "Filter results based on the file modification time. The argument can be provided \575 as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \576 If the time is not specified, it defaults to 00:00:00. \577 '--change-newer-than' or '--newer' can be used as aliases.\n\578 Examples:\n \579 --changed-within 2weeks\n \580 --change-newer-than '2018-10-27 10:00:00'\n \581 --newer 2018-10-27",582 ),583 )584 .arg(585 Arg::new("changed-before")586 .long("changed-before")587 .alias("change-older-than")588 .alias("older")589 .takes_value(true)590 .value_name("date|dur")591 .number_of_values(1)592 .help("Filter by file modification time (older than)")593 .long_help(594 "Filter results based on the file modification time. The argument can be provided \595 as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \596 '--change-older-than' or '--older' can be used as aliases.\n\597 Examples:\n \598 --changed-before '2018-10-27 10:00:00'\n \599 --change-older-than 2weeks\n \600 --older 2018-10-27",601 ),602 )603 .arg(604 Arg::new("max-results")605 .long("max-results")606 .takes_value(true)607 .value_name("count")608 // We currently do not support --max-results in combination with609 // program execution because the results that come up in a --max-results610 // search are non-deterministic. Users might think that they can run the611 // same search with `--exec rm` attached and get a reliable removal of612 // the files they saw in the previous search.613 .conflicts_with_all(&["exec", "exec-batch", "list-details"])614 .hide_short_help(true)615 .help("Limit number of search results")616 .long_help("Limit the number of search results to 'count' and quit immediately."),617 )618 .arg(619 Arg::new("max-one-result")620 .short('1')621 .hide_short_help(true)622 .overrides_with("max-results")623 .conflicts_with_all(&["exec", "exec-batch", "list-details"])624 .help("Limit search to a single result")625 .long_help("Limit the search to a single result and quit immediately. \626 This is an alias for '--max-results=1'.")627 )628 .arg(629 Arg::new("quiet")630 .long("quiet")631 .short('q')632 .alias("has-results")633 .hide_short_help(true)634 .conflicts_with_all(&["exec", "exec-batch", "list-details", "max-results"])635 .help("Print nothing, exit code 0 if match found, 1 otherwise")636 .long_help(637 "When the flag is present, the program does not print anything and will \638 return with an exit code of 0 if there is at least one match. Otherwise, the \639 exit code will be 1. \640 '--has-results' can be used as an alias."641 )642 )643 .arg(644 Arg::new("show-errors")645 .long("show-errors")646 .hide_short_help(true)647 .overrides_with("show-errors")648 .help("Show filesystem errors")649 .long_help(650 "Enable the display of filesystem errors for situations such as \651 insufficient permissions or dead symlinks.",652 ),653 )654 .arg(655 Arg::new("base-directory")656 .long("base-directory")657 .takes_value(true)658 .value_name("path")659 .number_of_values(1)660 .allow_invalid_utf8(true)661 .hide_short_help(true)662 .help("Change current working directory")663 .long_help(664 "Change the current working directory of fd to the provided path. This \665 means that search results will be shown with respect to the given base \666 path. Note that relative paths which are passed to fd via the positional \667 <path> argument or the '--search-path' option will also be resolved \668 relative to this directory.",669 ),670 )671 .arg(672 Arg::new("pattern")673 .allow_invalid_utf8(true)674 .help(675 "the search pattern (a regular expression, unless '--glob' is used; optional)",676 ).long_help(677 "the search pattern which is either a regular expression (default) or a glob \678 pattern (if --glob is used). If no pattern has been specified, every entry \679 is considered a match. If your pattern starts with a dash (-), make sure to \680 pass '--' first, or it will be considered as a flag (fd -- '-foo').")681 )682 .arg(683 Arg::new("path-separator")684 .takes_value(true)685 .value_name("separator")686 .long("path-separator")687 .hide_short_help(true)688 .help("Set path separator when printing file paths")689 .long_help(690 "Set the path separator to use when printing file paths. The default is \691 the OS-specific separator ('/' on Unix, '\\' on Windows).",692 ),693 )694 .arg(695 Arg::new("path")696 .multiple_occurrences(true)697 .allow_invalid_utf8(true)698 .help("the root directory for the filesystem search (optional)")699 .long_help(700 "The directory where the filesystem search is rooted (optional). If \701 omitted, search the current working directory.",702 ),703 )704 .arg(705 Arg::new("search-path")706 .long("search-path")707 .takes_value(true)708 .conflicts_with("path")709 .multiple_occurrences(true)710 .hide_short_help(true)711 .number_of_values(1)712 .allow_invalid_utf8(true)713 .help("Provide paths to search as an alternative to the positional <path>")714 .long_help(715 "Provide paths to search as an alternative to the positional <path> \716 argument. Changes the usage to `fd [OPTIONS] --search-path <path> \717 --search-path <path2> [<pattern>]`",718 ),719 )720 .arg(721 Arg::new("strip-cwd-prefix")722 .long("strip-cwd-prefix")723 .conflicts_with_all(&["path", "search-path"])724 .hide_short_help(true)725 .help("strip './' prefix from -0/--print0 output")726 .long_help(727 "By default, relative paths are prefixed with './' when -x/--exec, \728 -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a \729 path starting with '-' being treated as a command line option. Use \730 this flag to disable this behaviour."731 )732 );733734 if cfg!(unix) {735 app = app.arg(736 Arg::new("owner")737 .long("owner")738 .short('o')739 .takes_value(true)740 .value_name("user:group")741 .help("Filter by owning user and/or group")742 .long_help(743 "Filter files by their user and/or group. \744 Format: [(user|uid)][:(group|gid)]. Either side is optional. \745 Precede either side with a '!' to exclude files instead.\n\746 Examples:\n \747 --owner john\n \748 --owner :students\n \749 --owner '!john:students'",750 ),751 );752 }753754 // Make `--one-file-system` available only on Unix and Windows platforms, as per the755 // restrictions on the corresponding option in the `ignore` crate.756 // Provide aliases `mount` and `xdev` for people coming from `find`.757 if cfg!(any(unix, windows)) {758 app = app.arg(759 Arg::new("one-file-system")760 .long("one-file-system")761 .aliases(&["mount", "xdev"])762 .hide_short_help(true)763 .help("Do not descend into a different file system")764 .long_help(765 "By default, fd will traverse the file system tree as far as other options \766 dictate. With this flag, fd ensures that it does not descend into a \767 different file system than the one it started in. Comparable to the -mount \768 or -xdev filters of find(1).",769 ),770 );771 }772773 app774}775776#[test]777fn verify_app() {778 build_app().debug_assert()779}
added:src/cli.rs+845 added
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 version,87 after_long_help = "Bugs can be reported on GitHub: https://github.com/sharkdp/fd/issues",88 args_override_self = true,89 group(ArgGroup::new("execs").args(&["exec", "exec_batch", "list_details"]).conflicts_with_all(&[90 "max_results", "has_results", "count"])),91)]92pub struct Opts {93 /// Search hidden files and directories94 #[arg(95 long,96 short = 'H',97 long_help = "Include hidden directories and files in the search results (default: \98 hidden files and directories are skipped). Files and directories are \99 considered to be hidden if their name starts with a `.` sign (dot). \100 The flag can be overridden with --no-hidden."101 )]102 pub hidden: bool,103104 /// Do not respect .(git|fd)ignore files105 #[arg(106 long,107 short = 'I',108 long_help = "Show search results from files and directories that would otherwise be \109 ignored by '.gitignore', '.ignore', '.fdignore', or the global ignore file. \110 The flag can be overridden with --ignore."111 )]112 pub no_ignore: bool,113114 /// Do not respect .gitignore files115 #[arg(116 long,117 hide_short_help = true,118 long_help = "Show search results from files and directories that would otherwise be \119 ignored by '.gitignore' files. The flag can be overridden with --ignore-vcs."120 )]121 pub no_ignore_vcs: bool,122123 /// Do not respect .(git|fd)ignore files in parent directories124 #[arg(125 long,126 hide_short_help = true,127 long_help = "Show search results from files and directories that would otherwise be \128 ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories."129 )]130 pub no_ignore_parent: bool,131132 /// Do not respect the global ignore file133 #[arg(long, hide = true)]134 pub no_global_ignore_file: bool,135136 /// Unrestricted search, alias for '--no-ignore --hidden'137 #[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,138 long_help = "Perform an unrestricted search, including ignored and hidden files. This is \139 an alias for '--no-ignore --hidden'."140 )]141 rg_alias_hidden_ignore: u8,142143 /// Case-sensitive search (default: smart case)144 #[arg(145 long,146 short = 's',147 overrides_with("ignore_case"),148 long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \149 searches, unless the pattern contains an uppercase character (smart \150 case)."151 )]152 pub case_sensitive: bool,153154 /// Case-insensitive search (default: smart case)155 #[arg(156 long,157 short = 'i',158 overrides_with("case_sensitive"),159 long_help = "Perform a case-insensitive search. By default, fd uses case-insensitive \160 searches, unless the pattern contains an uppercase character (smart \161 case)."162 )]163 pub ignore_case: bool,164165 /// Glob-based search (default: regular expression)166 #[arg(167 long,168 short = 'g',169 conflicts_with("fixed_strings"),170 long_help = "Perform a glob-based search instead of a regular expression search."171 )]172 pub glob: bool,173174 /// Regular-expression based search (default)175 #[arg(176 long,177 overrides_with("glob"),178 hide_short_help = true,179 long_help = "Perform a regular-expression based search (default). This can be used to \180 override --glob."181 )]182 pub regex: bool,183184 /// Treat pattern as literal string stead of regex185 #[arg(186 long,187 short = 'F',188 alias = "literal",189 hide_short_help = true,190 long_help = "Treat the pattern as a literal string instead of a regular expression. Note \191 that this also performs substring comparison. If you want to match on an \192 exact filename, consider using '--glob'."193 )]194 pub fixed_strings: bool,195196 /// Show absolute instead of relative paths197 #[arg(198 long,199 short = 'a',200 long_help = "Shows the full path starting from the root as opposed to relative paths. \201 The flag can be overridden with --relative-path."202 )]203 pub absolute_path: bool,204205 /// Use a long listing format with file metadata206 #[arg(207 long,208 short = 'l',209 conflicts_with("absolute_path"),210 long_help = "Use a detailed listing format like 'ls -l'. This is basically an alias \211 for '--exec-batch ls -l' with some additional 'ls' options. This can be \212 used to see more metadata, to show symlink targets and to achieve a \213 deterministic sort order."214 )]215 pub list_details: bool,216217 /// Follow symbolic links218 #[arg(219 long,220 short = 'L',221 alias = "dereference",222 long_help = "By default, fd does not descend into symlinked directories. Using this \223 flag, symbolic links are also traversed. \224 Flag can be overriden with --no-follow."225 )]226 pub follow: bool,227228 /// Search full abs. path (default: filename only)229 #[arg(230 long,231 short = 'p',232 long_help = "By default, the search pattern is only matched against the filename (or \233 directory name). Using this flag, the pattern is matched against the full \234 (absolute) path. Example:\n \235 fd --glob -p '**/.git/config'"236 )]237 pub full_path: bool,238239 /// Separate search results by the null character240 #[arg(241 long = "print0",242 short = '0',243 conflicts_with("list_details"),244 hide_short_help = true,245 long_help = "Separate search results by the null character (instead of newlines). \246 Useful for piping results to 'xargs'."247 )]248 pub null_separator: bool,249250 /// Set maximum search depth (default: none)251 #[arg(252 long,253 short = 'd',254 value_name = "depth",255 alias("maxdepth"),256 long_help = "Limit the directory traversal to a given depth. By default, there is no \257 limit on the search depth."258 )]259 max_depth: Option<usize>,260261 /// Only show search results starting at the given depth.262 #[arg(263 long,264 value_name = "depth",265 hide_short_help = true,266 long_help = "Only show search results starting at the given depth. \267 See also: '--max-depth' and '--exact-depth'"268 )]269 min_depth: Option<usize>,270271 /// Only show search results at the exact given depth272 #[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),273 long_help = "Only show search results at the exact given depth. This is an alias for \274 '--min-depth <depth> --max-depth <depth>'.",275 )]276 exact_depth: Option<usize>,277278 /// Do not traverse into directories that match the search criteria. If279 /// you want to exclude specific directories, use the '--exclude=…' option.280 #[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),281 long_help = "Do not traverse into directories that match the search criteria. If \282 you want to exclude specific directories, use the '--exclude=…' option.",283 )]284 pub prune: bool,285286 /// Filter by type: file (f), directory (d), symlink (l),287 /// executable (x), empty (e), socket (s), pipe (p)288 #[arg(289 long = "type",290 short = 't',291 value_name = "filetype",292 hide_possible_values = true,293 value_enum,294 long_help = "Filter the search by type:\n \295 'f' or 'file': regular files\n \296 'd' or 'directory': directories\n \297 'l' or 'symlink': symbolic links\n \298 's' or 'socket': socket\n \299 'p' or 'pipe': named pipe (FIFO)\n\n \300 'x' or 'executable': executables\n \301 'e' or 'empty': empty files or directories\n\n\302 This option can be specified more than once to include multiple file types. \303 Searching for '--type file --type symlink' will show both regular files as \304 well as symlinks. Note that the 'executable' and 'empty' filters work differently: \305 '--type executable' implies '--type file' by default. And '--type empty' searches \306 for empty files and directories, unless either '--type file' or '--type directory' \307 is specified in addition.\n\n\308 Examples:\n \309 - Only search for files:\n \310 fd --type file …\n \311 fd -tf …\n \312 - Find both files and symlinks\n \313 fd --type file --type symlink …\n \314 fd -tf -tl …\n \315 - Find executable files:\n \316 fd --type executable\n \317 fd -tx\n \318 - Find empty files:\n \319 fd --type empty --type file\n \320 fd -te -tf\n \321 - Find empty directories:\n \322 fd --type empty --type directory\n \323 fd -te -td"324 )]325 pub filetype: Option<Vec<FileType>>,326327 /// Filter by file extension328 #[arg(329 long = "extension",330 short = 'e',331 value_name = "ext",332 long_help = "(Additionally) filter search results by their file extension. Multiple \333 allowable file extensions can be specified.\n\334 If you want to search for files without extension, \335 you can use the regex '^[^.]+$' as a normal search pattern."336 )]337 pub extensions: Option<Vec<String>>,338339 #[command(flatten)]340 pub exec: Exec,341342 /// Max number of arguments to run as a batch size with -X343 #[arg(344 long,345 value_name = "size",346 hide_short_help = true,347 requires("exec_batch"),348 value_parser = value_parser!(usize),349 default_value_t,350 long_help = "Maximum number of arguments to pass to the command given with -X. \351 If the number of results is greater than the given size, \352 the command given with -X is run again with remaining arguments. \353 A batch size of zero means there is no limit (default), but note \354 that batching might still happen due to OS restrictions on the \355 maximum length of command lines.",356 )]357 pub batch_size: usize,358359 /// Exclude entries that match the given glob pattern360 #[arg(361 long,362 short = 'E',363 value_name = "pattern",364 long_help = "Exclude files/directories that match the given glob pattern. This \365 overrides any other ignore logic. Multiple exclude patterns can be \366 specified.\n\n\367 Examples:\n \368 --exclude '*.pyc'\n \369 --exclude node_modules"370 )]371 pub exclude: Vec<String>,372373 /// Add a custom ignore-file in '.gitignore' format374 #[arg(375 long,376 value_name = "path",377 hide_short_help = true,378 long_help = "Add a custom ignore-file in '.gitignore' format. These files have a low precedence."379 )]380 pub ignore_file: Vec<PathBuf>,381382 /// When to use colors383 #[arg(384 long,385 short = 'c',386 value_enum,387 default_value_t = ColorWhen::Auto,388 value_name = "when",389 long_help = "Declare when to use color for the pattern match output",390 )]391 pub color: ColorWhen,392393 /// Set number of threads to use for searching & executing (default: number394 /// of available CPU cores)395 #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = 1..)]396 pub threads: Option<u32>,397398 /// Limit results based on the size of files399 #[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",400 long_help = "Limit results based on the size of files using the format <+-><NUM><UNIT>.\n \401 '+': file size must be greater than or equal to this\n \402 '-': file size must be less than or equal to this\n\403 If neither '+' nor '-' is specified, file size must be exactly equal to this.\n \404 'NUM': The numeric size (e.g. 500)\n \405 'UNIT': The units for NUM. They are not case-sensitive.\n\406 Allowed unit values:\n \407 'b': bytes\n \408 'k': kilobytes (base ten, 10^3 = 1000 bytes)\n \409 'm': megabytes\n \410 'g': gigabytes\n \411 't': terabytes\n \412 'ki': kibibytes (base two, 2^10 = 1024 bytes)\n \413 'mi': mebibytes\n \414 'gi': gibibytes\n \415 'ti': tebibytes",416 )]417 pub size: Vec<SizeFilter>,418419 /// Milliseconds to buffer before streaming search results to console420 ///421 /// Amount of time in milliseconds to buffer, before streaming the search422 /// results to the console.423 #[arg(long, hide = true, value_parser = parse_millis)]424 pub max_buffer_time: Option<Duration>,425426 /// Filter by file modification time (newer than)427 #[arg(428 long,429 alias("change-newer-than"),430 alias("newer"),431 value_name = "date|dur",432 long_help = "Filter results based on the file modification time. The argument can be provided \433 as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \434 If the time is not specified, it defaults to 00:00:00. \435 '--change-newer-than' or '--newer' can be used as aliases.\n\436 Examples:\n \437 --changed-within 2weeks\n \438 --change-newer-than '2018-10-27 10:00:00'\n \439 --newer 2018-10-27"440 )]441 pub changed_within: Option<String>,442443 /// Filter by file modification time (older than)444 #[arg(445 long,446 alias("change-older-than"),447 alias("older"),448 value_name = "date|dur",449 long_help = "Filter results based on the file modification time. The argument can be provided \450 as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \451 '--change-older-than' or '--older' can be used as aliases.\n\452 Examples:\n \453 --changed-before '2018-10-27 10:00:00'\n \454 --change-older-than 2weeks\n \455 --older 2018-10-27"456 )]457 pub changed_before: Option<String>,458459 /// Limit number of search results460 #[arg(461 long,462 value_name = "count",463 hide_short_help = true,464 long_help = "Limit the number of search results to 'count' and quit immediately."465 )]466 max_results: Option<usize>,467468 /// Limit search to a single result469 #[arg(470 short = '1',471 hide_short_help = true,472 overrides_with("max_results"),473 long_help = "Limit the search to a single result and quit immediately. \474 This is an alias for '--max-results=1'."475 )]476 max_one_result: bool,477478 /// Print nothing, exit code 0 if match found, 1 otherwise479 #[arg(480 long,481 short = 'q',482 alias = "has-results",483 hide_short_help = true,484 conflicts_with("max_results"),485 long_help = "When the flag is present, the program does not print anything and will \486 return with an exit code of 0 if there is at least one match. Otherwise, the \487 exit code will be 1. \488 '--has-results' can be used as an alias."489 )]490 pub quiet: bool,491492 /// Show filesystem errors493 #[arg(494 long,495 hide_short_help = true,496 long_help = "Enable the display of filesystem errors for situations such as \497 insufficient permissions or dead symlinks."498 )]499 pub show_errors: bool,500501 /// Change current working directory502 #[arg(503 long,504 value_name = "path",505 hide_short_help = true,506 long_help = "Change the current working directory of fd to the provided path. This \507 means that search results will be shown with respect to the given base \508 path. Note that relative paths which are passed to fd via the positional \509 <path> argument or the '--search-path' option will also be resolved \510 relative to this directory."511 )]512 pub base_directory: Option<PathBuf>,513514 /// the search pattern (a regular expression, unless '--glob' is used; optional)515 #[arg(516 default_value = "",517 hide_default_value = true,518 value_name = "pattern",519 long_help = "the search pattern which is either a regular expression (default) or a glob \520 pattern (if --glob is used). If no pattern has been specified, every entry \521 is considered a match. If your pattern starts with a dash (-), make sure to \522 pass '--' first, or it will be considered as a flag (fd -- '-foo')."523 )]524 pub pattern: String,525526 /// Set path separator when printing file paths527 #[arg(528 long,529 value_name = "separator",530 hide_short_help = true,531 long_help = "Set the path separator to use when printing file paths. The default is \532 the OS-specific separator ('/' on Unix, '\\' on Windows)."533 )]534 pub path_separator: Option<String>,535536 /// the root directories for the filesystem search (optional)537 #[arg(action = ArgAction::Append,538 value_name = "path",539 long_help = "The directory where the filesystem search is rooted (optional). If \540 omitted, search the current working directory.",541 )]542 path: Vec<PathBuf>,543544 /// Provides paths to search as an alternative to the positional <path> argument545 #[arg(546 long,547 conflicts_with("path"),548 value_name = "search-path",549 hide_short_help = true,550 long_help = "Provide paths to search as an alternative to the positional <path> \551 argument. Changes the usage to `fd [OPTIONS] --search-path <path> \552 --search-path <path2> [<pattern>]`"553 )]554 search_path: Vec<PathBuf>,555556 /// By default, relative paths are prefixed with './' when -x/--exec,557 /// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a558 /// path starting with '-' being treated as a command line option. Use559 /// this flag to disable this behaviour.560 #[arg(long, conflicts_with_all(&["path", "search_path"]), hide_short_help = true,561 long_help = "By default, relative paths are prefixed with './' when -x/--exec, \562 -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a \563 path starting with '-' being treated as a command line option. Use \564 this flag to disable this behaviour.",565 )]566 pub strip_cwd_prefix: bool,567568 /// Filter by owning user and/or group569 #[cfg(unix)]570 #[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",571 long_help = "Filter files by their user and/or group. \572 Format: [(user|uid)][:(group|gid)]. Either side is optional. \573 Precede either side with a '!' to exclude files instead.\n\574 Examples:\n \575 --owner john\n \576 --owner :students\n \577 --owner '!john:students'"578 )]579 pub owner: Option<OwnerFilter>,580 #[cfg(any(unix, windows))]581 #[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true,582 long_help = "By default, fd will traverse the file system tree as far as other options \583 dictate. With this flag, fd ensures that it does not descend into a \584 different file system than the one it started in. Comparable to the -mount \585 or -xdev filters of find(1).")]586 pub one_file_system: bool,587588 #[cfg(feature = "completions")]589 #[arg(long, hide = true, exclusive = true)]590 gen_completions: Option<Option<Shell>>,591592 #[clap(flatten)]593 _negations: Negations,594}595596impl Opts {597 pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {598 // would it make sense to concatenate these?599 let paths = if !self.path.is_empty() {600 &self.path601 } else if !self.search_path.is_empty() {602 &self.search_path603 } else {604 let current_directory = Path::new(".");605 ensure_current_directory_exists(current_directory)?;606 return Ok(vec![self.normalize_path(current_directory)]);607 };608 Ok(paths609 .iter()610 .filter_map(|path| {611 if filesystem::is_existing_directory(path) {612 Some(self.normalize_path(path))613 } else {614 print_error(format!(615 "Search path '{}' is not a directory.",616 path.to_string_lossy()617 ));618 None619 }620 })621 .collect())622 }623624 fn normalize_path(&self, path: &Path) -> PathBuf {625 if self.absolute_path {626 filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()627 } else {628 path.to_path_buf()629 }630 }631632 pub fn no_search_paths(&self) -> bool {633 self.path.is_empty() && self.search_path.is_empty()634 }635636 #[inline]637 pub fn rg_alias_ignore(&self) -> bool {638 self.rg_alias_hidden_ignore > 0639 }640641 pub fn max_depth(&self) -> Option<usize> {642 self.max_depth.or(self.exact_depth)643 }644645 pub fn min_depth(&self) -> Option<usize> {646 self.min_depth.or(self.exact_depth)647 }648649 pub fn threads(&self) -> usize {650 // This will panic if the number of threads passed in is more than usize::MAX in an environment651 // where usize is less than 32 bits (for example 16-bit architectures). It's pretty652 // unlikely fd will be running in such an environment, and even more unlikely someone would653 // be trying to use that many threads on such an environment, so I think panicing is an654 // appropriate way to handle that.655 std::cmp::max(656 self.threads657 .map_or_else(num_cpus::get, |n| n.try_into().expect("too many threads")),658 1,659 )660 }661662 pub fn max_results(&self) -> Option<usize> {663 self.max_results664 .filter(|&m| m > 0)665 .or_else(|| self.max_one_result.then(|| 1))666 }667668 #[cfg(feature = "completions")]669 pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {670 self.gen_completions671 .map(|maybe_shell| match maybe_shell {672 Some(sh) => Ok(sh),673 None => guess_shell(),674 })675 .transpose()676 }677}678679#[cfg(feature = "completions")]680fn guess_shell() -> anyhow::Result<Shell> {681 let env_shell = std::env::var_os("SHELL").map(PathBuf::from);682 if let Some(shell) = env_shell683 .as_ref()684 .and_then(|s| s.file_name())685 .and_then(|s| s.to_str())686 {687 shell688 .parse::<Shell>()689 .map_err(|_| anyhow!("Unknown shell {}", shell))690 } else {691 // Assume powershell on windows692 #[cfg(windows)]693 return Ok(Shell::PowerShell);694 #[cfg(not(windows))]695 return Err(anyhow!("Unable to get shell from environment"));696 }697}698699#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]700pub enum FileType {701 #[value(alias = "f")]702 File,703 #[value(alias = "d")]704 Directory,705 #[value(alias = "l")]706 Symlink,707 #[value(alias = "x")]708 Executable,709 #[value(alias = "e")]710 Empty,711 #[value(alias = "s")]712 Socket,713 #[value(alias = "p")]714 Pipe,715}716717#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]718pub enum ColorWhen {719 /// show colors if the output goes to an interactive console (default)720 Auto,721 /// always use colorized output722 Always,723 /// do not use colorized output724 Never,725}726727impl ColorWhen {728 pub fn as_str(&self) -> &'static str {729 use ColorWhen::*;730 match *self {731 Auto => "auto",732 Never => "never",733 Always => "always",734 }735 }736}737738// there isn't a derive api for getting grouped values yet,739// so we have to use hand-rolled parsing for exec and exec-batch740pub struct Exec {741 pub command: Option<CommandSet>,742}743744impl clap::FromArgMatches for Exec {745 fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {746 let command = matches747 .grouped_values_of("exec")748 .map(CommandSet::new)749 .or_else(|| {750 matches751 .grouped_values_of("exec_batch")752 .map(CommandSet::new_batch)753 })754 .transpose()755 .map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;756 Ok(Exec { command })757 }758759 fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {760 *self = Self::from_arg_matches(matches)?;761 Ok(())762 }763}764765impl clap::Args for Exec {766 fn augment_args(cmd: Command) -> Command {767 cmd.arg(Arg::new("exec")768 .action(ArgAction::Append)769 .long("exec")770 .short('x')771 .num_args(1..)772 .allow_hyphen_values(true)773 .value_terminator(";")774 .value_name("cmd")775 .conflicts_with("list_details")776 .help("Execute a command for each search result")777 .long_help(778 "Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \779 All positional arguments following --exec are considered to be arguments to the command - not to fd. \780 It is therefore recommended to place the '-x'/'--exec' option last.\n\781 The following placeholders are substituted before the command is executed:\n \782 '{}': path (of the current search result)\n \783 '{/}': basename\n \784 '{//}': parent directory\n \785 '{.}': path without file extension\n \786 '{/.}': basename without file extension\n\n\787 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\788 Examples:\n\n \789 - find all *.zip files and unzip them:\n\n \790 fd -e zip -x unzip\n\n \791 - find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n \792 fd -e h -e cpp -x clang-format -i\n\n \793 - Convert all *.jpg files to *.png files:\n\n \794 fd -e jpg -x convert {} {.}.png\795 ",796 ),797 )798 .arg(799 Arg::new("exec_batch")800 .action(ArgAction::Append)801 .long("exec-batch")802 .short('X')803 .num_args(1..)804 .allow_hyphen_values(true)805 .value_terminator(";")806 .value_name("cmd")807 .conflicts_with_all(&["exec", "list_details"])808 .help("Execute a command with all search results at once")809 .long_help(810 "Execute the given command once, with all search results as arguments.\n\811 One of the following placeholders is substituted before the command is executed:\n \812 '{}': path (of all search results)\n \813 '{/}': basename\n \814 '{//}': parent directory\n \815 '{.}': path without file extension\n \816 '{/.}': basename without file extension\n\n\817 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\818 Examples:\n\n \819 - Find all test_*.py files and open them in your favorite editor:\n\n \820 fd -g 'test_*.py' -X vim\n\n \821 - Find all *.rs files and count the lines with \"wc -l ...\":\n\n \822 fd -e rs -X wc -l\823 "824 ),825 )826 }827828 fn augment_args_for_update(cmd: Command) -> Command {829 Self::augment_args(cmd)830 }831}832833fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {834 Ok(Duration::from_millis(arg.parse()?))835}836837fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {838 if filesystem::is_existing_directory(current_directory) {839 Ok(())840 } else {841 Err(anyhow!(842 "Could not retrieve current directory (has it been deleted?)."843 ))844 }845}
modified:src/main.rs+115 added-245 removed
1mod app;1mod cli;2mod config;3mod dir_entry;4mod error;5mod exec;
5 unmodified lines
11mod regex_helper;12mod walk;1314use std::env;15use std::path::{Path, PathBuf};15use std::path::Path;16use std::sync::Arc;17use std::time;1819use anyhow::{anyhow, Context, Result};19use anyhow::{anyhow, bail, Context, Result};20use atty::Stream;21use clap::{CommandFactory, Parser};22use globset::GlobBuilder;23use lscolors::LsColors;23use normpath::PathExt;24use regex::bytes::{RegexBuilder, RegexSetBuilder};2526use crate::cli::{ColorWhen, Opts};27use crate::config::Config;27use crate::error::print_error;28use crate::exec::CommandSet;29use crate::exit_codes::ExitCode;30use crate::filetypes::FileTypes;31#[cfg(unix)]32use crate::filter::OwnerFilter;33use crate::filter::{SizeFilter, TimeFilter};33use crate::filter::TimeFilter;34use crate::regex_helper::{pattern_has_uppercase_char, pattern_matches_strings_with_leading_dot};3536// We use jemalloc for performance reasons, see https://github.com/sharkdp/fd/pull/48137// FIXME: re-enable jemalloc on macOS, see comment in Cargo.toml file for more infos
28 unmodified lines
66 }67}6869fn run() -> Result<ExitCode> {70 let matches = app::build_app().get_matches_from(env::args_os());70 let opts = Opts::parse();7172 set_working_dir(&matches)?;73 let search_paths = extract_search_paths(&matches)?;74 let pattern = extract_search_pattern(&matches)?;75 ensure_search_pattern_is_not_a_path(&matches, pattern)?;76 let pattern_regex = build_pattern_regex(&matches, pattern)?;72 #[cfg(feature = "completions")]73 if let Some(shell) = opts.gen_completions()? {74 return print_completions(shell);75 }7677 set_working_dir(&opts)?;78 let search_paths = opts.search_paths()?;79 if search_paths.is_empty() {80 bail!("No valid search paths given.");81 }8283 ensure_search_pattern_is_not_a_path(&opts)?;84 let pattern_regex = build_pattern_regex(&opts)?;8578 let config = construct_config(matches, &pattern_regex)?;86 let config = construct_config(opts, &pattern_regex)?;87 ensure_use_hidden_option_for_leading_dot_pattern(&config, &pattern_regex)?;88 let re = build_regex(pattern_regex, &config)?;89 walk::scan(&search_paths, Arc::new(re), Arc::new(config))90}9184fn set_working_dir(matches: &clap::ArgMatches) -> Result<()> {85 if let Some(base_directory) = matches.value_of_os("base-directory") {86 let base_directory = Path::new(base_directory);92#[cfg(feature = "completions")]93#[cold]94fn print_completions(shell: clap_complete::Shell) -> Result<ExitCode> {95 // The program name is the first argument.96 let program_name = env::args().next().unwrap_or_else(|| "fd".to_string());97 let mut cmd = Opts::command();98 cmd.build();99 // TODO: fix panic100 clap_complete::generate(shell, &mut cmd, &program_name, &mut std::io::stdout());101 Ok(ExitCode::Success)102}103104fn set_working_dir(opts: &Opts) -> Result<()> {105 if let Some(ref base_directory) = opts.base_directory {106 if !filesystem::is_existing_directory(base_directory) {107 return Err(anyhow!(108 "The '--base-directory' path '{}' is not a directory.",109 base_directory.to_string_lossy()
8 unmodified lines
118 }119 Ok(())120}121103fn ensure_current_directory_exists(current_directory: &Path) -> Result<()> {104 if filesystem::is_existing_directory(current_directory) {105 Ok(())106 } else {107 Err(anyhow!(108 "Could not retrieve current directory (has it been deleted?)."109 ))110 }111}112113fn extract_search_pattern(matches: &clap::ArgMatches) -> Result<&'_ str> {114 let pattern = matches115 .value_of_os("pattern")116 .map(|p| {117 p.to_str()118 .ok_or_else(|| anyhow!("The search pattern includes invalid UTF-8 sequences."))119 })120 .transpose()?121 .unwrap_or("");122 Ok(pattern)123}124125fn extract_search_paths(matches: &clap::ArgMatches) -> Result<Vec<PathBuf>> {126 let parameter_paths = matches127 .values_of_os("path")128 .or_else(|| matches.values_of_os("search-path"));129130 let mut search_paths = match parameter_paths {131 Some(paths) => paths132 .filter_map(|path| {133 let path_buffer = PathBuf::from(path);134 if filesystem::is_existing_directory(&path_buffer) {135 Some(path_buffer)136 } else {137 print_error(format!(138 "Search path '{}' is not a directory.",139 path_buffer.to_string_lossy(),140 ));141 None142 }143 })144 .collect(),145 None => {146 let current_directory = Path::new(".");147 ensure_current_directory_exists(current_directory)?;148 vec![current_directory.to_path_buf()]149 }150 };151152 if search_paths.is_empty() {153 return Err(anyhow!("No valid search paths given."));154 }155 if matches.is_present("absolute-path") {156 update_to_absolute_paths(&mut search_paths);157 }158 Ok(search_paths)159}160161fn update_to_absolute_paths(search_paths: &mut [PathBuf]) {162 for buffer in search_paths.iter_mut() {163 *buffer = filesystem::absolute_path(buffer.normalize().unwrap().as_path()).unwrap();164 }165}166122/// Detect if the user accidentally supplied a path instead of a search pattern168fn ensure_search_pattern_is_not_a_path(matches: &clap::ArgMatches, pattern: &str) -> Result<()> {169 if !matches.is_present("full-path")170 && pattern.contains(std::path::MAIN_SEPARATOR)171 && Path::new(pattern).is_dir()123fn ensure_search_pattern_is_not_a_path(opts: &Opts) -> Result<()> {124 if !opts.full_path125 && opts.pattern.contains(std::path::MAIN_SEPARATOR)126 && Path::new(&opts.pattern).is_dir()127 {128 Err(anyhow!(129 "The search pattern '{pattern}' contains a path-separation character ('{sep}') \130 and will not lead to any search results.\n\n\131 If you want to search for all files inside the '{pattern}' directory, use a match-all pattern:\n\n \132 fd . '{pattern}'\n\n\133 Instead, if you want your pattern to match the full file path, use:\n\n \134 fd --full-path '{pattern}'",180 pattern = pattern,135 pattern = &opts.pattern,136 sep = std::path::MAIN_SEPARATOR,137 ))138 } else {139 Ok(())140 }141}142188fn build_pattern_regex(matches: &clap::ArgMatches, pattern: &str) -> Result<String> {189 Ok(if matches.is_present("glob") && !pattern.is_empty() {143fn build_pattern_regex(opts: &Opts) -> Result<String> {144 let pattern = &opts.pattern;145 Ok(if opts.glob && !pattern.is_empty() {146 let glob = GlobBuilder::new(pattern).literal_separator(true).build()?;147 glob.regex().to_owned()192 } else if matches.is_present("fixed-strings") {148 } else if opts.fixed_strings {149 // Treat pattern as literal string if '--fixed-strings' is used150 regex::escape(pattern)151 } else {152 String::from(pattern)
13 unmodified lines
166 _ => Ok(()),167 }168}169214fn construct_config(matches: clap::ArgMatches, pattern_regex: &str) -> Result<Config> {170fn construct_config(mut opts: Opts, pattern_regex: &str) -> Result<Config> {171 // The search will be case-sensitive if the command line flag is set or172 // if the pattern has an uppercase character (smart case).217 let case_sensitive = !matches.is_present("ignore-case")218 && (matches.is_present("case-sensitive") || pattern_has_uppercase_char(pattern_regex));173 let case_sensitive =174 !opts.ignore_case && (opts.case_sensitive || pattern_has_uppercase_char(pattern_regex));175220 let path_separator = matches221 .value_of("path-separator")222 .map_or_else(filesystem::default_path_separator, |s| Some(s.to_owned()));176 let path_separator = opts177 .path_separator178 .take()179 .or_else(filesystem::default_path_separator);180 let actual_path_separator = path_separator181 .clone()182 .unwrap_or_else(|| std::path::MAIN_SEPARATOR.to_string());183 check_path_separator_length(path_separator.as_deref())?;184228 let size_limits = extract_size_limits(&matches)?;229 let time_constraints = extract_time_constraints(&matches)?;185 let size_limits = std::mem::take(&mut opts.size);186 let time_constraints = extract_time_constraints(&opts)?;187 #[cfg(unix)]231 let owner_constraint = matches232 .value_of("owner")233 .map(OwnerFilter::from_string)234 .transpose()?235 .flatten();188 let owner_constraint: Option<OwnerFilter> = opts.owner;189190 #[cfg(windows)]191 let ansi_colors_support =192 ansi_term::enable_ansi_support().is_ok() || std::env::var_os("TERM").is_some();193 #[cfg(not(windows))]194 let ansi_colors_support = true;195196 let interactive_terminal = atty::is(Stream::Stdout);244 let colored_output = match matches.value_of("color") {245 Some("always") => true,246 Some("never") => false,247 _ => ansi_colors_support && env::var_os("NO_COLOR").is_none() && interactive_terminal,197 let colored_output = match opts.color {198 ColorWhen::Always => true,199 ColorWhen::Never => false,200 ColorWhen::Auto => {201 ansi_colors_support && env::var_os("NO_COLOR").is_none() && interactive_terminal202 }203 };204205 let ls_colors = if colored_output {206 Some(LsColors::from_env().unwrap_or_else(|| LsColors::from_string(DEFAULT_LS_COLORS)))207 } else {208 None209 };255 let command = extract_command(&matches, path_separator.as_deref(), colored_output)?;210 let command = extract_command(&mut opts, colored_output)?;211 let has_command = command.is_some();212213 Ok(Config {214 case_sensitive,259 search_full_path: matches.is_present("full-path"),260 ignore_hidden: !(matches.is_present("hidden")261 || matches.is_present("rg-alias-hidden-ignore")),262 read_fdignore: !(matches.is_present("no-ignore")263 || matches.is_present("rg-alias-hidden-ignore")),264 read_vcsignore: !(matches.is_present("no-ignore")265 || matches.is_present("rg-alias-hidden-ignore")266 || matches.is_present("no-ignore-vcs")),267 read_parent_ignore: !matches.is_present("no-ignore-parent"),268 read_global_ignore: !(matches.is_present("no-ignore")269 || matches.is_present("rg-alias-hidden-ignore")270 || matches.is_present("no-global-ignore-file")),271 follow_links: matches.is_present("follow"),272 one_file_system: matches.is_present("one-file-system"),273 null_separator: matches.is_present("null_separator"),274 quiet: matches.is_present("quiet"),275 max_depth: matches276 .value_of("max-depth")277 .or_else(|| matches.value_of("rg-depth"))278 .or_else(|| matches.value_of("exact-depth"))279 .map(|n| n.parse::<usize>())280 .transpose()281 .context("Failed to parse argument to --max-depth/--exact-depth")?,282 min_depth: matches283 .value_of("min-depth")284 .or_else(|| matches.value_of("exact-depth"))285 .map(|n| n.parse::<usize>())286 .transpose()287 .context("Failed to parse argument to --min-depth/--exact-depth")?,288 prune: matches.is_present("prune"),289 threads: std::cmp::max(290 matches291 .value_of("threads")292 .map(|n| n.parse::<usize>())293 .transpose()294 .context("Failed to parse number of threads")?295 .map(|n| {296 if n > 0 {297 Ok(n)298 } else {299 Err(anyhow!("Number of threads must be positive."))300 }301 })302 .transpose()?303 .unwrap_or_else(num_cpus::get),304 1,305 ),306 max_buffer_time: matches307 .value_of("max-buffer-time")308 .map(|n| n.parse::<u64>())309 .transpose()310 .context("Failed to parse max. buffer time argument")?311 .map(time::Duration::from_millis),215 search_full_path: opts.full_path,216 ignore_hidden: !(opts.hidden || opts.rg_alias_ignore()),217 read_fdignore: !(opts.no_ignore || opts.rg_alias_ignore()),218 read_vcsignore: !(opts.no_ignore || opts.rg_alias_ignore() || opts.no_ignore_vcs),219 read_parent_ignore: !opts.no_ignore_parent,220 read_global_ignore: !opts.no_ignore || opts.rg_alias_ignore() || opts.no_global_ignore_file,221 follow_links: opts.follow,222 one_file_system: opts.one_file_system,223 null_separator: opts.null_separator,224 quiet: opts.quiet,225 max_depth: opts.max_depth(),226 min_depth: opts.min_depth(),227 prune: opts.prune,228 threads: opts.threads(),229 max_buffer_time: opts.max_buffer_time,230 ls_colors,231 interactive_terminal,314 file_types: matches.values_of("file-type").map(|values| {232 file_types: opts.filetype.as_ref().map(|values| {233 use crate::cli::FileType::*;234 let mut file_types = FileTypes::default();235 for value in values {236 match value {318 "f" | "file" => file_types.files = true,319 "d" | "directory" => file_types.directories = true,320 "l" | "symlink" => file_types.symlinks = true,321 "x" | "executable" => {237 File => file_types.files = true,238 Directory => file_types.directories = true,239 Symlink => file_types.symlinks = true,240 Executable => {241 file_types.executables_only = true;242 file_types.files = true;243 }325 "e" | "empty" => file_types.empty_only = true,326 "s" | "socket" => file_types.sockets = true,327 "p" | "pipe" => file_types.pipes = true,328 _ => unreachable!(),244 Empty => file_types.empty_only = true,245 Socket => file_types.sockets = true,246 Pipe => file_types.pipes = true,247 }248 }249250 // If only 'empty' was specified, search for both files and directories:
3 unmodified lines
254 }255256 file_types257 }),340 extensions: matches341 .values_of("extension")258 extensions: opts259 .extensions260 .as_ref()261 .map(|exts| {262 let patterns = exts263 .iter()264 .map(|e| e.trim_start_matches('.'))265 .map(|e| format!(r".\.{}$", regex::escape(e)));266 RegexSetBuilder::new(patterns)267 .case_insensitive(true)268 .build()269 })270 .transpose()?,271 command: command.map(Arc::new),352 batch_size: matches353 .value_of("batch-size")354 .map(|n| n.parse::<usize>())355 .transpose()356 .context("Failed to parse --batch-size argument")?357 .unwrap_or_default(),358 exclude_patterns: matches359 .values_of("exclude")360 .map(|v| v.map(|p| String::from("!") + p).collect())361 .unwrap_or_else(Vec::new),362 ignore_files: matches363 .values_of("ignore-file")364 .map(|vs| vs.map(PathBuf::from).collect())365 .unwrap_or_else(Vec::new),272 batch_size: opts.batch_size,273 exclude_patterns: opts.exclude.iter().map(|p| String::from("!") + p).collect(),274 ignore_files: std::mem::take(&mut opts.ignore_file),275 size_constraints: size_limits,276 time_constraints,277 #[cfg(unix)]278 owner_constraint,370 show_filesystem_errors: matches.is_present("show-errors"),279 show_filesystem_errors: opts.show_errors,280 path_separator,281 actual_path_separator,373 max_results: matches374 .value_of("max-results")375 .map(|n| n.parse::<usize>())376 .transpose()377 .context("Failed to parse --max-results argument")?378 .filter(|&n| n > 0)379 .or_else(|| {380 if matches.is_present("max-one-result") {381 Some(1)382 } else {383 None384 }385 }),386 strip_cwd_prefix: !matches.is_present("path")387 && !matches.is_present("search-path")388 && (matches.is_present("strip-cwd-prefix")389 || !(matches.is_present("null_separator")390 || matches.is_present("exec")391 || matches.is_present("exec-batch"))),282 max_results: opts.max_results(),283 strip_cwd_prefix: (opts.no_search_paths()284 && (opts.strip_cwd_prefix || !(opts.null_separator || has_command))),285 })286}287395fn extract_command(396 matches: &clap::ArgMatches,397 path_separator: Option<&str>,398 colored_output: bool,399) -> Result<Option<CommandSet>> {400 None.or_else(|| {401 matches402 .grouped_values_of("exec")403 .map(|args| CommandSet::new(args, path_separator.map(str::to_string)))404 })405 .or_else(|| {406 matches407 .grouped_values_of("exec-batch")408 .map(|args| CommandSet::new_batch(args, path_separator.map(str::to_string)))409 })410 .or_else(|| {411 if !matches.is_present("list-details") {412 return None;413 }288fn extract_command(opts: &mut Opts, colored_output: bool) -> Result<Option<CommandSet>> {289 opts.exec290 .command291 .take()292 .map(Ok)293 .or_else(|| {294 if !opts.list_details {295 return None;296 }297 let color_arg = format!("--color={}", opts.color.as_str());298415 let color = matches.value_of("color").unwrap_or("auto");416 let color_arg = format!("--color={}", color);417418 let res = determine_ls_command(&color_arg, colored_output)419 .map(|cmd| CommandSet::new_batch([cmd], path_separator.map(str::to_string)).unwrap());420421 Some(res)422 })423 .transpose()299 let res = determine_ls_command(&color_arg, colored_output)300 .map(|cmd| CommandSet::new_batch([cmd]).unwrap());301 Some(res)302 })303 .transpose()304}305306fn determine_ls_command(color_arg: &str, colored_output: bool) -> Result<Vec<&str>> {307 #[allow(unused)]
73 unmodified lines
381 };382 Ok(cmd)383}384505fn extract_size_limits(matches: &clap::ArgMatches) -> Result<Vec<SizeFilter>> {506 matches.values_of("size").map_or(Ok(Vec::new()), |vs| {507 vs.map(|sf| {508 SizeFilter::from_string(sf)509 .ok_or_else(|| anyhow!("'{}' is not a valid size constraint. See 'fd --help'.", sf))510 })511 .collect::<Result<Vec<_>>>()512 })513}514515fn extract_time_constraints(matches: &clap::ArgMatches) -> Result<Vec<TimeFilter>> {385fn extract_time_constraints(opts: &Opts) -> Result<Vec<TimeFilter>> {386 let now = time::SystemTime::now();387 let mut time_constraints: Vec<TimeFilter> = Vec::new();518 if let Some(t) = matches.value_of("changed-within") {388 if let Some(ref t) = opts.changed_within {389 if let Some(f) = TimeFilter::after(&now, t) {390 time_constraints.push(f);391 } else {392 return Err(anyhow!(
1 unmodified line
394 t395 ));396 }397 }528 if let Some(t) = matches.value_of("changed-before") {398 if let Some(ref t) = opts.changed_before {399 if let Some(f) = TimeFilter::before(&now, t) {400 time_constraints.push(f);401 } else {402 return Err(anyhow!(
38 unmodified lines
modified:src/walk.rs-1 removed
358 unmodified lines
359 // Push the handle of the spawned thread into the vector for later joining.360 handles.push(handle);361 }362363 // Wait for all threads to exit before exiting the program.363 let exit_codes = handles364 .into_iter()365 .map(|handle| handle.join().unwrap())366 .collect::<Vec<_>>();
185 unmodified lines
modified:tests/tests.rs+12 added-2 removed
1477 unmodified lines
1478 );14791480 te.assert_failure_with_error(1481 &["foo", "--exec-batch", "echo", "{}", "{}"],1482 "[fd error]: Only one placeholder allowed for batch commands",1482 "error: Only one placeholder allowed for batch commands\n\1483 \n\1484 Usage: fd-find [OPTIONS] [pattern] [path]...\n\1485 \n\1486 For more information try '--help'\n\1487 ",1488 );14891490 te.assert_failure_with_error(1491 &["foo", "--exec-batch", "echo", "{/}", ";", "-x", "echo"],
6 unmodified lines
1498 );14991500 te.assert_failure_with_error(1501 &["foo", "--exec-batch", "echo {}"],1497 "[fd error]: First argument of exec-batch is expected to be a fixed executable",1502 "error: First argument of exec-batch is expected to be a fixed executable\n\1503 \n\1504 Usage: fd-find [OPTIONS] [pattern] [path]...\n\1505 \n\1506 For more information try '--help'\n\1507 ",1508 );1509 }1510}1511
641 unmodified lines
modified:.gitignore+1 added
1target/2/autocomplete/3**/*.rs.bk
modified:build.rs+1 added-22 removed
1use std::fs;23use clap_complete::{generate_to, Shell};4use Shell::*;5//use clap_complete::shells::Shel{Bash, Fish, PowerShell, Elvish};67include!("src/app.rs");81fn main() {10 let min_version = "1.57";2 let min_version = "1.60";34 match version_check::is_min_version(min_version) {5 Some(true) => {}6 // rustc version too small or can't figure it out
1 unmodified line
8 eprintln!("'fd' requires rustc >= {}", min_version);9 std::process::exit(1);10 }11 }2021 let var = std::env::var_os("SHELL_COMPLETIONS_DIR").or_else(|| std::env::var_os("OUT_DIR"));22 let outdir = match var {23 None => return,24 Some(outdir) => outdir,25 };26 fs::create_dir_all(&outdir).unwrap();2728 let mut app = build_app();29 // NOTE: zsh completions are hand written in contrib/completion/_fd30 for shell in [Bash, PowerShell, Fish, Elvish] {31 generate_to(shell, &mut app, "fd", &outdir).unwrap();32 }12}
modified:Cargo.lock+24 added-41 removed
111 unmodified lines
112]113114[[package]]115name = "clap"116version = "3.2.22"116version = "4.0.18"117source = "registry+https://github.com/rust-lang/crates.io-index"118checksum = "86447ad904c7fb335a790c9d7fe3d0d971dc523b8ccd1561a520de9a85302750"118checksum = "335867764ed2de42325fafe6d18b8af74ba97ee0c590fa016f157535b42ab04b"119dependencies = [120 "atty",121 "bitflags",122 "clap_derive",123 "clap_lex",123 "indexmap",124 "once_cell",125 "strsim",126 "termcolor",127 "terminal_size 0.2.1",128 "textwrap",127 "terminal_size",128]129130[[package]]131name = "clap_complete"133version = "3.2.5"132version = "4.0.3"133source = "registry+https://github.com/rust-lang/crates.io-index"135checksum = "3f7a2e0a962c45ce25afce14220bc24f9dade0a1787f185cecf96bfba7847cd8"134checksum = "dfe581a2035db4174cdbdc91265e1aba50f381577f0510d0ad36c7bc59cc84a3"135dependencies = [136 "clap",137]138139[[package]]140name = "clap_derive"141version = "4.0.18"142source = "registry+https://github.com/rust-lang/crates.io-index"143checksum = "16a1b0f6422af32d5da0c58e2703320f379216ee70198241c84173a8c5ac28f3"144dependencies = [145 "heck",146 "proc-macro-error",147 "proc-macro2",148 "quote",149 "syn",150]151152[[package]]153name = "clap_lex"142version = "0.2.4"154version = "0.3.0"155source = "registry+https://github.com/rust-lang/crates.io-index"144checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5"156checksum = "0d4198f73e42b4936b35b5bb248d81d2b595ecb170da0bac7655c54eedfa8da8"157dependencies = [158 "os_str_bytes",159]160
234 unmodified lines
395 "regex",396]397398[[package]]387name = "hashbrown"388version = "0.12.3"399name = "heck"400version = "0.4.0"401source = "registry+https://github.com/rust-lang/crates.io-index"390checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"402checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"403404[[package]]405name = "hermit-abi"406version = "0.1.19"
51 unmodified lines
458 "winapi-util",459]460461[[package]]450name = "indexmap"451version = "1.9.1"452source = "registry+https://github.com/rust-lang/crates.io-index"453checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e"454dependencies = [455 "autocfg",456 "hashbrown",457]458459[[package]]462name = "io-lifetimes"463version = "0.7.4"464source = "registry+https://github.com/rust-lang/crates.io-index"465checksum = "e6e481ccbe3dea62107216d0d1138bb8ad8e5e5c43009a098bd1990272c497b0"
343 unmodified lines
809]810811[[package]]812name = "terminal_size"811version = "0.1.17"812source = "registry+https://github.com/rust-lang/crates.io-index"813checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df"814dependencies = [815 "libc",816 "winapi",817]818819[[package]]820name = "terminal_size"813version = "0.2.1"814source = "registry+https://github.com/rust-lang/crates.io-index"815checksum = "8440c860cf79def6164e4a0a983bcc2305d82419177a0e0c71930d049e3ac5a1"816dependencies = [
23 unmodified lines
840 "syn",841]842843[[package]]852name = "textwrap"853version = "0.15.2"854source = "registry+https://github.com/rust-lang/crates.io-index"855checksum = "b7b3e525a49ec206798b40326a44121291b530c963cfb01018f63e135bac543d"856dependencies = [857 "terminal_size 0.1.17",858]859860[[package]]844name = "thiserror"845version = "1.0.37"846source = "registry+https://github.com/rust-lang/crates.io-index"847checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e"
270 unmodified lines
modified:Cargo.toml+6 added-5 removed
28 unmodified lines
29name = "fd"30path = "src/main.rs"3132[build-dependencies]33clap = { version = "3.1", features = ["cargo"] }34clap_complete = "3.1"33version_check = "0.9"3435[dependencies]36ansi_term = "0.12"
12 unmodified lines
49normpath = "0.3.2"50chrono = "0.4"51once_cell = "1.15.0"52crossbeam-channel = "0.5.6"53clap_complete = {version = "4.0", optional = true}5455[dependencies.clap]57version = "3.1"58features = ["suggestions", "color", "wrap_help", "cargo", "unstable-grouped"]56version = "4.0.12"57features = ["suggestions", "color", "wrap_help", "cargo", "unstable-grouped", "derive"]5859[target.'cfg(unix)'.dependencies]60users = "0.11.0"61nix = { version = "0.24.2", default-features = false, features = ["signal"] }
21 unmodified lines
83codegen-units = 18485[features]86use-jemalloc = ["jemallocator"]87completions = ["clap_complete"]88default = ["use-jemalloc"]88base = ["use-jemalloc"]89default = ["use-jemalloc", "completions"]
modified:clippy.toml+1 added-1 removed
1msrv = "1.57.0"1msrv = "1.60.0"
added:Makefile+37 added
1PROFILE=release2EXE=target/$(PROFILE)/fd3prefix=/usr/local4bindir=$(prefix)/bin5datadir=$(prefix)/share6exe_name=fd78$(EXE): Cargo.toml src/**/*.rs9 cargo build --profile $(PROFILE)1011.PHONY: completions12completions: autocomplete/fd.bash autocomplete/fd.fish autocomplete/fd.ps1 autocomplete/_fd1314comp_dir=@mkdir -p autocomplete1516autocomplete/fd.bash: $(EXE)17 $(comp_dir)18 $(EXE) --gen-completions bash > $@1920autocomplete/fd.fish: $(EXE)21 $(comp_dir)22 $(EXE) --gen-completions fish > $@2324autocomplete/fd.ps1: $(EXE)25 $(comp_dir)26 $(EXE) --gen-completions powershell > $@2728autocomplete/_fd: contrib/completion/_fd29 $(comp_dir)30 cp $< $@3132install: $(EXE) completions33 install -Dm755 $(EXE) $(DESTDIR)$(bindir)/fd34 install -Dm644 autocomplete/fd.bash $(DESTDIR)/$(datadir)/bash-completion/completions/$(exe_name)35 install -Dm644 autocomplete/fd.fish $(DESTDIR)/$(datadir)/fish/vendor_completions.d/$(exe_name).fish36 install -Dm644 autocomplete/_fd $(DESTDIR)/$(datadir)/zsh/site-functions/_$(exe_name)37 install -Dm644 doc/fd.1 $(DESTDIR)/$(datadir)/man/man1/$(exe_name).1