mod.rs
This file
Path
src/exec/mod.rs
597 lines · 19.4 KiB · Rust
Last changed by
Merge pull request #1333 from tmccombs/rust-170Thayne McCombsbefore adoptiona0370aa
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::{Mutex, OnceLock};1314use anyhow::{bail, Result};15use argmax::Command;16use regex::Regex;1718use crate::exit_codes::{merge_exitcodes, ExitCode};1920use self::command::{execute_commands, handle_cmd_error};21use self::input::{basename, dirname, remove_extension};22pub use self::job::{batch, job};23use self::token::Token;2425/// Execution mode of the command26#[derive(Debug, Clone, Copy, PartialEq, Eq)]27pub enum ExecutionMode {28 /// Command is executed for each search result29 OneByOne,30 /// Command is run for a batch of results at once31 Batch,32}3334#[derive(Debug, Clone, PartialEq)]35pub struct CommandSet {36 mode: ExecutionMode,37 commands: Vec<CommandTemplate>,38}3940impl CommandSet {41 pub fn new<I, T, S>(input: I) -> Result<CommandSet>42 where43 I: IntoIterator<Item = T>,44 T: IntoIterator<Item = 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, T, S>(input: I) -> Result<CommandSet>57 where58 I: IntoIterator<Item = T>,59 T: IntoIterator<Item = S>,60 S: AsRef<str>,61 {62 Ok(CommandSet {63 mode: ExecutionMode::Batch,64 commands: input65 .into_iter()66 .map(|args| {67 let cmd = CommandTemplate::new(args)?;68 if cmd.number_of_tokens() > 1 {69 bail!("Only one placeholder allowed for batch commands");70 }71 if cmd.args[0].has_tokens() {72 bail!("First argument of exec-batch is expected to be a fixed executable");73 }74 Ok(cmd)75 })76 .collect::<Result<Vec<_>>>()?,77 })78 }7980 pub fn in_batch_mode(&self) -> bool {81 self.mode == ExecutionMode::Batch82 }8384 pub fn execute(85 &self,86 input: &Path,87 path_separator: Option<&str>,88 out_perm: &Mutex<()>,89 buffer_output: bool,90 ) -> ExitCode {91 let commands = self92 .commands93 .iter()94 .map(|c| c.generate(input, path_separator));95 execute_commands(commands, out_perm, buffer_output)96 }9798 pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode99 where100 I: Iterator<Item = PathBuf>,101 {102 let builders: io::Result<Vec<_>> = self103 .commands104 .iter()105 .map(|c| CommandBuilder::new(c, limit))106 .collect();107108 match builders {109 Ok(mut builders) => {110 for path in paths {111 for builder in &mut builders {112 if let Err(e) = builder.push(&path, path_separator) {113 return handle_cmd_error(Some(&builder.cmd), e);114 }115 }116 }117118 for builder in &mut builders {119 if let Err(e) = builder.finish() {120 return handle_cmd_error(Some(&builder.cmd), e);121 }122 }123124 merge_exitcodes(builders.iter().map(|b| b.exit_code()))125 }126 Err(e) => handle_cmd_error(None, e),127 }128 }129}130131/// Represents a multi-exec command as it is built.132#[derive(Debug)]133struct CommandBuilder {134 pre_args: Vec<OsString>,135 path_arg: ArgumentTemplate,136 post_args: Vec<OsString>,137 cmd: Command,138 count: usize,139 limit: usize,140 exit_code: ExitCode,141}142143impl CommandBuilder {144 fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {145 let mut pre_args = vec![];146 let mut path_arg = None;147 let mut post_args = vec![];148149 for arg in &template.args {150 if arg.has_tokens() {151 path_arg = Some(arg.clone());152 } else if path_arg.is_none() {153 pre_args.push(arg.generate("", None));154 } else {155 post_args.push(arg.generate("", None));156 }157 }158159 let cmd = Self::new_command(&pre_args)?;160161 Ok(Self {162 pre_args,163 path_arg: path_arg.unwrap(),164 post_args,165 cmd,166 count: 0,167 limit,168 exit_code: ExitCode::Success,169 })170 }171172 fn new_command(pre_args: &[OsString]) -> io::Result<Command> {173 let mut cmd = Command::new(&pre_args[0]);174 cmd.stdin(Stdio::inherit());175 cmd.stdout(Stdio::inherit());176 cmd.stderr(Stdio::inherit());177 cmd.try_args(&pre_args[1..])?;178 Ok(cmd)179 }180181 fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {182 if self.limit > 0 && self.count >= self.limit {183 self.finish()?;184 }185186 let arg = self.path_arg.generate(path, separator);187 if !self188 .cmd189 .args_would_fit(iter::once(&arg).chain(&self.post_args))190 {191 self.finish()?;192 }193194 self.cmd.try_arg(arg)?;195 self.count += 1;196 Ok(())197 }198199 fn finish(&mut self) -> io::Result<()> {200 if self.count > 0 {201 self.cmd.try_args(&self.post_args)?;202 if !self.cmd.status()?.success() {203 self.exit_code = ExitCode::GeneralError;204 }205206 self.cmd = Self::new_command(&self.pre_args)?;207 self.count = 0;208 }209210 Ok(())211 }212213 fn exit_code(&self) -> ExitCode {214 self.exit_code215 }216}217218/// Represents a template that is utilized to generate command strings.219///220/// The template is meant to be coupled with an input in order to generate a command. The221/// `generate_and_execute()` method will be used to generate a command and execute it.222#[derive(Debug, Clone, PartialEq)]223struct CommandTemplate {224 args: Vec<ArgumentTemplate>,225}226227impl CommandTemplate {228 fn new<I, S>(input: I) -> Result<CommandTemplate>229 where230 I: IntoIterator<Item = S>,231 S: AsRef<str>,232 {233 static PLACEHOLDER_PATTERN: OnceLock<Regex> = OnceLock::new();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 let pattern =245 PLACEHOLDER_PATTERN.get_or_init(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());246247 for placeholder in pattern.find_iter(arg) {248 // Leading text before the placeholder.249 if placeholder.start() > start {250 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));251 }252253 start = placeholder.end();254255 match placeholder.as_str() {256 "{}" => tokens.push(Token::Placeholder),257 "{.}" => tokens.push(Token::NoExt),258 "{/}" => tokens.push(Token::Basename),259 "{//}" => tokens.push(Token::Parent),260 "{/.}" => tokens.push(Token::BasenameNoExt),261 _ => unreachable!("Unhandled placeholder"),262 }263264 has_placeholder = true;265 }266267 // Without a placeholder, the argument is just fixed text.268 if tokens.is_empty() {269 args.push(ArgumentTemplate::Text(arg.to_owned()));270 continue;271 }272273 if start < arg.len() {274 // Trailing text after last placeholder.275 tokens.push(Token::Text(arg[start..].to_owned()));276 }277278 args.push(ArgumentTemplate::Tokens(tokens));279 }280281 // We need to check that we have at least one argument, because if not282 // it will try to execute each file and directory it finds.283 //284 // Sadly, clap can't currently handle this for us, see285 // https://github.com/clap-rs/clap/issues/3542286 if args.is_empty() {287 bail!("No executable provided for --exec or --exec-batch");288 }289290 // If a placeholder token was not supplied, append one at the end of the command.291 if !has_placeholder {292 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));293 }294295 Ok(CommandTemplate { args })296 }297298 fn number_of_tokens(&self) -> usize {299 self.args.iter().filter(|arg| arg.has_tokens()).count()300 }301302 /// Generates and executes a command.303 ///304 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be305 /// build.306 fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {307 let mut cmd = Command::new(self.args[0].generate(input, path_separator));308 for arg in &self.args[1..] {309 cmd.try_arg(arg.generate(input, path_separator))?;310 }311 Ok(cmd)312 }313}314315/// Represents a template for a single command argument.316///317/// The argument is either a collection of `Token`s including at least one placeholder variant, or318/// a fixed text.319#[derive(Clone, Debug, PartialEq)]320enum ArgumentTemplate {321 Tokens(Vec<Token>),322 Text(String),323}324325impl ArgumentTemplate {326 pub fn has_tokens(&self) -> bool {327 matches!(self, ArgumentTemplate::Tokens(_))328 }329330 /// Generate an argument from this template. If path_separator is Some, then it will replace331 /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by332 /// path separator substitution.333 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {334 use self::Token::*;335 let path = path.as_ref();336337 match *self {338 ArgumentTemplate::Tokens(ref tokens) => {339 let mut s = OsString::new();340 for token in tokens {341 match *token {342 Basename => s.push(Self::replace_separator(basename(path), path_separator)),343 BasenameNoExt => s.push(Self::replace_separator(344 &remove_extension(basename(path).as_ref()),345 path_separator,346 )),347 NoExt => s.push(Self::replace_separator(348 &remove_extension(path),349 path_separator,350 )),351 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),352 Placeholder => {353 s.push(Self::replace_separator(path.as_ref(), path_separator))354 }355 Text(ref string) => s.push(string),356 }357 }358 s359 }360 ArgumentTemplate::Text(ref text) => OsString::from(text),361 }362 }363364 /// Replace the path separator in the input with the custom separator string. If path_separator365 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is366 /// interpreted as a Path and its components are iterated through and re-joined into a new367 /// OsString.368 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {369 // fast-path - no replacement necessary370 if path_separator.is_none() {371 return Cow::Borrowed(path);372 }373374 let path_separator = path_separator.unwrap();375 let mut out = OsString::with_capacity(path.len());376 let mut components = Path::new(path).components().peekable();377378 while let Some(comp) = components.next() {379 match comp {380 // Absolute paths on Windows are tricky. A Prefix component is usually a drive381 // letter or UNC path, and is usually followed by RootDir. There are also382 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to383 // ignore verbatim path prefixes here because they're very rare, might be384 // impossible to reach here, and there's no good way to deal with them. If users385 // are doing something advanced involving verbatim windows paths, they can do their386 // own output filtering with a tool like sed.387 Component::Prefix(prefix) => {388 if let Prefix::UNC(server, share) = prefix.kind() {389 // Prefix::UNC is a parsed version of '\\server\share'390 out.push(path_separator);391 out.push(path_separator);392 out.push(server);393 out.push(path_separator);394 out.push(share);395 } else {396 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for397 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,398 // but they're not returned by directories fd can search anyway so we don't worry399 // about them.400 out.push(comp.as_os_str());401 }402 }403404 // Root directory is always replaced with the custom separator.405 Component::RootDir => out.push(path_separator),406407 // Everything else is joined normally, with a trailing separator if we're not last408 _ => {409 out.push(comp.as_os_str());410 if components.peek().is_some() {411 out.push(path_separator);412 }413 }414 }415 }416 Cow::Owned(out)417 }418}419420#[cfg(test)]421mod tests {422 use super::*;423424 #[test]425 fn tokens_with_placeholder() {426 assert_eq!(427 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),428 CommandSet {429 commands: vec![CommandTemplate {430 args: vec![431 ArgumentTemplate::Text("echo".into()),432 ArgumentTemplate::Text("${SHELL}:".into()),433 ArgumentTemplate::Tokens(vec![Token::Placeholder]),434 ]435 }],436 mode: ExecutionMode::OneByOne,437 }438 );439 }440441 #[test]442 fn tokens_with_no_extension() {443 assert_eq!(444 CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),445 CommandSet {446 commands: vec![CommandTemplate {447 args: vec![448 ArgumentTemplate::Text("echo".into()),449 ArgumentTemplate::Tokens(vec![Token::NoExt]),450 ],451 }],452 mode: ExecutionMode::OneByOne,453 }454 );455 }456457 #[test]458 fn tokens_with_basename() {459 assert_eq!(460 CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),461 CommandSet {462 commands: vec![CommandTemplate {463 args: vec![464 ArgumentTemplate::Text("echo".into()),465 ArgumentTemplate::Tokens(vec![Token::Basename]),466 ],467 }],468 mode: ExecutionMode::OneByOne,469 }470 );471 }472473 #[test]474 fn tokens_with_parent() {475 assert_eq!(476 CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),477 CommandSet {478 commands: vec![CommandTemplate {479 args: vec![480 ArgumentTemplate::Text("echo".into()),481 ArgumentTemplate::Tokens(vec![Token::Parent]),482 ],483 }],484 mode: ExecutionMode::OneByOne,485 }486 );487 }488489 #[test]490 fn tokens_with_basename_no_extension() {491 assert_eq!(492 CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),493 CommandSet {494 commands: vec![CommandTemplate {495 args: vec![496 ArgumentTemplate::Text("echo".into()),497 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),498 ],499 }],500 mode: ExecutionMode::OneByOne,501 }502 );503 }504505 #[test]506 fn tokens_multiple() {507 assert_eq!(508 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),509 CommandSet {510 commands: vec![CommandTemplate {511 args: vec![512 ArgumentTemplate::Text("cp".into()),513 ArgumentTemplate::Tokens(vec![Token::Placeholder]),514 ArgumentTemplate::Tokens(vec![515 Token::BasenameNoExt,516 Token::Text(".ext".into())517 ]),518 ],519 }],520 mode: ExecutionMode::OneByOne,521 }522 );523 }524525 #[test]526 fn tokens_single_batch() {527 assert_eq!(528 CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),529 CommandSet {530 commands: vec![CommandTemplate {531 args: vec![532 ArgumentTemplate::Text("echo".into()),533 ArgumentTemplate::Tokens(vec![Token::NoExt]),534 ],535 }],536 mode: ExecutionMode::Batch,537 }538 );539 }540541 #[test]542 fn tokens_multiple_batch() {543 assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());544 }545546 #[test]547 fn template_no_args() {548 assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());549 }550551 #[test]552 fn command_set_no_args() {553 assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());554 }555556 #[test]557 fn generate_custom_path_separator() {558 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);559 macro_rules! check {560 ($input:expr, $expected:expr) => {561 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));562 };563 }564565 check!("foo", "foo");566 check!("foo/bar", "foo#bar");567 check!("/foo/bar/baz", "#foo#bar#baz");568 }569570 #[cfg(windows)]571 #[test]572 fn generate_custom_path_separator_windows() {573 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);574 macro_rules! check {575 ($input:expr, $expected:expr) => {576 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));577 };578 }579580 // path starting with a drive letter581 check!(r"C:\foo\bar", "C:#foo#bar");582 // UNC path583 check!(r"\\server\share\path", "##server#share#path");584 // Drive Relative path - no separator after the colon omits the RootDir path component.585 // This is uncommon, but valid586 check!(r"C:foo\bar", "C:foo#bar");587588 // forward slashes should get normalized and interpreted as separators589 check!("C:/foo/bar", "C:#foo#bar");590 check!("C:foo/bar", "C:foo#bar");591592 // Rust does not interpret "//server/share" as a UNC path, but rather as a normal593 // absolute path that begins with RootDir, and the two slashes get combined together as594 // a single path separator during normalization.595 //check!("//server/share/path", "##server#share#path");596 }597}