Skip to content
Myr

Support multiple `--exec` instances

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

and `--exec-batch`.

authored by Thayne McCombs · committed by David Peter · parent 45f490a · Browse files · 6 files+170 added−111 removed
This commit

State

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

Trailers

  • Fixes: #406

Diff stats

6 files+170 added−111 removed

  • other:+170 added−111 removed

6 files+170 added−111 removed

modified:src/exec/job.rs+6 added-6 removed
4 unmodified lines
5use crate::error::print_error;6use crate::exit_codes::{merge_exitcodes, ExitCode};7use crate::walk::WorkerResult;89use super::CommandTemplate;9use super::CommandSet;1011/// An event loop that listens for inputs from the `rx` receiver. Each received input will12/// generate a command with the supplied command template. The generated command will then13/// be executed, and this process will continue until the receiver's sender has closed.14pub fn job(15 rx: Arc<Mutex<Receiver<WorkerResult>>>,16 cmd: Arc<CommandTemplate>,16 cmd: Arc<CommandSet>,17 out_perm: Arc<Mutex<()>>,18 show_filesystem_errors: bool,19 buffer_output: bool,20) -> ExitCode {
17 unmodified lines
3839 // Drop the lock so that other threads can read from the receiver.40 drop(lock);41 // Generate a command, execute it and store its exit code.42 results.push(cmd.generate_and_execute(&value, Arc::clone(&out_perm), buffer_output))42 results.push(cmd.execute(&value, Arc::clone(&out_perm), buffer_output))43 }44 // Returns error in case of any error.45 merge_exitcodes(results)46}4748pub fn batch(49 rx: Receiver<WorkerResult>,50 cmd: &CommandTemplate,50 cmd: &CommandSet,51 show_filesystem_errors: bool,52 buffer_output: bool,53 limit: usize,54) -> ExitCode {
7 unmodified lines
62 }63 });64 if limit == 0 {65 // no limit66 return cmd.generate_and_execute_batch(paths, buffer_output);66 return cmd.execute_batch(paths, buffer_output);67 }6869 let mut exit_codes = Vec::new();70 let mut peekable = paths.peekable();71 while peekable.peek().is_some() {72 let limited = peekable.by_ref().take(limit);73 let exit_code = cmd.generate_and_execute_batch(limited, buffer_output);73 let exit_code = cmd.execute_batch(limited, buffer_output);74 exit_codes.push(exit_code);75 }76 merge_exitcodes(exit_codes)77}
modified:src/exec/mod.rs+150 added-89 removed
27 unmodified lines
28 /// Command is run for a batch of results at once29 Batch,30}3132/// Represents a template that is utilized to generate command strings.33///34/// The template is meant to be coupled with an input in order to generate a command. The35/// `generate_and_execute()` method will be used to generate a command and execute it.32#[derive(Debug, Clone, PartialEq)]37pub struct CommandTemplate {38 args: Vec<ArgumentTemplate>,33pub struct CommandSet {34 mode: ExecutionMode,35 path_separator: Option<String>,36 commands: Vec<CommandTemplate>,37}3843impl CommandTemplate {44 pub fn new<I, S>(input: I, path_separator: Option<String>) -> CommandTemplate39impl CommandSet {40 pub fn new<I, S>(input: I, path_separator: Option<String>) -> CommandSet41 where46 I: IntoIterator<Item = S>,42 I: IntoIterator<Item = Vec<S>>,43 S: AsRef<str>,44 {49 Self::build(input, ExecutionMode::OneByOne, path_separator)45 CommandSet {46 mode: ExecutionMode::OneByOne,47 path_separator,48 commands: input.into_iter().map(CommandTemplate::new).collect(),49 }50 }5152 pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandTemplate>52 pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandSet>53 where54 I: IntoIterator<Item = S>,54 I: IntoIterator<Item = Vec<S>>,55 S: AsRef<str>,56 {57 Ok(CommandSet {58 mode: ExecutionMode::Batch,59 path_separator,60 commands: input61 .into_iter()62 .map(|args| {57 let cmd = Self::build(input, ExecutionMode::Batch, path_separator);58 if cmd.number_of_tokens() > 1 {59 return Err(anyhow!("Only one placeholder allowed for batch commands"));63 let cmd = CommandTemplate::new(args);64 if cmd.number_of_tokens() > 1 {65 return Err(anyhow!("Only one placeholder allowed for batch commands"));66 }67 if cmd.args[0].has_tokens() {68 return Err(anyhow!(69 "First argument of exec-batch is expected to be a fixed executable"70 ));71 }72 Ok(cmd)73 })74 .collect::<Result<Vec<_>>>()?,75 })76 }7778 pub fn in_batch_mode(&self) -> bool {79 self.mode == ExecutionMode::Batch80 }8182 pub fn execute(83 &self,84 input: &Path,85 mut out_perm: Arc<Mutex<()>>,86 buffer_output: bool,87 ) -> ExitCode {88 let path_separator = self.path_separator.as_deref();89 for cmd in &self.commands {90 let exit =91 cmd.generate_and_execute(input, path_separator, &mut out_perm, buffer_output);92 if exit != ExitCode::Success {93 return exit;94 }95 }61 if cmd.args[0].has_tokens() {62 return Err(anyhow!(63 "First argument of exec-batch is expected to be a fixed executable"64 ));96 ExitCode::Success97 }9899 pub fn execute_batch<I>(&self, paths: I, buffer_output: bool) -> ExitCode100 where101 I: Iterator<Item = PathBuf>,102 {103 let path_separator = self.path_separator.as_deref();104 let mut paths = paths.collect::<Vec<_>>();105 paths.sort();106 for cmd in &self.commands {107 let exit = cmd.generate_and_execute_batch(&paths, path_separator, buffer_output);108 if exit != ExitCode::Success {109 return exit;110 }111 }66 Ok(cmd)112 ExitCode::Success113 }114}11569 fn build<I, S>(input: I, mode: ExecutionMode, path_separator: Option<String>) -> CommandTemplate116/// Represents a template that is utilized to generate command strings.117///118/// The template is meant to be coupled with an input in order to generate a command. The119/// `generate_and_execute()` method will be used to generate a command and execute it.120#[derive(Debug, Clone, PartialEq)]121struct CommandTemplate {122 args: Vec<ArgumentTemplate>,123}124125impl CommandTemplate {126 fn new<I, S>(input: I) -> CommandTemplate127 where128 I: IntoIterator<Item = S>,129 S: AsRef<str>,130 {
47 unmodified lines
178 if !has_placeholder {179 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));180 }181125 CommandTemplate {126 args,127 mode,128 path_separator,129 }182 CommandTemplate { args }183 }184185 fn number_of_tokens(&self) -> usize {186 self.args.iter().filter(|arg| arg.has_tokens()).count()
2 unmodified lines
189 /// Generates and executes a command.190 ///191 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be192 /// build. Once all arguments have been processed, the command is executed.140 pub fn generate_and_execute(193 fn generate_and_execute(194 &self,195 input: &Path,196 path_separator: Option<&str>,143 out_perm: Arc<Mutex<()>>,197 out_perm: &mut Arc<Mutex<()>>,198 buffer_output: bool,199 ) -> ExitCode {146 let mut cmd = Command::new(self.args[0].generate(&input, self.path_separator.as_deref()));200 let mut cmd = Command::new(self.args[0].generate(&input, path_separator));201 for arg in &self.args[1..] {148 cmd.arg(arg.generate(&input, self.path_separator.as_deref()));202 cmd.arg(arg.generate(&input, path_separator));203 }204205 execute_command(cmd, &out_perm, buffer_output)206 }207154 pub fn in_batch_mode(&self) -> bool {155 self.mode == ExecutionMode::Batch156 }157158 pub fn generate_and_execute_batch<I>(&self, paths: I, buffer_output: bool) -> ExitCode159 where160 I: Iterator<Item = PathBuf>,161 {208 fn generate_and_execute_batch(209 &self,210 paths: &Vec<PathBuf>,211 path_separator: Option<&str>,212 buffer_output: bool,213 ) -> ExitCode {214 let mut cmd = Command::new(self.args[0].generate("", None));215 cmd.stdin(Stdio::inherit());216 cmd.stdout(Stdio::inherit());217 cmd.stderr(Stdio::inherit());218167 let mut paths: Vec<_> = paths.collect();219 let mut has_path = false;220221 for arg in &self.args[1..] {222 if arg.has_tokens() {172 paths.sort();173174 // A single `Tokens` is expected175 // So we can directly consume the iterator once and for all176 for path in &mut paths {177 cmd.arg(arg.generate(path, self.path_separator.as_deref()));223 for path in paths {224 cmd.arg(arg.generate(path, path_separator));225 has_path = true;226 }227 } else {228 cmd.arg(arg.generate("", None));
119 unmodified lines
348349 #[test]350 fn tokens_with_placeholder() {351 assert_eq!(305 CommandTemplate::new(&[&"echo", &"${SHELL}:"], None),306 CommandTemplate {307 args: vec![308 ArgumentTemplate::Text("echo".into()),309 ArgumentTemplate::Text("${SHELL}:".into()),310 ArgumentTemplate::Tokens(vec![Token::Placeholder]),311 ],352 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]], None),353 CommandSet {354 commands: vec![CommandTemplate {355 args: vec![356 ArgumentTemplate::Text("echo".into()),357 ArgumentTemplate::Text("${SHELL}:".into()),358 ArgumentTemplate::Tokens(vec![Token::Placeholder]),359 ]360 }],361 mode: ExecutionMode::OneByOne,362 path_separator: None,363 }364 );
1 unmodified line
366367 #[test]368 fn tokens_with_no_extension() {369 assert_eq!(370 CommandSet::new(vec![vec!["echo", "{.}"]], None),321 CommandTemplate::new(&["echo", "{.}"], None),322 CommandTemplate {323 args: vec![324 ArgumentTemplate::Text("echo".into()),325 ArgumentTemplate::Tokens(vec![Token::NoExt]),326 ],371 CommandSet {372 commands: vec![CommandTemplate {373 args: vec![374 ArgumentTemplate::Text("echo".into()),375 ArgumentTemplate::Tokens(vec![Token::NoExt]),376 ],377 }],378 mode: ExecutionMode::OneByOne,379 path_separator: None,380 }381 );
1 unmodified line
383384 #[test]385 fn tokens_with_basename() {386 assert_eq!(387 CommandSet::new(vec![vec!["echo", "{/}"]], None),336 CommandTemplate::new(&["echo", "{/}"], None),337 CommandTemplate {338 args: vec![339 ArgumentTemplate::Text("echo".into()),340 ArgumentTemplate::Tokens(vec![Token::Basename]),341 ],388 CommandSet {389 commands: vec![CommandTemplate {390 args: vec![391 ArgumentTemplate::Text("echo".into()),392 ArgumentTemplate::Tokens(vec![Token::Basename]),393 ],394 }],395 mode: ExecutionMode::OneByOne,396 path_separator: None,397 }398 );
1 unmodified line
400401 #[test]402 fn tokens_with_parent() {403 assert_eq!(404 CommandSet::new(vec![vec!["echo", "{//}"]], None),351 CommandTemplate::new(&["echo", "{//}"], None),352 CommandTemplate {353 args: vec![354 ArgumentTemplate::Text("echo".into()),355 ArgumentTemplate::Tokens(vec![Token::Parent]),356 ],405 CommandSet {406 commands: vec![CommandTemplate {407 args: vec![408 ArgumentTemplate::Text("echo".into()),409 ArgumentTemplate::Tokens(vec![Token::Parent]),410 ],411 }],412 mode: ExecutionMode::OneByOne,413 path_separator: None,414 }415 );
1 unmodified line
417418 #[test]419 fn tokens_with_basename_no_extension() {420 assert_eq!(421 CommandSet::new(vec![vec!["echo", "{/.}"]], None),366 CommandTemplate::new(&["echo", "{/.}"], None),367 CommandTemplate {368 args: vec![369 ArgumentTemplate::Text("echo".into()),370 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),371 ],422 CommandSet {423 commands: vec![CommandTemplate {424 args: vec![425 ArgumentTemplate::Text("echo".into()),426 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),427 ],428 }],429 mode: ExecutionMode::OneByOne,430 path_separator: None,431 }432 );
1 unmodified line
434435 #[test]436 fn tokens_multiple() {437 assert_eq!(438 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]], None),381 CommandTemplate::new(&["cp", "{}", "{/.}.ext"], None),382 CommandTemplate {383 args: vec![384 ArgumentTemplate::Text("cp".into()),385 ArgumentTemplate::Tokens(vec![Token::Placeholder]),386 ArgumentTemplate::Tokens(vec![387 Token::BasenameNoExt,388 Token::Text(".ext".into())389 ]),390 ],439 CommandSet {440 commands: vec![CommandTemplate {441 args: vec![442 ArgumentTemplate::Text("cp".into()),443 ArgumentTemplate::Tokens(vec![Token::Placeholder]),444 ArgumentTemplate::Tokens(vec![445 Token::BasenameNoExt,446 Token::Text(".ext".into())447 ]),448 ],449 }],450 mode: ExecutionMode::OneByOne,451 path_separator: None,452 }453 );
1 unmodified line
455456 #[test]457 fn tokens_single_batch() {458 assert_eq!(400 CommandTemplate::new_batch(&["echo", "{.}"], None).unwrap(),401 CommandTemplate {459 CommandSet::new_batch(vec![vec!["echo", "{.}"]], None).unwrap(),460 CommandSet {461 commands: vec![CommandTemplate {462 args: vec![463 ArgumentTemplate::Text("echo".into()),464 ArgumentTemplate::Tokens(vec![Token::NoExt]),465 ],466 }],467 mode: ExecutionMode::Batch,468 path_separator: None,469 }470 );471 }472473 #[test]474 fn tokens_multiple_batch() {414 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"], None).is_err());475 assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]], None).is_err());476 }477478 #[test]479 fn generate_custom_path_separator() {
40 unmodified lines
modified:src/app.rs+2 added
384 unmodified lines
385 Arg::new("exec")386 .long("exec")387 .short('x')388 .min_values(1)389 .multiple_occurrences(true)390 .allow_hyphen_values(true)391 .value_terminator(";")392 .value_name("cmd")393 .conflicts_with("list-details")
23 unmodified lines
417 Arg::new("exec-batch")418 .long("exec-batch")419 .short('X')420 .min_values(1)421 .multiple_occurrences(true)422 .allow_hyphen_values(true)423 .value_terminator(";")424 .value_name("cmd")425 .conflicts_with_all(&["exec", "list-details"])
347 unmodified lines
modified:src/config.rs+2 added-2 removed
1 unmodified line
23use lscolors::LsColors;4use regex::bytes::RegexSet;56use crate::exec::CommandTemplate;6use crate::exec::CommandSet;7use crate::filetypes::FileTypes;8#[cfg(unix)]9use crate::filter::OwnerFilter;10use crate::filter::{SizeFilter, TimeFilter};
71 unmodified lines
82 /// The value (if present) will be a lowercase string without leading dots.83 pub extensions: Option<RegexSet>,8485 /// If a value is supplied, each item found will be used to generate and execute commands.86 pub command: Option<Arc<CommandTemplate>>,86 pub command: Option<Arc<CommandSet>>,8788 /// Maximum number of search results to pass to each `command`. If zero, the number is89 /// unlimited.90 pub batch_size: usize,
29 unmodified lines
modified:src/main.rs+9 added-13 removed
22 unmodified lines
23use regex::bytes::{RegexBuilder, RegexSetBuilder};2425use crate::config::Config;26use crate::error::print_error;27use crate::exec::CommandTemplate;27use crate::exec::CommandSet;28use crate::exit_codes::ExitCode;29use crate::filetypes::FileTypes;30#[cfg(unix)]31use crate::filter::OwnerFilter;
357 unmodified lines
389fn extract_command(390 matches: &clap::ArgMatches,391 path_separator: Option<&str>,392 colored_output: bool,393) -> Result<Option<CommandTemplate>> {393) -> Result<Option<CommandSet>> {394 None.or_else(|| {395 matches.values_of("exec").map(|args| {396 Ok(CommandTemplate::new(397 args,398 path_separator.map(str::to_string),399 ))400 })395 matches396 .grouped_values_of("exec")397 .map(|args| Ok(CommandSet::new(args, path_separator.map(str::to_string))))398 })399 .or_else(|| {400 matches404 .values_of("exec-batch")405 .map(|args| CommandTemplate::new_batch(args, path_separator.map(str::to_string)))401 .grouped_values_of("exec-batch")402 .map(|args| CommandSet::new_batch(args, path_separator.map(str::to_string)))403 })404 .or_else(|| {405 if !matches.is_present("list-details") {406 return None;
1 unmodified line
408409 let color = matches.value_of("color").unwrap_or("auto");410 let color_arg = format!("--color={}", color);411415 let res = determine_ls_command(&color_arg, colored_output).map(|cmd| {416 CommandTemplate::new_batch(cmd, path_separator.map(str::to_string)).unwrap()417 });412 let res = determine_ls_command(&color_arg, colored_output)413 .map(|cmd| CommandSet::new_batch([cmd], path_separator.map(str::to_string)).unwrap());414415 Some(res)416 })417 .transpose()
147 unmodified lines
modified:Cargo.toml+1 added-1 removed