Merge remote-tracking branch 'origin/master' into pr/opposing-options
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Peter · committed by David Peter · parents c749c95, 2570fbd · Browse files · 21 files·+823 added−479 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
21 files+823 added−479 removed
- tests:+129 added−1 removed
- other:+694 added−478 removed
Provenance
- Commit
cdc6a37- Tree
17ee61a- Author
David Peter <mail@david-peter.de>- Committer
David Peter <mail@david-peter.de>- Parent 1
c749c95- Parent 2
2570fbd
21 files changed+823 added−479 removed
deleted:.github/ISSUE_TEMPLATE/bug_report.md-28 removed
12345678910111213141516171819202122232425262728---name: Bug Reportabout: Report a bug.title: ""labels: bugassignees: ''
---
**Describe the bug you encountered:**
<!--Please check out the troubleshooting section first: https://github.com/sharkdp/fd#troubleshooting-->
**Describe what you expected to happen:**
**What version of `fd` are you using?**<!-- paste the output of `fd --version` here -->
**Which operating system / distribution are you on?**<!--Unix: paste the output of `uname -srm` and `lsb_release -a` here.Windows: please tell us your Windows version-->added:.github/ISSUE_TEMPLATE/bug_report.yaml+41 added
1234567891011121314151617181920212223242526272829303132333435363738394041name: Bug Reportdescription: Report a bug.title: "[BUG] "labels: bugbody: - type: markdown attributes: value: | Please check out the [troubleshooting section](https://github.com/sharkdp/fd#troubleshooting) first. - type: checkboxes attributes: options: - label: I have read the troubleshooting section and still think this is a bug. required: true - type: textarea id: bug attributes: label: "Describe the bug you encountered:" validations: required: true - type: textarea id: expected attributes: label: "Describe what you expected to happen:" - type: input id: version attributes: label: "What version of `fd` are you using?" placeholder: "paste the output of `fd --version` here" validations: required: true - type: textarea id: os attributes: label: Which operating system / distribution are you on? placeholder: | Unix: paste the output of `uname -srm` and lsb_release -a` here. Windows: please tell us your Windows version render: shell validations: required: truemodified:.github/workflows/CICD.yml+21 added-7 removed
1 name: CICD2 3 env:4- MIN_SUPPORTED_RUST_VERSION: "1.42.0"4+ MIN_SUPPORTED_RUST_VERSION: "1.53.0"5 CICD_INTERMEDIATES_DIR: "_cicd-intermediates"6 7 on:8 workflow_dispatch:4 unmodified lines13 tags:14 - '*'15 16 jobs:17- min_version:18- name: Minimum supported rust version17+ code_quality:18+ name: Code quality19 runs-on: ubuntu-20.0420 steps:21 - name: Checkout source code22 uses: actions/checkout@v223-24- - name: Install rust toolchain (v${{ env.MIN_SUPPORTED_RUST_VERSION }})23+ - name: Install rust toolchain24 uses: actions-rs/toolchain@v125 with:27- toolchain: ${{ env.MIN_SUPPORTED_RUST_VERSION }}26+ toolchain: stable27 default: true28 profile: minimal # minimal component installation (ie, no documentation)29 components: clippy, rustfmt30 - name: Ensure `cargo fmt` has been run31 uses: actions-rs/cargo@v132 with:33 command: fmt34 args: -- --check36- - name: Run clippy (on minimum supported rust version to prevent warnings we can't fix)35+ - name: Ensure MSRV is set in `clippy.toml`36+ run: grep "^msrv = \"${{ env.MIN_SUPPORTED_RUST_VERSION }}\"\$" clippy.toml37+ - name: Run clippy38 uses: actions-rs/cargo@v139 with:40 command: clippy41 args: --locked --all-targets --all-features42+43+ min_version:44+ name: Minimum supported rust version45+ runs-on: ubuntu-20.0446+ steps:47+ - name: Checkout source code48+ uses: actions/checkout@v249+ - name: Install rust toolchain (v${{ env.MIN_SUPPORTED_RUST_VERSION }})50+ uses: actions-rs/toolchain@v151+ with:52+ toolchain: ${{ env.MIN_SUPPORTED_RUST_VERSION }}53+ default: true54+ profile: minimal # minimal component installation (ie, no documentation)55 - name: Run tests56 uses: actions-rs/cargo@v157 with:58 command: test296 unmodified linesmodified:contrib/completion/_fd+2 added-1 removed
136 unmodified lines137 138 + '(exec-cmds)' # execute command139 '(long-listing max-results)'{-x+,--exec=}'[execute command for each search result]:command: _command_names -e:*\;::program arguments: _normal'140 '(long-listing max-results)'{-X+,--exec-batch=}'[execute command for all search results at once]:command: _command_names -e:*\;::program arguments: _normal'141+ '(long-listing max-results)--batch-size=[max number of args for each -X call]:size'142 143 + other144 '!(--max-buffer-time)--max-buffer-time=[set amount of time to buffer before showing output]:time (ms)'145 74 unmodified lines220 221 _fd "$@"222 223 # ------------------------------------------------------------------------------223-# Copyright (c) 2011 Github zsh-users - http://github.com/zsh-users224+# Copyright (c) 2011 GitHub zsh-users - http://github.com/zsh-users225 # All rights reserved.226 #227 # Redistribution and use in source and binary forms, with or without228 # modification, are permitted provided that the following conditions are met:41 unmodified linesmodified:doc/fd.1+6 added
407 unmodified lines408 $ fd -e py409 .TP410 .RI "Open all search results with vim:"411 $ fd pattern -X vim412+.TP413+.BI "\-\-batch\-size " size414+Pass at most415+.I size416+arguments to each call to the command given with -X.417+.TP418 .SH SEE ALSO419 .BR find (1)modified:src/exec/job.rs+15 added-2 removed
40 unmodified lines41 // Generate a command, execute it and store its exit code.42 results.push(cmd.generate_and_execute(&value, Arc::clone(&out_perm), buffer_output))43 }44 // Returns error in case of any error.45- merge_exitcodes(&results)45+ merge_exitcodes(results)46 }47 48 pub fn batch(49 rx: Receiver<WorkerResult>,50 cmd: &CommandTemplate,51 show_filesystem_errors: bool,52 buffer_output: bool,53+ limit: usize,54 ) -> ExitCode {55 let paths = rx.iter().filter_map(|value| match value {56 WorkerResult::Entry(val) => Some(val),57 WorkerResult::Error(err) => {2 unmodified lines60 }61 None62 }63 });63- cmd.generate_and_execute_batch(paths, buffer_output)64+ if limit == 0 {65+ // no limit66+ return cmd.generate_and_execute_batch(paths, buffer_output);67+ }68+69+ let mut exit_codes = Vec::new();70+ let mut peekable = paths.peekable();71+ while peekable.peek().is_some() {72+ let limited = peekable.by_ref().take(limit);73+ let exit_code = cmd.generate_and_execute_batch(limited, buffer_output);74+ exit_codes.push(exit_code);75+ }76+ merge_exitcodes(exit_codes)77 }modified:src/app.rs+49 added-2 removed
62 unmodified lines63 Arg::with_name("no-ignore-vcs")64 .long("no-ignore-vcs")65 .overrides_with("no-ignore-vcs")66 .hidden_short_help(true)67+ .help("Do not respect .gitignore files")68 .long_help(69 "Show search results from files and directories that would otherwise be \70 ignored by '.gitignore' files. The flag can be overridden with --ignore-vcs.",71 ),7 unmodified lines79 "Overrides --no-ignore-vcs.",80 ),81 )82 .arg(83+ Arg::with_name("no-ignore-parent")84+ .long("no-ignore-parent")85+ .overrides_with("no-ignore-parent")86+ .hidden_short_help(true)87+ .help("Do not respect .(git|fd)ignore files in parent directories")88+ .long_help(89+ "Show search results from files and directories that would otherwise be \90+ ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories.",91+ ),92+ )93+ .arg(94 Arg::with_name("no-global-ignore-file")95 .long("no-global-ignore-file")96 .hidden(true)97+ .help("Do not respect the global ignore file")98 .long_help("Do not respect the global ignore file."),99 )100 .arg(101 Arg::with_name("rg-alias-hidden-ignore")1 unmodified line103 .long("unrestricted")104 .overrides_with_all(&["ignore", "no-hidden"])105 .multiple(true)106 .hidden_short_help(true)107+ .help("Alias for '--no-ignore', and '--hidden' when given twice")108 .long_help(109 "Alias for '--no-ignore'. Can be repeated. '-uu' is an alias for \110 '--no-ignore --hidden'.",111 ),35 unmodified lines147 Arg::with_name("regex")148 .long("regex")149 .overrides_with_all(&["glob", "regex"])150 .hidden_short_help(true)151+ .help("Regular-expression based search (default)")152 .long_help(153 "Perform a regular-expression based search (default). This can be used to \154 override --glob.",155 ),4 unmodified lines160 .short("F")161 .alias("literal")162 .overrides_with("fixed-strings")163 .hidden_short_help(true)164+ .help("Treat pattern as literal string instead of regex")165 .long_help(166 "Treat the pattern as a literal string instead of a regular expression. Note \167 that this also performs substring comparison. If you want to match on an \168 exact filename, consider using '--glob'.",96 unmodified lines265 Arg::with_name("rg-depth")266 .long("maxdepth")267 .hidden(true)268 .takes_value(true)269+ .help("Set maximum search depth (default: none)")270 )271 .arg(272 Arg::with_name("min-depth")273 .long("min-depth")274 .takes_value(true)275 .value_name("depth")276 .hidden_short_help(true)277+ .help("Only show results starting at given depth")278 .long_help(279 "Only show search results starting at the given depth. \280 See also: '--max-depth' and '--exact-depth'",281 ),4 unmodified lines286 .takes_value(true)287 .value_name("depth")288 .hidden_short_help(true)289 .conflicts_with_all(&["max-depth", "min-depth"])290+ .help("Only show results at exact given depth")291 .long_help(292 "Only show search results at the exact given depth. This is an alias for \293 '--min-depth <depth> --max-depth <depth>'.",294 ),2 unmodified lines297 Arg::with_name("prune")298 .long("prune")299 .conflicts_with_all(&["size", "exact-depth"])300 .hidden_short_help(true)282- .long_help("Do not traverse into matching directories.")301+ .help("Do not traverse into matching directories")302+ .long_help("Do not traverse into directories that match the search criteria. If \303+ you want to exclude specific directories, use the '--exclude=…' option.")304 )305 .arg(306 Arg::with_name("file-type")307 .long("type")108 unmodified lines416 "417 ),418 )419 .arg(420+ Arg::with_name("batch-size")421+ .long("batch-size")422+ .takes_value(true)423+ .value_name("size")424+ .hidden_short_help(true)425+ .requires("exec-batch")426+ .help("Max number of arguments to run as a batch with -X")427+ .long_help(428+ "Maximum number of arguments to pass to the command given with -X. \429+ If the number of results is greater than the given size, \430+ the command given with -X is run again with remaining arguments. \431+ A batch size of zero means there is no limit.",432+ ),433+ )434+ .arg(435 Arg::with_name("exclude")436 .long("exclude")437 .short("E")438 .takes_value(true)17 unmodified lines456 .value_name("path")457 .number_of_values(1)458 .multiple(true)459 .hidden_short_help(true)460+ .help("Add custom ignore-file in '.gitignore' format")461 .long_help(462 "Add a custom ignore-file in '.gitignore' format. These files have a low \463 precedence.",464 ),20 unmodified lines485 .short("j")486 .takes_value(true)487 .value_name("num")488 .hidden_short_help(true)489+ .help("Set number of threads")490 .long_help(491 "Set number of threads to use for searching & executing (default: number \492 of available CPU cores)",493 ),5 unmodified lines499 .takes_value(true)500 .number_of_values(1)501 .allow_hyphen_values(true)502 .multiple(true)465- .help("Limit results based on the size of files.")503+ .help("Limit results based on the size of files")504 .long_help(505 "Limit results based on the size of files using the format <+-><NUM><UNIT>.\n \506 '+': file size must be greater than or equal to this\n \507 '-': file size must be less than or equal to this\n\16 unmodified lines524 Arg::with_name("max-buffer-time")525 .long("max-buffer-time")526 .takes_value(true)527 .hidden(true)528+ .help("Milliseconds to buffer before streaming search results to console")529 .long_help(530 "Amount of time in milliseconds to buffer, before streaming the search \531 results to the console.",532 ),48 unmodified lines581 // same search with `--exec rm` attached and get a reliable removal of582 // the files they saw in the previous search.583 .conflicts_with_all(&["exec", "exec-batch", "list-details"])584 .hidden_short_help(true)585+ .help("Limit number of search results")586 .long_help("Limit the number of search results to 'count' and quit immediately."),587 )588 .arg(589 Arg::with_name("max-one-result")590 .short("1")591 .hidden_short_help(true)592 .overrides_with("max-results")593 .conflicts_with_all(&["exec", "exec-batch", "list-details"])594+ .help("Limit search to a single result")595 .long_help("Limit the search to a single result and quit immediately. \596 This is an alias for '--max-results=1'.")597 )598 .arg(2 unmodified lines601 .short("q")602 .alias("has-results")603 .hidden_short_help(true)604 .conflicts_with_all(&["exec", "exec-batch", "list-details", "max-results"])605+ .help("Print nothing, exit code 0 if match found, 1 otherwise")606 .long_help(607 "When the flag is present, the program does not print anything and will \608 return with an exit code of 0 if there is at least one match. Otherwise, the \609 exit code will be 1. \4 unmodified lines614 Arg::with_name("show-errors")615 .long("show-errors")616 .hidden_short_help(true)617 .overrides_with("show-errors")618+ .help("Show filesystem errors")619 .long_help(620 "Enable the display of filesystem errors for situations such as \621 insufficient permissions or dead symlinks.",622 ),4 unmodified lines627 .takes_value(true)628 .value_name("path")629 .number_of_values(1)630 .hidden_short_help(true)631+ .help("Change current working directory")632 .long_help(633 "Change the current working directory of fd to the provided path. This \634 means that search results will be shown with respect to the given base \635 path. Note that relative paths which are passed to fd via the positional \15 unmodified lines651 .takes_value(true)652 .value_name("separator")653 .long("path-separator")654 .hidden_short_help(true)655+ .help("Set path separator when printing file paths")656 .long_help(657 "Set the path separator to use when printing file paths. The default is \658 the OS-specific separator ('/' on Unix, '\\' on Windows).",659 ),14 unmodified lines674 .conflicts_with("path")675 .multiple(true)676 .hidden_short_help(true)677 .number_of_values(1)678+ .help("Provide paths to search as an alternative to the positional <path>")679 .long_help(680 "Provide paths to search as an alternative to the positional <path> \681 argument. Changes the usage to `fd [FLAGS/OPTIONS] --search-path <path> \682 --search-path <path2> [<pattern>]`",28 unmodified lines711 Arg::with_name("one-file-system")712 .long("one-file-system")713 .aliases(&["mount", "xdev"])714 .hidden_short_help(true)715+ .help("Do not descend into a different file system")716 .long_help(717 "By default, fd will traverse the file system tree as far as other options \718 dictate. With this flag, fd ensures that it does not descend into a \719 different file system than the one it started in. Comparable to the -mount \7 unmodified linesadded:src/config.rs+116 added
1+use std::{path::PathBuf, sync::Arc, time::Duration};2+3+use lscolors::LsColors;4+use regex::bytes::RegexSet;5+6+use crate::exec::CommandTemplate;7+use crate::filetypes::FileTypes;8+#[cfg(unix)]9+use crate::filter::OwnerFilter;10+use crate::filter::{SizeFilter, TimeFilter};11+12+/// Configuration options for *fd*.13+pub struct Config {14+ /// Whether the search is case-sensitive or case-insensitive.15+ pub case_sensitive: bool,16+17+ /// Whether to search within the full file path or just the base name (filename or directory18+ /// name).19+ pub search_full_path: bool,20+21+ /// Whether to ignore hidden files and directories (or not).22+ pub ignore_hidden: bool,23+24+ /// Whether to respect `.fdignore` files or not.25+ pub read_fdignore: bool,26+27+ /// Whether to respect ignore files in parent directories or not.28+ pub read_parent_ignore: bool,29+30+ /// Whether to respect VCS ignore files (`.gitignore`, ..) or not.31+ pub read_vcsignore: bool,32+33+ /// Whether to respect the global ignore file or not.34+ pub read_global_ignore: bool,35+36+ /// Whether to follow symlinks or not.37+ pub follow_links: bool,38+39+ /// Whether to limit the search to starting file system or not.40+ pub one_file_system: bool,41+42+ /// Whether elements of output should be separated by a null character43+ pub null_separator: bool,44+45+ /// The maximum search depth, or `None` if no maximum search depth should be set.46+ ///47+ /// A depth of `1` includes all files under the current directory, a depth of `2` also includes48+ /// all files under subdirectories of the current directory, etc.49+ pub max_depth: Option<usize>,50+51+ /// The minimum depth for reported entries, or `None`.52+ pub min_depth: Option<usize>,53+54+ /// Whether to stop traversing into matching directories.55+ pub prune: bool,56+57+ /// The number of threads to use.58+ pub threads: usize,59+60+ /// If true, the program doesn't print anything and will instead return an exit code of 061+ /// if there's at least one match. Otherwise, the exit code will be 1.62+ pub quiet: bool,63+64+ /// Time to buffer results internally before streaming to the console. This is useful to65+ /// provide a sorted output, in case the total execution time is shorter than66+ /// `max_buffer_time`.67+ pub max_buffer_time: Option<Duration>,68+69+ /// `None` if the output should not be colorized. Otherwise, a `LsColors` instance that defines70+ /// how to style different filetypes.71+ pub ls_colors: Option<LsColors>,72+73+ /// Whether or not we are writing to an interactive terminal74+ pub interactive_terminal: bool,75+76+ /// The type of file to search for. If set to `None`, all file types are displayed. If77+ /// set to `Some(..)`, only the types that are specified are shown.78+ pub file_types: Option<FileTypes>,79+80+ /// The extension to search for. Only entries matching the extension will be included.81+ ///82+ /// The value (if present) will be a lowercase string without leading dots.83+ pub extensions: Option<RegexSet>,84+85+ /// If a value is supplied, each item found will be used to generate and execute commands.86+ pub command: Option<Arc<CommandTemplate>>,87+88+ /// Maximum number of search results to pass to each `command`. If zero, the number is89+ /// unlimited.90+ pub batch_size: usize,91+92+ /// A list of glob patterns that should be excluded from the search.93+ pub exclude_patterns: Vec<String>,94+95+ /// A list of custom ignore files.96+ pub ignore_files: Vec<PathBuf>,97+98+ /// The given constraints on the size of returned files99+ pub size_constraints: Vec<SizeFilter>,100+101+ /// Constraints on last modification time of files102+ pub time_constraints: Vec<TimeFilter>,103+104+ #[cfg(unix)]105+ /// User/group ownership constraint106+ pub owner_constraint: Option<OwnerFilter>,107+108+ /// Whether or not to display filesystem errors109+ pub show_filesystem_errors: bool,110+111+ /// The separator used to print file paths.112+ pub path_separator: Option<String>,113+114+ /// The maximum number of search results115+ pub max_results: Option<usize>,116+}modified:src/exit_codes.rs+10 added-10 removed
21 unmodified lines22 i32::from(self) != 023 }24 }25 26-pub fn merge_exitcodes(results: &[ExitCode]) -> ExitCode {27- if results.iter().any(|&c| ExitCode::is_error(c)) {26+pub fn merge_exitcodes(results: impl IntoIterator<Item = ExitCode>) -> ExitCode {27+ if results.into_iter().any(ExitCode::is_error) {28 return ExitCode::GeneralError;29 }30 ExitCode::Success31 }3 unmodified lines35 use super::*;36 37 #[test]38 fn success_when_no_results() {39- assert_eq!(merge_exitcodes(&[]), ExitCode::Success);39+ assert_eq!(merge_exitcodes([]), ExitCode::Success);40 }41 42 #[test]43 fn general_error_if_at_least_one_error() {44 assert_eq!(45- merge_exitcodes(&[ExitCode::GeneralError]),45+ merge_exitcodes([ExitCode::GeneralError]),46 ExitCode::GeneralError47 );48 assert_eq!(49- merge_exitcodes(&[ExitCode::KilledBySigint]),49+ merge_exitcodes([ExitCode::KilledBySigint]),50 ExitCode::GeneralError51 );52 assert_eq!(53- merge_exitcodes(&[ExitCode::KilledBySigint, ExitCode::Success]),53+ merge_exitcodes([ExitCode::KilledBySigint, ExitCode::Success]),54 ExitCode::GeneralError55 );56 assert_eq!(57- merge_exitcodes(&[ExitCode::Success, ExitCode::GeneralError]),57+ merge_exitcodes([ExitCode::Success, ExitCode::GeneralError]),58 ExitCode::GeneralError59 );60 assert_eq!(61- merge_exitcodes(&[ExitCode::GeneralError, ExitCode::KilledBySigint]),61+ merge_exitcodes([ExitCode::GeneralError, ExitCode::KilledBySigint]),62 ExitCode::GeneralError63 );64 }65 66 #[test]67 fn success_if_no_error() {68- assert_eq!(merge_exitcodes(&[ExitCode::Success]), ExitCode::Success);68+ assert_eq!(merge_exitcodes([ExitCode::Success]), ExitCode::Success);69 assert_eq!(70- merge_exitcodes(&[ExitCode::Success, ExitCode::Success]),70+ merge_exitcodes([ExitCode::Success, ExitCode::Success]),71 ExitCode::Success72 );73 }74 }modified:src/filetypes.rs+2 added-2 removed
35 unmodified lines36 || (!self.pipes && filesystem::is_pipe(*entry_type))37 || (self.executables_only38 && !entry39 .metadata()40- .map(|m| filesystem::is_executable(&m))40+ .map(|m| filesystem::is_executable(m))41 .unwrap_or(false))42- || (self.empty_only && !filesystem::is_empty(&entry))42+ || (self.empty_only && !filesystem::is_empty(entry))43 || !(entry_type.is_file()44 || entry_type.is_dir()45 || entry_type.is_symlink()46 || filesystem::is_socket(*entry_type)6 unmodified linesmodified:src/main.rs+294 added-222 removed
1 mod app;2+mod config;3 mod error;4 mod exec;5 mod exit_codes;6 mod filesystem;7 mod filetypes;8 mod filter;8-mod options;9 mod output;10 mod regex_helper;11 mod walk;12 9 unmodified lines22 use lscolors::LsColors;23 use normpath::PathExt;24 use regex::bytes::{RegexBuilder, RegexSetBuilder};25 26+use crate::config::Config;27 use crate::error::print_error;28 use crate::exec::CommandTemplate;29 use crate::exit_codes::ExitCode;30 use crate::filetypes::FileTypes;31 #[cfg(unix)]32 use crate::filter::OwnerFilter;33 use crate::filter::{SizeFilter, TimeFilter};33-use crate::options::Options;34 use crate::regex_helper::{pattern_has_uppercase_char, pattern_matches_strings_with_leading_dot};35 36 // 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 infos11 unmodified lines49 ow=0:or=0;38;5;16;48;5;203:no=0:ex=1;38;5;203:cd=0;38;5;203;48;5;236:mi=0;38;5;16;48;5;203:*~=0;38;5;243:st=0:pi=0;38;5;16;48;5;81:fi=0:di=0;38;5;81:so=0;38;5;16;48;5;203:bd=0;38;5;81;48;5;236:tw=0:ln=0;38;5;203:*.m=0;38;5;48:*.o=0;38;5;243:*.z=4;38;5;203:*.a=1;38;5;203:*.r=0;38;5;48:*.c=0;38;5;48:*.d=0;38;5;48:*.t=0;38;5;48:*.h=0;38;5;48:*.p=0;38;5;48:*.cc=0;38;5;48:*.ll=0;38;5;48:*.jl=0;38;5;48:*css=0;38;5;48:*.md=0;38;5;185:*.gz=4;38;5;203:*.nb=0;38;5;48:*.mn=0;38;5;48:*.go=0;38;5;48:*.xz=4;38;5;203:*.so=1;38;5;203:*.rb=0;38;5;48:*.pm=0;38;5;48:*.bc=0;38;5;243:*.py=0;38;5;48:*.as=0;38;5;48:*.pl=0;38;5;48:*.rs=0;38;5;48:*.sh=0;38;5;48:*.7z=4;38;5;203:*.ps=0;38;5;186:*.cs=0;38;5;48:*.el=0;38;5;48:*.rm=0;38;5;208:*.hs=0;38;5;48:*.td=0;38;5;48:*.ui=0;38;5;149:*.ex=0;38;5;48:*.js=0;38;5;48:*.cp=0;38;5;48:*.cr=0;38;5;48:*.la=0;38;5;243:*.kt=0;38;5;48:*.ml=0;38;5;48:*.vb=0;38;5;48:*.gv=0;38;5;48:*.lo=0;38;5;243:*.hi=0;38;5;243:*.ts=0;38;5;48:*.ko=1;38;5;203:*.hh=0;38;5;48:*.pp=0;38;5;48:*.di=0;38;5;48:*.bz=4;38;5;203:*.fs=0;38;5;48:*.png=0;38;5;208:*.zsh=0;38;5;48:*.mpg=0;38;5;208:*.pid=0;38;5;243:*.xmp=0;38;5;149:*.iso=4;38;5;203:*.m4v=0;38;5;208:*.dot=0;38;5;48:*.ods=0;38;5;186:*.inc=0;38;5;48:*.sxw=0;38;5;186:*.aif=0;38;5;208:*.git=0;38;5;243:*.gvy=0;38;5;48:*.tbz=4;38;5;203:*.log=0;38;5;243:*.txt=0;38;5;185:*.ico=0;38;5;208:*.csx=0;38;5;48:*.vob=0;38;5;208:*.pgm=0;38;5;208:*.pps=0;38;5;186:*.ics=0;38;5;186:*.img=4;38;5;203:*.fon=0;38;5;208:*.hpp=0;38;5;48:*.bsh=0;38;5;48:*.sql=0;38;5;48:*TODO=1:*.php=0;38;5;48:*.pkg=4;38;5;203:*.ps1=0;38;5;48:*.csv=0;38;5;185:*.ilg=0;38;5;243:*.ini=0;38;5;149:*.pyc=0;38;5;243:*.psd=0;38;5;208:*.htc=0;38;5;48:*.swp=0;38;5;243:*.mli=0;38;5;48:*hgrc=0;38;5;149:*.bst=0;38;5;149:*.ipp=0;38;5;48:*.fsi=0;38;5;48:*.tcl=0;38;5;48:*.exs=0;38;5;48:*.out=0;38;5;243:*.jar=4;38;5;203:*.xls=0;38;5;186:*.ppm=0;38;5;208:*.apk=4;38;5;203:*.aux=0;38;5;243:*.rpm=4;38;5;203:*.dll=1;38;5;203:*.eps=0;38;5;208:*.exe=1;38;5;203:*.doc=0;38;5;186:*.wma=0;38;5;208:*.deb=4;38;5;203:*.pod=0;38;5;48:*.ind=0;38;5;243:*.nix=0;38;5;149:*.lua=0;38;5;48:*.epp=0;38;5;48:*.dpr=0;38;5;48:*.htm=0;38;5;185:*.ogg=0;38;5;208:*.bin=4;38;5;203:*.otf=0;38;5;208:*.yml=0;38;5;149:*.pro=0;38;5;149:*.cxx=0;38;5;48:*.tex=0;38;5;48:*.fnt=0;38;5;208:*.erl=0;38;5;48:*.sty=0;38;5;243:*.bag=4;38;5;203:*.rst=0;38;5;185:*.pdf=0;38;5;186:*.pbm=0;38;5;208:*.xcf=0;38;5;208:*.clj=0;38;5;48:*.gif=0;38;5;208:*.rar=4;38;5;203:*.elm=0;38;5;48:*.bib=0;38;5;149:*.tsx=0;38;5;48:*.dmg=4;38;5;203:*.tmp=0;38;5;243:*.bcf=0;38;5;243:*.mkv=0;38;5;208:*.svg=0;38;5;208:*.cpp=0;38;5;48:*.vim=0;38;5;48:*.bmp=0;38;5;208:*.ltx=0;38;5;48:*.fls=0;38;5;243:*.flv=0;38;5;208:*.wav=0;38;5;208:*.m4a=0;38;5;208:*.mid=0;38;5;208:*.hxx=0;38;5;48:*.pas=0;38;5;48:*.wmv=0;38;5;208:*.tif=0;38;5;208:*.kex=0;38;5;186:*.mp4=0;38;5;208:*.bak=0;38;5;243:*.xlr=0;38;5;186:*.dox=0;38;5;149:*.swf=0;38;5;208:*.tar=4;38;5;203:*.tgz=4;38;5;203:*.cfg=0;38;5;149:*.xml=0;50 38;5;185:*.jpg=0;38;5;208:*.mir=0;38;5;48:*.sxi=0;38;5;186:*.bz2=4;38;5;203:*.odt=0;38;5;186:*.mov=0;38;5;208:*.toc=0;38;5;243:*.bat=1;38;5;203:*.asa=0;38;5;48:*.awk=0;38;5;48:*.sbt=0;38;5;48:*.vcd=4;38;5;203:*.kts=0;38;5;48:*.arj=4;38;5;203:*.blg=0;38;5;243:*.c++=0;38;5;48:*.odp=0;38;5;186:*.bbl=0;38;5;243:*.idx=0;38;5;243:*.com=1;38;5;203:*.mp3=0;38;5;208:*.avi=0;38;5;208:*.def=0;38;5;48:*.cgi=0;38;5;48:*.zip=4;38;5;203:*.ttf=0;38;5;208:*.ppt=0;38;5;186:*.tml=0;38;5;149:*.fsx=0;38;5;48:*.h++=0;38;5;48:*.rtf=0;38;5;186:*.inl=0;38;5;48:*.yaml=0;38;5;149:*.html=0;38;5;185:*.mpeg=0;38;5;208:*.java=0;38;5;48:*.hgrc=0;38;5;149:*.orig=0;38;5;243:*.conf=0;38;5;149:*.dart=0;38;5;48:*.psm1=0;38;5;48:*.rlib=0;38;5;243:*.fish=0;38;5;48:*.bash=0;38;5;48:*.make=0;38;5;149:*.docx=0;38;5;186:*.json=0;38;5;149:*.psd1=0;38;5;48:*.lisp=0;38;5;48:*.tbz2=4;38;5;203:*.diff=0;38;5;48:*.epub=0;38;5;186:*.xlsx=0;38;5;186:*.pptx=0;38;5;186:*.toml=0;38;5;149:*.h264=0;38;5;208:*.purs=0;38;5;48:*.flac=0;38;5;208:*.tiff=0;38;5;208:*.jpeg=0;38;5;208:*.lock=0;38;5;243:*.less=0;38;5;48:*.dyn_o=0;38;5;243:*.scala=0;38;5;48:*.mdown=0;38;5;185:*.shtml=0;38;5;185:*.class=0;38;5;243:*.cache=0;38;5;243:*.cmake=0;38;5;149:*passwd=0;38;5;149:*.swift=0;38;5;48:*shadow=0;38;5;149:*.xhtml=0;38;5;185:*.patch=0;38;5;48:*.cabal=0;38;5;48:*README=0;38;5;16;48;5;186:*.toast=4;38;5;203:*.ipynb=0;38;5;48:*COPYING=0;38;5;249:*.gradle=0;38;5;48:*.matlab=0;38;5;48:*.config=0;38;5;149:*LICENSE=0;38;5;249:*.dyn_hi=0;38;5;243:*.flake8=0;38;5;149:*.groovy=0;38;5;48:*INSTALL=0;38;5;16;48;5;186:*TODO.md=1:*.ignore=0;38;5;149:*Doxyfile=0;38;5;149:*TODO.txt=1:*setup.py=0;38;5;149:*Makefile=0;38;5;149:*.gemspec=0;38;5;149:*.desktop=0;38;5;149:*.rgignore=0;38;5;149:*.markdown=0;38;5;185:*COPYRIGHT=0;38;5;249:*configure=0;38;5;149:*.DS_Store=0;38;5;243:*.kdevelop=0;38;5;149:*.fdignore=0;38;5;149:*README.md=0;38;5;16;48;5;186:*.cmake.in=0;38;5;149:*SConscript=0;38;5;149:*CODEOWNERS=0;38;5;149:*.localized=0;38;5;243:*.gitignore=0;38;5;149:*Dockerfile=0;38;5;149:*.gitconfig=0;38;5;149:*INSTALL.md=0;38;5;16;48;5;186:*README.txt=0;38;5;16;48;5;186:*SConstruct=0;38;5;149:*.scons_opt=0;38;5;243:*.travis.yml=0;38;5;186:*.gitmodules=0;38;5;149:*.synctex.gz=0;38;5;243:*LICENSE-MIT=0;38;5;249:*MANIFEST.in=0;38;5;149:*Makefile.in=0;38;5;243:*Makefile.am=0;38;5;149:*INSTALL.txt=0;38;5;16;48;5;186:*configure.ac=0;38;5;149:*.applescript=0;38;5;48:*appveyor.yml=0;38;5;186:*.fdb_latexmk=0;38;5;243:*CONTRIBUTORS=0;38;5;16;48;5;186:*.clang-format=0;38;5;149:*LICENSE-APACHE=0;38;5;249:*CMakeLists.txt=0;38;5;149:*CMakeCache.txt=0;38;5;243:*.gitattributes=0;38;5;149:*CONTRIBUTORS.md=0;38;5;16;48;5;186:*.sconsign.dblite=0;38;5;243:*requirements.txt=0;38;5;149:*CONTRIBUTORS.txt=0;38;5;16;48;5;186:*package-lock.json=0;38;5;243:*.CFUserTextEncoding=0;38;5;24351 ";52 53+fn main() {54+ let result = run();55+ match result {56+ Ok(exit_code) => {57+ process::exit(exit_code.into());58+ }59+ Err(err) => {60+ eprintln!("[fd error]: {:#}", err);61+ process::exit(ExitCode::GeneralError.into());62+ }63+ }64+}65+66 fn run() -> Result<ExitCode> {67 let matches = app::build_app().get_matches_from(env::args_os());68 56- // Set the current working directory of the process69+ set_working_dir(&matches)?;70+ let current_directory = Path::new(".");71+ ensure_current_directory_exists(current_directory)?;72+ let search_paths = extract_search_paths(&matches, current_directory)?;73+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)?;77+78+ let config = construct_config(matches, &pattern_regex)?;79+ ensure_use_hidden_option_for_leading_dot_pattern(&config, &pattern_regex)?;80+ let re = build_regex(pattern_regex, &config)?;81+ walk::scan(&search_paths, Arc::new(re), Arc::new(config))82+}83+84+fn 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);87 if !filesystem::is_existing_directory(base_directory) {88 return Err(anyhow!(7 unmodified lines96 base_directory.to_string_lossy()97 )98 })?;99 }100+ Ok(())101+}102 73- let current_directory = Path::new(".");74- if !filesystem::is_existing_directory(current_directory) {75- return Err(anyhow!(103+fn 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?)."77- ));109+ ))110 }111+}112 80- // Get the search pattern113+fn extract_search_pattern<'a>(matches: &'a clap::ArgMatches) -> Result<&'a 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+}124 90- // Get one or more root directories to search.91- let passed_arguments = matches125+fn extract_search_paths(126+ matches: &clap::ArgMatches,127+ current_directory: &Path,128+) -> Result<Vec<PathBuf>> {129+ let mut search_paths = matches130 .values_of_os("path")93- .or_else(|| matches.values_of_os("search-path"));94-95- let mut search_paths = if let Some(paths) = passed_arguments {96- let mut directories = vec![];97- for path in paths {98- let path_buffer = PathBuf::from(path);99- if filesystem::is_existing_directory(&path_buffer) {100- directories.push(path_buffer);101- } else {102- print_error(format!(103- "Search path '{}' is not a directory.",104- path_buffer.to_string_lossy()105- ));106- }107- }108-109- directories110- } else {111- vec![current_directory.to_path_buf()]112- };113-114- // Check if we have no valid search paths.131+ .or_else(|| matches.values_of_os("search-path"))132+ .map_or_else(133+ || vec![current_directory.to_path_buf()],134+ |paths| {135+ paths136+ .filter_map(|path| {137+ let path_buffer = PathBuf::from(path);138+ if filesystem::is_existing_directory(&path_buffer) {139+ Some(path_buffer)140+ } else {141+ print_error(format!(142+ "Search path '{}' is not a directory.",143+ path_buffer.to_string_lossy()144+ ));145+ None146+ }147+ })148+ .collect()149+ },150+ );151 if search_paths.is_empty() {152 return Err(anyhow!("No valid search paths given."));153 }118-154 if matches.is_present("absolute-path") {120- search_paths = search_paths121- .iter()122- .map(|path_buffer| {123- path_buffer124- .normalize()125- .and_then(|pb| filesystem::absolute_path(pb.as_path()))126- .unwrap()127- })128- .collect();155+ update_to_absolute_paths(&mut search_paths);156 }157+ Ok(search_paths)158+}159 160+fn update_to_absolute_paths(search_paths: &mut [PathBuf]) {161+ for buffer in search_paths.iter_mut() {162+ *buffer = filesystem::absolute_path(buffer.normalize().unwrap().as_path()).unwrap();163+ }164+}165+131- // Detect if the user accidentally supplied a path instead of a search pattern166+/// Detect if the user accidentally supplied a path instead of a search pattern167+fn ensure_search_pattern_is_not_a_path(matches: &clap::ArgMatches, pattern: &str) -> Result<()> {168 if !matches.is_present("full-path")169 && pattern.contains(std::path::MAIN_SEPARATOR)170 && Path::new(pattern).is_dir()171 {136- return Err(anyhow!(172+ Err(anyhow!(173 "The search pattern '{pattern}' contains a path-separation character ('{sep}') \174 and will not lead to any search results.\n\n\175 If you want to search for all files inside the '{pattern}' directory, use a match-all pattern:\n\n \176 fd . '{pattern}'\n\n\177 Instead, if you want your pattern to match the full file path, use:\n\n \178 fd --full-path '{pattern}'",179 pattern = pattern,180 sep = std::path::MAIN_SEPARATOR,145- ));181+ ))182+ } else {183+ Ok(())184 }185+}186 187+fn build_pattern_regex(matches: &clap::ArgMatches, pattern: &str) -> Result<String> {148- let pattern_regex = if matches.is_present("glob") && !pattern.is_empty() {188+ Ok(if matches.is_present("glob") && !pattern.is_empty() {189 let glob = GlobBuilder::new(pattern).literal_separator(true).build()?;190 glob.regex().to_owned()191 } else if matches.is_present("fixed-strings") {192 // Treat pattern as literal string if '--fixed-strings' is used193 regex::escape(pattern)194 } else {195 String::from(pattern)156- };196+ })197+}198 199+fn check_path_separator_length(path_separator: Option<&str>) -> Result<()> {200+ match (cfg!(windows), path_separator) {201+ (true, Some(sep)) if sep.len() > 1 => Err(anyhow!(202+ "A path separator must be exactly one byte, but \203+ the given separator is {} bytes: '{}'.\n\204+ In some shells on Windows, '/' is automatically \205+ expanded. Try to use '//' instead.",206+ sep.len(),207+ sep208+ )),209+ _ => Ok(()),210+ }211+}212+213+fn construct_config(matches: clap::ArgMatches, pattern_regex: &str) -> Result<Config> {214 // The search will be case-sensitive if the command line flag is set or215 // if the pattern has an uppercase character (smart case).216 let case_sensitive = !matches.is_present("ignore-case")161- && (matches.is_present("case-sensitive") || pattern_has_uppercase_char(&pattern_regex));217+ && (matches.is_present("case-sensitive") || pattern_has_uppercase_char(pattern_regex));218 219+ let path_separator = matches220+ .value_of("path-separator")221+ .map_or_else(filesystem::default_path_separator, |s| Some(s.to_owned()));222+ check_path_separator_length(path_separator.as_deref())?;223+224+ let size_limits = extract_size_limits(&matches)?;225+ let time_constraints = extract_time_constraints(&matches)?;226+ #[cfg(unix)]227+ let owner_constraint = matches228+ .value_of("owner")229+ .map(OwnerFilter::from_string)230+ .transpose()?231+ .flatten();232+233 #[cfg(windows)]234 let ansi_colors_support =235 ansi_term::enable_ansi_support().is_ok() || std::env::var_os("TERM").is_some();166-236 #[cfg(not(windows))]237 let ansi_colors_support = true;238 239 let interactive_terminal = atty::is(Stream::Stdout);2 unmodified lines242 Some("never") => false,243 _ => ansi_colors_support && env::var_os("NO_COLOR").is_none() && interactive_terminal,244 };245 177- let path_separator = matches178- .value_of("path-separator")179- .map_or_else(filesystem::default_path_separator, |s| Some(s.to_owned()));180-181- #[cfg(windows)]182- {183- if let Some(ref sep) = path_separator {184- if sep.len() > 1 {185- return Err(anyhow!(186- "A path separator must be exactly one byte, but \187- the given separator is {} bytes: '{}'.\n\188- In some shells on Windows, '/' is automatically \189- expanded. Try to use '//' instead.",190- sep.len(),191- sep192- ));193- };194- };195- }196-246 let ls_colors = if colored_output {247 Some(LsColors::from_env().unwrap_or_else(|| LsColors::from_string(DEFAULT_LS_COLORS)))248 } else {249 None250 };251+ let command = extract_command(&matches, path_separator.as_deref(), colored_output)?;252 203- let command = if let Some(args) = matches.values_of("exec") {204- Some(CommandTemplate::new(args, path_separator.clone()))205- } else if let Some(args) = matches.values_of("exec-batch") {206- Some(CommandTemplate::new_batch(args, path_separator.clone())?)207- } else if matches.is_present("list-details") {208- let color = matches.value_of("color").unwrap_or("auto");209- let color_arg = ["--color=", color].concat();210-211- #[allow(unused)]212- let gnu_ls = |command_name| {213- // Note: we use short options here (instead of --long-options) to support more214- // platforms (like BusyBox).215- vec![216- command_name,217- "-l", // long listing format218- "-h", // human readable file sizes219- "-d", // list directories themselves, not their contents220- &color_arg,221- ]222- };223-224- let cmd: Vec<&str> = if cfg!(unix) {225- if !cfg!(any(226- target_os = "macos",227- target_os = "dragonfly",228- target_os = "freebsd",229- target_os = "netbsd",230- target_os = "openbsd"231- )) {232- // Assume ls is GNU ls233- gnu_ls("ls")234- } else {235- // MacOS, DragonFlyBSD, FreeBSD236- use std::process::{Command, Stdio};237-238- // Use GNU ls, if available (support for --color=auto, better LS_COLORS support)239- let gnu_ls_exists = Command::new("gls")240- .arg("--version")241- .stdout(Stdio::null())242- .stderr(Stdio::null())243- .status()244- .is_ok();245-246- if gnu_ls_exists {247- gnu_ls("gls")248- } else {249- let mut cmd = vec![250- "ls", // BSD version of ls251- "-l", // long listing format252- "-h", // '--human-readable' is not available, '-h' is253- "-d", // '--directory' is not available, but '-d' is254- ];255-256- if !cfg!(any(target_os = "netbsd", target_os = "openbsd")) && colored_output {257- // -G is not available in NetBSD's and OpenBSD's ls258- cmd.push("-G");259- }260-261- cmd262- }263- }264- } else if cfg!(windows) {265- use std::process::{Command, Stdio};266-267- // Use GNU ls, if available268- let gnu_ls_exists = Command::new("ls")269- .arg("--version")270- .stdout(Stdio::null())271- .stderr(Stdio::null())272- .status()273- .is_ok();274-275- if gnu_ls_exists {276- gnu_ls("ls")277- } else {278- return Err(anyhow!(279- "'fd --list-details' is not supported on Windows unless GNU 'ls' is installed."280- ));281- }282- } else {283- return Err(anyhow!(284- "'fd --list-details' is not supported on this platform."285- ));286- };287-288- Some(CommandTemplate::new_batch(&cmd, path_separator.clone()).unwrap())289- } else {290- None291- };292-293- let size_limits = if let Some(vs) = matches.values_of("size") {294- vs.map(|sf| {295- SizeFilter::from_string(sf)296- .ok_or_else(|| anyhow!("'{}' is not a valid size constraint. See 'fd --help'.", sf))297- })298- .collect::<Result<Vec<_>>>()?299- } else {300- vec![]301- };302-303- let now = time::SystemTime::now();304- let mut time_constraints: Vec<TimeFilter> = Vec::new();305- if let Some(t) = matches.value_of("changed-within") {306- if let Some(f) = TimeFilter::after(&now, t) {307- time_constraints.push(f);308- } else {309- return Err(anyhow!(310- "'{}' is not a valid date or duration. See 'fd --help'.",311- t312- ));313- }314- }315- if let Some(t) = matches.value_of("changed-before") {316- if let Some(f) = TimeFilter::before(&now, t) {317- time_constraints.push(f);318- } else {319- return Err(anyhow!(320- "'{}' is not a valid date or duration. See 'fd --help'.",321- t322- ));323- }324- }325-326- #[cfg(unix)]327- let owner_constraint = if let Some(s) = matches.value_of("owner") {328- OwnerFilter::from_string(s)?329- } else {330- None331- };332-333- let config = Options {253+ Ok(Config {254 case_sensitive,255 search_full_path: matches.is_present("full-path"),256 ignore_hidden: !(matches.is_present("hidden")257 || matches.occurrences_of("rg-alias-hidden-ignore") >= 2),1 unmodified line259 || matches.is_present("rg-alias-hidden-ignore")),260 read_vcsignore: !(matches.is_present("no-ignore")261 || matches.is_present("rg-alias-hidden-ignore")262 || matches.is_present("no-ignore-vcs")),263+ read_parent_ignore: !(matches.is_present("no-ignore")264+ || matches.is_present("rg-alias-hidden-ignore")265+ || matches.is_present("no-ignore-vcs")266+ || matches.is_present("no-ignore-parent")),267 read_global_ignore: !(matches.is_present("no-ignore")268 || matches.is_present("rg-alias-hidden-ignore")269 || matches.is_present("no-global-ignore-file")),270 follow_links: matches.is_present("follow"),76 unmodified lines347 .build()348 })349 .transpose()?,350 command: command.map(Arc::new),351+ batch_size: matches352+ .value_of("batch-size")353+ .map(|n| n.parse::<usize>())354+ .transpose()355+ .context("Failed to parse --batch-size argument")?356+ .unwrap_or_default(),357 exclude_patterns: matches358 .values_of("exclude")359 .map(|v| v.map(|p| String::from("!") + p).collect())360 .unwrap_or_else(Vec::new),19 unmodified lines380 } else {381 None382 }383 }),384+ })385+}386+387+fn extract_command(388+ matches: &clap::ArgMatches,389+ path_separator: Option<&str>,390+ colored_output: bool,391+) -> Result<Option<CommandTemplate>> {392+ None.or_else(|| {393+ matches.values_of("exec").map(|args| {394+ Ok(CommandTemplate::new(395+ args,396+ path_separator.map(str::to_string),397+ ))398+ })399+ })400+ .or_else(|| {401+ matches402+ .values_of("exec-batch")403+ .map(|args| CommandTemplate::new_batch(args, path_separator.map(str::to_string)))404+ })405+ .or_else(|| {406+ if !matches.is_present("list-details") {407+ return None;408+ }409+410+ let color = matches.value_of("color").unwrap_or("auto");411+ let color_arg = format!("--color={}", color);412+413+ let res = determine_ls_command(&color_arg, colored_output).map(|cmd| {414+ CommandTemplate::new_batch(cmd, path_separator.map(str::to_string)).unwrap()415+ });416+417+ Some(res)418+ })419+ .transpose()420+}421+422+fn determine_ls_command(color_arg: &str, colored_output: bool) -> Result<Vec<&str>> {423+ #[allow(unused)]424+ let gnu_ls = |command_name| {425+ // Note: we use short options here (instead of --long-options) to support more426+ // platforms (like BusyBox).427+ vec![428+ command_name,429+ "-l", // long listing format430+ "-h", // human readable file sizes431+ "-d", // list directories themselves, not their contents432+ color_arg,433+ ]434 };435+ let cmd: Vec<&str> = if cfg!(unix) {436+ if !cfg!(any(437+ target_os = "macos",438+ target_os = "dragonfly",439+ target_os = "freebsd",440+ target_os = "netbsd",441+ target_os = "openbsd"442+ )) {443+ // Assume ls is GNU ls444+ gnu_ls("ls")445+ } else {446+ // MacOS, DragonFlyBSD, FreeBSD447+ use std::process::{Command, Stdio};448 456- if cfg!(unix)457- && config.ignore_hidden458- && pattern_matches_strings_with_leading_dot(&pattern_regex)459- {449+ // Use GNU ls, if available (support for --color=auto, better LS_COLORS support)450+ let gnu_ls_exists = Command::new("gls")451+ .arg("--version")452+ .stdout(Stdio::null())453+ .stderr(Stdio::null())454+ .status()455+ .is_ok();456+457+ if gnu_ls_exists {458+ gnu_ls("gls")459+ } else {460+ let mut cmd = vec![461+ "ls", // BSD version of ls462+ "-l", // long listing format463+ "-h", // '--human-readable' is not available, '-h' is464+ "-d", // '--directory' is not available, but '-d' is465+ ];466+467+ if !cfg!(any(target_os = "netbsd", target_os = "openbsd")) && colored_output {468+ // -G is not available in NetBSD's and OpenBSD's ls469+ cmd.push("-G");470+ }471+472+ cmd473+ }474+ }475+ } else if cfg!(windows) {476+ use std::process::{Command, Stdio};477+478+ // Use GNU ls, if available479+ let gnu_ls_exists = Command::new("ls")480+ .arg("--version")481+ .stdout(Stdio::null())482+ .stderr(Stdio::null())483+ .status()484+ .is_ok();485+486+ if gnu_ls_exists {487+ gnu_ls("ls")488+ } else {489+ return Err(anyhow!(490+ "'fd --list-details' is not supported on Windows unless GNU 'ls' is installed."491+ ));492+ }493+ } else {494 return Err(anyhow!(495+ "'fd --list-details' is not supported on this platform."496+ ));497+ };498+ Ok(cmd)499+}500+501+fn extract_size_limits(matches: &clap::ArgMatches) -> Result<Vec<SizeFilter>> {502+ matches.values_of("size").map_or(Ok(Vec::new()), |vs| {503+ vs.map(|sf| {504+ SizeFilter::from_string(sf)505+ .ok_or_else(|| anyhow!("'{}' is not a valid size constraint. See 'fd --help'.", sf))506+ })507+ .collect::<Result<Vec<_>>>()508+ })509+}510+511+fn extract_time_constraints(matches: &clap::ArgMatches) -> Result<Vec<TimeFilter>> {512+ let now = time::SystemTime::now();513+ let mut time_constraints: Vec<TimeFilter> = Vec::new();514+ if let Some(t) = matches.value_of("changed-within") {515+ if let Some(f) = TimeFilter::after(&now, t) {516+ time_constraints.push(f);517+ } else {518+ return Err(anyhow!(519+ "'{}' is not a valid date or duration. See 'fd --help'.",520+ t521+ ));522+ }523+ }524+ if let Some(t) = matches.value_of("changed-before") {525+ if let Some(f) = TimeFilter::before(&now, t) {526+ time_constraints.push(f);527+ } else {528+ return Err(anyhow!(529+ "'{}' is not a valid date or duration. See 'fd --help'.",530+ t531+ ));532+ }533+ }534+ Ok(time_constraints)535+}536+537+fn ensure_use_hidden_option_for_leading_dot_pattern(538+ config: &Config,539+ pattern_regex: &str,540+) -> Result<()> {541+ if cfg!(unix) && config.ignore_hidden && pattern_matches_strings_with_leading_dot(pattern_regex)542+ {543+ Err(anyhow!(544 "The pattern seems to only match files with a leading dot, but hidden files are \545 filtered by default. Consider adding -H/--hidden to search hidden files as well \546 or adjust your search pattern."464- ));547+ ))548+ } else {549+ Ok(())550 }551+}552 553+fn build_regex(pattern_regex: String, config: &Config) -> Result<regex::bytes::Regex> {467- let re = RegexBuilder::new(&pattern_regex)554+ RegexBuilder::new(&pattern_regex)555 .case_insensitive(!config.case_sensitive)556 .dot_matches_new_line(true)557 .build()558 .map_err(|e| {2 unmodified lines561 literal string instead of a regular expression. Alternatively, you can \562 also use the '--glob' option to match on a glob pattern.",563 e.to_string()564 )478- })?;479-480- walk::scan(&search_paths, Arc::new(re), Arc::new(config))565+ })566 }482-483-fn main() {484- let result = run();485- match result {486- Ok(exit_code) => {487- process::exit(exit_code.into());488- }489- Err(err) => {490- eprintln!("[fd error]: {:#}", err);491- process::exit(ExitCode::GeneralError.into());492- }493- }494-}deleted:src/options.rs-109 removed
1-use std::{path::PathBuf, sync::Arc, time::Duration};2-3-use lscolors::LsColors;4-use regex::bytes::RegexSet;5-6-use crate::exec::CommandTemplate;7-use crate::filetypes::FileTypes;8-#[cfg(unix)]9-use crate::filter::OwnerFilter;10-use crate::filter::{SizeFilter, TimeFilter};11-12-/// Configuration options for *fd*.13-pub struct Options {14- /// Whether the search is case-sensitive or case-insensitive.15- pub case_sensitive: bool,16-17- /// Whether to search within the full file path or just the base name (filename or directory18- /// name).19- pub search_full_path: bool,20-21- /// Whether to ignore hidden files and directories (or not).22- pub ignore_hidden: bool,23-24- /// Whether to respect `.fdignore` files or not.25- pub read_fdignore: bool,26-27- /// Whether to respect VCS ignore files (`.gitignore`, ..) or not.28- pub read_vcsignore: bool,29-30- /// Whether to respect the global ignore file or not.31- pub read_global_ignore: bool,32-33- /// Whether to follow symlinks or not.34- pub follow_links: bool,35-36- /// Whether to limit the search to starting file system or not.37- pub one_file_system: bool,38-39- /// Whether elements of output should be separated by a null character40- pub null_separator: bool,41-42- /// The maximum search depth, or `None` if no maximum search depth should be set.43- ///44- /// A depth of `1` includes all files under the current directory, a depth of `2` also includes45- /// all files under subdirectories of the current directory, etc.46- pub max_depth: Option<usize>,47-48- /// The minimum depth for reported entries, or `None`.49- pub min_depth: Option<usize>,50-51- /// Whether to stop traversing into matching directories.52- pub prune: bool,53-54- /// The number of threads to use.55- pub threads: usize,56-57- /// If true, the program doesn't print anything and will instead return an exit code of 058- /// if there's at least one match. Otherwise, the exit code will be 1.59- pub quiet: bool,60-61- /// Time to buffer results internally before streaming to the console. This is useful to62- /// provide a sorted output, in case the total execution time is shorter than63- /// `max_buffer_time`.64- pub max_buffer_time: Option<Duration>,65-66- /// `None` if the output should not be colorized. Otherwise, a `LsColors` instance that defines67- /// how to style different filetypes.68- pub ls_colors: Option<LsColors>,69-70- /// Whether or not we are writing to an interactive terminal71- pub interactive_terminal: bool,72-73- /// The type of file to search for. If set to `None`, all file types are displayed. If74- /// set to `Some(..)`, only the types that are specified are shown.75- pub file_types: Option<FileTypes>,76-77- /// The extension to search for. Only entries matching the extension will be included.78- ///79- /// The value (if present) will be a lowercase string without leading dots.80- pub extensions: Option<RegexSet>,81-82- /// If a value is supplied, each item found will be used to generate and execute commands.83- pub command: Option<Arc<CommandTemplate>>,84-85- /// A list of glob patterns that should be excluded from the search.86- pub exclude_patterns: Vec<String>,87-88- /// A list of custom ignore files.89- pub ignore_files: Vec<PathBuf>,90-91- /// The given constraints on the size of returned files92- pub size_constraints: Vec<SizeFilter>,93-94- /// Constraints on last modification time of files95- pub time_constraints: Vec<TimeFilter>,96-97- #[cfg(unix)]98- /// User/group ownership constraint99- pub owner_constraint: Option<OwnerFilter>,100-101- /// Whether or not to display filesystem errors102- pub show_filesystem_errors: bool,103-104- /// The separator used to print file paths.105- pub path_separator: Option<String>,106-107- /// The maximum number of search results108- pub max_results: Option<usize>,109-}modified:src/output.rs+6 added-6 removed
4 unmodified lines5 use std::sync::Arc;6 7 use lscolors::{LsColors, Style};8 9+use crate::config::Config;10 use crate::error::print_error;11 use crate::exit_codes::ExitCode;12 use crate::filesystem::strip_current_dir;12-use crate::options::Options;13 14 fn replace_path_separator(path: &str, new_path_separator: &str) -> String {15 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)16 }1 unmodified line18 // TODO: this function is performance critical and can probably be optimized19 pub fn print_entry(20 stdout: &mut StdoutLock,21 entry: &Path,22- config: &Options,22+ config: &Config,23 wants_to_quit: &Arc<AtomicBool>,24 ) {25 let path = if entry.is_absolute() {26 entry21 unmodified lines48 // TODO: this function is performance critical and can probably be optimized49 fn print_entry_colorized(50 stdout: &mut StdoutLock,51 path: &Path,52- config: &Options,52+ config: &Config,53 ls_colors: &LsColors,54 wants_to_quit: &Arc<AtomicBool>,55 ) -> io::Result<()> {56 let default_style = ansi_term::Style::default();27 unmodified lines84 // TODO: this function is performance critical and can probably be optimized85 fn print_entry_uncolorized_base(86 stdout: &mut StdoutLock,87 path: &Path,88- config: &Options,88+ config: &Config,89 ) -> io::Result<()> {90 let separator = if config.null_separator { "\0" } else { "\n" };91 92 let mut path_string = path.to_string_lossy();6 unmodified lines99 #[cfg(not(unix))]100 fn print_entry_uncolorized(101 stdout: &mut StdoutLock,102 path: &Path,103- config: &Options,103+ config: &Config,104 ) -> io::Result<()> {105 print_entry_uncolorized_base(stdout, path, config)106 }107 108 #[cfg(unix)]109 fn print_entry_uncolorized(110 stdout: &mut StdoutLock,111 path: &Path,112- config: &Options,112+ config: &Config,113 ) -> io::Result<()> {114 use std::os::unix::ffi::OsStrExt;115 116 if config.interactive_terminal || config.path_separator.is_some() {9 unmodified linesmodified:src/walk.rs+71 added-49 removed
11 unmodified lines12 13 use anyhow::{anyhow, Result};14 use ignore::overrides::OverrideBuilder;15 use ignore::{self, WalkBuilder};16+use once_cell::unsync::OnceCell;17 use regex::bytes::Regex;18 19+use crate::config::Config;20 use crate::error::print_error;21 use crate::exec;22 use crate::exit_codes::{merge_exitcodes, ExitCode};23 use crate::filesystem;22-use crate::options::Options;24 use crate::output;25 26 /// The receiver thread can either be buffering results or directly streaming to the console.27 enum ReceiverMode {12 unmodified lines40 }41 42 /// Maximum size of the output buffer before flushing results to the console43 pub const MAX_BUFFER_LENGTH: usize = 1000;44+/// Default duration until output buffering switches to streaming.45+pub const DEFAULT_MAX_BUFFER_TIME: time::Duration = time::Duration::from_millis(100);46 47 /// Recursively scan the given search path for files / pathnames matching the pattern.48 ///49 /// If the `--exec` argument was supplied, this will create a thread pool for executing50 /// jobs in parallel from a given command line and the discovered paths. Otherwise, each51 /// path will simply be written to standard output.49-pub fn scan(path_vec: &[PathBuf], pattern: Arc<Regex>, config: Arc<Options>) -> Result<ExitCode> {52+pub fn scan(path_vec: &[PathBuf], pattern: Arc<Regex>, config: Arc<Config>) -> Result<ExitCode> {53 let mut path_iter = path_vec.iter();54 let first_path_buf = path_iter55 .next()56 .expect("Error: Path vector can not be empty");13 unmodified lines70 let mut walker = WalkBuilder::new(first_path_buf.as_path());71 walker72 .hidden(config.ignore_hidden)73 .ignore(config.read_fdignore)71- .parents(config.read_fdignore || config.read_vcsignore)74+ .parents(config.read_parent_ignore)75 .git_ignore(config.read_vcsignore)76 .git_global(config.read_vcsignore)77 .git_exclude(config.read_vcsignore)78 .overrides(overrides)84 unmodified lines163 }164 }165 166 fn spawn_receiver(164- config: &Arc<Options>,167+ config: &Arc<Config>,168 wants_to_quit: &Arc<AtomicBool>,169 rx: Receiver<WorkerResult>,170 ) -> thread::JoinHandle<ExitCode> {171 let config = Arc::clone(config);6 unmodified lines178 thread::spawn(move || {179 // This will be set to `Some` if the `--exec` argument was supplied.180 if let Some(ref cmd) = config.command {181 if cmd.in_batch_mode() {179- exec::batch(rx, cmd, show_filesystem_errors, enable_output_buffering)182+ exec::batch(183+ rx,184+ cmd,185+ show_filesystem_errors,186+ enable_output_buffering,187+ config.batch_size,188+ )189 } else {190 let shared_rx = Arc::new(Mutex::new(rx));191 192 let out_perm = Arc::new(Mutex::new(()));20 unmodified lines213 handles.push(handle);214 }215 216 // Wait for all threads to exit before exiting the program.208- let mut results: Vec<ExitCode> = Vec::new();209- for h in handles {210- results.push(h.join().unwrap());211- }212-213- merge_exitcodes(&results)217+ let exit_codes = handles218+ .into_iter()219+ .map(|handle| handle.join().unwrap())220+ .collect::<Vec<_>>();221+ merge_exitcodes(exit_codes)222 }223 } else {224 let start = time::Instant::now();225 2 unmodified lines228 // Start in buffering mode229 let mut mode = ReceiverMode::Buffering;230 231 // Maximum time to wait before we start streaming to the console.224- let max_buffer_time = config225- .max_buffer_time226- .unwrap_or_else(|| time::Duration::from_millis(100));232+ let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);233 234 let stdout = io::stdout();235 let mut stdout = stdout.lock();236 11 unmodified lines248 buffer.push(value);249 250 // Have we reached the maximum buffer size or maximum buffering time?251 if buffer.len() > MAX_BUFFER_LENGTH246- || time::Instant::now() - start > max_buffer_time252+ || start.elapsed() > max_buffer_time253 {254 // Flush the buffer255 for v in &buffer {256 output::print_entry(14 unmodified lines271 }272 }273 274 num_results += 1;275+ if let Some(max_results) = config.max_results {276+ if num_results >= max_results {277+ break;278+ }279+ }280 }281 WorkerResult::Error(err) => {282 if show_filesystem_errors {283 print_error(err.to_string());284 }285 }286 }276-277- if let Some(max_results) = config.max_results {278- if num_results >= max_results {279- break;280- }281- }287 }288 289 // If we have finished fast enough (faster than max_buffer_time), we haven't streamed290 // anything to the console, yet. In this case, sort the results and print them:286- if !buffer.is_empty() {287- buffer.sort();288- for value in buffer {289- output::print_entry(&mut stdout, &value, &config, &wants_to_quit);291+ buffer.sort();292+ for value in buffer {293+ output::print_entry(&mut stdout, &value, &config, &wants_to_quit);290- }294 }295 296 if config.quiet {297 ExitCode::HasResults(false)3 unmodified lines301 }302 })303 }304 302-pub enum DirEntry {305+enum DirEntryInner {306 Normal(ignore::DirEntry),307 BrokenSymlink(PathBuf),308 }309 310+pub struct DirEntry {311+ inner: DirEntryInner,312+ metadata: OnceCell<Option<Metadata>>,313+}314+315 impl DirEntry {316+ fn normal(e: ignore::DirEntry) -> Self {317+ Self {318+ inner: DirEntryInner::Normal(e),319+ metadata: OnceCell::new(),320+ }321+ }322+323+ fn broken_symlink(path: PathBuf) -> Self {324+ Self {325+ inner: DirEntryInner::BrokenSymlink(path),326+ metadata: OnceCell::new(),327+ }328+ }329+330 pub fn path(&self) -> &Path {309- match self {310- DirEntry::Normal(e) => e.path(),311- DirEntry::BrokenSymlink(pathbuf) => pathbuf.as_path(),331+ match &self.inner {332+ DirEntryInner::Normal(e) => e.path(),333+ DirEntryInner::BrokenSymlink(pathbuf) => pathbuf.as_path(),334 }335 }336 337 pub fn file_type(&self) -> Option<FileType> {316- match self {317- DirEntry::Normal(e) => e.file_type(),318- DirEntry::BrokenSymlink(pathbuf) => {319- pathbuf.symlink_metadata().map(|m| m.file_type()).ok()320- }338+ match &self.inner {339+ DirEntryInner::Normal(e) => e.file_type(),340+ DirEntryInner::BrokenSymlink(_) => self.metadata().map(|m| m.file_type()),341 }342 }343 324- pub fn metadata(&self) -> Option<Metadata> {325- match self {326- DirEntry::Normal(e) => e.metadata().ok(),327- DirEntry::BrokenSymlink(_) => None,328- }344+ pub fn metadata(&self) -> Option<&Metadata> {345+ self.metadata346+ .get_or_init(|| match &self.inner {347+ DirEntryInner::Normal(e) => e.metadata().ok(),348+ DirEntryInner::BrokenSymlink(path) => path.symlink_metadata().ok(),349+ })350+ .as_ref()351 }352 353 pub fn depth(&self) -> Option<usize> {332- match self {333- DirEntry::Normal(e) => Some(e.depth()),334- DirEntry::BrokenSymlink(_) => None,354+ match &self.inner {355+ DirEntryInner::Normal(e) => Some(e.depth()),356+ DirEntryInner::BrokenSymlink(_) => None,357 }358 }359 }360 361 fn spawn_senders(340- config: &Arc<Options>,362+ config: &Arc<Config>,363 wants_to_quit: &Arc<AtomicBool>,364 pattern: Arc<Regex>,365 parallel_walker: ignore::WalkParallel,366 tx: Sender<WorkerResult>,13 unmodified lines380 Ok(ref e) if e.depth() == 0 => {381 // Skip the root directory entry.382 return ignore::WalkState::Continue;383 }362- Ok(e) => DirEntry::Normal(e),384+ Ok(e) => DirEntry::normal(e),385 Err(ignore::Error::WithPath {386 path,387 err: inner_err,388 }) => match inner_err.as_ref() {3 unmodified lines392 .symlink_metadata()393 .ok()394 .map_or(false, |m| m.file_type().is_symlink()) =>395 {374- DirEntry::BrokenSymlink(path)396+ DirEntry::broken_symlink(path)397 }398 _ => {399 return match tx_thread.send(WorkerResult::Error(ignore::Error::WithPath {400 path,60 unmodified lines461 462 #[cfg(unix)]463 {464 if let Some(ref owner_constraint) = config.owner_constraint {443- if let Ok(ref metadata) = entry_path.metadata() {465+ if let Some(metadata) = entry.metadata() {466 if !owner_constraint.matches(metadata) {467 return ignore::WalkState::Continue;468 }469 } else {4 unmodified lines474 475 // Filter out unwanted sizes if it is a file and we have been given size constraints.476 if !config.size_constraints.is_empty() {477 if entry_path.is_file() {456- if let Ok(metadata) = entry_path.metadata() {478+ if let Some(metadata) = entry.metadata() {479 let file_size = metadata.len();480 if config481 .size_constraints482 .iter()11 unmodified lines494 495 // Filter out unwanted modification times496 if !config.time_constraints.is_empty() {497 let mut matched = false;476- if let Ok(metadata) = entry_path.metadata() {498+ if let Some(metadata) = entry.metadata() {499 if let Ok(modified) = metadata.modified() {500 matched = config501 .time_constraints502 .iter()23 unmodified linesmodified:tests/tests.rs+129 added-1 removed
497 unmodified lines498 ignored-by-both",499 );500 }501 502+/// Ignore parent ignore files (--no-ignore-parent)503+#[test]504+fn test_no_ignore_parent() {505+ let dirs = &["inner"];506+ let files = &[507+ "inner/parent-ignored",508+ "inner/child-ignored",509+ "inner/not-ignored",510+ ];511+ let te = TestEnv::new(dirs, files);512+513+ // Ignore 'parent-ignored' in root514+ fs::File::create(te.test_root().join(".gitignore"))515+ .unwrap()516+ .write_all(b"parent-ignored")517+ .unwrap();518+ // Ignore 'child-ignored' in inner519+ fs::File::create(te.test_root().join("inner/.gitignore"))520+ .unwrap()521+ .write_all(b"child-ignored")522+ .unwrap();523+524+ te.assert_output_subdirectory("inner", &[], "not-ignored");525+526+ te.assert_output_subdirectory(527+ "inner",528+ &["--no-ignore-parent"],529+ "parent-ignored530+ not-ignored",531+ );532+}533+534+/// Ignore parent ignore files (--no-ignore-parent) with an inner git repo535+#[test]536+fn test_no_ignore_parent_inner_git() {537+ let dirs = &["inner"];538+ let files = &[539+ "inner/parent-ignored",540+ "inner/child-ignored",541+ "inner/not-ignored",542+ ];543+ let te = TestEnv::new(dirs, files);544+545+ // Make the inner folder also appear as a git repo546+ fs::create_dir_all(te.test_root().join("inner/.git")).unwrap();547+548+ // Ignore 'parent-ignored' in root549+ fs::File::create(te.test_root().join(".gitignore"))550+ .unwrap()551+ .write_all(b"parent-ignored")552+ .unwrap();553+ // Ignore 'child-ignored' in inner554+ fs::File::create(te.test_root().join("inner/.gitignore"))555+ .unwrap()556+ .write_all(b"child-ignored")557+ .unwrap();558+559+ te.assert_output_subdirectory(560+ "inner",561+ &[],562+ "not-ignored563+ parent-ignored",564+ );565+566+ te.assert_output_subdirectory(567+ "inner",568+ &["--no-ignore-parent"],569+ "not-ignored570+ parent-ignored",571+ );572+}573+574 /// Precedence of .fdignore files575 #[test]576 fn test_custom_ignore_precedence() {577 let dirs = &["inner"];840 unmodified lines1418 );1419 }1420 }1421 1422+#[test]1423+fn test_exec_batch_with_limit() {1424+ // TODO Test for windows1425+ if cfg!(windows) {1426+ return;1427+ }1428+1429+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);1430+1431+ te.assert_output(1432+ &["foo", "--batch-size", "0", "--exec-batch", "echo", "{}"],1433+ "a.foo one/b.foo one/two/C.Foo2 one/two/c.foo one/two/three/d.foo one/two/three/directory_foo",1434+ );1435+1436+ let output = te.assert_success_and_get_output(1437+ ".",1438+ &["foo", "--batch-size=2", "--exec-batch", "echo", "{}"],1439+ );1440+ let stdout = String::from_utf8_lossy(&output.stdout);1441+1442+ for line in stdout.lines() {1443+ assert_eq!(2, line.split_whitespace().count());1444+ }1445+1446+ let mut paths: Vec<_> = stdout1447+ .lines()1448+ .flat_map(|line| line.split_whitespace())1449+ .collect();1450+ paths.sort_unstable();1451+ assert_eq!(1452+ &paths,1453+ &[1454+ "a.foo",1455+ "one/b.foo",1456+ "one/two/C.Foo2",1457+ "one/two/c.foo",1458+ "one/two/three/d.foo",1459+ "one/two/three/directory_foo"1460+ ],1461+ );1462+}1463+1464 /// Shell script execution (--exec) with a custom --path-separator1465 #[test]1466 fn test_exec_with_separator() {1467 let (te, abs_path) = get_test_env_with_abs_path(DEFAULT_DIRS, DEFAULT_FILES);226 unmodified lines1694 fs::File::create(&path).expect("creation failed");1695 filetime::set_file_times(&path, ft, ft).expect("time modification failed");1696 }1697 1698+#[cfg(test)]1699+fn remove_symlink<P: AsRef<Path>>(path: P) {1700+ #[cfg(unix)]1701+ fs::remove_file(path).expect("remove symlink");1702+1703+ // On Windows, symlinks remember whether they point to files or directories, so try both1704+ #[cfg(windows)]1705+ fs::remove_file(path.as_ref())1706+ .or_else(|_| fs::remove_dir(path.as_ref()))1707+ .expect("remove symlink");1708+}1709+1710 #[test]1711 fn test_modified_relative() {1712 let te = TestEnv::new(&[], &[]);1713+ remove_symlink(te.test_root().join("symlink"));1714 create_file_with_modified(te.test_root().join("foo_0_now"), 0);1715 create_file_with_modified(te.test_root().join("bar_1_min"), 60);1716 create_file_with_modified(te.test_root().join("foo_10_min"), 600);1717 create_file_with_modified(te.test_root().join("bar_1_h"), 60 * 60);29 unmodified lines1747 filetime::set_file_times(path, ft, ft).expect("time modification failde");1748 }1749 1750 #[test]1624-fn test_modified_asolute() {1751+fn test_modified_absolute() {1752 let te = TestEnv::new(&[], &["15mar2018", "30dec2017"]);1753+ remove_symlink(te.test_root().join("symlink"));1754 change_file_modified(te.test_root().join("15mar2018"), "2018-03-15T12:00:00Z");1755 change_file_modified(te.test_root().join("30dec2017"), "2017-12-30T23:59:00Z");1756 1757 te.assert_output(213 unmodified linesmodified:build.rs+1 added-1 removed
3 unmodified lines4 5 include!("src/app.rs");6 7 fn main() {8- let min_version = "1.42";8+ let min_version = "1.53";9 10 match version_check::is_min_version(min_version) {11 Some(true) => {}12 // rustc version too small or can't figure it out18 unmodified linesmodified:Cargo.lock+31 added-30 removed
29 unmodified lines30 ]31 32 [[package]]33 name = "anyhow"34-version = "1.0.42"34+version = "1.0.44"35 source = "registry+https://github.com/rust-lang/crates.io-index"36-checksum = "595d3cfa7a60d4555cb5067b99f07142a08ea778de5cf993f7b75c7d8fabc486"36+checksum = "61604a8f862e1d5c3229fdd78f8b02c68dcf73a4c4b05fd636d12240aaa242c1"37 38 [[package]]39 name = "atty"40 version = "0.2.14"12 unmodified lines53 checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"54 55 [[package]]56 name = "bitflags"57-version = "1.2.1"57+version = "1.3.2"58 source = "registry+https://github.com/rust-lang/crates.io-index"59-checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"59+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"60 61 [[package]]62 name = "bstr"63-version = "0.2.16"63+version = "0.2.17"64 source = "registry+https://github.com/rust-lang/crates.io-index"65-checksum = "90682c8d613ad3373e66de8c6411e0ae2ab2571e879d2efbf73558cc66f21279"65+checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223"66 dependencies = [67 "memchr",68 ]69 70 [[package]]71 name = "cc"72-version = "1.0.69"72+version = "1.0.71"73 source = "registry+https://github.com/rust-lang/crates.io-index"74-checksum = "e70cc2f62c6ce1868963827bd677764c62d07c3d9a3e1fb1177ee1a9ab199eb2"74+checksum = "79c2681d6594606957bbb8631c4b90a7fcaaa72cdb714743a437b156d6a7eedd"75 76 [[package]]77 name = "cfg-if"78 version = "1.0.0"40 unmodified lines119 ]120 121 [[package]]122 name = "ctrlc"123-version = "3.2.0"123+version = "3.2.1"124 source = "registry+https://github.com/rust-lang/crates.io-index"125-checksum = "377c9b002a72a0b2c1a18c62e2f3864bdfea4a015e3683a96e24aa45dd6c02d1"125+checksum = "a19c6cedffdc8c03a3346d723eb20bd85a13362bb96dc2ac000842c6381ec7bf"126 dependencies = [127 "nix",128 "winapi",129 ]46 unmodified lines176 "libc",177 "lscolors",178 "normpath",179 "num_cpus",180+ "once_cell",181 "regex",182 "regex-syntax",183 "tempdir",184 "test-case",116 unmodified lines301 checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"302 303 [[package]]304 name = "libc"304-version = "0.2.99"305+version = "0.2.106"306 source = "registry+https://github.com/rust-lang/crates.io-index"306-checksum = "a7f823d141fe0a24df1e23b4af4e3c7ba9e5966ec514ea068c93024aa7deb765"307+checksum = "a60553f9a9e039a333b4e9b20573b9e9b9c0bb3a11e201ccc48ef4283456d673"308 309 [[package]]310 name = "log"311 version = "0.4.14"4 unmodified lines316 ]317 318 [[package]]319 name = "lscolors"319-version = "0.7.1"320+version = "0.8.0"321 source = "registry+https://github.com/rust-lang/crates.io-index"321-checksum = "d24b894c45c9da468621cdd615a5a79ee5e5523dd4f75c76ebc03d458940c16e"322+checksum = "bd0aa49b10c47f9a4391a99198b5e65c74f9ca771c0dcc856bb75a3f46c8627d"323 dependencies = [324 "ansi_term 0.12.1",325 ]326 327 [[package]]328 name = "memchr"328-version = "2.4.0"329+version = "2.4.1"330 source = "registry+https://github.com/rust-lang/crates.io-index"330-checksum = "b16bd47d9e329435e309c58469fe0791c2d0d1ba96ec0954152a5ae2b04387dc"331+checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"332 333 [[package]]334 name = "memoffset"335 version = "0.6.4"4 unmodified lines340 ]341 342 [[package]]343 name = "nix"343-version = "0.22.0"344+version = "0.23.0"345 source = "registry+https://github.com/rust-lang/crates.io-index"345-checksum = "cf1e25ee6b412c2a1e3fcb6a4499a5c1bfe7f43e014bdce9a6b6666e5aa2d187"346+checksum = "f305c2c2e4c39a82f7bf0bf65fb557f9070ce06781d4f2454295cc34b1c43188"347 dependencies = [348 "bitflags",349 "cc",350 "cfg-if",2 unmodified lines353 ]354 355 [[package]]356 name = "normpath"356-version = "0.3.0"357+version = "0.3.1"358 source = "registry+https://github.com/rust-lang/crates.io-index"358-checksum = "27e6e8f70e9fbbe3752d330d769e3424f24b9458ce266df93a3b456902fd696a"359+checksum = "640c20e9df4a2d4a5adad5b47e17d76dac3e824346b181931c3ec9f7a85687b1"360 dependencies = [361 "winapi",362 ]363 33 unmodified lines397 checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56"398 399 [[package]]400 name = "proc-macro2"400-version = "1.0.28"401+version = "1.0.32"402 source = "registry+https://github.com/rust-lang/crates.io-index"402-checksum = "5c7ed8b8c7b886ea3ed7dde405212185f423ab44682667c8c6dd14aa1d9f6612"403+checksum = "ba508cc11742c0dc5c1659771673afbab7a0efab23aa17e854cbab0837ed0b43"404 dependencies = [405 "unicode-xid",406 ]407 408 [[package]]409 name = "quote"409-version = "1.0.9"410+version = "1.0.10"411 source = "registry+https://github.com/rust-lang/crates.io-index"411-checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7"412+checksum = "38bc8cc6a5f2e3655e0899c1b848643b2562f853f114bfec7be120678e3ace05"413 dependencies = [414 "proc-macro2",415 ]416 95 unmodified lines512 checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"513 514 [[package]]515 name = "syn"515-version = "1.0.74"516+version = "1.0.81"517 source = "registry+https://github.com/rust-lang/crates.io-index"517-checksum = "1873d832550d4588c3dbc20f01361ab00bfe741048f71e3fecf145a7cc18b29c"518+checksum = "f2afee18b8beb5a596ecb4a2dce128c719b4ba399d34126b9e4396e3f9860966"519 dependencies = [520 "proc-macro2",521 "quote",522 "unicode-xid",20 unmodified lines543 ]544 545 [[package]]546 name = "test-case"546-version = "1.2.0"547+version = "1.2.1"548 source = "registry+https://github.com/rust-lang/crates.io-index"548-checksum = "3b114ece25254e97bf48dd4bfc2a12bad0647adacfe4cae1247a9ca6ad302cec"549+checksum = "c7cad0a06f9a61e94355aa3b3dc92d85ab9c83406722b1ca5e918d4297c12c23"550 dependencies = [551 "cfg-if",552 "proc-macro2",553 "quote",31 unmodified lines585 ]586 587 [[package]]588 name = "unicode-width"588-version = "0.1.8"589+version = "0.1.9"590 source = "registry+https://github.com/rust-lang/crates.io-index"590-checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"591+checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973"592 593 [[package]]594 name = "unicode-xid"595 version = "0.2.2"72 unmodified linesmodified:Cargo.toml+7 added-6 removed
39 unmodified lines40 lazy_static = "1.1.0"41 num_cpus = "1.8"42 regex = "1.5.4"43 regex-syntax = "0.6"44-ctrlc = "3.1"45-humantime = "2.0"46-lscolors = "0.7"44+ctrlc = "3.2"45+humantime = "2.1"46+lscolors = "0.8"47 globset = "0.4"48 anyhow = "1.0"49 dirs-next = "2.0"50 normpath = "0.3"51 chrono = "0.4"52+once_cell = "1.8.0"53 54 [dependencies.clap]54-version = "2.31.2"55+version = "2.31.3"56 features = ["suggestions", "color", "wrap_help"]57 58 [target.'cfg(unix)'.dependencies]59 users = "0.11.0"9 unmodified lines69 70 [dev-dependencies]71 diff = "0.1"72 tempdir = "0.3"72-filetime = "0.2.14"73-test-case = "1.2.0"73+filetime = "0.2"74+test-case = "1.2"75 76 [profile.release]77 lto = true78 codegen-units = 1modified:CHANGELOG.md+11 added
1 # Upcoming release2 3+## Performance improvements4+5+- File metadata is now cached between the different filters that require it (e.g. `--owner`,6+ `--size`), reducing the number of `stat` syscalls when multiple filters are used; see #8637+8 ## Features9 - Don't buffer command output from `--exec` when using a single thread. See #52210 11 - Add new `-q, --quiet` flag, see #303 (@Asha20)12 13+- Add new `--no-ignore-parent` flag, see #787 (@will459)14+15+- Add new `--batch-size` flag, see #410 (@devonhollowood)16+17 - Add opposing command-line options, see #595 (@Asha20)18 19 ## Bugfixes20 2 unmodified lines23 - fd doesn't show substituted drive on Windows, see #36524 - Properly handle write errors to devices that are full, see #73725 - Use local time zone for time functions (`--change-newer-than`, `--change-older-than`), see #631 (@jacobmischka)26 - Support `--list-details` on more platforms (like BusyBox), see #78327+- The filters `--owner`, `--size`, and `--changed-{within,before}` now apply to symbolic links28+ themselves, rather than the link target, except when `--follow` is specified; see #86329 30 ## Changes31 32 - Apply custom `--path-separator` to commands run with `--exec(-batch)` and `--list-details`, see #697 (@aswild)509 unmodified linesadded:clippy.toml+1 added
1+msrv = "1.53.0"modified:README.md+10 added-3 removed
416 unmodified lines417 > fd -- '-pattern'418 > fd '[-]pattern'419 ```420 421+### "Command not found" for `alias`es or shell functions422+423+Shell `alias`es and shell functions can not be used for command execution via `fd -x` or424+`fd -X`. In `zsh`, you can make the alias global via `alias -g myalias="…"`. In `bash`,425+you can use `export -f my_function` to make available to child processes. You would still426+need to call `fd -x bash -c 'my_function "$1"' bash`. For other use cases or shells, use427+a (temporary) shell script.428+429 ## Integration with other programs430 431 ### Using fd with `fzf`432 199 unmodified lines632 ```633 pkg install fd-find634 ```635 628-### From NPM636+### From npm637 638 On linux and macOS, you can install the [fd-find](https://npm.im/fd-find) package:639 640 ```5 unmodified lines646 With Rust's package manager [cargo](https://github.com/rust-lang/cargo), you can install *fd* via:647 ```648 cargo install fd-find649 ```642-Note that rust version *1.42.0* or later is required.650+Note that rust version *1.53.0* or later is required.651 652 `make` is also needed for the build.653 654 ### From binaries19 unmodified lines674 675 - [sharkdp](https://github.com/sharkdp)676 - [tmccombs](https://github.com/tmccombs)677 - [tavianator](https://github.com/tavianator)670-- [pemistahl](https://github.com/pemistahl/)678 679 ## License680 681 Copyright (c) 2017-2021 The fd developers4 unmodified lines