Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

526 lines · 17.8 KiB · Rust

Last changed by

Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08

History of this file

Take it

1mod command;2mod input;3mod job;4mod token;56use std::borrow::Cow;7use std::ffi::{OsStr, OsString};8use std::path::{Component, Path, PathBuf, Prefix};9use std::process::{Command, Stdio};10use std::sync::{Arc, Mutex};1112use anyhow::{bail, Result};13use once_cell::sync::Lazy;14use regex::Regex;1516use crate::exit_codes::ExitCode;1718use self::command::{execute_commands, handle_cmd_error};19use self::input::{basename, dirname, remove_extension};20pub use self::job::{batch, job};21use self::token::Token;2223/// Execution mode of the command24#[derive(Debug, Clone, Copy, PartialEq)]25pub enum ExecutionMode {26    /// Command is executed for each search result27    OneByOne,28    /// Command is run for a batch of results at once29    Batch,30}3132#[derive(Debug, Clone, PartialEq)]33pub struct CommandSet {34    mode: ExecutionMode,35    path_separator: Option<String>,36    commands: Vec<CommandTemplate>,37}3839impl CommandSet {40    pub fn new<I, S>(input: I, path_separator: Option<String>) -> Result<CommandSet>41    where42        I: IntoIterator<Item = Vec<S>>,43        S: AsRef<str>,44    {45        Ok(CommandSet {46            mode: ExecutionMode::OneByOne,47            path_separator,48            commands: input49                .into_iter()50                .map(CommandTemplate::new)51                .collect::<Result<_>>()?,52        })53    }5455    pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandSet>56    where57        I: IntoIterator<Item = Vec<S>>,58        S: AsRef<str>,59    {60        Ok(CommandSet {61            mode: ExecutionMode::Batch,62            path_separator,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(&self, input: &Path, out_perm: Arc<Mutex<()>>, buffer_output: bool) -> ExitCode {84        let path_separator = self.path_separator.as_deref();85        let commands = self86            .commands87            .iter()88            .map(|c| c.generate(input, path_separator));89        execute_commands(commands, &out_perm, buffer_output)90    }9192    pub fn execute_batch<I>(&self, paths: I) -> ExitCode93    where94        I: Iterator<Item = PathBuf>,95    {96        let path_separator = self.path_separator.as_deref();97        let mut paths = paths.collect::<Vec<_>>();98        paths.sort();99        for cmd in &self.commands {100            let exit = cmd.generate_and_execute_batch(&paths, path_separator);101            if exit != ExitCode::Success {102                return exit;103            }104        }105        ExitCode::Success106    }107}108109/// Represents a template that is utilized to generate command strings.110///111/// The template is meant to be coupled with an input in order to generate a command. The112/// `generate_and_execute()` method will be used to generate a command and execute it.113#[derive(Debug, Clone, PartialEq)]114struct CommandTemplate {115    args: Vec<ArgumentTemplate>,116}117118impl CommandTemplate {119    fn new<I, S>(input: I) -> Result<CommandTemplate>120    where121        I: IntoIterator<Item = S>,122        S: AsRef<str>,123    {124        static PLACEHOLDER_PATTERN: Lazy<Regex> =125            Lazy::new(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());126127        let mut args = Vec::new();128        let mut has_placeholder = false;129130        for arg in input {131            let arg = arg.as_ref();132133            let mut tokens = Vec::new();134            let mut start = 0;135136            for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {137                // Leading text before the placeholder.138                if placeholder.start() > start {139                    tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));140                }141142                start = placeholder.end();143144                match placeholder.as_str() {145                    "{}" => tokens.push(Token::Placeholder),146                    "{.}" => tokens.push(Token::NoExt),147                    "{/}" => tokens.push(Token::Basename),148                    "{//}" => tokens.push(Token::Parent),149                    "{/.}" => tokens.push(Token::BasenameNoExt),150                    _ => unreachable!("Unhandled placeholder"),151                }152153                has_placeholder = true;154            }155156            // Without a placeholder, the argument is just fixed text.157            if tokens.is_empty() {158                args.push(ArgumentTemplate::Text(arg.to_owned()));159                continue;160            }161162            if start < arg.len() {163                // Trailing text after last placeholder.164                tokens.push(Token::Text(arg[start..].to_owned()));165            }166167            args.push(ArgumentTemplate::Tokens(tokens));168        }169170        // We need to check that we have at least one argument, because if not171        // it will try to execute each file and directory it finds.172        //173        // Sadly, clap can't currently handle this for us, see174        // https://github.com/clap-rs/clap/issues/3542175        if args.is_empty() {176            bail!("No executable provided for --exec or --exec-batch");177        }178179        // If a placeholder token was not supplied, append one at the end of the command.180        if !has_placeholder {181            args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));182        }183184        Ok(CommandTemplate { args })185    }186187    fn number_of_tokens(&self) -> usize {188        self.args.iter().filter(|arg| arg.has_tokens()).count()189    }190191    /// Generates and executes a command.192    ///193    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be194    /// build.195    fn generate(&self, input: &Path, path_separator: Option<&str>) -> Command {196        let mut cmd = Command::new(self.args[0].generate(&input, path_separator));197        for arg in &self.args[1..] {198            cmd.arg(arg.generate(&input, path_separator));199        }200        cmd201    }202203    fn generate_and_execute_batch(204        &self,205        paths: &[PathBuf],206        path_separator: Option<&str>,207    ) -> ExitCode {208        let mut cmd = Command::new(self.args[0].generate("", None));209        cmd.stdin(Stdio::inherit());210        cmd.stdout(Stdio::inherit());211        cmd.stderr(Stdio::inherit());212213        let mut has_path = false;214215        for arg in &self.args[1..] {216            if arg.has_tokens() {217                for path in paths {218                    cmd.arg(arg.generate(path, path_separator));219                    has_path = true;220                }221            } else {222                cmd.arg(arg.generate("", None));223            }224        }225226        if has_path {227            match cmd.spawn().and_then(|mut c| c.wait()) {228                Ok(_) => ExitCode::Success,229                Err(e) => handle_cmd_error(&cmd, e),230            }231        } else {232            ExitCode::Success233        }234    }235}236237/// Represents a template for a single command argument.238///239/// The argument is either a collection of `Token`s including at least one placeholder variant, or240/// a fixed text.241#[derive(Clone, Debug, PartialEq)]242enum ArgumentTemplate {243    Tokens(Vec<Token>),244    Text(String),245}246247impl ArgumentTemplate {248    pub fn has_tokens(&self) -> bool {249        matches!(self, ArgumentTemplate::Tokens(_))250    }251252    /// Generate an argument from this template. If path_separator is Some, then it will replace253    /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by254    /// path separator substitution.255    pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {256        use self::Token::*;257        let path = path.as_ref();258259        match *self {260            ArgumentTemplate::Tokens(ref tokens) => {261                let mut s = OsString::new();262                for token in tokens {263                    match *token {264                        Basename => s.push(Self::replace_separator(basename(path), path_separator)),265                        BasenameNoExt => s.push(Self::replace_separator(266                            &remove_extension(basename(path).as_ref()),267                            path_separator,268                        )),269                        NoExt => s.push(Self::replace_separator(270                            &remove_extension(path),271                            path_separator,272                        )),273                        Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),274                        Placeholder => {275                            s.push(Self::replace_separator(path.as_ref(), path_separator))276                        }277                        Text(ref string) => s.push(string),278                    }279                }280                s281            }282            ArgumentTemplate::Text(ref text) => OsString::from(text),283        }284    }285286    /// Replace the path separator in the input with the custom separator string. If path_separator287    /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is288    /// interpreted as a Path and its components are iterated through and re-joined into a new289    /// OsString.290    fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {291        // fast-path - no replacement necessary292        if path_separator.is_none() {293            return Cow::Borrowed(path);294        }295296        let path_separator = path_separator.unwrap();297        let mut out = OsString::with_capacity(path.len());298        let mut components = Path::new(path).components().peekable();299300        while let Some(comp) = components.next() {301            match comp {302                // Absolute paths on Windows are tricky.  A Prefix component is usually a drive303                // letter or UNC path, and is usually followed by RootDir. There are also304                // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to305                // ignore verbatim path prefixes here because they're very rare, might be306                // impossible to reach here, and there's no good way to deal with them. If users307                // are doing something advanced involving verbatim windows paths, they can do their308                // own output filtering with a tool like sed.309                Component::Prefix(prefix) => {310                    if let Prefix::UNC(server, share) = prefix.kind() {311                        // Prefix::UNC is a parsed version of '\\server\share'312                        out.push(path_separator);313                        out.push(path_separator);314                        out.push(server);315                        out.push(path_separator);316                        out.push(share);317                    } else {318                        // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for319                        // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,320                        // but they're not returned by directories fd can search anyway so we don't worry321                        // about them.322                        out.push(comp.as_os_str());323                    }324                }325326                // Root directory is always replaced with the custom separator.327                Component::RootDir => out.push(path_separator),328329                // Everything else is joined normally, with a trailing separator if we're not last330                _ => {331                    out.push(comp.as_os_str());332                    if components.peek().is_some() {333                        out.push(path_separator);334                    }335                }336            }337        }338        Cow::Owned(out)339    }340}341342#[cfg(test)]343mod tests {344    use super::*;345346    #[test]347    fn tokens_with_placeholder() {348        assert_eq!(349            CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]], None).unwrap(),350            CommandSet {351                commands: vec![CommandTemplate {352                    args: vec![353                        ArgumentTemplate::Text("echo".into()),354                        ArgumentTemplate::Text("${SHELL}:".into()),355                        ArgumentTemplate::Tokens(vec![Token::Placeholder]),356                    ]357                }],358                mode: ExecutionMode::OneByOne,359                path_separator: None,360            }361        );362    }363364    #[test]365    fn tokens_with_no_extension() {366        assert_eq!(367            CommandSet::new(vec![vec!["echo", "{.}"]], None).unwrap(),368            CommandSet {369                commands: vec![CommandTemplate {370                    args: vec![371                        ArgumentTemplate::Text("echo".into()),372                        ArgumentTemplate::Tokens(vec![Token::NoExt]),373                    ],374                }],375                mode: ExecutionMode::OneByOne,376                path_separator: None,377            }378        );379    }380381    #[test]382    fn tokens_with_basename() {383        assert_eq!(384            CommandSet::new(vec![vec!["echo", "{/}"]], None).unwrap(),385            CommandSet {386                commands: vec![CommandTemplate {387                    args: vec![388                        ArgumentTemplate::Text("echo".into()),389                        ArgumentTemplate::Tokens(vec![Token::Basename]),390                    ],391                }],392                mode: ExecutionMode::OneByOne,393                path_separator: None,394            }395        );396    }397398    #[test]399    fn tokens_with_parent() {400        assert_eq!(401            CommandSet::new(vec![vec!["echo", "{//}"]], None).unwrap(),402            CommandSet {403                commands: vec![CommandTemplate {404                    args: vec![405                        ArgumentTemplate::Text("echo".into()),406                        ArgumentTemplate::Tokens(vec![Token::Parent]),407                    ],408                }],409                mode: ExecutionMode::OneByOne,410                path_separator: None,411            }412        );413    }414415    #[test]416    fn tokens_with_basename_no_extension() {417        assert_eq!(418            CommandSet::new(vec![vec!["echo", "{/.}"]], None).unwrap(),419            CommandSet {420                commands: vec![CommandTemplate {421                    args: vec![422                        ArgumentTemplate::Text("echo".into()),423                        ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),424                    ],425                }],426                mode: ExecutionMode::OneByOne,427                path_separator: None,428            }429        );430    }431432    #[test]433    fn tokens_multiple() {434        assert_eq!(435            CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]], None).unwrap(),436            CommandSet {437                commands: vec![CommandTemplate {438                    args: vec![439                        ArgumentTemplate::Text("cp".into()),440                        ArgumentTemplate::Tokens(vec![Token::Placeholder]),441                        ArgumentTemplate::Tokens(vec![442                            Token::BasenameNoExt,443                            Token::Text(".ext".into())444                        ]),445                    ],446                }],447                mode: ExecutionMode::OneByOne,448                path_separator: None,449            }450        );451    }452453    #[test]454    fn tokens_single_batch() {455        assert_eq!(456            CommandSet::new_batch(vec![vec!["echo", "{.}"]], None).unwrap(),457            CommandSet {458                commands: vec![CommandTemplate {459                    args: vec![460                        ArgumentTemplate::Text("echo".into()),461                        ArgumentTemplate::Tokens(vec![Token::NoExt]),462                    ],463                }],464                mode: ExecutionMode::Batch,465                path_separator: None,466            }467        );468    }469470    #[test]471    fn tokens_multiple_batch() {472        assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]], None).is_err());473    }474475    #[test]476    fn template_no_args() {477        assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());478    }479480    #[test]481    fn command_set_no_args() {482        assert!(CommandSet::new(vec![vec!["echo"], vec![]], None).is_err());483    }484485    #[test]486    fn generate_custom_path_separator() {487        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);488        macro_rules! check {489            ($input:expr, $expected:expr) => {490                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));491            };492        }493494        check!("foo", "foo");495        check!("foo/bar", "foo#bar");496        check!("/foo/bar/baz", "#foo#bar#baz");497    }498499    #[cfg(windows)]500    #[test]501    fn generate_custom_path_separator_windows() {502        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);503        macro_rules! check {504            ($input:expr, $expected:expr) => {505                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));506            };507        }508509        // path starting with a drive letter510        check!(r"C:\foo\bar", "C:#foo#bar");511        // UNC path512        check!(r"\\server\share\path", "##server#share#path");513        // Drive Relative path - no separator after the colon omits the RootDir path component.514        // This is uncommon, but valid515        check!(r"C:foo\bar", "C:foo#bar");516517        // forward slashes should get normalized and interpreted as separators518        check!("C:/foo/bar", "C:#foo#bar");519        check!("C:foo/bar", "C:foo#bar");520521        // Rust does not interpret "//server/share" as a UNC path, but rather as a normal522        // absolute path that begins with RootDir, and the two slashes get combined together as523        // a single path separator during normalization.524        //check!("//server/share/path", "##server#share#path");525    }526}