Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

462 lines · 15.7 KiB · Rust

Last changed by

fix spellinga1346054before adoption5b4869a

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 lazy_static::lazy_static;14use regex::Regex;1516use crate::exit_codes::ExitCode;17use crate::filesystem::strip_current_dir;1819use self::command::execute_command;20use self::input::{basename, dirname, remove_extension};21pub use self::job::{batch, job};22use self::token::Token;2324/// Execution mode of the command25#[derive(Debug, Clone, Copy, PartialEq)]26pub enum ExecutionMode {27    /// Command is executed for each search result28    OneByOne,29    /// Command is run for a batch of results at once30    Batch,31}3233/// Represents a template that is utilized to generate command strings.34///35/// The template is meant to be coupled with an input in order to generate a command. The36/// `generate_and_execute()` method will be used to generate a command and execute it.37#[derive(Debug, Clone, PartialEq)]38pub struct CommandTemplate {39    args: Vec<ArgumentTemplate>,40    mode: ExecutionMode,41    path_separator: Option<String>,42}4344impl CommandTemplate {45    pub fn new<I, S>(input: I, path_separator: Option<String>) -> CommandTemplate46    where47        I: IntoIterator<Item = S>,48        S: AsRef<str>,49    {50        Self::build(input, ExecutionMode::OneByOne, path_separator)51    }5253    pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandTemplate>54    where55        I: IntoIterator<Item = S>,56        S: AsRef<str>,57    {58        let cmd = Self::build(input, ExecutionMode::Batch, path_separator);59        if cmd.number_of_tokens() > 1 {60            return Err(anyhow!("Only one placeholder allowed for batch commands"));61        }62        if cmd.args[0].has_tokens() {63            return Err(anyhow!(64                "First argument of exec-batch is expected to be a fixed executable"65            ));66        }67        Ok(cmd)68    }6970    fn build<I, S>(input: I, mode: ExecutionMode, path_separator: Option<String>) -> CommandTemplate71    where72        I: IntoIterator<Item = S>,73        S: AsRef<str>,74    {75        lazy_static! {76            static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();77        }7879        let mut args = Vec::new();80        let mut has_placeholder = false;8182        for arg in input {83            let arg = arg.as_ref();8485            let mut tokens = Vec::new();86            let mut start = 0;8788            for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {89                // Leading text before the placeholder.90                if placeholder.start() > start {91                    tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));92                }9394                start = placeholder.end();9596                match placeholder.as_str() {97                    "{}" => tokens.push(Token::Placeholder),98                    "{.}" => tokens.push(Token::NoExt),99                    "{/}" => tokens.push(Token::Basename),100                    "{//}" => tokens.push(Token::Parent),101                    "{/.}" => tokens.push(Token::BasenameNoExt),102                    _ => unreachable!("Unhandled placeholder"),103                }104105                has_placeholder = true;106            }107108            // Without a placeholder, the argument is just fixed text.109            if tokens.is_empty() {110                args.push(ArgumentTemplate::Text(arg.to_owned()));111                continue;112            }113114            if start < arg.len() {115                // Trailing text after last placeholder.116                tokens.push(Token::Text(arg[start..].to_owned()));117            }118119            args.push(ArgumentTemplate::Tokens(tokens));120        }121122        // If a placeholder token was not supplied, append one at the end of the command.123        if !has_placeholder {124            args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));125        }126127        CommandTemplate {128            args,129            mode,130            path_separator,131        }132    }133134    fn number_of_tokens(&self) -> usize {135        self.args.iter().filter(|arg| arg.has_tokens()).count()136    }137138    /// Generates and executes a command.139    ///140    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be141    /// build. Once all arguments have been processed, the command is executed.142    pub fn generate_and_execute(143        &self,144        input: &Path,145        out_perm: Arc<Mutex<()>>,146        buffer_output: bool,147    ) -> ExitCode {148        let input = strip_current_dir(input);149150        let mut cmd = Command::new(self.args[0].generate(&input, self.path_separator.as_deref()));151        for arg in &self.args[1..] {152            cmd.arg(arg.generate(&input, self.path_separator.as_deref()));153        }154155        execute_command(cmd, &out_perm, buffer_output)156    }157158    pub fn in_batch_mode(&self) -> bool {159        self.mode == ExecutionMode::Batch160    }161162    pub fn generate_and_execute_batch<I>(&self, paths: I, buffer_output: bool) -> ExitCode163    where164        I: Iterator<Item = PathBuf>,165    {166        let mut cmd = Command::new(self.args[0].generate("", None));167        cmd.stdin(Stdio::inherit());168        cmd.stdout(Stdio::inherit());169        cmd.stderr(Stdio::inherit());170171        let mut paths: Vec<_> = paths.collect();172        let mut has_path = false;173174        for arg in &self.args[1..] {175            if arg.has_tokens() {176                paths.sort();177178                // A single `Tokens` is expected179                // So we can directly consume the iterator once and for all180                for path in &mut paths {181                    cmd.arg(arg.generate(strip_current_dir(path), self.path_separator.as_deref()));182                    has_path = true;183                }184            } else {185                cmd.arg(arg.generate("", None));186            }187        }188189        if has_path {190            execute_command(cmd, &Mutex::new(()), buffer_output)191        } else {192            ExitCode::Success193        }194    }195}196197/// Represents a template for a single command argument.198///199/// The argument is either a collection of `Token`s including at least one placeholder variant, or200/// a fixed text.201#[derive(Clone, Debug, PartialEq)]202enum ArgumentTemplate {203    Tokens(Vec<Token>),204    Text(String),205}206207impl ArgumentTemplate {208    pub fn has_tokens(&self) -> bool {209        matches!(self, ArgumentTemplate::Tokens(_))210    }211212    /// Generate an argument from this template. If path_separator is Some, then it will replace213    /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by214    /// path separator substitution.215    pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {216        use self::Token::*;217        let path = path.as_ref();218219        match *self {220            ArgumentTemplate::Tokens(ref tokens) => {221                let mut s = OsString::new();222                for token in tokens {223                    match *token {224                        Basename => s.push(Self::replace_separator(basename(path), path_separator)),225                        BasenameNoExt => s.push(Self::replace_separator(226                            &remove_extension(basename(path).as_ref()),227                            path_separator,228                        )),229                        NoExt => s.push(Self::replace_separator(230                            &remove_extension(path),231                            path_separator,232                        )),233                        Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),234                        Placeholder => {235                            s.push(Self::replace_separator(path.as_ref(), path_separator))236                        }237                        Text(ref string) => s.push(string),238                    }239                }240                s241            }242            ArgumentTemplate::Text(ref text) => OsString::from(text),243        }244    }245246    /// Replace the path separator in the input with the custom separator string. If path_separator247    /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is248    /// interpreted as a Path and its components are iterated through and re-joined into a new249    /// OsString.250    fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {251        // fast-path - no replacement necessary252        if path_separator.is_none() {253            return Cow::Borrowed(path);254        }255256        let path_separator = path_separator.unwrap();257        let mut out = OsString::with_capacity(path.len());258        let mut components = Path::new(path).components().peekable();259260        while let Some(comp) = components.next() {261            match comp {262                // Absolute paths on Windows are tricky.  A Prefix component is usually a drive263                // letter or UNC path, and is usually followed by RootDir. There are also264                // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to265                // ignore verbatim path prefixes here because they're very rare, might be266                // impossible to reach here, and there's no good way to deal with them. If users267                // are doing something advanced involving verbatim windows paths, they can do their268                // own output filtering with a tool like sed.269                Component::Prefix(prefix) => {270                    if let Prefix::UNC(server, share) = prefix.kind() {271                        // Prefix::UNC is a parsed version of '\\server\share'272                        out.push(path_separator);273                        out.push(path_separator);274                        out.push(server);275                        out.push(path_separator);276                        out.push(share);277                    } else {278                        // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for279                        // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,280                        // but they're not returned by directories fd can search anyway so we don't worry281                        // about them.282                        out.push(comp.as_os_str());283                    }284                }285286                // Root directory is always replaced with the custom separator.287                Component::RootDir => out.push(path_separator),288289                // Everything else is joined normally, with a trailing separator if we're not last290                _ => {291                    out.push(comp.as_os_str());292                    if components.peek().is_some() {293                        out.push(path_separator);294                    }295                }296            }297        }298        Cow::Owned(out)299    }300}301302#[cfg(test)]303mod tests {304    use super::*;305306    #[test]307    fn tokens_with_placeholder() {308        assert_eq!(309            CommandTemplate::new(&[&"echo", &"${SHELL}:"], None),310            CommandTemplate {311                args: vec![312                    ArgumentTemplate::Text("echo".into()),313                    ArgumentTemplate::Text("${SHELL}:".into()),314                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),315                ],316                mode: ExecutionMode::OneByOne,317                path_separator: None,318            }319        );320    }321322    #[test]323    fn tokens_with_no_extension() {324        assert_eq!(325            CommandTemplate::new(&["echo", "{.}"], None),326            CommandTemplate {327                args: vec![328                    ArgumentTemplate::Text("echo".into()),329                    ArgumentTemplate::Tokens(vec![Token::NoExt]),330                ],331                mode: ExecutionMode::OneByOne,332                path_separator: None,333            }334        );335    }336337    #[test]338    fn tokens_with_basename() {339        assert_eq!(340            CommandTemplate::new(&["echo", "{/}"], None),341            CommandTemplate {342                args: vec![343                    ArgumentTemplate::Text("echo".into()),344                    ArgumentTemplate::Tokens(vec![Token::Basename]),345                ],346                mode: ExecutionMode::OneByOne,347                path_separator: None,348            }349        );350    }351352    #[test]353    fn tokens_with_parent() {354        assert_eq!(355            CommandTemplate::new(&["echo", "{//}"], None),356            CommandTemplate {357                args: vec![358                    ArgumentTemplate::Text("echo".into()),359                    ArgumentTemplate::Tokens(vec![Token::Parent]),360                ],361                mode: ExecutionMode::OneByOne,362                path_separator: None,363            }364        );365    }366367    #[test]368    fn tokens_with_basename_no_extension() {369        assert_eq!(370            CommandTemplate::new(&["echo", "{/.}"], None),371            CommandTemplate {372                args: vec![373                    ArgumentTemplate::Text("echo".into()),374                    ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),375                ],376                mode: ExecutionMode::OneByOne,377                path_separator: None,378            }379        );380    }381382    #[test]383    fn tokens_multiple() {384        assert_eq!(385            CommandTemplate::new(&["cp", "{}", "{/.}.ext"], None),386            CommandTemplate {387                args: vec![388                    ArgumentTemplate::Text("cp".into()),389                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),390                    ArgumentTemplate::Tokens(vec![391                        Token::BasenameNoExt,392                        Token::Text(".ext".into())393                    ]),394                ],395                mode: ExecutionMode::OneByOne,396                path_separator: None,397            }398        );399    }400401    #[test]402    fn tokens_single_batch() {403        assert_eq!(404            CommandTemplate::new_batch(&["echo", "{.}"], None).unwrap(),405            CommandTemplate {406                args: vec![407                    ArgumentTemplate::Text("echo".into()),408                    ArgumentTemplate::Tokens(vec![Token::NoExt]),409                ],410                mode: ExecutionMode::Batch,411                path_separator: None,412            }413        );414    }415416    #[test]417    fn tokens_multiple_batch() {418        assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"], None).is_err());419    }420421    #[test]422    fn generate_custom_path_separator() {423        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);424        macro_rules! check {425            ($input:expr, $expected:expr) => {426                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));427            };428        }429430        check!("foo", "foo");431        check!("foo/bar", "foo#bar");432        check!("/foo/bar/baz", "#foo#bar#baz");433    }434435    #[cfg(windows)]436    #[test]437    fn generate_custom_path_separator_windows() {438        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);439        macro_rules! check {440            ($input:expr, $expected:expr) => {441                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));442            };443        }444445        // path starting with a drive letter446        check!(r"C:\foo\bar", "C:#foo#bar");447        // UNC path448        check!(r"\\server\share\path", "##server#share#path");449        // Drive Relative path - no separator after the colon omits the RootDir path component.450        // This is uncommon, but valid451        check!(r"C:foo\bar", "C:foo#bar");452453        // forward slashes should get normalized and interpreted as separators454        check!("C:/foo/bar", "C:#foo#bar");455        check!("C:foo/bar", "C:foo#bar");456457        // Rust does not interpret "//server/share" as a UNC path, but rather as a normal458        // absolute path that begins with RootDir, and the two slashes get combined together as459        // a single path separator during normalization.460        //check!("//server/share/path", "##server#share#path");461    }462}