mod.rs
This file
Path
src/exec/mod.rs
596 lines · 19.4 KiB · Rust
Last changed by
Merge pull request #1244 from tmccombs/grouped-occurrencesDavid Peterbefore adoption73a693e
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, T, S>(input: I) -> Result<CommandSet>43 where44 I: IntoIterator<Item = T>,45 T: IntoIterator<Item = S>,46 S: AsRef<str>,47 {48 Ok(CommandSet {49 mode: ExecutionMode::OneByOne,50 commands: input51 .into_iter()52 .map(CommandTemplate::new)53 .collect::<Result<_>>()?,54 })55 }5657 pub fn new_batch<I, T, S>(input: I) -> Result<CommandSet>58 where59 I: IntoIterator<Item = T>,60 T: IntoIterator<Item = S>,61 S: AsRef<str>,62 {63 Ok(CommandSet {64 mode: ExecutionMode::Batch,65 commands: input66 .into_iter()67 .map(|args| {68 let cmd = CommandTemplate::new(args)?;69 if cmd.number_of_tokens() > 1 {70 bail!("Only one placeholder allowed for batch commands");71 }72 if cmd.args[0].has_tokens() {73 bail!("First argument of exec-batch is expected to be a fixed executable");74 }75 Ok(cmd)76 })77 .collect::<Result<Vec<_>>>()?,78 })79 }8081 pub fn in_batch_mode(&self) -> bool {82 self.mode == ExecutionMode::Batch83 }8485 pub fn execute(86 &self,87 input: &Path,88 path_separator: Option<&str>,89 out_perm: Arc<Mutex<()>>,90 buffer_output: bool,91 ) -> ExitCode {92 let commands = self93 .commands94 .iter()95 .map(|c| c.generate(input, path_separator));96 execute_commands(commands, &out_perm, buffer_output)97 }9899 pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode100 where101 I: Iterator<Item = PathBuf>,102 {103 let builders: io::Result<Vec<_>> = self104 .commands105 .iter()106 .map(|c| CommandBuilder::new(c, limit))107 .collect();108109 match builders {110 Ok(mut builders) => {111 for path in paths {112 for builder in &mut builders {113 if let Err(e) = builder.push(&path, path_separator) {114 return handle_cmd_error(Some(&builder.cmd), e);115 }116 }117 }118119 for builder in &mut builders {120 if let Err(e) = builder.finish() {121 return handle_cmd_error(Some(&builder.cmd), e);122 }123 }124125 merge_exitcodes(builders.iter().map(|b| b.exit_code()))126 }127 Err(e) => handle_cmd_error(None, e),128 }129 }130}131132/// Represents a multi-exec command as it is built.133#[derive(Debug)]134struct CommandBuilder {135 pre_args: Vec<OsString>,136 path_arg: ArgumentTemplate,137 post_args: Vec<OsString>,138 cmd: Command,139 count: usize,140 limit: usize,141 exit_code: ExitCode,142}143144impl CommandBuilder {145 fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {146 let mut pre_args = vec![];147 let mut path_arg = None;148 let mut post_args = vec![];149150 for arg in &template.args {151 if arg.has_tokens() {152 path_arg = Some(arg.clone());153 } else if path_arg.is_none() {154 pre_args.push(arg.generate("", None));155 } else {156 post_args.push(arg.generate("", None));157 }158 }159160 let cmd = Self::new_command(&pre_args)?;161162 Ok(Self {163 pre_args,164 path_arg: path_arg.unwrap(),165 post_args,166 cmd,167 count: 0,168 limit,169 exit_code: ExitCode::Success,170 })171 }172173 fn new_command(pre_args: &[OsString]) -> io::Result<Command> {174 let mut cmd = Command::new(&pre_args[0]);175 cmd.stdin(Stdio::inherit());176 cmd.stdout(Stdio::inherit());177 cmd.stderr(Stdio::inherit());178 cmd.try_args(&pre_args[1..])?;179 Ok(cmd)180 }181182 fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {183 if self.limit > 0 && self.count >= self.limit {184 self.finish()?;185 }186187 let arg = self.path_arg.generate(path, separator);188 if !self189 .cmd190 .args_would_fit(iter::once(&arg).chain(&self.post_args))191 {192 self.finish()?;193 }194195 self.cmd.try_arg(arg)?;196 self.count += 1;197 Ok(())198 }199200 fn finish(&mut self) -> io::Result<()> {201 if self.count > 0 {202 self.cmd.try_args(&self.post_args)?;203 if !self.cmd.status()?.success() {204 self.exit_code = ExitCode::GeneralError;205 }206207 self.cmd = Self::new_command(&self.pre_args)?;208 self.count = 0;209 }210211 Ok(())212 }213214 fn exit_code(&self) -> ExitCode {215 self.exit_code216 }217}218219/// Represents a template that is utilized to generate command strings.220///221/// The template is meant to be coupled with an input in order to generate a command. The222/// `generate_and_execute()` method will be used to generate a command and execute it.223#[derive(Debug, Clone, PartialEq)]224struct CommandTemplate {225 args: Vec<ArgumentTemplate>,226}227228impl CommandTemplate {229 fn new<I, S>(input: I) -> Result<CommandTemplate>230 where231 I: IntoIterator<Item = S>,232 S: AsRef<str>,233 {234 static PLACEHOLDER_PATTERN: Lazy<Regex> =235 Lazy::new(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());236237 let mut args = Vec::new();238 let mut has_placeholder = false;239240 for arg in input {241 let arg = arg.as_ref();242243 let mut tokens = Vec::new();244 let mut start = 0;245246 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {247 // Leading text before the placeholder.248 if placeholder.start() > start {249 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));250 }251252 start = placeholder.end();253254 match placeholder.as_str() {255 "{}" => tokens.push(Token::Placeholder),256 "{.}" => tokens.push(Token::NoExt),257 "{/}" => tokens.push(Token::Basename),258 "{//}" => tokens.push(Token::Parent),259 "{/.}" => tokens.push(Token::BasenameNoExt),260 _ => unreachable!("Unhandled placeholder"),261 }262263 has_placeholder = true;264 }265266 // Without a placeholder, the argument is just fixed text.267 if tokens.is_empty() {268 args.push(ArgumentTemplate::Text(arg.to_owned()));269 continue;270 }271272 if start < arg.len() {273 // Trailing text after last placeholder.274 tokens.push(Token::Text(arg[start..].to_owned()));275 }276277 args.push(ArgumentTemplate::Tokens(tokens));278 }279280 // We need to check that we have at least one argument, because if not281 // it will try to execute each file and directory it finds.282 //283 // Sadly, clap can't currently handle this for us, see284 // https://github.com/clap-rs/clap/issues/3542285 if args.is_empty() {286 bail!("No executable provided for --exec or --exec-batch");287 }288289 // If a placeholder token was not supplied, append one at the end of the command.290 if !has_placeholder {291 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));292 }293294 Ok(CommandTemplate { args })295 }296297 fn number_of_tokens(&self) -> usize {298 self.args.iter().filter(|arg| arg.has_tokens()).count()299 }300301 /// Generates and executes a command.302 ///303 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be304 /// build.305 fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {306 let mut cmd = Command::new(self.args[0].generate(input, path_separator));307 for arg in &self.args[1..] {308 cmd.try_arg(arg.generate(input, path_separator))?;309 }310 Ok(cmd)311 }312}313314/// Represents a template for a single command argument.315///316/// The argument is either a collection of `Token`s including at least one placeholder variant, or317/// a fixed text.318#[derive(Clone, Debug, PartialEq)]319enum ArgumentTemplate {320 Tokens(Vec<Token>),321 Text(String),322}323324impl ArgumentTemplate {325 pub fn has_tokens(&self) -> bool {326 matches!(self, ArgumentTemplate::Tokens(_))327 }328329 /// Generate an argument from this template. If path_separator is Some, then it will replace330 /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by331 /// path separator substitution.332 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {333 use self::Token::*;334 let path = path.as_ref();335336 match *self {337 ArgumentTemplate::Tokens(ref tokens) => {338 let mut s = OsString::new();339 for token in tokens {340 match *token {341 Basename => s.push(Self::replace_separator(basename(path), path_separator)),342 BasenameNoExt => s.push(Self::replace_separator(343 &remove_extension(basename(path).as_ref()),344 path_separator,345 )),346 NoExt => s.push(Self::replace_separator(347 &remove_extension(path),348 path_separator,349 )),350 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),351 Placeholder => {352 s.push(Self::replace_separator(path.as_ref(), path_separator))353 }354 Text(ref string) => s.push(string),355 }356 }357 s358 }359 ArgumentTemplate::Text(ref text) => OsString::from(text),360 }361 }362363 /// Replace the path separator in the input with the custom separator string. If path_separator364 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is365 /// interpreted as a Path and its components are iterated through and re-joined into a new366 /// OsString.367 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {368 // fast-path - no replacement necessary369 if path_separator.is_none() {370 return Cow::Borrowed(path);371 }372373 let path_separator = path_separator.unwrap();374 let mut out = OsString::with_capacity(path.len());375 let mut components = Path::new(path).components().peekable();376377 while let Some(comp) = components.next() {378 match comp {379 // Absolute paths on Windows are tricky. A Prefix component is usually a drive380 // letter or UNC path, and is usually followed by RootDir. There are also381 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to382 // ignore verbatim path prefixes here because they're very rare, might be383 // impossible to reach here, and there's no good way to deal with them. If users384 // are doing something advanced involving verbatim windows paths, they can do their385 // own output filtering with a tool like sed.386 Component::Prefix(prefix) => {387 if let Prefix::UNC(server, share) = prefix.kind() {388 // Prefix::UNC is a parsed version of '\\server\share'389 out.push(path_separator);390 out.push(path_separator);391 out.push(server);392 out.push(path_separator);393 out.push(share);394 } else {395 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for396 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,397 // but they're not returned by directories fd can search anyway so we don't worry398 // about them.399 out.push(comp.as_os_str());400 }401 }402403 // Root directory is always replaced with the custom separator.404 Component::RootDir => out.push(path_separator),405406 // Everything else is joined normally, with a trailing separator if we're not last407 _ => {408 out.push(comp.as_os_str());409 if components.peek().is_some() {410 out.push(path_separator);411 }412 }413 }414 }415 Cow::Owned(out)416 }417}418419#[cfg(test)]420mod tests {421 use super::*;422423 #[test]424 fn tokens_with_placeholder() {425 assert_eq!(426 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),427 CommandSet {428 commands: vec![CommandTemplate {429 args: vec![430 ArgumentTemplate::Text("echo".into()),431 ArgumentTemplate::Text("${SHELL}:".into()),432 ArgumentTemplate::Tokens(vec![Token::Placeholder]),433 ]434 }],435 mode: ExecutionMode::OneByOne,436 }437 );438 }439440 #[test]441 fn tokens_with_no_extension() {442 assert_eq!(443 CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),444 CommandSet {445 commands: vec![CommandTemplate {446 args: vec![447 ArgumentTemplate::Text("echo".into()),448 ArgumentTemplate::Tokens(vec![Token::NoExt]),449 ],450 }],451 mode: ExecutionMode::OneByOne,452 }453 );454 }455456 #[test]457 fn tokens_with_basename() {458 assert_eq!(459 CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),460 CommandSet {461 commands: vec![CommandTemplate {462 args: vec![463 ArgumentTemplate::Text("echo".into()),464 ArgumentTemplate::Tokens(vec![Token::Basename]),465 ],466 }],467 mode: ExecutionMode::OneByOne,468 }469 );470 }471472 #[test]473 fn tokens_with_parent() {474 assert_eq!(475 CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),476 CommandSet {477 commands: vec![CommandTemplate {478 args: vec![479 ArgumentTemplate::Text("echo".into()),480 ArgumentTemplate::Tokens(vec![Token::Parent]),481 ],482 }],483 mode: ExecutionMode::OneByOne,484 }485 );486 }487488 #[test]489 fn tokens_with_basename_no_extension() {490 assert_eq!(491 CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),492 CommandSet {493 commands: vec![CommandTemplate {494 args: vec![495 ArgumentTemplate::Text("echo".into()),496 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),497 ],498 }],499 mode: ExecutionMode::OneByOne,500 }501 );502 }503504 #[test]505 fn tokens_multiple() {506 assert_eq!(507 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),508 CommandSet {509 commands: vec![CommandTemplate {510 args: vec![511 ArgumentTemplate::Text("cp".into()),512 ArgumentTemplate::Tokens(vec![Token::Placeholder]),513 ArgumentTemplate::Tokens(vec![514 Token::BasenameNoExt,515 Token::Text(".ext".into())516 ]),517 ],518 }],519 mode: ExecutionMode::OneByOne,520 }521 );522 }523524 #[test]525 fn tokens_single_batch() {526 assert_eq!(527 CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),528 CommandSet {529 commands: vec![CommandTemplate {530 args: vec![531 ArgumentTemplate::Text("echo".into()),532 ArgumentTemplate::Tokens(vec![Token::NoExt]),533 ],534 }],535 mode: ExecutionMode::Batch,536 }537 );538 }539540 #[test]541 fn tokens_multiple_batch() {542 assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());543 }544545 #[test]546 fn template_no_args() {547 assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());548 }549550 #[test]551 fn command_set_no_args() {552 assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());553 }554555 #[test]556 fn generate_custom_path_separator() {557 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);558 macro_rules! check {559 ($input:expr, $expected:expr) => {560 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));561 };562 }563564 check!("foo", "foo");565 check!("foo/bar", "foo#bar");566 check!("/foo/bar/baz", "#foo#bar#baz");567 }568569 #[cfg(windows)]570 #[test]571 fn generate_custom_path_separator_windows() {572 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);573 macro_rules! check {574 ($input:expr, $expected:expr) => {575 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));576 };577 }578579 // path starting with a drive letter580 check!(r"C:\foo\bar", "C:#foo#bar");581 // UNC path582 check!(r"\\server\share\path", "##server#share#path");583 // Drive Relative path - no separator after the colon omits the RootDir path component.584 // This is uncommon, but valid585 check!(r"C:foo\bar", "C:foo#bar");586587 // forward slashes should get normalized and interpreted as separators588 check!("C:/foo/bar", "C:#foo#bar");589 check!("C:foo/bar", "C:foo#bar");590591 // Rust does not interpret "//server/share" as a UNC path, but rather as a normal592 // absolute path that begins with RootDir, and the two slashes get combined together as593 // a single path separator during normalization.594 //check!("//server/share/path", "##server#share#path");595 }596}