Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

458 lines · 15.6 KiB · Rust

Last changed by

Merge pull request #861 from jcaplan/no-strip/760David Peterbefore adoptionb211ded

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::{anyhow, Result};13use once_cell::sync::Lazy;14use regex::Regex;1516use crate::exit_codes::ExitCode;1718use self::command::execute_command;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/// Represents a template that is utilized to generate command strings.33///34/// The template is meant to be coupled with an input in order to generate a command. The35/// `generate_and_execute()` method will be used to generate a command and execute it.36#[derive(Debug, Clone, PartialEq)]37pub struct CommandTemplate {38    args: Vec<ArgumentTemplate>,39    mode: ExecutionMode,40    path_separator: Option<String>,41}4243impl CommandTemplate {44    pub fn new<I, S>(input: I, path_separator: Option<String>) -> CommandTemplate45    where46        I: IntoIterator<Item = S>,47        S: AsRef<str>,48    {49        Self::build(input, ExecutionMode::OneByOne, path_separator)50    }5152    pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandTemplate>53    where54        I: IntoIterator<Item = S>,55        S: AsRef<str>,56    {57        let cmd = Self::build(input, ExecutionMode::Batch, path_separator);58        if cmd.number_of_tokens() > 1 {59            return Err(anyhow!("Only one placeholder allowed for batch commands"));60        }61        if cmd.args[0].has_tokens() {62            return Err(anyhow!(63                "First argument of exec-batch is expected to be a fixed executable"64            ));65        }66        Ok(cmd)67    }6869    fn build<I, S>(input: I, mode: ExecutionMode, path_separator: Option<String>) -> CommandTemplate70    where71        I: IntoIterator<Item = S>,72        S: AsRef<str>,73    {74        static PLACEHOLDER_PATTERN: Lazy<Regex> =75            Lazy::new(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());7677        let mut args = Vec::new();78        let mut has_placeholder = false;7980        for arg in input {81            let arg = arg.as_ref();8283            let mut tokens = Vec::new();84            let mut start = 0;8586            for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {87                // Leading text before the placeholder.88                if placeholder.start() > start {89                    tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));90                }9192                start = placeholder.end();9394                match placeholder.as_str() {95                    "{}" => tokens.push(Token::Placeholder),96                    "{.}" => tokens.push(Token::NoExt),97                    "{/}" => tokens.push(Token::Basename),98                    "{//}" => tokens.push(Token::Parent),99                    "{/.}" => tokens.push(Token::BasenameNoExt),100                    _ => unreachable!("Unhandled placeholder"),101                }102103                has_placeholder = true;104            }105106            // Without a placeholder, the argument is just fixed text.107            if tokens.is_empty() {108                args.push(ArgumentTemplate::Text(arg.to_owned()));109                continue;110            }111112            if start < arg.len() {113                // Trailing text after last placeholder.114                tokens.push(Token::Text(arg[start..].to_owned()));115            }116117            args.push(ArgumentTemplate::Tokens(tokens));118        }119120        // If a placeholder token was not supplied, append one at the end of the command.121        if !has_placeholder {122            args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));123        }124125        CommandTemplate {126            args,127            mode,128            path_separator,129        }130    }131132    fn number_of_tokens(&self) -> usize {133        self.args.iter().filter(|arg| arg.has_tokens()).count()134    }135136    /// Generates and executes a command.137    ///138    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be139    /// build. Once all arguments have been processed, the command is executed.140    pub fn generate_and_execute(141        &self,142        input: &Path,143        out_perm: Arc<Mutex<()>>,144        buffer_output: bool,145    ) -> ExitCode {146        let mut cmd = Command::new(self.args[0].generate(&input, self.path_separator.as_deref()));147        for arg in &self.args[1..] {148            cmd.arg(arg.generate(&input, self.path_separator.as_deref()));149        }150151        execute_command(cmd, &out_perm, buffer_output)152    }153154    pub fn in_batch_mode(&self) -> bool {155        self.mode == ExecutionMode::Batch156    }157158    pub fn generate_and_execute_batch<I>(&self, paths: I, buffer_output: bool) -> ExitCode159    where160        I: Iterator<Item = PathBuf>,161    {162        let mut cmd = Command::new(self.args[0].generate("", None));163        cmd.stdin(Stdio::inherit());164        cmd.stdout(Stdio::inherit());165        cmd.stderr(Stdio::inherit());166167        let mut paths: Vec<_> = paths.collect();168        let mut has_path = false;169170        for arg in &self.args[1..] {171            if arg.has_tokens() {172                paths.sort();173174                // A single `Tokens` is expected175                // So we can directly consume the iterator once and for all176                for path in &mut paths {177                    cmd.arg(arg.generate(path, self.path_separator.as_deref()));178                    has_path = true;179                }180            } else {181                cmd.arg(arg.generate("", None));182            }183        }184185        if has_path {186            execute_command(cmd, &Mutex::new(()), buffer_output)187        } else {188            ExitCode::Success189        }190    }191}192193/// Represents a template for a single command argument.194///195/// The argument is either a collection of `Token`s including at least one placeholder variant, or196/// a fixed text.197#[derive(Clone, Debug, PartialEq)]198enum ArgumentTemplate {199    Tokens(Vec<Token>),200    Text(String),201}202203impl ArgumentTemplate {204    pub fn has_tokens(&self) -> bool {205        matches!(self, ArgumentTemplate::Tokens(_))206    }207208    /// Generate an argument from this template. If path_separator is Some, then it will replace209    /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by210    /// path separator substitution.211    pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {212        use self::Token::*;213        let path = path.as_ref();214215        match *self {216            ArgumentTemplate::Tokens(ref tokens) => {217                let mut s = OsString::new();218                for token in tokens {219                    match *token {220                        Basename => s.push(Self::replace_separator(basename(path), path_separator)),221                        BasenameNoExt => s.push(Self::replace_separator(222                            &remove_extension(basename(path).as_ref()),223                            path_separator,224                        )),225                        NoExt => s.push(Self::replace_separator(226                            &remove_extension(path),227                            path_separator,228                        )),229                        Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),230                        Placeholder => {231                            s.push(Self::replace_separator(path.as_ref(), path_separator))232                        }233                        Text(ref string) => s.push(string),234                    }235                }236                s237            }238            ArgumentTemplate::Text(ref text) => OsString::from(text),239        }240    }241242    /// Replace the path separator in the input with the custom separator string. If path_separator243    /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is244    /// interpreted as a Path and its components are iterated through and re-joined into a new245    /// OsString.246    fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {247        // fast-path - no replacement necessary248        if path_separator.is_none() {249            return Cow::Borrowed(path);250        }251252        let path_separator = path_separator.unwrap();253        let mut out = OsString::with_capacity(path.len());254        let mut components = Path::new(path).components().peekable();255256        while let Some(comp) = components.next() {257            match comp {258                // Absolute paths on Windows are tricky.  A Prefix component is usually a drive259                // letter or UNC path, and is usually followed by RootDir. There are also260                // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to261                // ignore verbatim path prefixes here because they're very rare, might be262                // impossible to reach here, and there's no good way to deal with them. If users263                // are doing something advanced involving verbatim windows paths, they can do their264                // own output filtering with a tool like sed.265                Component::Prefix(prefix) => {266                    if let Prefix::UNC(server, share) = prefix.kind() {267                        // Prefix::UNC is a parsed version of '\\server\share'268                        out.push(path_separator);269                        out.push(path_separator);270                        out.push(server);271                        out.push(path_separator);272                        out.push(share);273                    } else {274                        // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for275                        // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,276                        // but they're not returned by directories fd can search anyway so we don't worry277                        // about them.278                        out.push(comp.as_os_str());279                    }280                }281282                // Root directory is always replaced with the custom separator.283                Component::RootDir => out.push(path_separator),284285                // Everything else is joined normally, with a trailing separator if we're not last286                _ => {287                    out.push(comp.as_os_str());288                    if components.peek().is_some() {289                        out.push(path_separator);290                    }291                }292            }293        }294        Cow::Owned(out)295    }296}297298#[cfg(test)]299mod tests {300    use super::*;301302    #[test]303    fn tokens_with_placeholder() {304        assert_eq!(305            CommandTemplate::new(&[&"echo", &"${SHELL}:"], None),306            CommandTemplate {307                args: vec![308                    ArgumentTemplate::Text("echo".into()),309                    ArgumentTemplate::Text("${SHELL}:".into()),310                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),311                ],312                mode: ExecutionMode::OneByOne,313                path_separator: None,314            }315        );316    }317318    #[test]319    fn tokens_with_no_extension() {320        assert_eq!(321            CommandTemplate::new(&["echo", "{.}"], None),322            CommandTemplate {323                args: vec![324                    ArgumentTemplate::Text("echo".into()),325                    ArgumentTemplate::Tokens(vec![Token::NoExt]),326                ],327                mode: ExecutionMode::OneByOne,328                path_separator: None,329            }330        );331    }332333    #[test]334    fn tokens_with_basename() {335        assert_eq!(336            CommandTemplate::new(&["echo", "{/}"], None),337            CommandTemplate {338                args: vec![339                    ArgumentTemplate::Text("echo".into()),340                    ArgumentTemplate::Tokens(vec![Token::Basename]),341                ],342                mode: ExecutionMode::OneByOne,343                path_separator: None,344            }345        );346    }347348    #[test]349    fn tokens_with_parent() {350        assert_eq!(351            CommandTemplate::new(&["echo", "{//}"], None),352            CommandTemplate {353                args: vec![354                    ArgumentTemplate::Text("echo".into()),355                    ArgumentTemplate::Tokens(vec![Token::Parent]),356                ],357                mode: ExecutionMode::OneByOne,358                path_separator: None,359            }360        );361    }362363    #[test]364    fn tokens_with_basename_no_extension() {365        assert_eq!(366            CommandTemplate::new(&["echo", "{/.}"], None),367            CommandTemplate {368                args: vec![369                    ArgumentTemplate::Text("echo".into()),370                    ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),371                ],372                mode: ExecutionMode::OneByOne,373                path_separator: None,374            }375        );376    }377378    #[test]379    fn tokens_multiple() {380        assert_eq!(381            CommandTemplate::new(&["cp", "{}", "{/.}.ext"], None),382            CommandTemplate {383                args: vec![384                    ArgumentTemplate::Text("cp".into()),385                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),386                    ArgumentTemplate::Tokens(vec![387                        Token::BasenameNoExt,388                        Token::Text(".ext".into())389                    ]),390                ],391                mode: ExecutionMode::OneByOne,392                path_separator: None,393            }394        );395    }396397    #[test]398    fn tokens_single_batch() {399        assert_eq!(400            CommandTemplate::new_batch(&["echo", "{.}"], None).unwrap(),401            CommandTemplate {402                args: vec![403                    ArgumentTemplate::Text("echo".into()),404                    ArgumentTemplate::Tokens(vec![Token::NoExt]),405                ],406                mode: ExecutionMode::Batch,407                path_separator: None,408            }409        );410    }411412    #[test]413    fn tokens_multiple_batch() {414        assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"], None).is_err());415    }416417    #[test]418    fn generate_custom_path_separator() {419        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);420        macro_rules! check {421            ($input:expr, $expected:expr) => {422                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));423            };424        }425426        check!("foo", "foo");427        check!("foo/bar", "foo#bar");428        check!("/foo/bar/baz", "#foo#bar#baz");429    }430431    #[cfg(windows)]432    #[test]433    fn generate_custom_path_separator_windows() {434        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);435        macro_rules! check {436            ($input:expr, $expected:expr) => {437                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));438            };439        }440441        // path starting with a drive letter442        check!(r"C:\foo\bar", "C:#foo#bar");443        // UNC path444        check!(r"\\server\share\path", "##server#share#path");445        // Drive Relative path - no separator after the colon omits the RootDir path component.446        // This is uncommon, but valid447        check!(r"C:foo\bar", "C:foo#bar");448449        // forward slashes should get normalized and interpreted as separators450        check!("C:/foo/bar", "C:#foo#bar");451        check!("C:foo/bar", "C:foo#bar");452453        // Rust does not interpret "//server/share" as a UNC path, but rather as a normal454        // absolute path that begins with RootDir, and the two slashes get combined together as455        // a single path separator during normalization.456        //check!("//server/share/path", "##server#share#path");457    }458}