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
Provenance
- Commit
0aee9b0- Tree
6bc3168- Author
Thayne McCombs <astrothayne@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
45f490a
6 files changed+170 added−111 removed
modified:src/exec/job.rs+6 added-6 removed
4 unmodified lines5 use crate::error::print_error;6 use crate::exit_codes::{merge_exitcodes, ExitCode};7 use crate::walk::WorkerResult;8 9-use super::CommandTemplate;9+use super::CommandSet;10 11 /// 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.14 pub 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 lines38 39 // 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 }47 48 pub 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 lines62 }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 }68 69 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 lines28 /// Command is run for a batch of results at once29 Batch,30 }31 32-/// 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)]37-pub struct CommandTemplate {38- args: Vec<ArgumentTemplate>,33+pub struct CommandSet {34 mode: ExecutionMode,35 path_separator: Option<String>,36+ commands: Vec<CommandTemplate>,37 }38 43-impl CommandTemplate {44- pub fn new<I, S>(input: I, path_separator: Option<String>) -> CommandTemplate39+impl 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 }51 52- 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+ }77+78+ pub fn in_batch_mode(&self) -> bool {79+ self.mode == ExecutionMode::Batch80+ }81+82+ 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+ }98+99+ 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+}115 69- 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)]121+struct CommandTemplate {122+ args: Vec<ArgumentTemplate>,123+}124+125+impl CommandTemplate {126+ fn new<I, S>(input: I) -> CommandTemplate127 where128 I: IntoIterator<Item = S>,129 S: AsRef<str>,130 {47 unmodified lines178 if !has_placeholder {179 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));180 }181 125- CommandTemplate {126- args,127- mode,128- path_separator,129- }182+ CommandTemplate { args }183 }184 185 fn number_of_tokens(&self) -> usize {186 self.args.iter().filter(|arg| arg.has_tokens()).count()2 unmodified lines189 /// 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 }204 205 execute_command(cmd, &out_perm, buffer_output)206 }207 154- pub fn in_batch_mode(&self) -> bool {155- self.mode == ExecutionMode::Batch156- }157-158- 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());218 167- let mut paths: Vec<_> = paths.collect();219 let mut has_path = false;220 221 for arg in &self.args[1..] {222 if arg.has_tokens() {172- paths.sort();173-174- // 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 lines348 349 #[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 line366 367 #[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 line383 384 #[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 line400 401 #[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 line417 418 #[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 line434 435 #[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 line455 456 #[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 }472 473 #[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 }477 478 #[test]479 fn generate_custom_path_separator() {40 unmodified linesmodified:src/app.rs+2 added
384 unmodified lines385 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 lines417 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 linesmodified:src/config.rs+2 added-2 removed
1 unmodified line2 3 use lscolors::LsColors;4 use regex::bytes::RegexSet;5 6-use crate::exec::CommandTemplate;6+use crate::exec::CommandSet;7 use crate::filetypes::FileTypes;8 #[cfg(unix)]9 use crate::filter::OwnerFilter;10 use crate::filter::{SizeFilter, TimeFilter};71 unmodified lines82 /// The value (if present) will be a lowercase string without leading dots.83 pub extensions: Option<RegexSet>,84 85 /// 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>>,87 88 /// Maximum number of search results to pass to each `command`. If zero, the number is89 /// unlimited.90 pub batch_size: usize,29 unmodified linesmodified:src/main.rs+9 added-13 removed
22 unmodified lines23 use regex::bytes::{RegexBuilder, RegexSetBuilder};24 25 use crate::config::Config;26 use crate::error::print_error;27-use crate::exec::CommandTemplate;27+use crate::exec::CommandSet;28 use crate::exit_codes::ExitCode;29 use crate::filetypes::FileTypes;30 #[cfg(unix)]31 use crate::filter::OwnerFilter;357 unmodified lines389 fn 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 line408 409 let color = matches.value_of("color").unwrap_or("auto");410 let color_arg = format!("--color={}", color);411 415- 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());414 415 Some(res)416 })417 .transpose()147 unmodified linesmodified:Cargo.toml+1 added-1 removed
51 unmodified lines5253545556565758596023 unmodified lines51 unmodified linesonce_cell = "1.9.0"
[dependencies.clap]version = "3.1"features = ["suggestions", "color", "wrap_help", "cargo"]features = ["suggestions", "color", "wrap_help", "cargo", "unstable-grouped"]
[target.'cfg(unix)'.dependencies]users = "0.11.0"nix = "0.23.1"23 unmodified lines