Skip to content
Myr

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

8 files+294 added−42 removed

modified:src/exec/command.rs+2 added-2 removed
7 unmodified lines
89use std::io;10use std::io::Write;11use std::process::Command;12use std::sync::{Arc, Mutex};12use std::sync::Mutex;1314/// Executes a command.15pub fn execute_command(mut cmd: Command, out_perm: Arc<Mutex<()>>) {15pub fn execute_command(mut cmd: Command, out_perm: &Mutex<()>) {16 // Spawn the supplied command.17 let output = cmd.output();1819 // Then wait for the command to exit, if it was spawned.
20 unmodified lines
modified:src/exec/job.rs+13 added
42 unmodified lines
43 // Generate a command and execute it.44 cmd.generate_and_execute(&value, Arc::clone(&out_perm));45 }46}4748pub 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 lines
12mod job;13mod token;1415use std::borrow::Cow;16use std::path::Path;16use std::path::{Path, PathBuf};17use std::process::Command;18use std::sync::{Arc, Mutex};1920use regex::Regex;2122use self::command::execute_command;23use self::input::{basename, dirname, remove_extension};24pub use self::job::job;24pub use self::job::{batch, job};25use self::token::Token;2627/// Execution mode of the command28#[derive(Debug, Clone, Copy, PartialEq)]29pub enum ExecutionMode {30 /// Command is executed for each path found31 OneByOne,32 /// Command is run for a batch of results at once33 Batch,34}3536/// 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)]41pub struct CommandTemplate {42 args: Vec<ArgumentTemplate>,43 mode: ExecutionMode,44}4546impl 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 }5455 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 }6667 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 lines
120 if !has_placeholder {121 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));122 }12394 CommandTemplate { args }124 CommandTemplate { args, mode }125 }126127 fn tokens_number(&self) -> usize {128 self.args.iter().filter(|arg| arg.has_tokens()).count()129 }130131 fn prepare_path(input: &Path) -> String {132 input133 .strip_prefix(".")134 .unwrap_or(input)135 .to_string_lossy()136 .into_owned()137 }138139 /// 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);145146 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 }150113 execute_command(cmd, out_perm)151 execute_command(cmd, &out_perm)152 }153154 pub fn is_batch(&self) -> bool {155 self.mode == ExecutionMode::Batch156 }157158 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;165166 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 }178179 if has_path {180 execute_command(cmd, &Mutex::new(()));181 }182 }183}184185/// Represents a template for a single command argument.186///
5 unmodified lines
192 Text(String),193}194195impl ArgumentTemplate {196 pub fn has_tokens(&self) -> bool {197 if let ArgumentTemplate::Tokens(_) = self {198 true199 } else {200 false201 }202 }203204 pub fn generate<'a>(&'a self, path: &str) -> Cow<'a, str> {205 use self::Token::*;206207 match *self {
29 unmodified lines
237 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 lines
251 args: vec![252 ArgumentTemplate::Text("echo".into()),253 ArgumentTemplate::Tokens(vec![Token::NoExt]),254 ],255 mode: ExecutionMode::OneByOne,256 }257 );258 }259
5 unmodified lines
265 args: vec![266 ArgumentTemplate::Text("echo".into()),267 ArgumentTemplate::Tokens(vec![Token::Basename]),268 ],269 mode: ExecutionMode::OneByOne,270 }271 );272 }273
5 unmodified lines
279 args: vec![280 ArgumentTemplate::Text("echo".into()),281 ArgumentTemplate::Tokens(vec![Token::Parent]),282 ],283 mode: ExecutionMode::OneByOne,284 }285 );286 }287
5 unmodified lines
293 args: vec![294 ArgumentTemplate::Text("echo".into()),295 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),296 ],297 mode: ExecutionMode::OneByOne,298 }299 );300 }301
9 unmodified lines
311 Token::BasenameNoExt,312 Token::Text(".ext".into())313 ]),314 ],315 mode: ExecutionMode::OneByOne,316 }317 );318 }319320 #[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 }333334 #[test]335 fn tokens_multiple_batch() {336 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"]).is_err());337 }338}
modified:src/app.rs+22 added
120 unmodified lines
121 .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 lines
286 '{/}': 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 lines
modified:src/main.rs+10 added-1 removed
140 unmodified lines
141 } else {142 None143 };144145 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 });155156 let size_limits: Vec<SizeFilter> = matches157 .values_of("size")158 .map(|v| {
124 unmodified lines
modified:src/walk.rs+26 added-22 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() {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));133131 let out_perm = Arc::new(Mutex::new(()));134 let out_perm = Arc::new(Mutex::new(()));135133 // 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());141139 // 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);148146 // 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));152150 // 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 }156154 // 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 lines
modified:tests/testenv/mod.rs+60 added-8 removed
30 unmodified lines
31 temp_dir: TempDir,3233 /// Path to the *fd* executable.34 fd_exe: PathBuf,3536 /// Normalize each line by splitting and sorting by whitespace as well37 normalize_line: bool,38}3940/// Create the working directory and the test files.41fn create_working_directory(
81 unmodified lines
123 )124}125126/// Normalize the output for comparison.124fn normalize_output(s: &str, trim_left: bool) -> String {127fn 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<_>>();143135 lines.sort_by_key(|s| s.clone());136144 lines.sort();145 lines.join("\n")146}147148impl TestEnv {
1 unmodified line
150 let temp_dir = create_working_directory(directories, files).expect("working directory");151 let fd_exe = find_fd_exe();152153 TestEnv {146 temp_dir: temp_dir,147 fd_exe: fd_exe,154 temp_dir,155 fd_exe,156 normalize_line: false,157 }158 }159160 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 }167168 /// 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 lines
202 panic!(format_exit_error(args, &output));203 }204205 // 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 );212213 // Compare actual output to expected output.214 if expected != actual {215 panic!(format_output_error(args, &expected, &actual));216 }217 }218219 /// 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 }223224 /// 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);231232 // Run *fd*.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 );241 }242243 // 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 lines
986 te.assert_output(&["e1", exec_style, "printf", "%s.%s\n"], "e1 e2.");987 }988}989990/// Shell script execution using -exec991#[test]992fn test_exec_batch() {993 assert_exec_batch_output("--exec-batch");994}995996// Shell script execution using -x997#[test]998fn test_exec_batch_short_arg() {999 assert_exec_batch_output("-X");1000}10011002#[cfg(test)]1003fn 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);10061007 // 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 );10161017 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 );10211022 te.assert_output(1023 &["foo", exec_style, "echo", "{/}"],1024 "a.foo b.foo C.Foo2 c.foo d.foo directory_foo",1025 );10261027 te.assert_output(&["no_match", exec_style, "echo", "Matched: ", "{/}"], "");10281029 te.assert_error(1030 &["foo", exec_style, "echo", "{}", "{}"],1031 "[fd error]: Only one placeholder allowed for batch commands",1032 );10331034 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}10401041/// Literal search (--fixed-strings)1042#[test]1043fn test_fixed_strings() {1044 let dirs = &["test1", "test2"];
185 unmodified lines