Add support for batch execution of command
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 32ec7af · Browse files · 8 files·+294 added−42 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+294 added−42 removed
- tests:+111 added−8 removed
- other:+183 added−34 removed
Provenance
- Commit
45d1b15- Tree
92cab41- Author
kimsnj <karim.snj@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
32ec7af
8 files changed+294 added−42 removed
modified:src/exec/command.rs+2 added-2 removed
7 unmodified lines8 9 use std::io;10 use std::io::Write;11 use std::process::Command;12-use std::sync::{Arc, Mutex};12+use std::sync::Mutex;13 14 /// Executes a command.15-pub fn execute_command(mut cmd: Command, out_perm: Arc<Mutex<()>>) {15+pub fn execute_command(mut cmd: Command, out_perm: &Mutex<()>) {16 // Spawn the supplied command.17 let output = cmd.output();18 19 // Then wait for the command to exit, if it was spawned.20 unmodified linesmodified:src/exec/job.rs+13 added
42 unmodified lines43 // Generate a command and execute it.44 cmd.generate_and_execute(&value, Arc::clone(&out_perm));45 }46 }47+48+pub fn batch(rx: Receiver<WorkerResult>, cmd: &CommandTemplate, show_filesystem_errors: bool) {49+ let paths = rx.iter().filter_map(|value| match value {50+ WorkerResult::Entry(val) => Some(val),51+ WorkerResult::Error(err) => {52+ if show_filesystem_errors {53+ print_error!("{}", err);54+ }55+ None56+ }57+ });58+ cmd.generate_and_execute_batch(paths);59+}modified:src/exec/mod.rs+110 added-9 removed
11 unmodified lines12 mod job;13 mod token;14 15 use std::borrow::Cow;16-use std::path::Path;16+use std::path::{Path, PathBuf};17 use std::process::Command;18 use std::sync::{Arc, Mutex};19 20 use regex::Regex;21 22 use self::command::execute_command;23 use self::input::{basename, dirname, remove_extension};24-pub use self::job::job;24+pub use self::job::{batch, job};25 use self::token::Token;26 27+/// Execution mode of the command28+#[derive(Debug, Clone, Copy, PartialEq)]29+pub enum ExecutionMode {30+ /// Command is executed for each path found31+ OneByOne,32+ /// Command is run for a batch of results at once33+ Batch,34+}35+36 /// Represents a template that is utilized to generate command strings.37 ///38 /// The template is meant to be coupled with an input in order to generate a command. The39 /// `generate_and_execute()` method will be used to generate a command and execute it.40 #[derive(Debug, Clone, PartialEq)]41 pub struct CommandTemplate {42 args: Vec<ArgumentTemplate>,43+ mode: ExecutionMode,44 }45 46 impl CommandTemplate {47 pub fn new<I, S>(input: I) -> CommandTemplate48 where49 I: IntoIterator<Item = S>,50 S: AsRef<str>,51 {52+ Self::build(input, ExecutionMode::OneByOne)53+ }54+55+ pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate, &'static str>56+ where57+ I: IntoIterator<Item = S>,58+ S: AsRef<str>,59+ {60+ let cmd = Self::build(input, ExecutionMode::Batch);61+ if cmd.tokens_number() > 1 {62+ return Err("Only one placeholder allowed for batch commands");63+ }64+ Ok(cmd)65+ }66+67+ fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate68+ where69+ I: IntoIterator<Item = S>,70+ S: AsRef<str>,71+ {72 lazy_static! {73 static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();74 }75 44 unmodified lines120 if !has_placeholder {121 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));122 }123 94- CommandTemplate { args }124+ CommandTemplate { args, mode }125 }126 127+ fn tokens_number(&self) -> usize {128+ self.args.iter().filter(|arg| arg.has_tokens()).count()129+ }130+131+ fn prepare_path(input: &Path) -> String {132+ input133+ .strip_prefix(".")134+ .unwrap_or(input)135+ .to_string_lossy()136+ .into_owned()137+ }138+139 /// Generates and executes a command.140 ///141 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be142 /// build. Once all arguments have been processed, the command is executed.143 pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) {102- let input = input103- .strip_prefix(".")104- .unwrap_or(input)105- .to_string_lossy()106- .into_owned();144+ let input = Self::prepare_path(input);145 146 let mut cmd = Command::new(self.args[0].generate(&input).as_ref());147 for arg in &self.args[1..] {148 cmd.arg(arg.generate(&input).as_ref());149 }150 113- execute_command(cmd, out_perm)151+ execute_command(cmd, &out_perm)152 }153+154+ pub fn is_batch(&self) -> bool {155+ self.mode == ExecutionMode::Batch156+ }157+158+ pub fn generate_and_execute_batch<I>(&self, paths: I)159+ where160+ I: Iterator<Item = PathBuf>,161+ {162+ let mut cmd = Command::new(self.args[0].generate("").as_ref());163+ let mut paths = paths.map(|p| Self::prepare_path(&p));164+ let mut has_path = false;165+166+ for arg in &self.args[1..] {167+ if arg.has_tokens() {168+ // A single `Tokens` is expected169+ // So we can directy consume the iterator once and for all170+ for path in &mut paths {171+ cmd.arg(arg.generate(&path).as_ref());172+ has_path = true;173+ }174+ } else {175+ cmd.arg(arg.generate("").as_ref());176+ }177+ }178+179+ if has_path {180+ execute_command(cmd, &Mutex::new(()));181+ }182+ }183 }184 185 /// Represents a template for a single command argument.186 ///5 unmodified lines192 Text(String),193 }194 195 impl ArgumentTemplate {196+ pub fn has_tokens(&self) -> bool {197+ if let ArgumentTemplate::Tokens(_) = self {198+ true199+ } else {200+ false201+ }202+ }203+204 pub fn generate<'a>(&'a self, path: &str) -> Cow<'a, str> {205 use self::Token::*;206 207 match *self {29 unmodified lines237 ArgumentTemplate::Text("echo".into()),238 ArgumentTemplate::Text("${SHELL}:".into()),239 ArgumentTemplate::Tokens(vec![Token::Placeholder]),240 ],241+ mode: ExecutionMode::OneByOne,242 }243 );244 }245 5 unmodified lines251 args: vec![252 ArgumentTemplate::Text("echo".into()),253 ArgumentTemplate::Tokens(vec![Token::NoExt]),254 ],255+ mode: ExecutionMode::OneByOne,256 }257 );258 }259 5 unmodified lines265 args: vec![266 ArgumentTemplate::Text("echo".into()),267 ArgumentTemplate::Tokens(vec![Token::Basename]),268 ],269+ mode: ExecutionMode::OneByOne,270 }271 );272 }273 5 unmodified lines279 args: vec![280 ArgumentTemplate::Text("echo".into()),281 ArgumentTemplate::Tokens(vec![Token::Parent]),282 ],283+ mode: ExecutionMode::OneByOne,284 }285 );286 }287 5 unmodified lines293 args: vec![294 ArgumentTemplate::Text("echo".into()),295 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),296 ],297+ mode: ExecutionMode::OneByOne,298 }299 );300 }301 9 unmodified lines311 Token::BasenameNoExt,312 Token::Text(".ext".into())313 ]),314 ],315+ mode: ExecutionMode::OneByOne,316 }317 );318 }319+320+ #[test]321+ fn tokens_single_batch() {322+ assert_eq!(323+ CommandTemplate::new_batch(&["echo", "{.}"]).unwrap(),324+ CommandTemplate {325+ args: vec![326+ ArgumentTemplate::Text("echo".into()),327+ ArgumentTemplate::Tokens(vec![Token::NoExt]),328+ ],329+ mode: ExecutionMode::Batch,330+ }331+ );332+ }333+334+ #[test]335+ fn tokens_multiple_batch() {336+ assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"]).is_err());337+ }338 }modified:src/app.rs+22 added
120 unmodified lines121 .value_terminator(";")122 .value_name("cmd"),123 )124 .arg(125+ arg("exec-batch")126+ .long("exec-batch")127+ .short("X")128+ .min_values(1)129+ .allow_hyphen_values(true)130+ .value_terminator(";")131+ .value_name("cmd")132+ .conflicts_with("exec"),133+ )134+ .arg(135 arg("exclude")136 .long("exclude")137 .short("E")138 .takes_value(true)147 unmodified lines286 '{/}': basename\n \287 '{//}': parent directory\n \288 '{.}': path without file extension\n \289 '{/.}': basename without file extension");290+ doc!(h, "exec-batch"291+ , "Execute a command with all search results at once"292+ , "Execute a command with all search results at once.\n\293+ All arguments following --exec-batch are taken to be arguments to the command until the \294+ argument ';' is encountered.\n\295+ A single occurence of the following placeholders is authorized and substituted by the paths derived from the \296+ search results before the command is executed:\n \297+ '{}': path\n \298+ '{/}': basename\n \299+ '{//}': parent directory\n \300+ '{.}': path without file extension\n \301+ '{/.}': basename without file extension");302 doc!(h, "exclude"303 , "Exclude entries that match the given glob pattern"304 , "Exclude files/directories that match the given glob pattern. This overrides any \305 other ignore logic. Multiple exclude patterns can be specified.");69 unmodified linesmodified:src/main.rs+10 added-1 removed
140 unmodified lines141 } else {142 None143 };144 145- let command = matches.values_of("exec").map(CommandTemplate::new);145+ let command = matches146+ .values_of("exec")147+ .map(CommandTemplate::new)148+ .or_else(|| {149+ matches.values_of("exec-batch").map(|m| {150+ CommandTemplate::new_batch(m).unwrap_or_else(|e| {151+ print_error_and_exit!("{}", e);152+ })153+ })154+ });155 156 let size_limits: Vec<SizeFilter> = matches157 .values_of("size")158 .map(|v| {124 unmodified linesmodified:src/walk.rs+26 added-22 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() {130+ exec::batch(rx, cmd, show_filesystem_errors);131+ } else {129- let shared_rx = Arc::new(Mutex::new(rx));132+ let shared_rx = Arc::new(Mutex::new(rx));133 131- let out_perm = Arc::new(Mutex::new(()));134+ let out_perm = Arc::new(Mutex::new(()));135 133- // TODO: the following line is a workaround to replace the `unsafe` block that was134- // previously used here to avoid the (unnecessary?) cloning of the command. The135- // `unsafe` block caused problems on some platforms (SIGILL instructions on Linux) and136- // therefore had to be removed.137- let cmd = Arc::new(cmd.clone());136+ // TODO: the following line is a workaround to replace the `unsafe` block that was137+ // previously used here to avoid the (unnecessary?) cloning of the command. The138+ // `unsafe` block caused problems on some platforms (SIGILL instructions on Linux) and139+ // therefore had to be removed.140+ let cmd = Arc::new(cmd.clone());141 139- // Each spawned job will store it's thread handle in here.140- let mut handles = Vec::with_capacity(threads);141- for _ in 0..threads {142- let rx = Arc::clone(&shared_rx);143- let cmd = Arc::clone(&cmd);144- let out_perm = Arc::clone(&out_perm);142+ // Each spawned job will store it's thread handle in here.143+ let mut handles = Vec::with_capacity(threads);144+ for _ in 0..threads {145+ let rx = Arc::clone(&shared_rx);146+ let cmd = Arc::clone(&cmd);147+ let out_perm = Arc::clone(&out_perm);148 146- // Spawn a job thread that will listen for and execute inputs.147- let handle =148- thread::spawn(move || exec::job(rx, cmd, out_perm, show_filesystem_errors));149+ // Spawn a job thread that will listen for and execute inputs.150+ let handle =151+ thread::spawn(move || exec::job(rx, cmd, out_perm, show_filesystem_errors));152 150- // Push the handle of the spawned thread into the vector for later joining.151- handles.push(handle);152- }153+ // Push the handle of the spawned thread into the vector for later joining.154+ handles.push(handle);155+ }156 154- // Wait for all threads to exit before exiting the program.155- for h in handles {156- h.join().unwrap();157+ // Wait for all threads to exit before exiting the program.158+ for h in handles {159+ h.join().unwrap();160+ }161 }162 } else {163 let start = time::Instant::now();164 192 unmodified linesmodified:tests/testenv/mod.rs+60 added-8 removed
30 unmodified lines31 temp_dir: TempDir,32 33 /// Path to the *fd* executable.34 fd_exe: PathBuf,35+36+ /// Normalize each line by splitting and sorting by whitespace as well37+ normalize_line: bool,38 }39 40 /// Create the working directory and the test files.41 fn create_working_directory(81 unmodified lines123 )124 }125 126 /// Normalize the output for comparison.124-fn normalize_output(s: &str, trim_left: bool) -> String {127+fn normalize_output(s: &str, trim_left: bool, normalize_line: bool) -> String {128 // Split into lines and normalize separators.129 let mut lines = s130 .replace('\0', "NULL\n")131 .lines()132 .map(|line| {133 let line = if trim_left { line.trim_left() } else { line };131- line.replace('/', &std::path::MAIN_SEPARATOR.to_string())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(" ");139+ }140+ line141 })142 .collect::<Vec<_>>();143 135- lines.sort_by_key(|s| s.clone());136-144+ lines.sort();145 lines.join("\n")146 }147 148 impl TestEnv {1 unmodified line150 let temp_dir = create_working_directory(directories, files).expect("working directory");151 let fd_exe = find_fd_exe();152 153 TestEnv {146- temp_dir: temp_dir,147- fd_exe: fd_exe,154+ temp_dir,155+ fd_exe,156+ normalize_line: false,157 }158 }159 160+ pub fn normalize_line(self, normalize: bool) -> TestEnv {161+ TestEnv {162+ temp_dir: self.temp_dir,163+ fd_exe: self.fd_exe,164+ normalize_line: normalize,165+ }166+ }167+168 /// Get the root directory for the tests.169 pub fn test_root(&self) -> PathBuf {170 self.temp_dir.path().to_path_buf()171 }30 unmodified lines202 panic!(format_exit_error(args, &output));203 }204 205 // Normalize both expected and actual output.189- let expected = normalize_output(expected, true);190- let actual = normalize_output(&String::from_utf8_lossy(&output.stdout), false);206+ let expected = normalize_output(expected, true, self.normalize_line);207+ let actual = normalize_output(208+ &String::from_utf8_lossy(&output.stdout),209+ false,210+ self.normalize_line,211+ );212 213 // Compare actual output to expected output.214 if expected != actual {215 panic!(format_output_error(args, &expected, &actual));216 }217 }218+219+ /// Assert that calling *fd* with the specified arguments produces the expected error.220+ pub fn assert_error(&self, args: &[&str], expected: &str) {221+ self.assert_error_subdirectory(".", args, expected)222+ }223+224+ /// Assert that calling *fd* in the specified path under the root working directory,225+ /// and with the specified arguments produces an error with the expected message.226+ fn assert_error_subdirectory<P: AsRef<Path>>(&self, path: P, args: &[&str], expected: &str) {227+ // Setup *fd* command.228+ let mut cmd = process::Command::new(&self.fd_exe);229+ cmd.current_dir(self.temp_dir.path().join(path));230+ cmd.args(args);231+232+ // Run *fd*.233+ 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+ );241+ }242+243+ // Compare actual output to expected output.244+ let actual = String::from_utf8_lossy(&output.stderr);245+ if expected.len() <= actual.len() && expected != &actual[..expected.len()] {246+ panic!(format_output_error(args, &expected, &actual));247+ }248+ }249 }modified:tests/tests.rs+51 added
985 unmodified lines986 te.assert_output(&["e1", exec_style, "printf", "%s.%s\n"], "e1 e2.");987 }988 }989 990+/// Shell script execution using -exec991+#[test]992+fn test_exec_batch() {993+ assert_exec_batch_output("--exec-batch");994+}995+996+// Shell script execution using -x997+#[test]998+fn test_exec_batch_short_arg() {999+ assert_exec_batch_output("-X");1000+}1001+1002+#[cfg(test)]1003+fn assert_exec_batch_output(exec_style: &str) {1004+ let (te, abs_path) = get_test_env_with_abs_path(DEFAULT_DIRS, DEFAULT_FILES);1005+ let te = te.normalize_line(true);1006+1007+ // TODO Windows tests: D:file.txt \file.txt \\server\share\file.txt ...1008+ if !cfg!(windows) {1009+ te.assert_output(1010+ &["--absolute-path", "foo", exec_style, "echo"],1011+ &format!(1012+ "{abs_path}/a.foo {abs_path}/one/b.foo {abs_path}/one/two/C.Foo2 {abs_path}/one/two/c.foo {abs_path}/one/two/three/d.foo {abs_path}/one/two/three/directory_foo",1013+ abs_path = &abs_path1014+ ),1015+ );1016+1017+ te.assert_output(1018+ &["foo", exec_style, "echo", "{}"],1019+ "a.foo one/b.foo one/two/C.Foo2 one/two/c.foo one/two/three/d.foo one/two/three/directory_foo",1020+ );1021+1022+ te.assert_output(1023+ &["foo", exec_style, "echo", "{/}"],1024+ "a.foo b.foo C.Foo2 c.foo d.foo directory_foo",1025+ );1026+1027+ te.assert_output(&["no_match", exec_style, "echo", "Matched: ", "{/}"], "");1028+1029+ te.assert_error(1030+ &["foo", exec_style, "echo", "{}", "{}"],1031+ "[fd error]: Only one placeholder allowed for batch commands",1032+ );1033+1034+ te.assert_error(1035+ &["foo", exec_style, "echo", "{/}", ";", "-x", "echo"],1036+ "error: The argument '--exec <cmd>' cannot be used with '--exec-batch <cmd>'",1037+ );1038+ }1039+}1040+1041 /// Literal search (--fixed-strings)1042 #[test]1043 fn test_fixed_strings() {1044 let dirs = &["test1", "test2"];185 unmodified lines