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
Provenance
- Commit
6b40a07- Tree
7995968- Author
kimsnj <karim.snj@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
45d1b15
4 files changed+33 added−22 removed
modified:src/exec/mod.rs+15 added-9 removed
12 unmodified lines13 mod token;14 15 use std::borrow::Cow;16 use std::path::{Path, PathBuf};17-use std::process::Command;17+use std::process::{Command, Stdio};18 use std::sync::{Arc, Mutex};19 20 use regex::Regex;21 4 unmodified lines26 27 /// Execution mode of the command28 #[derive(Debug, Clone, Copy, PartialEq)]29 pub 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 lines57 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 }69 70 fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate55 unmodified lines126 127 CommandTemplate { args, mode }128 }129 127- fn tokens_number(&self) -> usize {130+ fn number_of_tokens(&self) -> usize {131 self.args.iter().filter(|arg| arg.has_tokens()).count()132 }133 134 fn prepare_path(input: &Path) -> String {18 unmodified lines153 154 execute_command(cmd, &out_perm)155 }156 154- pub fn is_batch(&self) -> bool {157+ pub fn in_batch_mode(&self) -> bool {158 self.mode == ExecutionMode::Batch159 }160 161 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());169+170 let mut paths = paths.map(|p| Self::prepare_path(&p));171 let mut has_path = false;172 173 for arg in &self.args[1..] {26 unmodified lines200 }201 202 impl 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 }209 210 pub fn generate<'a>(&'a self, path: &str) -> Cow<'a, str> {134 unmodified linesmodified:src/walk.rs+1 added-1 removed
124 unmodified lines125 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 linesmodified:tests/testenv/mod.rs+6 added-9 removed
31 unmodified lines32 33 /// Path to the *fd* executable.34 fd_exe: PathBuf,35 36- /// Normalize each line by splitting and sorting by whitespace as well36+ /// Normalize each line by sorting the whitespace-separated words37 normalize_line: bool,38 }39 40 /// Create the working directory and the test files.91 unmodified lines132 .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 lines233 let output = cmd.output().expect("fd output");234 235 // 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 }239 240 // 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 lines986 te.assert_output(&["e1", exec_style, "printf", "%s.%s\n"], "e1 e2.");987 }988 }989 990-/// Shell script execution using -exec990 #[test]991 fn test_exec_batch() {992 assert_exec_batch_output("--exec-batch");993 }994 996-// Shell script execution using -x995 #[test]996 fn test_exec_batch_short_arg() {997 assert_exec_batch_output("-X");998 }2 unmodified lines1001 fn 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);1004 1007- // 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 lines1032 te.assert_error(1033 &["foo", exec_style, "echo", "{/}", ";", "-x", "echo"],1034 "error: The argument '--exec <cmd>' cannot be used with '--exec-batch <cmd>'",1035 );1036+1037+ te.assert_error(1038+ &["foo", exec_style],1039+ "error: The argument '--exec-batch <cmd>' requires a value but none was supplied",1040+ );1041+1042+ 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 }1048 1049 /// Literal search (--fixed-strings)188 unmodified lines