mod.rs
This file
Path
src/exec/mod.rs
594 lines · 19.3 KiB · Rust
Last changed by
Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
History of this fileTake it
1mod command;2mod input;3mod job;4mod token;56use std::borrow::Cow;7use std::ffi::{OsStr, OsString};8use std::io;9use std::iter;10use std::path::{Component, Path, PathBuf, Prefix};11use std::process::Stdio;12use std::sync::{Arc, Mutex};1314use anyhow::{bail, Result};15use argmax::Command;16use once_cell::sync::Lazy;17use regex::Regex;1819use crate::exit_codes::{merge_exitcodes, ExitCode};2021use self::command::{execute_commands, handle_cmd_error};22use self::input::{basename, dirname, remove_extension};23pub use self::job::{batch, job};24use self::token::Token;2526/// Execution mode of the command27#[derive(Debug, Clone, Copy, PartialEq, Eq)]28pub enum ExecutionMode {29 /// Command is executed for each search result30 OneByOne,31 /// Command is run for a batch of results at once32 Batch,33}3435#[derive(Debug, Clone, PartialEq)]36pub struct CommandSet {37 mode: ExecutionMode,38 commands: Vec<CommandTemplate>,39}4041impl CommandSet {42 pub fn new<I, S>(input: I) -> Result<CommandSet>43 where44 I: IntoIterator<Item = Vec<S>>,45 S: AsRef<str>,46 {47 Ok(CommandSet {48 mode: ExecutionMode::OneByOne,49 commands: input50 .into_iter()51 .map(CommandTemplate::new)52 .collect::<Result<_>>()?,53 })54 }5556 pub fn new_batch<I, S>(input: I) -> Result<CommandSet>57 where58 I: IntoIterator<Item = Vec<S>>,59 S: AsRef<str>,60 {61 Ok(CommandSet {62 mode: ExecutionMode::Batch,63 commands: input64 .into_iter()65 .map(|args| {66 let cmd = CommandTemplate::new(args)?;67 if cmd.number_of_tokens() > 1 {68 bail!("Only one placeholder allowed for batch commands");69 }70 if cmd.args[0].has_tokens() {71 bail!("First argument of exec-batch is expected to be a fixed executable");72 }73 Ok(cmd)74 })75 .collect::<Result<Vec<_>>>()?,76 })77 }7879 pub fn in_batch_mode(&self) -> bool {80 self.mode == ExecutionMode::Batch81 }8283 pub fn execute(84 &self,85 input: &Path,86 path_separator: Option<&str>,87 out_perm: Arc<Mutex<()>>,88 buffer_output: bool,89 ) -> ExitCode {90 let commands = self91 .commands92 .iter()93 .map(|c| c.generate(input, path_separator));94 execute_commands(commands, &out_perm, buffer_output)95 }9697 pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode98 where99 I: Iterator<Item = PathBuf>,100 {101 let builders: io::Result<Vec<_>> = self102 .commands103 .iter()104 .map(|c| CommandBuilder::new(c, limit))105 .collect();106107 match builders {108 Ok(mut builders) => {109 for path in paths {110 for builder in &mut builders {111 if let Err(e) = builder.push(&path, path_separator) {112 return handle_cmd_error(Some(&builder.cmd), e);113 }114 }115 }116117 for builder in &mut builders {118 if let Err(e) = builder.finish() {119 return handle_cmd_error(Some(&builder.cmd), e);120 }121 }122123 merge_exitcodes(builders.iter().map(|b| b.exit_code()))124 }125 Err(e) => handle_cmd_error(None, e),126 }127 }128}129130/// Represents a multi-exec command as it is built.131#[derive(Debug)]132struct CommandBuilder {133 pre_args: Vec<OsString>,134 path_arg: ArgumentTemplate,135 post_args: Vec<OsString>,136 cmd: Command,137 count: usize,138 limit: usize,139 exit_code: ExitCode,140}141142impl CommandBuilder {143 fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {144 let mut pre_args = vec![];145 let mut path_arg = None;146 let mut post_args = vec![];147148 for arg in &template.args {149 if arg.has_tokens() {150 path_arg = Some(arg.clone());151 } else if path_arg == None {152 pre_args.push(arg.generate("", None));153 } else {154 post_args.push(arg.generate("", None));155 }156 }157158 let cmd = Self::new_command(&pre_args)?;159160 Ok(Self {161 pre_args,162 path_arg: path_arg.unwrap(),163 post_args,164 cmd,165 count: 0,166 limit,167 exit_code: ExitCode::Success,168 })169 }170171 fn new_command(pre_args: &[OsString]) -> io::Result<Command> {172 let mut cmd = Command::new(&pre_args[0]);173 cmd.stdin(Stdio::inherit());174 cmd.stdout(Stdio::inherit());175 cmd.stderr(Stdio::inherit());176 cmd.try_args(&pre_args[1..])?;177 Ok(cmd)178 }179180 fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {181 if self.limit > 0 && self.count >= self.limit {182 self.finish()?;183 }184185 let arg = self.path_arg.generate(path, separator);186 if !self187 .cmd188 .args_would_fit(iter::once(&arg).chain(&self.post_args))189 {190 self.finish()?;191 }192193 self.cmd.try_arg(arg)?;194 self.count += 1;195 Ok(())196 }197198 fn finish(&mut self) -> io::Result<()> {199 if self.count > 0 {200 self.cmd.try_args(&self.post_args)?;201 if !self.cmd.status()?.success() {202 self.exit_code = ExitCode::GeneralError;203 }204205 self.cmd = Self::new_command(&self.pre_args)?;206 self.count = 0;207 }208209 Ok(())210 }211212 fn exit_code(&self) -> ExitCode {213 self.exit_code214 }215}216217/// Represents a template that is utilized to generate command strings.218///219/// The template is meant to be coupled with an input in order to generate a command. The220/// `generate_and_execute()` method will be used to generate a command and execute it.221#[derive(Debug, Clone, PartialEq)]222struct CommandTemplate {223 args: Vec<ArgumentTemplate>,224}225226impl CommandTemplate {227 fn new<I, S>(input: I) -> Result<CommandTemplate>228 where229 I: IntoIterator<Item = S>,230 S: AsRef<str>,231 {232 static PLACEHOLDER_PATTERN: Lazy<Regex> =233 Lazy::new(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());234235 let mut args = Vec::new();236 let mut has_placeholder = false;237238 for arg in input {239 let arg = arg.as_ref();240241 let mut tokens = Vec::new();242 let mut start = 0;243244 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {245 // Leading text before the placeholder.246 if placeholder.start() > start {247 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));248 }249250 start = placeholder.end();251252 match placeholder.as_str() {253 "{}" => tokens.push(Token::Placeholder),254 "{.}" => tokens.push(Token::NoExt),255 "{/}" => tokens.push(Token::Basename),256 "{//}" => tokens.push(Token::Parent),257 "{/.}" => tokens.push(Token::BasenameNoExt),258 _ => unreachable!("Unhandled placeholder"),259 }260261 has_placeholder = true;262 }263264 // Without a placeholder, the argument is just fixed text.265 if tokens.is_empty() {266 args.push(ArgumentTemplate::Text(arg.to_owned()));267 continue;268 }269270 if start < arg.len() {271 // Trailing text after last placeholder.272 tokens.push(Token::Text(arg[start..].to_owned()));273 }274275 args.push(ArgumentTemplate::Tokens(tokens));276 }277278 // We need to check that we have at least one argument, because if not279 // it will try to execute each file and directory it finds.280 //281 // Sadly, clap can't currently handle this for us, see282 // https://github.com/clap-rs/clap/issues/3542283 if args.is_empty() {284 bail!("No executable provided for --exec or --exec-batch");285 }286287 // If a placeholder token was not supplied, append one at the end of the command.288 if !has_placeholder {289 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));290 }291292 Ok(CommandTemplate { args })293 }294295 fn number_of_tokens(&self) -> usize {296 self.args.iter().filter(|arg| arg.has_tokens()).count()297 }298299 /// Generates and executes a command.300 ///301 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be302 /// build.303 fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {304 let mut cmd = Command::new(self.args[0].generate(&input, path_separator));305 for arg in &self.args[1..] {306 cmd.try_arg(arg.generate(&input, path_separator))?;307 }308 Ok(cmd)309 }310}311312/// Represents a template for a single command argument.313///314/// The argument is either a collection of `Token`s including at least one placeholder variant, or315/// a fixed text.316#[derive(Clone, Debug, PartialEq)]317enum ArgumentTemplate {318 Tokens(Vec<Token>),319 Text(String),320}321322impl ArgumentTemplate {323 pub fn has_tokens(&self) -> bool {324 matches!(self, ArgumentTemplate::Tokens(_))325 }326327 /// Generate an argument from this template. If path_separator is Some, then it will replace328 /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by329 /// path separator substitution.330 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {331 use self::Token::*;332 let path = path.as_ref();333334 match *self {335 ArgumentTemplate::Tokens(ref tokens) => {336 let mut s = OsString::new();337 for token in tokens {338 match *token {339 Basename => s.push(Self::replace_separator(basename(path), path_separator)),340 BasenameNoExt => s.push(Self::replace_separator(341 &remove_extension(basename(path).as_ref()),342 path_separator,343 )),344 NoExt => s.push(Self::replace_separator(345 &remove_extension(path),346 path_separator,347 )),348 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),349 Placeholder => {350 s.push(Self::replace_separator(path.as_ref(), path_separator))351 }352 Text(ref string) => s.push(string),353 }354 }355 s356 }357 ArgumentTemplate::Text(ref text) => OsString::from(text),358 }359 }360361 /// Replace the path separator in the input with the custom separator string. If path_separator362 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is363 /// interpreted as a Path and its components are iterated through and re-joined into a new364 /// OsString.365 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {366 // fast-path - no replacement necessary367 if path_separator.is_none() {368 return Cow::Borrowed(path);369 }370371 let path_separator = path_separator.unwrap();372 let mut out = OsString::with_capacity(path.len());373 let mut components = Path::new(path).components().peekable();374375 while let Some(comp) = components.next() {376 match comp {377 // Absolute paths on Windows are tricky. A Prefix component is usually a drive378 // letter or UNC path, and is usually followed by RootDir. There are also379 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to380 // ignore verbatim path prefixes here because they're very rare, might be381 // impossible to reach here, and there's no good way to deal with them. If users382 // are doing something advanced involving verbatim windows paths, they can do their383 // own output filtering with a tool like sed.384 Component::Prefix(prefix) => {385 if let Prefix::UNC(server, share) = prefix.kind() {386 // Prefix::UNC is a parsed version of '\\server\share'387 out.push(path_separator);388 out.push(path_separator);389 out.push(server);390 out.push(path_separator);391 out.push(share);392 } else {393 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for394 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,395 // but they're not returned by directories fd can search anyway so we don't worry396 // about them.397 out.push(comp.as_os_str());398 }399 }400401 // Root directory is always replaced with the custom separator.402 Component::RootDir => out.push(path_separator),403404 // Everything else is joined normally, with a trailing separator if we're not last405 _ => {406 out.push(comp.as_os_str());407 if components.peek().is_some() {408 out.push(path_separator);409 }410 }411 }412 }413 Cow::Owned(out)414 }415}416417#[cfg(test)]418mod tests {419 use super::*;420421 #[test]422 fn tokens_with_placeholder() {423 assert_eq!(424 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),425 CommandSet {426 commands: vec![CommandTemplate {427 args: vec![428 ArgumentTemplate::Text("echo".into()),429 ArgumentTemplate::Text("${SHELL}:".into()),430 ArgumentTemplate::Tokens(vec![Token::Placeholder]),431 ]432 }],433 mode: ExecutionMode::OneByOne,434 }435 );436 }437438 #[test]439 fn tokens_with_no_extension() {440 assert_eq!(441 CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),442 CommandSet {443 commands: vec![CommandTemplate {444 args: vec![445 ArgumentTemplate::Text("echo".into()),446 ArgumentTemplate::Tokens(vec![Token::NoExt]),447 ],448 }],449 mode: ExecutionMode::OneByOne,450 }451 );452 }453454 #[test]455 fn tokens_with_basename() {456 assert_eq!(457 CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),458 CommandSet {459 commands: vec![CommandTemplate {460 args: vec![461 ArgumentTemplate::Text("echo".into()),462 ArgumentTemplate::Tokens(vec![Token::Basename]),463 ],464 }],465 mode: ExecutionMode::OneByOne,466 }467 );468 }469470 #[test]471 fn tokens_with_parent() {472 assert_eq!(473 CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),474 CommandSet {475 commands: vec![CommandTemplate {476 args: vec![477 ArgumentTemplate::Text("echo".into()),478 ArgumentTemplate::Tokens(vec![Token::Parent]),479 ],480 }],481 mode: ExecutionMode::OneByOne,482 }483 );484 }485486 #[test]487 fn tokens_with_basename_no_extension() {488 assert_eq!(489 CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),490 CommandSet {491 commands: vec![CommandTemplate {492 args: vec![493 ArgumentTemplate::Text("echo".into()),494 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),495 ],496 }],497 mode: ExecutionMode::OneByOne,498 }499 );500 }501502 #[test]503 fn tokens_multiple() {504 assert_eq!(505 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),506 CommandSet {507 commands: vec![CommandTemplate {508 args: vec![509 ArgumentTemplate::Text("cp".into()),510 ArgumentTemplate::Tokens(vec![Token::Placeholder]),511 ArgumentTemplate::Tokens(vec![512 Token::BasenameNoExt,513 Token::Text(".ext".into())514 ]),515 ],516 }],517 mode: ExecutionMode::OneByOne,518 }519 );520 }521522 #[test]523 fn tokens_single_batch() {524 assert_eq!(525 CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),526 CommandSet {527 commands: vec![CommandTemplate {528 args: vec![529 ArgumentTemplate::Text("echo".into()),530 ArgumentTemplate::Tokens(vec![Token::NoExt]),531 ],532 }],533 mode: ExecutionMode::Batch,534 }535 );536 }537538 #[test]539 fn tokens_multiple_batch() {540 assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());541 }542543 #[test]544 fn template_no_args() {545 assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());546 }547548 #[test]549 fn command_set_no_args() {550 assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());551 }552553 #[test]554 fn generate_custom_path_separator() {555 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);556 macro_rules! check {557 ($input:expr, $expected:expr) => {558 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));559 };560 }561562 check!("foo", "foo");563 check!("foo/bar", "foo#bar");564 check!("/foo/bar/baz", "#foo#bar#baz");565 }566567 #[cfg(windows)]568 #[test]569 fn generate_custom_path_separator_windows() {570 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);571 macro_rules! check {572 ($input:expr, $expected:expr) => {573 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));574 };575 }576577 // path starting with a drive letter578 check!(r"C:\foo\bar", "C:#foo#bar");579 // UNC path580 check!(r"\\server\share\path", "##server#share#path");581 // Drive Relative path - no separator after the colon omits the RootDir path component.582 // This is uncommon, but valid583 check!(r"C:foo\bar", "C:foo#bar");584585 // forward slashes should get normalized and interpreted as separators586 check!("C:/foo/bar", "C:#foo#bar");587 check!("C:foo/bar", "C:foo#bar");588589 // Rust does not interpret "//server/share" as a UNC path, but rather as a normal590 // absolute path that begins with RootDir, and the two slashes get combined together as591 // a single path separator during normalization.592 //check!("//server/share/path", "##server#share#path");593 }594}