Skip to content
Myr

exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmd

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by kimsnj · committed by David Peter · parent 45d1b15 · Browse files · 4 files+33 added−22 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+33 added−22 removed

  • tests:+17 added−12 removed
  • other:+16 added−10 removed

4 files+33 added−22 removed

modified:src/exec/mod.rs+15 added-9 removed
12 unmodified lines
13mod token;1415use std::borrow::Cow;16use std::path::{Path, PathBuf};17use std::process::Command;17use std::process::{Command, Stdio};18use std::sync::{Arc, Mutex};1920use regex::Regex;21
4 unmodified lines
2627/// Execution mode of the command28#[derive(Debug, Clone, Copy, PartialEq)]29pub enum ExecutionMode {30 /// Command is executed for each path found30 /// Command is executed for each search result31 OneByOne,32 /// Command is run for a batch of results at once33 Batch,34}
22 unmodified lines
57 I: IntoIterator<Item = S>,58 S: AsRef<str>,59 {60 let cmd = Self::build(input, ExecutionMode::Batch);61 if cmd.tokens_number() > 1 {61 if cmd.number_of_tokens() > 1 {62 return Err("Only one placeholder allowed for batch commands");63 }64 if cmd.args[0].has_tokens() {65 return Err("First argument of exec-batch is expected to be a fixed executable");66 }67 Ok(cmd)68 }6970 fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate
55 unmodified lines
126127 CommandTemplate { args, mode }128 }129127 fn tokens_number(&self) -> usize {130 fn number_of_tokens(&self) -> usize {131 self.args.iter().filter(|arg| arg.has_tokens()).count()132 }133134 fn prepare_path(input: &Path) -> String {
18 unmodified lines
153154 execute_command(cmd, &out_perm)155 }156154 pub fn is_batch(&self) -> bool {157 pub fn in_batch_mode(&self) -> bool {158 self.mode == ExecutionMode::Batch159 }160161 pub fn generate_and_execute_batch<I>(&self, paths: I)162 where163 I: Iterator<Item = PathBuf>,164 {165 let mut cmd = Command::new(self.args[0].generate("").as_ref());166 cmd.stdin(Stdio::inherit());167 cmd.stdout(Stdio::inherit());168 cmd.stderr(Stdio::inherit());169170 let mut paths = paths.map(|p| Self::prepare_path(&p));171 let mut has_path = false;172173 for arg in &self.args[1..] {
26 unmodified lines
200}201202impl ArgumentTemplate {203 pub fn has_tokens(&self) -> bool {197 if let ArgumentTemplate::Tokens(_) = self {198 true199 } else {200 false204 match self {205 ArgumentTemplate::Tokens(_) => true,206 _ => false,207 }208 }209210 pub fn generate<'a>(&'a self, path: &str) -> Cow<'a, str> {
134 unmodified lines
modified:src/walk.rs+1 added-1 removed
124 unmodified lines
125 let rx_config = Arc::clone(&config);126 let receiver_thread = thread::spawn(move || {127 // This will be set to `Some` if the `--exec` argument was supplied.128 if let Some(ref cmd) = rx_config.command {129 if cmd.is_batch() {129 if cmd.in_batch_mode() {130 exec::batch(rx, cmd, show_filesystem_errors);131 } else {132 let shared_rx = Arc::new(Mutex::new(rx));133
223 unmodified lines
modified:tests/testenv/mod.rs+6 added-9 removed
31 unmodified lines
3233 /// Path to the *fd* executable.34 fd_exe: PathBuf,3536 /// Normalize each line by splitting and sorting by whitespace as well36 /// Normalize each line by sorting the whitespace-separated words37 normalize_line: bool,38}3940/// Create the working directory and the test files.
91 unmodified lines
132 .map(|line| {133 let line = if trim_left { line.trim_left() } else { line };134 let line = line.replace('/', &std::path::MAIN_SEPARATOR.to_string());135 if normalize_line {136 let mut worlds: Vec<_> = line.split_whitespace().collect();137 worlds.sort();138 return worlds.join(" ");136 let mut words: Vec<_> = line.split_whitespace().collect();137 words.sort();138 return words.join(" ");139 }140 line141 })142 .collect::<Vec<_>>();
90 unmodified lines
233 let output = cmd.output().expect("fd output");234235 // Check for exit status.236 if output.status.success() {237 panic!(238 "fd exited successfully. Expected error {} did not occur.",239 expected240 );237 panic!("error '{}' did not occur.", expected);238 }239240 // Compare actual output to expected output.241 let actual = String::from_utf8_lossy(&output.stderr);245 if expected.len() <= actual.len() && expected != &actual[..expected.len()] {242 if !actual.starts_with(expected) {243 panic!(format_output_error(args, &expected, &actual));244 }245 }246}
modified:tests/tests.rs+11 added-3 removed
985 unmodified lines
986 te.assert_output(&["e1", exec_style, "printf", "%s.%s\n"], "e1 e2.");987 }988}989990/// Shell script execution using -exec990#[test]991fn test_exec_batch() {992 assert_exec_batch_output("--exec-batch");993}994996// Shell script execution using -x995#[test]996fn test_exec_batch_short_arg() {997 assert_exec_batch_output("-X");998}
2 unmodified lines
1001fn assert_exec_batch_output(exec_style: &str) {1002 let (te, abs_path) = get_test_env_with_abs_path(DEFAULT_DIRS, DEFAULT_FILES);1003 let te = te.normalize_line(true);10041007 // TODO Windows tests: D:file.txt \file.txt \\server\share\file.txt ...1005 // TODO Test for windows1006 if !cfg!(windows) {1007 te.assert_output(1008 &["--absolute-path", "foo", exec_style, "echo"],1009 &format!(
22 unmodified lines
1032 te.assert_error(1033 &["foo", exec_style, "echo", "{/}", ";", "-x", "echo"],1034 "error: The argument '--exec <cmd>' cannot be used with '--exec-batch <cmd>'",1035 );10361037 te.assert_error(1038 &["foo", exec_style],1039 "error: The argument '--exec-batch <cmd>' requires a value but none was supplied",1040 );10411042 te.assert_error(1043 &["foo", exec_style, "echo {}"],1044 "[fd error]: First argument of exec-batch is expected to be a fixed executable",1045 );1046 }1047}10481049/// Literal search (--fixed-strings)
188 unmodified lines