Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

457 lines · 15.7 KiB · Rust

Last changed by

No buffering cmd output when running on 1 threadMax Trianobefore adoption394e967

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(&self, input: &Path, out_perm: Arc<Mutex<()>>, is_multithread: bool) -> ExitCode {143        let input = strip_current_dir(input);144145        let mut cmd = Command::new(self.args[0].generate(&input, self.path_separator.as_deref()));146        for arg in &self.args[1..] {147            cmd.arg(arg.generate(&input, self.path_separator.as_deref()));148        }149150        execute_command(cmd, &out_perm, is_multithread)151    }152153    pub fn in_batch_mode(&self) -> bool {154        self.mode == ExecutionMode::Batch155    }156157    pub fn generate_and_execute_batch<I>(&self, paths: I, is_multithread: bool) -> ExitCode158    where159        I: Iterator<Item = PathBuf>,160    {161        let mut cmd = Command::new(self.args[0].generate("", None));162        cmd.stdin(Stdio::inherit());163        cmd.stdout(Stdio::inherit());164        cmd.stderr(Stdio::inherit());165166        let mut paths: Vec<_> = paths.collect();167        let mut has_path = false;168169        for arg in &self.args[1..] {170            if arg.has_tokens() {171                paths.sort();172173                // A single `Tokens` is expected174                // So we can directly consume the iterator once and for all175                for path in &mut paths {176                    cmd.arg(arg.generate(strip_current_dir(path), self.path_separator.as_deref()));177                    has_path = true;178                }179            } else {180                cmd.arg(arg.generate("", None));181            }182        }183184        if has_path {185            execute_command(cmd, &Mutex::new(()), is_multithread)186        } else {187            ExitCode::Success188        }189    }190}191192/// Represents a template for a single command argument.193///194/// The argument is either a collection of `Token`s including at least one placeholder variant, or195/// a fixed text.196#[derive(Clone, Debug, PartialEq)]197enum ArgumentTemplate {198    Tokens(Vec<Token>),199    Text(String),200}201202impl ArgumentTemplate {203    pub fn has_tokens(&self) -> bool {204        matches!(self, ArgumentTemplate::Tokens(_))205    }206207    /// Generate an argument from this template. If path_separator is Some, then it will replace208    /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by209    /// path separator substitution.210    pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {211        use self::Token::*;212        let path = path.as_ref();213214        match *self {215            ArgumentTemplate::Tokens(ref tokens) => {216                let mut s = OsString::new();217                for token in tokens {218                    match *token {219                        Basename => s.push(Self::replace_separator(basename(path), path_separator)),220                        BasenameNoExt => s.push(Self::replace_separator(221                            &remove_extension(basename(path).as_ref()),222                            path_separator,223                        )),224                        NoExt => s.push(Self::replace_separator(225                            &remove_extension(path),226                            path_separator,227                        )),228                        Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),229                        Placeholder => {230                            s.push(Self::replace_separator(path.as_ref(), path_separator))231                        }232                        Text(ref string) => s.push(string),233                    }234                }235                s236            }237            ArgumentTemplate::Text(ref text) => OsString::from(text),238        }239    }240241    /// Replace the path separator in the input with the custom separator string. If path_separator242    /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is243    /// interpreted as a Path and its components are iterated through and re-joined into a new244    /// OsString.245    fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {246        // fast-path - no replacement necessary247        if path_separator.is_none() {248            return Cow::Borrowed(path);249        }250251        let path_separator = path_separator.unwrap();252        let mut out = OsString::with_capacity(path.len());253        let mut components = Path::new(path).components().peekable();254255        while let Some(comp) = components.next() {256            match comp {257                // Absolute paths on Windows are tricky.  A Prefix component is usually a drive258                // letter or UNC path, and is usually followed by RootDir. There are also259                // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to260                // ignore verbatim path prefixes here because they're very rare, might be261                // impossible to reach here, and there's no good way to deal with them. If users262                // are doing something advanced involving verbatim windows paths, they can do their263                // own output filtering with a tool like sed.264                Component::Prefix(prefix) => {265                    if let Prefix::UNC(server, share) = prefix.kind() {266                        // Prefix::UNC is a parsed version of '\\server\share'267                        out.push(path_separator);268                        out.push(path_separator);269                        out.push(server);270                        out.push(path_separator);271                        out.push(share);272                    } else {273                        // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for274                        // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,275                        // but they're not returned by directories fd can search anyway so we don't worry276                        // about them.277                        out.push(comp.as_os_str());278                    }279                }280281                // Root directory is always replaced with the custom separator.282                Component::RootDir => out.push(path_separator),283284                // Everything else is joined normally, with a trailing separator if we're not last285                _ => {286                    out.push(comp.as_os_str());287                    if components.peek().is_some() {288                        out.push(path_separator);289                    }290                }291            }292        }293        Cow::Owned(out)294    }295}296297#[cfg(test)]298mod tests {299    use super::*;300301    #[test]302    fn tokens_with_placeholder() {303        assert_eq!(304            CommandTemplate::new(&[&"echo", &"${SHELL}:"], None),305            CommandTemplate {306                args: vec![307                    ArgumentTemplate::Text("echo".into()),308                    ArgumentTemplate::Text("${SHELL}:".into()),309                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),310                ],311                mode: ExecutionMode::OneByOne,312                path_separator: None,313            }314        );315    }316317    #[test]318    fn tokens_with_no_extension() {319        assert_eq!(320            CommandTemplate::new(&["echo", "{.}"], None),321            CommandTemplate {322                args: vec![323                    ArgumentTemplate::Text("echo".into()),324                    ArgumentTemplate::Tokens(vec![Token::NoExt]),325                ],326                mode: ExecutionMode::OneByOne,327                path_separator: None,328            }329        );330    }331332    #[test]333    fn tokens_with_basename() {334        assert_eq!(335            CommandTemplate::new(&["echo", "{/}"], None),336            CommandTemplate {337                args: vec![338                    ArgumentTemplate::Text("echo".into()),339                    ArgumentTemplate::Tokens(vec![Token::Basename]),340                ],341                mode: ExecutionMode::OneByOne,342                path_separator: None,343            }344        );345    }346347    #[test]348    fn tokens_with_parent() {349        assert_eq!(350            CommandTemplate::new(&["echo", "{//}"], None),351            CommandTemplate {352                args: vec![353                    ArgumentTemplate::Text("echo".into()),354                    ArgumentTemplate::Tokens(vec![Token::Parent]),355                ],356                mode: ExecutionMode::OneByOne,357                path_separator: None,358            }359        );360    }361362    #[test]363    fn tokens_with_basename_no_extension() {364        assert_eq!(365            CommandTemplate::new(&["echo", "{/.}"], None),366            CommandTemplate {367                args: vec![368                    ArgumentTemplate::Text("echo".into()),369                    ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),370                ],371                mode: ExecutionMode::OneByOne,372                path_separator: None,373            }374        );375    }376377    #[test]378    fn tokens_multiple() {379        assert_eq!(380            CommandTemplate::new(&["cp", "{}", "{/.}.ext"], None),381            CommandTemplate {382                args: vec![383                    ArgumentTemplate::Text("cp".into()),384                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),385                    ArgumentTemplate::Tokens(vec![386                        Token::BasenameNoExt,387                        Token::Text(".ext".into())388                    ]),389                ],390                mode: ExecutionMode::OneByOne,391                path_separator: None,392            }393        );394    }395396    #[test]397    fn tokens_single_batch() {398        assert_eq!(399            CommandTemplate::new_batch(&["echo", "{.}"], None).unwrap(),400            CommandTemplate {401                args: vec![402                    ArgumentTemplate::Text("echo".into()),403                    ArgumentTemplate::Tokens(vec![Token::NoExt]),404                ],405                mode: ExecutionMode::Batch,406                path_separator: None,407            }408        );409    }410411    #[test]412    fn tokens_multiple_batch() {413        assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"], None).is_err());414    }415416    #[test]417    fn generate_custom_path_separator() {418        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);419        macro_rules! check {420            ($input:expr, $expected:expr) => {421                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));422            };423        }424425        check!("foo", "foo");426        check!("foo/bar", "foo#bar");427        check!("/foo/bar/baz", "#foo#bar#baz");428    }429430    #[cfg(windows)]431    #[test]432    fn generate_custom_path_separator_windows() {433        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);434        macro_rules! check {435            ($input:expr, $expected:expr) => {436                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));437            };438        }439440        // path starting with a drive letter441        check!(r"C:\foo\bar", "C:#foo#bar");442        // UNC path443        check!(r"\\server\share\path", "##server#share#path");444        // Drive Relative path - no separator after the colon omits the RootDir path component.445        // This is uncommon, but valid446        check!(r"C:foo\bar", "C:foo#bar");447448        // forward slashses should get normalized and interpreted as separators449        check!("C:/foo/bar", "C:#foo#bar");450        check!("C:foo/bar", "C:foo#bar");451452        // Rust does not intrepret "//server/share" as a UNC path, but rather as a normal453        // absolute path that begins with RootDir, and the two slashes get combined together as454        // a single path separator during normalization.455        //check!("//server/share/path", "##server#share#path");456    }457}