Skip to content
Myr

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

7 files+49 added−24 removed

modified:doc/fd.1+7 added
447 unmodified lines
448option.449450If no placeholder is present, an implicit "{}" at the end is assumed.451452If --print0 is also given, then a null character (\\0) will be printed between the output for each found entry.453This allows another program to easily distinguish the output for each file if the command(s) produce multiple lines.454455Examples:456457 - find all *.zip files and unzip them:458
5 unmodified lines
464465 - Convert all *.jpg files to *.png files:466467 fd -e jpg -x convert {} {.}.png468469 - Run stat for each *.txt file, separated by null characters470471 fd -0 -e txt -x stat472.RE473.TP474.BI "\-X, \-\-exec-batch " command475.RS
99 unmodified lines
modified:src/exec/command.rs+18 added-13 removed
1use std::io;2use std::io::Write;3use std::sync::Mutex;34use argmax::Command;56use crate::error::print_error;
2 unmodified lines
9struct Outputs {10 stdout: Vec<u8>,11 stderr: Vec<u8>,12}14struct OutputBuffer<'a> {15 output_permission: &'a Mutex<()>,13pub struct OutputBuffer {14 null_separator: bool,15 outputs: Vec<Outputs>,16}1719impl<'a> OutputBuffer<'a> {20 fn new(output_permission: &'a Mutex<()>) -> Self {18impl 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 line
27 self.outputs.push(Outputs { stdout, stderr });28 }2930 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();3839 let stdout = io::stdout();40 let stderr = io::stderr();4142 // 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();4647 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}5859/// Executes a command.60pub 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 lines
modified:src/exec/job.rs+1 added-4 removed
1use std::sync::Mutex;21use crate::config::Config;2use crate::error::print_error;3use crate::exit_codes::{merge_exitcodes, ExitCode};4use crate::walk::WorkerResult;
5 unmodified lines
10/// be executed, and this process will continue until the receiver's sender has closed.11pub 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 lines
33 // 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 lines
modified:src/exec/mod.rs+3 added-3 removed
4 unmodified lines
5use std::io;6use std::iter;7use std::path::{Path, PathBuf};8use std::process::Stdio;9use std::sync::Mutex;910use anyhow::{bail, Result};11use argmax::Command;1213use crate::exec::command::OutputBuffer;14use crate::exit_codes::{merge_exitcodes, ExitCode};15use crate::fmt::{FormatTemplate, Token};1617use self::command::{execute_commands, handle_cmd_error};
61 unmodified lines
79 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 }9293 pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode94 where
379 unmodified lines
modified:src/walk.rs+2 added-4 removed
411 unmodified lines
412 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(());417416 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();422423 // 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));426427 // Push the handle of the spawned thread into the vector for later joining.428 handles.push(handle);429 }
239 unmodified lines
modified:tests/tests.rs+15 added
1824 unmodified lines
1825 directory_foo: ./one/two/three",1826 );1827}18281829#[cfg(not(windows))]1830#[test]1831fn 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}18431844#[test]1845fn 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 lines
modified:CHANGELOG.md+3 added
3 unmodified lines
456## Bugfixes78- `--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.101112## Changes131415## Other
819 unmodified lines