Skip to content
Myr

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

21 files+823 added−479 removed

deleted:.github/ISSUE_TEMPLATE/bug_report.md-28 removed
added:.github/ISSUE_TEMPLATE/bug_report.yaml+41 added
modified:.github/workflows/CICD.yml+21 added-7 removed
1name: CICD23env:4 MIN_SUPPORTED_RUST_VERSION: "1.42.0"4 MIN_SUPPORTED_RUST_VERSION: "1.53.0"5 CICD_INTERMEDIATES_DIR: "_cicd-intermediates"67on:8 workflow_dispatch:
4 unmodified lines
13 tags:14 - '*'1516jobs: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@v22324 - 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-features4243 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: test
296 unmodified lines
modified:contrib/completion/_fd+2 added-1 removed
136 unmodified lines
137138 + '(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'142143 + other144 '!(--max-buffer-time)--max-buffer-time=[set amount of time to buffer before showing output]:time (ms)'145
74 unmodified lines
220221_fd "$@"222223# ------------------------------------------------------------------------------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 lines
modified:doc/fd.1+6 added
407 unmodified lines
408$ fd -e py409.TP410.RI "Open all search results with vim:"411$ fd pattern -X vim412.TP413.BI "\-\-batch\-size " size414Pass at most415.I size416arguments 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 lines
41 // 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}4748pub 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 lines
60 }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 }6869 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 lines
63 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 lines
79 "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 line
103 .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 lines
147 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 lines
160 .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 lines
265 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 lines
286 .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 lines
297 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 lines
416 "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 lines
456 .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 lines
485 .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 lines
499 .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 lines
524 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 lines
581 // 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 lines
601 .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 lines
614 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 lines
627 .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 lines
651 .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 lines
674 .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 lines
711 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 lines
added:src/config.rs+116 added
1use std::{path::PathBuf, sync::Arc, time::Duration};23use lscolors::LsColors;4use regex::bytes::RegexSet;56use crate::exec::CommandTemplate;7use crate::filetypes::FileTypes;8#[cfg(unix)]9use crate::filter::OwnerFilter;10use crate::filter::{SizeFilter, TimeFilter};1112/// Configuration options for *fd*.13pub struct Config {14 /// Whether the search is case-sensitive or case-insensitive.15 pub case_sensitive: bool,1617 /// Whether to search within the full file path or just the base name (filename or directory18 /// name).19 pub search_full_path: bool,2021 /// Whether to ignore hidden files and directories (or not).22 pub ignore_hidden: bool,2324 /// Whether to respect `.fdignore` files or not.25 pub read_fdignore: bool,2627 /// Whether to respect ignore files in parent directories or not.28 pub read_parent_ignore: bool,2930 /// Whether to respect VCS ignore files (`.gitignore`, ..) or not.31 pub read_vcsignore: bool,3233 /// Whether to respect the global ignore file or not.34 pub read_global_ignore: bool,3536 /// Whether to follow symlinks or not.37 pub follow_links: bool,3839 /// Whether to limit the search to starting file system or not.40 pub one_file_system: bool,4142 /// Whether elements of output should be separated by a null character43 pub null_separator: bool,4445 /// 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>,5051 /// The minimum depth for reported entries, or `None`.52 pub min_depth: Option<usize>,5354 /// Whether to stop traversing into matching directories.55 pub prune: bool,5657 /// The number of threads to use.58 pub threads: usize,5960 /// 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,6364 /// 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>,6869 /// `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>,7273 /// Whether or not we are writing to an interactive terminal74 pub interactive_terminal: bool,7576 /// 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>,7980 /// 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>,8485 /// If a value is supplied, each item found will be used to generate and execute commands.86 pub command: Option<Arc<CommandTemplate>>,8788 /// Maximum number of search results to pass to each `command`. If zero, the number is89 /// unlimited.90 pub batch_size: usize,9192 /// A list of glob patterns that should be excluded from the search.93 pub exclude_patterns: Vec<String>,9495 /// A list of custom ignore files.96 pub ignore_files: Vec<PathBuf>,9798 /// The given constraints on the size of returned files99 pub size_constraints: Vec<SizeFilter>,100101 /// Constraints on last modification time of files102 pub time_constraints: Vec<TimeFilter>,103104 #[cfg(unix)]105 /// User/group ownership constraint106 pub owner_constraint: Option<OwnerFilter>,107108 /// Whether or not to display filesystem errors109 pub show_filesystem_errors: bool,110111 /// The separator used to print file paths.112 pub path_separator: Option<String>,113114 /// The maximum number of search results115 pub max_results: Option<usize>,116}
modified:src/exit_codes.rs+10 added-10 removed
21 unmodified lines
22 i32::from(self) != 023 }24}2526pub fn merge_exitcodes(results: &[ExitCode]) -> ExitCode {27 if results.iter().any(|&c| ExitCode::is_error(c)) {26pub 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 lines
35 use super::*;3637 #[test]38 fn success_when_no_results() {39 assert_eq!(merge_exitcodes(&[]), ExitCode::Success);39 assert_eq!(merge_exitcodes([]), ExitCode::Success);40 }4142 #[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 }6566 #[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 lines
36 || (!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 lines
modified:src/main.rs+294 added-222 removed
1mod app;2mod config;3mod error;4mod exec;5mod exit_codes;6mod filesystem;7mod filetypes;8mod filter;8mod options;9mod output;10mod regex_helper;11mod walk;12
9 unmodified lines
22use lscolors::LsColors;23use normpath::PathExt;24use regex::bytes::{RegexBuilder, RegexSetBuilder};2526use crate::config::Config;27use crate::error::print_error;28use crate::exec::CommandTemplate;29use crate::exit_codes::ExitCode;30use crate::filetypes::FileTypes;31#[cfg(unix)]32use crate::filter::OwnerFilter;33use crate::filter::{SizeFilter, TimeFilter};33use crate::options::Options;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
11 unmodified lines
49ow=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;5038;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";5253fn 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}6566fn run() -> Result<ExitCode> {67 let matches = app::build_app().get_matches_from(env::args_os());6856 // 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)?;7374 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)?;7778 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}8384fn 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 lines
96 base_directory.to_string_lossy()97 )98 })?;99 }100 Ok(())101}10273 let current_directory = Path::new(".");74 if !filesystem::is_existing_directory(current_directory) {75 return Err(anyhow!(103fn 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}11280 // Get the search pattern113fn 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}12490 // Get one or more root directories to search.91 let passed_arguments = matches125fn 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"));9495 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 }108109 directories110 } else {111 vec![current_directory.to_path_buf()]112 };113114 // 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 }118154 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}159160fn 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}165131 // 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 pattern167fn 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}186187fn 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}198199fn 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}212213fn 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));218219 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())?;223224 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();232233 #[cfg(windows)]234 let ansi_colors_support =235 ansi_term::enable_ansi_support().is_ok() || std::env::var_os("TERM").is_some();166236 #[cfg(not(windows))]237 let ansi_colors_support = true;238239 let interactive_terminal = atty::is(Stream::Stdout);
2 unmodified lines
242 Some("never") => false,243 _ => ansi_colors_support && env::var_os("NO_COLOR").is_none() && interactive_terminal,244 };245177 let path_separator = matches178 .value_of("path-separator")179 .map_or_else(filesystem::default_path_separator, |s| Some(s.to_owned()));180181 #[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 }196246 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)?;252203 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();210211 #[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 };223224 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};237238 // 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();245246 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 ];255256 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 }260261 cmd262 }263 }264 } else if cfg!(windows) {265 use std::process::{Command, Stdio};266267 // 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();274275 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 };287288 Some(CommandTemplate::new_batch(&cmd, path_separator.clone()).unwrap())289 } else {290 None291 };292293 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 };302303 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 }325326 #[cfg(unix)]327 let owner_constraint = if let Some(s) = matches.value_of("owner") {328 OwnerFilter::from_string(s)?329 } else {330 None331 };332333 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 line
259 || 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 lines
347 .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 lines
380 } else {381 None382 }383 }),384 })385}386387fn 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 }409410 let color = matches.value_of("color").unwrap_or("auto");411 let color_arg = format!("--color={}", color);412413 let res = determine_ls_command(&color_arg, colored_output).map(|cmd| {414 CommandTemplate::new_batch(cmd, path_separator.map(str::to_string)).unwrap()415 });416417 Some(res)418 })419 .transpose()420}421422fn 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};448456 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();456457 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 ];466467 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 }471472 cmd473 }474 }475 } else if cfg!(windows) {476 use std::process::{Command, Stdio};477478 // 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();485486 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}500501fn 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}510511fn 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}536537fn 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}552553fn 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 lines
561 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 })?;479480 walk::scan(&search_paths, Arc::new(re), Arc::new(config))565 })566}482483fn 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
1use std::{path::PathBuf, sync::Arc, time::Duration};23use lscolors::LsColors;4use regex::bytes::RegexSet;56use crate::exec::CommandTemplate;7use crate::filetypes::FileTypes;8#[cfg(unix)]9use crate::filter::OwnerFilter;10use crate::filter::{SizeFilter, TimeFilter};1112/// Configuration options for *fd*.13pub struct Options {14 /// Whether the search is case-sensitive or case-insensitive.15 pub case_sensitive: bool,1617 /// Whether to search within the full file path or just the base name (filename or directory18 /// name).19 pub search_full_path: bool,2021 /// Whether to ignore hidden files and directories (or not).22 pub ignore_hidden: bool,2324 /// Whether to respect `.fdignore` files or not.25 pub read_fdignore: bool,2627 /// Whether to respect VCS ignore files (`.gitignore`, ..) or not.28 pub read_vcsignore: bool,2930 /// Whether to respect the global ignore file or not.31 pub read_global_ignore: bool,3233 /// Whether to follow symlinks or not.34 pub follow_links: bool,3536 /// Whether to limit the search to starting file system or not.37 pub one_file_system: bool,3839 /// Whether elements of output should be separated by a null character40 pub null_separator: bool,4142 /// 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>,4748 /// The minimum depth for reported entries, or `None`.49 pub min_depth: Option<usize>,5051 /// Whether to stop traversing into matching directories.52 pub prune: bool,5354 /// The number of threads to use.55 pub threads: usize,5657 /// 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,6061 /// 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>,6566 /// `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>,6970 /// Whether or not we are writing to an interactive terminal71 pub interactive_terminal: bool,7273 /// 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>,7677 /// 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>,8182 /// If a value is supplied, each item found will be used to generate and execute commands.83 pub command: Option<Arc<CommandTemplate>>,8485 /// A list of glob patterns that should be excluded from the search.86 pub exclude_patterns: Vec<String>,8788 /// A list of custom ignore files.89 pub ignore_files: Vec<PathBuf>,9091 /// The given constraints on the size of returned files92 pub size_constraints: Vec<SizeFilter>,9394 /// Constraints on last modification time of files95 pub time_constraints: Vec<TimeFilter>,9697 #[cfg(unix)]98 /// User/group ownership constraint99 pub owner_constraint: Option<OwnerFilter>,100101 /// Whether or not to display filesystem errors102 pub show_filesystem_errors: bool,103104 /// The separator used to print file paths.105 pub path_separator: Option<String>,106107 /// The maximum number of search results108 pub max_results: Option<usize>,109}
modified:src/output.rs+6 added-6 removed
4 unmodified lines
5use std::sync::Arc;67use lscolors::{LsColors, Style};89use crate::config::Config;10use crate::error::print_error;11use crate::exit_codes::ExitCode;12use crate::filesystem::strip_current_dir;12use crate::options::Options;1314fn replace_path_separator(path: &str, new_path_separator: &str) -> String {15 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)16}
1 unmodified line
18// TODO: this function is performance critical and can probably be optimized19pub 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 entry
21 unmodified lines
48// TODO: this function is performance critical and can probably be optimized49fn 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 lines
84// TODO: this function is performance critical and can probably be optimized85fn 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" };9192 let mut path_string = path.to_string_lossy();
6 unmodified lines
99#[cfg(not(unix))]100fn 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}107108#[cfg(unix)]109fn 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;115116 if config.interactive_terminal || config.path_separator.is_some() {
9 unmodified lines
modified:src/walk.rs+71 added-49 removed
11 unmodified lines
1213use anyhow::{anyhow, Result};14use ignore::overrides::OverrideBuilder;15use ignore::{self, WalkBuilder};16use once_cell::unsync::OnceCell;17use regex::bytes::Regex;1819use crate::config::Config;20use crate::error::print_error;21use crate::exec;22use crate::exit_codes::{merge_exitcodes, ExitCode};23use crate::filesystem;22use crate::options::Options;24use crate::output;2526/// The receiver thread can either be buffering results or directly streaming to the console.27enum ReceiverMode {
12 unmodified lines
40}4142/// Maximum size of the output buffer before flushing results to the console43pub const MAX_BUFFER_LENGTH: usize = 1000;44/// Default duration until output buffering switches to streaming.45pub const DEFAULT_MAX_BUFFER_TIME: time::Duration = time::Duration::from_millis(100);4647/// 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.49pub fn scan(path_vec: &[PathBuf], pattern: Arc<Regex>, config: Arc<Options>) -> Result<ExitCode> {52pub 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 lines
70 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 lines
163 }164}165166fn 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 lines
178 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));191192 let out_perm = Arc::new(Mutex::new(()));
20 unmodified lines
213 handles.push(handle);214 }215216 // 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 }212213 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 lines
228 // Start in buffering mode229 let mut mode = ReceiverMode::Buffering;230231 // 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);233234 let stdout = io::stdout();235 let mut stdout = stdout.lock();236
11 unmodified lines
248 buffer.push(value);249250 // 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 lines
271 }272 }273274 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 }276277 if let Some(max_results) = config.max_results {278 if num_results >= max_results {279 break;280 }281 }287 }288289 // 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 }295296 if config.quiet {297 ExitCode::HasResults(false)
3 unmodified lines
301 }302 })303}304302pub enum DirEntry {305enum DirEntryInner {306 Normal(ignore::DirEntry),307 BrokenSymlink(PathBuf),308}309310pub struct DirEntry {311 inner: DirEntryInner,312 metadata: OnceCell<Option<Metadata>>,313}314315impl DirEntry {316 fn normal(e: ignore::DirEntry) -> Self {317 Self {318 inner: DirEntryInner::Normal(e),319 metadata: OnceCell::new(),320 }321 }322323 fn broken_symlink(path: PathBuf) -> Self {324 Self {325 inner: DirEntryInner::BrokenSymlink(path),326 metadata: OnceCell::new(),327 }328 }329330 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 }336337 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 }343324 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 }352353 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}360361fn 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 lines
380 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 lines
392 .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 lines
461462 #[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 lines
474475 // 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 lines
494495 // 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 lines
modified:tests/tests.rs+129 added-1 removed
497 unmodified lines
498 ignored-by-both",499 );500}501502/// Ignore parent ignore files (--no-ignore-parent)503#[test]504fn 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);512513 // 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();523524 te.assert_output_subdirectory("inner", &[], "not-ignored");525526 te.assert_output_subdirectory(527 "inner",528 &["--no-ignore-parent"],529 "parent-ignored530 not-ignored",531 );532}533534/// Ignore parent ignore files (--no-ignore-parent) with an inner git repo535#[test]536fn 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);544545 // Make the inner folder also appear as a git repo546 fs::create_dir_all(te.test_root().join("inner/.git")).unwrap();547548 // 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();558559 te.assert_output_subdirectory(560 "inner",561 &[],562 "not-ignored563 parent-ignored",564 );565566 te.assert_output_subdirectory(567 "inner",568 &["--no-ignore-parent"],569 "not-ignored570 parent-ignored",571 );572}573574/// Precedence of .fdignore files575#[test]576fn test_custom_ignore_precedence() {577 let dirs = &["inner"];
840 unmodified lines
1418 );1419 }1420}14211422#[test]1423fn test_exec_batch_with_limit() {1424 // TODO Test for windows1425 if cfg!(windows) {1426 return;1427 }14281429 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);14301431 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 );14351436 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);14411442 for line in stdout.lines() {1443 assert_eq!(2, line.split_whitespace().count());1444 }14451446 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}14631464/// Shell script execution (--exec) with a custom --path-separator1465#[test]1466fn test_exec_with_separator() {1467 let (te, abs_path) = get_test_env_with_abs_path(DEFAULT_DIRS, DEFAULT_FILES);
226 unmodified lines
1694 fs::File::create(&path).expect("creation failed");1695 filetime::set_file_times(&path, ft, ft).expect("time modification failed");1696}16971698#[cfg(test)]1699fn remove_symlink<P: AsRef<Path>>(path: P) {1700 #[cfg(unix)]1701 fs::remove_file(path).expect("remove symlink");17021703 // 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}17091710#[test]1711fn 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 lines
1747 filetime::set_file_times(path, ft, ft).expect("time modification failde");1748}17491750#[test]1624fn test_modified_asolute() {1751fn 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");17561757 te.assert_output(
213 unmodified lines
modified:build.rs+1 added-1 removed
3 unmodified lines
45include!("src/app.rs");67fn main() {8 let min_version = "1.42";8 let min_version = "1.53";910 match version_check::is_min_version(min_version) {11 Some(true) => {}12 // rustc version too small or can't figure it out
18 unmodified lines
modified:Cargo.lock+31 added-30 removed
29 unmodified lines
30]3132[[package]]33name = "anyhow"34version = "1.0.42"34version = "1.0.44"35source = "registry+https://github.com/rust-lang/crates.io-index"36checksum = "595d3cfa7a60d4555cb5067b99f07142a08ea778de5cf993f7b75c7d8fabc486"36checksum = "61604a8f862e1d5c3229fdd78f8b02c68dcf73a4c4b05fd636d12240aaa242c1"3738[[package]]39name = "atty"40version = "0.2.14"
12 unmodified lines
53checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"5455[[package]]56name = "bitflags"57version = "1.2.1"57version = "1.3.2"58source = "registry+https://github.com/rust-lang/crates.io-index"59checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"59checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"6061[[package]]62name = "bstr"63version = "0.2.16"63version = "0.2.17"64source = "registry+https://github.com/rust-lang/crates.io-index"65checksum = "90682c8d613ad3373e66de8c6411e0ae2ab2571e879d2efbf73558cc66f21279"65checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223"66dependencies = [67 "memchr",68]6970[[package]]71name = "cc"72version = "1.0.69"72version = "1.0.71"73source = "registry+https://github.com/rust-lang/crates.io-index"74checksum = "e70cc2f62c6ce1868963827bd677764c62d07c3d9a3e1fb1177ee1a9ab199eb2"74checksum = "79c2681d6594606957bbb8631c4b90a7fcaaa72cdb714743a437b156d6a7eedd"7576[[package]]77name = "cfg-if"78version = "1.0.0"
40 unmodified lines
119]120121[[package]]122name = "ctrlc"123version = "3.2.0"123version = "3.2.1"124source = "registry+https://github.com/rust-lang/crates.io-index"125checksum = "377c9b002a72a0b2c1a18c62e2f3864bdfea4a015e3683a96e24aa45dd6c02d1"125checksum = "a19c6cedffdc8c03a3346d723eb20bd85a13362bb96dc2ac000842c6381ec7bf"126dependencies = [127 "nix",128 "winapi",129]
46 unmodified lines
176 "libc",177 "lscolors",178 "normpath",179 "num_cpus",180 "once_cell",181 "regex",182 "regex-syntax",183 "tempdir",184 "test-case",
116 unmodified lines
301checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"302303[[package]]304name = "libc"304version = "0.2.99"305version = "0.2.106"306source = "registry+https://github.com/rust-lang/crates.io-index"306checksum = "a7f823d141fe0a24df1e23b4af4e3c7ba9e5966ec514ea068c93024aa7deb765"307checksum = "a60553f9a9e039a333b4e9b20573b9e9b9c0bb3a11e201ccc48ef4283456d673"308309[[package]]310name = "log"311version = "0.4.14"
4 unmodified lines
316]317318[[package]]319name = "lscolors"319version = "0.7.1"320version = "0.8.0"321source = "registry+https://github.com/rust-lang/crates.io-index"321checksum = "d24b894c45c9da468621cdd615a5a79ee5e5523dd4f75c76ebc03d458940c16e"322checksum = "bd0aa49b10c47f9a4391a99198b5e65c74f9ca771c0dcc856bb75a3f46c8627d"323dependencies = [324 "ansi_term 0.12.1",325]326327[[package]]328name = "memchr"328version = "2.4.0"329version = "2.4.1"330source = "registry+https://github.com/rust-lang/crates.io-index"330checksum = "b16bd47d9e329435e309c58469fe0791c2d0d1ba96ec0954152a5ae2b04387dc"331checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"332333[[package]]334name = "memoffset"335version = "0.6.4"
4 unmodified lines
340]341342[[package]]343name = "nix"343version = "0.22.0"344version = "0.23.0"345source = "registry+https://github.com/rust-lang/crates.io-index"345checksum = "cf1e25ee6b412c2a1e3fcb6a4499a5c1bfe7f43e014bdce9a6b6666e5aa2d187"346checksum = "f305c2c2e4c39a82f7bf0bf65fb557f9070ce06781d4f2454295cc34b1c43188"347dependencies = [348 "bitflags",349 "cc",350 "cfg-if",
2 unmodified lines
353]354355[[package]]356name = "normpath"356version = "0.3.0"357version = "0.3.1"358source = "registry+https://github.com/rust-lang/crates.io-index"358checksum = "27e6e8f70e9fbbe3752d330d769e3424f24b9458ce266df93a3b456902fd696a"359checksum = "640c20e9df4a2d4a5adad5b47e17d76dac3e824346b181931c3ec9f7a85687b1"360dependencies = [361 "winapi",362]363
33 unmodified lines
397checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56"398399[[package]]400name = "proc-macro2"400version = "1.0.28"401version = "1.0.32"402source = "registry+https://github.com/rust-lang/crates.io-index"402checksum = "5c7ed8b8c7b886ea3ed7dde405212185f423ab44682667c8c6dd14aa1d9f6612"403checksum = "ba508cc11742c0dc5c1659771673afbab7a0efab23aa17e854cbab0837ed0b43"404dependencies = [405 "unicode-xid",406]407408[[package]]409name = "quote"409version = "1.0.9"410version = "1.0.10"411source = "registry+https://github.com/rust-lang/crates.io-index"411checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7"412checksum = "38bc8cc6a5f2e3655e0899c1b848643b2562f853f114bfec7be120678e3ace05"413dependencies = [414 "proc-macro2",415]416
95 unmodified lines
512checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"513514[[package]]515name = "syn"515version = "1.0.74"516version = "1.0.81"517source = "registry+https://github.com/rust-lang/crates.io-index"517checksum = "1873d832550d4588c3dbc20f01361ab00bfe741048f71e3fecf145a7cc18b29c"518checksum = "f2afee18b8beb5a596ecb4a2dce128c719b4ba399d34126b9e4396e3f9860966"519dependencies = [520 "proc-macro2",521 "quote",522 "unicode-xid",
20 unmodified lines
543]544545[[package]]546name = "test-case"546version = "1.2.0"547version = "1.2.1"548source = "registry+https://github.com/rust-lang/crates.io-index"548checksum = "3b114ece25254e97bf48dd4bfc2a12bad0647adacfe4cae1247a9ca6ad302cec"549checksum = "c7cad0a06f9a61e94355aa3b3dc92d85ab9c83406722b1ca5e918d4297c12c23"550dependencies = [551 "cfg-if",552 "proc-macro2",553 "quote",
31 unmodified lines
585]586587[[package]]588name = "unicode-width"588version = "0.1.8"589version = "0.1.9"590source = "registry+https://github.com/rust-lang/crates.io-index"590checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"591checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973"592593[[package]]594name = "unicode-xid"595version = "0.2.2"
72 unmodified lines
modified:Cargo.toml+7 added-6 removed
39 unmodified lines
40lazy_static = "1.1.0"41num_cpus = "1.8"42regex = "1.5.4"43regex-syntax = "0.6"44ctrlc = "3.1"45humantime = "2.0"46lscolors = "0.7"44ctrlc = "3.2"45humantime = "2.1"46lscolors = "0.8"47globset = "0.4"48anyhow = "1.0"49dirs-next = "2.0"50normpath = "0.3"51chrono = "0.4"52once_cell = "1.8.0"5354[dependencies.clap]54version = "2.31.2"55version = "2.31.3"56features = ["suggestions", "color", "wrap_help"]5758[target.'cfg(unix)'.dependencies]59users = "0.11.0"
9 unmodified lines
6970[dev-dependencies]71diff = "0.1"72tempdir = "0.3"72filetime = "0.2.14"73test-case = "1.2.0"73filetime = "0.2"74test-case = "1.2"7576[profile.release]77lto = true78codegen-units = 1
modified:CHANGELOG.md+11 added
1# Upcoming release23## Performance improvements45- 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 #86378## Features9- Don't buffer command output from `--exec` when using a single thread. See #5221011- Add new `-q, --quiet` flag, see #303 (@Asha20)1213- Add new `--no-ignore-parent` flag, see #787 (@will459)1415- Add new `--batch-size` flag, see #410 (@devonhollowood)1617- Add opposing command-line options, see #595 (@Asha20)1819## Bugfixes20
2 unmodified lines
23- 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 #8632930## Changes3132- Apply custom `--path-separator` to commands run with `--exec(-batch)` and `--list-details`, see #697 (@aswild)
509 unmodified lines
added:clippy.toml+1 added
1msrv = "1.53.0"
modified:README.md+10 added-3 removed
416 unmodified lines
417> fd -- '-pattern'418> fd '[-]pattern'419```420421### "Command not found" for `alias`es or shell functions422423Shell `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`,425you can use `export -f my_function` to make available to child processes. You would still426need to call `fd -x bash -c 'my_function "$1"' bash`. For other use cases or shells, use427a (temporary) shell script.428429## Integration with other programs430431### Using fd with `fzf`432
199 unmodified lines
632```633pkg install fd-find634```635628### From NPM636### From npm637638On linux and macOS, you can install the [fd-find](https://npm.im/fd-find) package:639640```
5 unmodified lines
646With Rust's package manager [cargo](https://github.com/rust-lang/cargo), you can install *fd* via:647```648cargo install fd-find649```642Note that rust version *1.42.0* or later is required.650Note that rust version *1.53.0* or later is required.651652`make` is also needed for the build.653654### From binaries
19 unmodified lines
674675- [sharkdp](https://github.com/sharkdp)676- [tmccombs](https://github.com/tmccombs)677- [tavianator](https://github.com/tavianator)670- [pemistahl](https://github.com/pemistahl/)678679## License680681Copyright (c) 2017-2021 The fd developers
4 unmodified lines