mod.rs
This file
Path
src/exec/mod.rs
481 lines · 14.1 KiB · Rust
Last changed by
improve patchcurious-rabbitbefore adoption63a7d85
History of this fileTake it
1mod command;2mod job;34use std::ffi::OsString;5use std::io;6use std::iter;7use std::path::{Path, PathBuf};8use std::process::Stdio;910use anyhow::{Result, bail};11use argmax::Command;1213use crate::exec::command::OutputBuffer;14use crate::exit_codes::{ExitCode, merge_exitcodes};15use crate::fmt::{FormatTemplate, Token};1617use self::command::{execute_commands, handle_cmd_error};18pub use self::job::{batch, job};1920/// Execution mode of the command21#[derive(Debug, Clone, Copy, PartialEq, Eq)]22pub enum ExecutionMode {23 /// Command is executed for each search result24 OneByOne,25 /// Command is run for a batch of results at once26 Batch,27}2829#[derive(Debug, Clone, PartialEq)]30pub struct CommandSet {31 mode: ExecutionMode,32 commands: Vec<CommandTemplate>,33}3435impl CommandSet {36 pub fn new<I, T, S>(input: I) -> Result<CommandSet>37 where38 I: IntoIterator<Item = T>,39 T: IntoIterator<Item = S>,40 S: AsRef<str>,41 {42 Ok(CommandSet {43 mode: ExecutionMode::OneByOne,44 commands: input45 .into_iter()46 .map(CommandTemplate::new)47 .collect::<Result<_>>()?,48 })49 }5051 pub fn new_batch<I, T, S>(input: I) -> Result<CommandSet>52 where53 I: IntoIterator<Item = T>,54 T: IntoIterator<Item = S>,55 S: AsRef<str>,56 {57 Ok(CommandSet {58 mode: ExecutionMode::Batch,59 commands: input60 .into_iter()61 .map(|args| {62 let cmd = CommandTemplate::new(args)?;63 if cmd.number_of_tokens() > 1 {64 bail!("Only one placeholder allowed for batch commands");65 }66 Ok(cmd)67 })68 .collect::<Result<Vec<_>>>()?,69 })70 }7172 pub fn in_batch_mode(&self) -> bool {73 self.mode == ExecutionMode::Batch74 }7576 pub fn execute(77 &self,78 input: &Path,79 path_separator: Option<&str>,80 null_separator: bool,81 buffer_output: bool,82 ) -> ExitCode {83 let commands = self84 .commands85 .iter()86 .map(|c| c.generate(input, path_separator));87 execute_commands(commands, OutputBuffer::new(null_separator), buffer_output)88 }8990 pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode91 where92 I: Iterator<Item = PathBuf>,93 {94 let builders: io::Result<Vec<_>> = self95 .commands96 .iter()97 .map(|c| CommandBuilder::new(c, limit))98 .collect();99100 match builders {101 Ok(mut builders) => {102 for path in paths {103 for builder in &mut builders {104 if let Err(e) = builder.push(&path, path_separator) {105 return handle_cmd_error(Some(&builder.cmd), e);106 }107 }108 }109110 for builder in &mut builders {111 if let Err(e) = builder.finish() {112 return handle_cmd_error(Some(&builder.cmd), e);113 }114 }115116 merge_exitcodes(builders.iter().map(|b| b.exit_code()))117 }118 Err(e) => handle_cmd_error(None, e),119 }120 }121}122123/// Represents a multi-exec command as it is built.124#[derive(Debug)]125struct CommandBuilder {126 pre_args: Vec<OsString>,127 path_arg: FormatTemplate,128 post_args: Vec<OsString>,129 cmd: Command,130 count: usize,131 limit: usize,132 exit_code: ExitCode,133}134135impl CommandBuilder {136 fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {137 let mut pre_args = vec![];138 let mut path_arg = None;139 let mut post_args = vec![];140141 for arg in &template.args {142 if arg.has_tokens() {143 path_arg = Some(arg.clone());144 } else if path_arg.is_none() {145 pre_args.push(arg.generate("", None));146 } else {147 post_args.push(arg.generate("", None));148 }149 }150151 let cmd = Self::new_command(&pre_args)?;152153 Ok(Self {154 pre_args,155 path_arg: path_arg.unwrap(),156 post_args,157 cmd,158 count: 0,159 limit,160 exit_code: ExitCode::Success,161 })162 }163164 fn new_command(pre_args: &[OsString]) -> io::Result<Command> {165 let mut cmd = Command::new(&pre_args[0]);166 cmd.stdin(Stdio::inherit());167 cmd.stdout(Stdio::inherit());168 cmd.stderr(Stdio::inherit());169 cmd.try_args(&pre_args[1..])?;170 Ok(cmd)171 }172173 fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {174 if self.limit > 0 && self.count >= self.limit {175 self.finish()?;176 }177178 let arg = self.path_arg.generate(path, separator);179 if !self180 .cmd181 .args_would_fit(iter::once(&arg).chain(&self.post_args))182 {183 self.finish()?;184 }185186 self.cmd.try_arg(arg)?;187 self.count += 1;188 Ok(())189 }190191 fn finish(&mut self) -> io::Result<()> {192 if self.count > 0 {193 self.cmd.try_args(&self.post_args)?;194 if !self.cmd.status()?.success() {195 self.exit_code = ExitCode::GeneralError;196 }197198 self.cmd = Self::new_command(&self.pre_args)?;199 self.count = 0;200 }201202 Ok(())203 }204205 fn exit_code(&self) -> ExitCode {206 self.exit_code207 }208}209210/// Represents a template that is utilized to generate command strings.211///212/// The template is meant to be coupled with an input in order to generate a command. The213/// `generate_and_execute()` method will be used to generate a command and execute it.214#[derive(Debug, Clone, PartialEq)]215struct CommandTemplate {216 args: Vec<FormatTemplate>,217}218219impl CommandTemplate {220 fn new<I, S>(input: I) -> Result<CommandTemplate>221 where222 I: IntoIterator<Item = S>,223 S: AsRef<str>,224 {225 let mut args = Vec::new();226 let mut has_placeholder = false;227228 for arg in input {229 let arg = arg.as_ref();230231 let tmpl = FormatTemplate::parse(arg);232 has_placeholder |= tmpl.has_tokens();233 args.push(tmpl);234 }235236 // We need to check that we have at least one argument, because if not237 // it will try to execute each file and directory it finds.238 //239 // Sadly, clap can't currently handle this for us, see240 // https://github.com/clap-rs/clap/issues/3542241 if args.is_empty() {242 bail!("No executable provided for --exec or --exec-batch");243 }244245 if args[0].has_tokens() {246 bail!("First argument of --exec/--exec-batch must be a fixed executable, not a placeholder");247 }248249 // If a placeholder token was not supplied, append one at the end of the command.250 if !has_placeholder {251 args.push(FormatTemplate::Tokens(vec![Token::Placeholder]));252 }253254 Ok(CommandTemplate { args })255 }256257 fn number_of_tokens(&self) -> usize {258 self.args.iter().filter(|arg| arg.has_tokens()).count()259 }260261 /// Generates and executes a command.262 ///263 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be264 /// build.265 fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {266 let mut cmd = Command::new(self.args[0].generate(input, path_separator));267 for arg in &self.args[1..] {268 cmd.try_arg(arg.generate(input, path_separator))?;269 }270 Ok(cmd)271 }272}273274#[cfg(test)]275mod tests {276 use super::*;277278 fn generate_str(template: &CommandTemplate, input: &str) -> Vec<String> {279 template280 .args281 .iter()282 .map(|arg| arg.generate(input, None).into_string().unwrap())283 .collect()284 }285286 #[test]287 fn tokens_with_placeholder() {288 assert_eq!(289 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),290 CommandSet {291 commands: vec![CommandTemplate {292 args: vec![293 FormatTemplate::Text("echo".into()),294 FormatTemplate::Text("${SHELL}:".into()),295 FormatTemplate::Tokens(vec![Token::Placeholder]),296 ]297 }],298 mode: ExecutionMode::OneByOne,299 }300 );301 }302303 #[test]304 fn tokens_with_no_extension() {305 assert_eq!(306 CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),307 CommandSet {308 commands: vec![CommandTemplate {309 args: vec![310 FormatTemplate::Text("echo".into()),311 FormatTemplate::Tokens(vec![Token::NoExt]),312 ],313 }],314 mode: ExecutionMode::OneByOne,315 }316 );317 }318319 #[test]320 fn tokens_with_basename() {321 assert_eq!(322 CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),323 CommandSet {324 commands: vec![CommandTemplate {325 args: vec![326 FormatTemplate::Text("echo".into()),327 FormatTemplate::Tokens(vec![Token::Basename]),328 ],329 }],330 mode: ExecutionMode::OneByOne,331 }332 );333 }334335 #[test]336 fn tokens_with_parent() {337 assert_eq!(338 CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),339 CommandSet {340 commands: vec![CommandTemplate {341 args: vec![342 FormatTemplate::Text("echo".into()),343 FormatTemplate::Tokens(vec![Token::Parent]),344 ],345 }],346 mode: ExecutionMode::OneByOne,347 }348 );349 }350351 #[test]352 fn tokens_with_basename_no_extension() {353 assert_eq!(354 CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),355 CommandSet {356 commands: vec![CommandTemplate {357 args: vec![358 FormatTemplate::Text("echo".into()),359 FormatTemplate::Tokens(vec![Token::BasenameNoExt]),360 ],361 }],362 mode: ExecutionMode::OneByOne,363 }364 );365 }366367 #[test]368 fn tokens_with_literal_braces() {369 let template = CommandTemplate::new(vec!["{{}}", "{{", "{.}}"]).unwrap();370 assert_eq!(371 generate_str(&template, "foo"),372 vec!["{}", "{", "{.}", "foo"]373 );374 }375376 #[test]377 fn tokens_with_literal_braces_and_placeholder() {378 let template = CommandTemplate::new(vec!["echo", "{{{},end}"]).unwrap();379 assert_eq!(generate_str(&template, "foo"), vec!["echo", "{foo,end}"]);380 }381382 #[test]383 fn tokens_multiple() {384 assert_eq!(385 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),386 CommandSet {387 commands: vec![CommandTemplate {388 args: vec![389 FormatTemplate::Text("cp".into()),390 FormatTemplate::Tokens(vec![Token::Placeholder]),391 FormatTemplate::Tokens(vec![392 Token::BasenameNoExt,393 Token::Text(".ext".into())394 ]),395 ],396 }],397 mode: ExecutionMode::OneByOne,398 }399 );400 }401402 #[test]403 fn tokens_single_batch() {404 assert_eq!(405 CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),406 CommandSet {407 commands: vec![CommandTemplate {408 args: vec![409 FormatTemplate::Text("echo".into()),410 FormatTemplate::Tokens(vec![Token::NoExt]),411 ],412 }],413 mode: ExecutionMode::Batch,414 }415 );416 }417418 #[test]419 fn tokens_multiple_batch() {420 assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());421 }422423 #[test]424 fn template_no_args() {425 assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());426 }427428 #[test]429 fn command_set_no_args() {430 assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());431 }432433 #[test]434 fn placeholder_as_executable_rejected() {435 assert!(CommandSet::new(vec![vec!["{}"]]).is_err());436 assert!(CommandSet::new(vec![vec!["{/}", "arg"]]).is_err());437 assert!(CommandSet::new_batch(vec![vec!["{}"]]).is_err());438 }439440 #[test]441 fn generate_custom_path_separator() {442 let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);443 macro_rules! check {444 ($input:expr, $expected:expr) => {445 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));446 };447 }448449 check!("foo", "foo");450 check!("foo/bar", "foo#bar");451 check!("/foo/bar/baz", "#foo#bar#baz");452 }453454 #[cfg(windows)]455 #[test]456 fn generate_custom_path_separator_windows() {457 let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);458 macro_rules! check {459 ($input:expr, $expected:expr) => {460 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));461 };462 }463464 // path starting with a drive letter465 check!(r"C:\foo\bar", "C:#foo#bar");466 // UNC path467 check!(r"\\server\share\path", "##server#share#path");468 // Drive Relative path - no separator after the colon omits the RootDir path component.469 // This is uncommon, but valid470 check!(r"C:foo\bar", "C:foo#bar");471472 // forward slashes should get normalized and interpreted as separators473 check!("C:/foo/bar", "C:#foo#bar");474 check!("C:foo/bar", "C:foo#bar");475476 // Rust does not interpret "//server/share" as a UNC path, but rather as a normal477 // absolute path that begins with RootDir, and the two slashes get combined together as478 // a single path separator during normalization.479 //check!("//server/share/path", "##server#share#path");480 }481}