Merge branch 'master' into pr/opposing-options
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Vukašin Stepanović · committed by Vukašin Stepanović · parents 3ebd78c, 3ba90dd · Browse files · 15 files·+144 added−44 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+144 added−44 removed
- tests:+13 added−0 removed
- other:+131 added−44 removed
Provenance
- Commit
c749c95- Tree
c60b4f6- Author
Vukašin Stepanović <vukasintepanovic@gmail.com>- Committer
Vukašin Stepanović <vukasintepanovic@gmail.com>- Parent 1
3ebd78c- Parent 2
3ba90dd
15 files changed+144 added−44 removed
modified:.github/ISSUE_TEMPLATE/config.yml-1 removed
12blank_issues_enabled: true
modified:.github/ISSUE_TEMPLATE/feature_request.md-2 removed
4 unmodified lines56789104 unmodified lineslabels: feature-requestassignees: ''
---
modified:.github/workflows/CICD.yml+11 added-4 removed
25 unmodified lines26 with:27 toolchain: ${{ env.MIN_SUPPORTED_RUST_VERSION }}28 default: true29 profile: minimal # minimal component installation (ie, no documentation)30- components: clippy30+ components: clippy, rustfmt31+ - name: Ensure `cargo fmt` has been run32+ uses: actions-rs/cargo@v133+ with:34+ command: fmt35+ args: -- --check36 - name: Run clippy (on minimum supported rust version to prevent warnings we can't fix)37 uses: actions-rs/cargo@v138 with:39 command: clippy35- args: --all-targets --all-features40+ args: --locked --all-targets --all-features41 - name: Run tests42 uses: actions-rs/cargo@v143 with:44 command: test45+ args: --locked46 47 build:48 name: ${{ matrix.job.os }} (${{ matrix.job.target }})49 runs-on: ${{ matrix.job.os }}55 unmodified lines105 uses: actions-rs/cargo@v1106 with:107 use-cross: ${{ matrix.job.use-cross }}108 command: build103- args: --release --target=${{ matrix.job.target }}109+ args: --locked --release --target=${{ matrix.job.target }}110 111 - name: Strip debug information from executable112 id: strip113 shell: bash33 unmodified lines147 - name: Set testing options148 id: test-options149 shell: bash150 run: |151+ # test only library unit tests and binary for arm-type targets152 unset CARGO_TEST_OPTIONS153 unset CARGO_TEST_OPTIONS ; case ${{ matrix.job.target }} in arm-* | aarch64-*) CARGO_TEST_OPTIONS="--bin ${PROJECT_NAME}" ;; esac;154 echo ::set-output name=CARGO_TEST_OPTIONS::${CARGO_TEST_OPTIONS}155 1 unmodified line157 uses: actions-rs/cargo@v1158 with:159 use-cross: ${{ matrix.job.use-cross }}160 command: test154- args: --target=${{ matrix.job.target }} ${{ steps.test-options.outputs.CARGO_TEST_OPTIONS}}161+ args: --locked --target=${{ matrix.job.target }} ${{ steps.test-options.outputs.CARGO_TEST_OPTIONS}}162 163 - name: Create tarball164 id: package165 shell: bash175 unmodified linesmodified:doc/fd.1+33 added-7 removed
30 unmodified lines31 (default: hidden files and directories are skipped). The flag can be overridden with '--no-hidden'.32 .TP33 .B \-I, \-\-no\-ignore34 Show search results from files and directories that would otherwise be ignored by35-.IR .gitignore ,36-.IR .ignore ,37-.IR .fdignore ,38-or the global ignore file.35+.RS36+.IP \[bu] 237+.I .gitignore38+.IP \[bu]39+.I .git/info/exclude40+.IP \[bu]41+The global gitignore configuration (by default42+.IR $HOME/.config/git/ignore )43+.IP \[bu]44+.I .ignore45+.IP \[bu]46+.I .fdignore47+.IP \[bu]48+The global fd ignore file (usually49+.I $HOME/.config/fd/ignore50+)51+.RE52+.IP53 The flag can be overridden with '--ignore'.54 .TP55 .B \-u, \-\-unrestricted56 Alias for '--no-ignore'. Can be repeated; '-uu' is an alias for '--no-ignore --hidden'.57 .TP58 .B \-\-no\-ignore\-vcs45-Show search results from files and directories that would otherwise be ignored by46-.I .gitignore47-files.59+Show search results from files and directories that would otherwise be ignored by gitignore files60+including61+.IR .gitignore ,62+.IR .git/info/exclude ,63+and the global gitignore configuration64+.RI ( core.excludesFile65+git setting, which defaults to66+.IR $HOME/.config/git/ignore ).67 The flag can be overridden with '--ignore-vcs'.68 .TP69 .B \-s, \-\-case\-sensitive70 Perform a case-sensitive search. By default, fd uses case-insensitive searches, unless the43 unmodified lines114 .TP115 .B \-1116 Limit the search to a single result and quit immediately. This is an alias for '--max-results=1'.117 .TP118+.B \-q, \-\-quiet119+When the flag is present, the program does not print anything and will instead exit with a code of 0 if there is at least one search result.120+Otherwise, the exit code will be 1.121+This is mainly for usage in scripts and can be faster than checking for output because the search can be stopped early after the first match.122+.B \-\-has\-results123+can be used as an alias.124+.TP125 .B \-\-show-errors126 Enable the display of filesystem errors for situations such as insufficient127 permissions or dead symlinks.128 .TP285 unmodified linesmodified:doc/screencast.sh+1 added-1 removed
18 unmodified lines1920212223232425262733 unmodified lines18 unmodified lines type "\\n"}
prompt() { printf '%b ' $PROMPT | pv -q printf '%b ' "$PROMPT" | pv -q}
type() { printf '%b' "$1" | pv -qL $((10+(-2 + RANDOM%5)))33 unmodified linesmodified:src/exec/command.rs+12 added-2 removed
5 unmodified lines6 use crate::error::print_error;7 use crate::exit_codes::ExitCode;8 9 /// Executes a command.10-pub fn execute_command(mut cmd: Command, out_perm: &Mutex<()>) -> ExitCode {10+pub fn execute_command(11+ mut cmd: Command,12+ out_perm: &Mutex<()>,13+ enable_output_buffering: bool,14+) -> ExitCode {15 // Spawn the supplied command.12- let output = cmd.output();16+ let output = if enable_output_buffering {17+ cmd.output()18+ } else {19+ // If running on only one thread, don't buffer output20+ // Allows for viewing and interacting with intermediate command output21+ cmd.spawn().and_then(|c| c.wait_with_output())22+ };23 24 // Then wait for the command to exit, if it was spawned.25 match output {26 Ok(output) => {26 unmodified linesmodified:src/exec/job.rs+4 added-2 removed
14 unmodified lines15 rx: Arc<Mutex<Receiver<WorkerResult>>>,16 cmd: Arc<CommandTemplate>,17 out_perm: Arc<Mutex<()>>,18 show_filesystem_errors: bool,19+ buffer_output: bool,20 ) -> ExitCode {21 let mut results: Vec<ExitCode> = Vec::new();22 loop {23 // Create a lock on the shared receiver for this thread.14 unmodified lines38 39 // Drop the lock so that other threads can read from the receiver.40 drop(lock);41 // Generate a command, execute it and store its exit code.41- results.push(cmd.generate_and_execute(&value, Arc::clone(&out_perm)))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)46 }1 unmodified line48 pub fn batch(49 rx: Receiver<WorkerResult>,50 cmd: &CommandTemplate,51 show_filesystem_errors: bool,52+ buffer_output: bool,53 ) -> ExitCode {54 let paths = rx.iter().filter_map(|value| match value {55 WorkerResult::Entry(val) => Some(val),56 WorkerResult::Error(err) => {2 unmodified lines59 }60 None61 }62 });61- cmd.generate_and_execute_batch(paths)63+ cmd.generate_and_execute_batch(paths, buffer_output)64 }modified:src/exec/mod.rs+11 added-6 removed
137 unmodified lines138 /// Generates and executes a command.139 ///140 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be141 /// build. Once all arguments have been processed, the command is executed.142- pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) -> ExitCode {142+ pub fn generate_and_execute(143+ &self,144+ input: &Path,145+ out_perm: Arc<Mutex<()>>,146+ buffer_output: bool,147+ ) -> ExitCode {148 let input = strip_current_dir(input);149 150 let mut cmd = Command::new(self.args[0].generate(&input, self.path_separator.as_deref()));151 for arg in &self.args[1..] {152 cmd.arg(arg.generate(&input, self.path_separator.as_deref()));153 }154 150- execute_command(cmd, &out_perm)155+ execute_command(cmd, &out_perm, buffer_output)156 }157 158 pub fn in_batch_mode(&self) -> bool {159 self.mode == ExecutionMode::Batch160 }161 157- pub fn generate_and_execute_batch<I>(&self, paths: I) -> ExitCode162+ pub fn generate_and_execute_batch<I>(&self, paths: I, buffer_output: bool) -> ExitCode163 where164 I: Iterator<Item = PathBuf>,165 {166 let mut cmd = Command::new(self.args[0].generate("", None));19 unmodified lines186 }187 }188 189 if has_path {185- execute_command(cmd, &Mutex::new(()))190+ execute_command(cmd, &Mutex::new(()), buffer_output)191 } else {192 ExitCode::Success193 }194 }254 unmodified lines449 // Drive Relative path - no separator after the colon omits the RootDir path component.450 // This is uncommon, but valid451 check!(r"C:foo\bar", "C:foo#bar");452 448- // forward slashses should get normalized and interpreted as separators453+ // forward slashes should get normalized and interpreted as separators454 check!("C:/foo/bar", "C:#foo#bar");455 check!("C:foo/bar", "C:foo#bar");456 452- // Rust does not intrepret "//server/share" as a UNC path, but rather as a normal457+ // Rust does not interpret "//server/share" as a UNC path, but rather as a normal458 // absolute path that begins with RootDir, and the two slashes get combined together as459 // a single path separator during normalization.460 //check!("//server/share/path", "##server#share#path");461 }1 unmodified linemodified:src/app.rs+14 added
553 unmodified lines554 .long_help("Limit the search to a single result and quit immediately. \555 This is an alias for '--max-results=1'.")556 )557 .arg(558+ Arg::with_name("quiet")559+ .long("quiet")560+ .short("q")561+ .alias("has-results")562+ .hidden_short_help(true)563+ .conflicts_with_all(&["exec", "exec-batch", "list-details", "max-results"])564+ .long_help(565+ "When the flag is present, the program does not print anything and will \566+ return with an exit code of 0 if there is at least one match. Otherwise, the \567+ exit code will be 1. \568+ '--has-results' can be used as an alias."569+ )570+ )571+ .arg(572 Arg::with_name("show-errors")573 .long("show-errors")574 .hidden_short_help(true)575 .overrides_with("show-errors")104 unmodified linesmodified:src/exit_codes.rs+3 added-1 removed
1 #[derive(Debug, Clone, Copy, PartialEq)]2 pub enum ExitCode {3 Success,4+ HasResults(bool),5 GeneralError,6 KilledBySigint,7 }8 9 impl From<ExitCode> for i32 {10 fn from(code: ExitCode) -> Self {11 match code {12 ExitCode::Success => 0,13+ ExitCode::HasResults(has_results) => !has_results as i32,14 ExitCode::GeneralError => 1,15 ExitCode::KilledBySigint => 130,16 }17 }18 }19 20 impl ExitCode {21 fn is_error(self) -> bool {20- self != ExitCode::Success22+ i32::from(self) != 023 }24 }25 26 pub fn merge_exitcodes(results: &[ExitCode]) -> ExitCode {48 unmodified linesmodified:src/main.rs+1 added
344 unmodified lines345 || matches.is_present("no-global-ignore-file")),346 follow_links: matches.is_present("follow"),347 one_file_system: matches.is_present("one-file-system"),348 null_separator: matches.is_present("null_separator"),349+ quiet: matches.is_present("quiet"),350 max_depth: matches351 .value_of("max-depth")352 .or_else(|| matches.value_of("rg-depth"))353 .or_else(|| matches.value_of("exact-depth"))141 unmodified linesmodified:src/options.rs+4 added
52 unmodified lines53 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>,45 unmodified linesmodified:src/walk.rs+21 added-5 removed
168 unmodified lines169 let wants_to_quit = Arc::clone(wants_to_quit);170 171 let show_filesystem_errors = config.show_filesystem_errors;172 let threads = config.threads;173-173+ // This will be used to check if output should be buffered when only running a single thread174+ let enable_output_buffering: bool = threads > 1;175 thread::spawn(move || {176 // This will be set to `Some` if the `--exec` argument was supplied.177 if let Some(ref cmd) = config.command {178 if cmd.in_batch_mode() {178- exec::batch(rx, cmd, show_filesystem_errors)179+ exec::batch(rx, cmd, show_filesystem_errors, enable_output_buffering)180 } else {181 let shared_rx = Arc::new(Mutex::new(rx));182 183 let out_perm = Arc::new(Mutex::new(()));5 unmodified lines189 let cmd = Arc::clone(cmd);190 let out_perm = Arc::clone(&out_perm);191 192 // Spawn a job thread that will listen for and execute inputs.192- let handle =193- thread::spawn(move || exec::job(rx, cmd, out_perm, show_filesystem_errors));193+ let handle = thread::spawn(move || {194+ exec::job(195+ rx,196+ cmd,197+ out_perm,198+ show_filesystem_errors,199+ enable_output_buffering,200+ )201+ });202 203 // Push the handle of the spawned thread into the vector for later joining.204 handles.push(handle);205 }26 unmodified lines232 233 for worker_result in rx {234 match worker_result {235 WorkerResult::Entry(value) => {236+ if config.quiet {237+ return ExitCode::HasResults(true);238+ }239+240 match mode {241 ReceiverMode::Buffering => {242 buffer.push(value);243 45 unmodified lines289 output::print_entry(&mut stdout, &value, &config, &wants_to_quit);290 }291 }292 293+ if config.quiet {294+ ExitCode::HasResults(false)295+ } else {281- ExitCode::Success296+ ExitCode::Success297+ }298 }299 })300 }301 202 unmodified linesmodified:tests/tests.rs+13 added
1424 unmodified lines1425 "e1 e2.",1426 );1427 }1428 1429+/// Non-zero exit code (--quiet)1430+#[test]1431+fn test_quiet() {1432+ let dirs = &[];1433+ let files = &["a.foo", "b.foo"];1434+ let te = TestEnv::new(dirs, files);1435+1436+ te.assert_output(&["-q"], "");1437+ te.assert_output(&["--quiet"], "");1438+ te.assert_output(&["--has-results"], "");1439+ te.assert_failure_with_error(&["--quiet", "c.foo"], "")1440+}1441+1442 /// Literal search (--fixed-strings)1443 #[test]1444 fn test_fixed_strings() {1445 let dirs = &["test1", "test2"];397 unmodified linesmodified:CHANGELOG.md+16 added-13 removed
1 # Upcoming release2 3 ## Features4+- Don't buffer command output from `--exec` when using a single thread. See #5225 6+- Add new `-q, --quiet` flag, see #303 (@Asha20)7+8 - Add opposing command-line options, see #595 (@Asha20)9 10 ## Bugfixes11 449 unmodified lines461 * Added filtering by file extension, for example `fd -e txt`, see #56 (@reima)462 * Add option to force colored output: `--color always`, see #49 (@Detegr)463 * Generate Shell completions for Bash, ZSH, Fish and Powershell, see #64 (@ImbaKnugel)464 * Better & extended `--help` text (@abaez and @Detegr)462-* Proper Windows support, see #70 465+* Proper Windows support, see #70466 467 ## Changes468 469 * The integration tests have been re-written in Rust :sparkles:, making them platform-independent and easily callable via `cargo test` - see #65 (many thanks to @reima!)19 unmodified lines489 # v2.0.0490 491 * Changed `--sensitive` to `--case-sensitive`492 * Changed `--absolute` to `--absolute-path`490-* Throw an error if root directory is not existent, see #39 491-* Use absolute paths if the root dir is an absolute path, see #40 492-* Handle invalid UTF-8, see #34 #38 493+* Throw an error if root directory is not existent, see #39494+* Use absolute paths if the root dir is an absolute path, see #40495+* Handle invalid UTF-8, see #34 #38496 * Support `-V`, `--version` by switching from `getopts` to `clap`.497 498 Misc:499 * It's now possible to install `fd` via homebrew on macOS: `brew install fd`.500 501 # v1.1.0502 500-- Windows compatibility (@sebasv), see #29 #35 501-- Safely exit on broken output pipes (e.g.: usage with `head`, `tail`, ..), see #24 503+- Windows compatibility (@sebasv), see #29 #35504+- Safely exit on broken output pipes (e.g.: usage with `head`, `tail`, ..), see #24505 - Backport for rust 1.16, see #23506 507 # v1.0.0508 3 unmodified lines512 * Added optional second argument (search path)513 514 # v0.3.0515 513-- Parse dircolors files, closes #20 514-- Colorize each path component, closes #19 515-- Add short command line option for --hidden, see #18 516+- Parse dircolors files, closes #20517+- Colorize each path component, closes #19518+- Add short command line option for --hidden, see #18519 520 # v0.2.0521 519-- Option to follow symlinks, disable colors, closes #16, closes #17 522+- Option to follow symlinks, disable colors, closes #16, closes #17523 - `--filename` instead of `--full-path`521-- Option to search hidden directories, closes #12 522-- Configurable search depth, closes #13 523-- Detect interactive terminal, closes #11 524+- Option to search hidden directories, closes #12525+- Configurable search depth, closes #13526+- Detect interactive terminal, closes #11527 528 # v0.1.0529 530 Initial release