Merge pull request #1805 from tmccombs/exec-nuls
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Thayne McCombs · committed by GitHub · parents f77b693, ee5332d · Browse files · 7 files·+49 added−24 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- fix: --print0 now works with --exec
Diff stats
7 files+49 added−24 removed
- tests:+15 added−0 removed
- other:+34 added−24 removed
Provenance
- Commit
5558e40- Tree
efd58ff- Author
Thayne McCombs <astrothayne@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
f77b693- Parent 2
ee5332d
7 files changed+49 added−24 removed
modified:doc/fd.1+7 added
447 unmodified lines448 option.449 450 If no placeholder is present, an implicit "{}" at the end is assumed.451 452+If --print0 is also given, then a null character (\\0) will be printed between the output for each found entry.453+This allows another program to easily distinguish the output for each file if the command(s) produce multiple lines.454+455 Examples:456 457 - find all *.zip files and unzip them:458 5 unmodified lines464 465 - Convert all *.jpg files to *.png files:466 467 fd -e jpg -x convert {} {.}.png468+469+ - Run stat for each *.txt file, separated by null characters470+471+ fd -0 -e txt -x stat472 .RE473 .TP474 .BI "\-X, \-\-exec-batch " command475 .RS99 unmodified linesmodified:src/exec/command.rs+18 added-13 removed
1 use std::io;2 use std::io::Write;3-use std::sync::Mutex;3 4 use argmax::Command;5 6 use crate::error::print_error;2 unmodified lines9 struct Outputs {10 stdout: Vec<u8>,11 stderr: Vec<u8>,12 }14-struct OutputBuffer<'a> {15- output_permission: &'a Mutex<()>,13+pub struct OutputBuffer {14+ null_separator: bool,15 outputs: Vec<Outputs>,16 }17 19-impl<'a> OutputBuffer<'a> {20- fn new(output_permission: &'a Mutex<()>) -> Self {18+impl OutputBuffer {19+ pub fn new(null_separator: bool) -> Self {20 Self {22- output_permission,21+ null_separator,22 outputs: Vec::new(),23 }24 }25 1 unmodified line27 self.outputs.push(Outputs { stdout, stderr });28 }29 30 fn write(self) {32- // avoid taking the lock if there is nothing to do33- if self.outputs.is_empty() {31+ // Avoid taking the lock if there is nothing to do.32+ // If null_separator is true, then we still need to write the33+ // null separator, because the output may have been written directly34+ // to stdout35+ if self.outputs.is_empty() && !self.null_separator {36 return;37 }36- // While this lock is active, this thread will be the only thread allowed37- // to write its outputs.38- let _lock = self.output_permission.lock().unwrap();38 39 let stdout = io::stdout();40 let stderr = io::stderr();41 42+ // While we hold these locks, only this thread will be able43+ // to write its outputs.44 let mut stdout = stdout.lock();45 let mut stderr = stderr.lock();46 47 for output in self.outputs.iter() {48 let _ = stdout.write_all(&output.stdout);49 let _ = stderr.write_all(&output.stderr);50 }51+ if self.null_separator {52+ // If null_separator is enabled, then we should write a \0 at the end53+ // of the output for this entry54+ let _ = stdout.write_all(b"\0");55+ }56 }57 }58 59 /// Executes a command.60 pub fn execute_commands<I: Iterator<Item = io::Result<Command>>>(61 cmds: I,56- out_perm: &Mutex<()>,62+ mut output_buffer: OutputBuffer,63 enable_output_buffering: bool,64 ) -> ExitCode {59- let mut output_buffer = OutputBuffer::new(out_perm);65 for result in cmds {66 let mut cmd = match result {67 Ok(cmd) => cmd,68 Err(e) => return handle_cmd_error(None, e),47 unmodified linesmodified:src/exec/job.rs+1 added-4 removed
1-use std::sync::Mutex;2-1 use crate::config::Config;2 use crate::error::print_error;3 use crate::exit_codes::{merge_exitcodes, ExitCode};4 use crate::walk::WorkerResult;5 unmodified lines10 /// be executed, and this process will continue until the receiver's sender has closed.11 pub fn job(12 results: impl IntoIterator<Item = WorkerResult>,13 cmd: &CommandSet,16- out_perm: &Mutex<()>,14 config: &Config,15 ) -> ExitCode {16 // Output should be buffered when only running a single thread17 let buffer_output: bool = config.threads > 1;15 unmodified lines33 // Generate a command, execute it and store its exit code.34 let code = cmd.execute(35 dir_entry.stripped_path(config),36 config.path_separator.as_deref(),40- out_perm,37+ config.null_separator,38 buffer_output,39 );40 ret = merge_exitcodes([ret, code]);41 }23 unmodified linesmodified:src/exec/mod.rs+3 added-3 removed
4 unmodified lines5 use std::io;6 use std::iter;7 use std::path::{Path, PathBuf};8 use std::process::Stdio;9-use std::sync::Mutex;9 10 use anyhow::{bail, Result};11 use argmax::Command;12 13+use crate::exec::command::OutputBuffer;14 use crate::exit_codes::{merge_exitcodes, ExitCode};15 use crate::fmt::{FormatTemplate, Token};16 17 use self::command::{execute_commands, handle_cmd_error};61 unmodified lines79 pub fn execute(80 &self,81 input: &Path,82 path_separator: Option<&str>,83- out_perm: &Mutex<()>,83+ null_separator: bool,84 buffer_output: bool,85 ) -> ExitCode {86 let commands = self87 .commands88 .iter()89 .map(|c| c.generate(input, path_separator));90- execute_commands(commands, out_perm, buffer_output)90+ execute_commands(commands, OutputBuffer::new(null_separator), buffer_output)91 }92 93 pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode94 where379 unmodified linesmodified:src/walk.rs+2 added-4 removed
411 unmodified lines412 if let Some(ref cmd) = config.command {413 if cmd.in_batch_mode() {414 exec::batch(rx.into_iter().flatten(), cmd, config)415 } else {416- let out_perm = Mutex::new(());417-416 thread::scope(|scope| {417 // Each spawned job will store its thread handle in here.418 let threads = config.threads;419 let mut handles = Vec::with_capacity(threads);420 for _ in 0..threads {421 let rx = rx.clone();422 423 // Spawn a job thread that will listen for and execute inputs.426- let handle = scope427- .spawn(|| exec::job(rx.into_iter().flatten(), cmd, &out_perm, config));424+ let handle =425+ scope.spawn(|| exec::job(rx.into_iter().flatten(), cmd, config));426 427 // Push the handle of the spawned thread into the vector for later joining.428 handles.push(handle);429 }239 unmodified linesmodified:tests/tests.rs+15 added
1824 unmodified lines1825 directory_foo: ./one/two/three",1826 );1827 }1828 1829+#[cfg(not(windows))]1830 #[test]1831+fn test_exec_nulls() {1832+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);1833+ te.assert_output(1834+ &["foo", "--print0", "--exec", "printf", "p=%s"],1835+ "p=./a.fooNULL1836+ p=./one/b.fooNULL1837+ p=./one/two/C.Foo2NULL1838+ p=./one/two/c.fooNULL1839+ p=./one/two/three/d.fooNULL1840+ p=./one/two/three/directory_fooNULL",1841+ );1842+}1843+1844+#[test]1845 fn test_exec_batch() {1846 let (te, abs_path) = get_test_env_with_abs_path(DEFAULT_DIRS, DEFAULT_FILES);1847 let te = te.normalize_line(true);1848 861 unmodified linesmodified:CHANGELOG.md+3 added
3 unmodified lines4 5 6 ## Bugfixes7 8+- `--print0` combined with `--exec` will now print a `\0` between the output of each entry. Note that if there are multiple instances9+ of `--exec`, the `\0` will be between each _set_ of commands, _not_ between each individual command run. Fixes #1797.10 11+12 ## Changes13 14 15 ## Other819 unmodified lines