Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

343 lines · 10.1 KiB · Rust

Last changed by

Remove outdated license headers (not strictly required by Apache-2.0)sharkdpbefore adoption4274075

History of this file

Take it

1// TODO: Possible optimization could avoid pushing characters on a buffer.2mod command;3mod input;4mod job;5mod token;67use std::borrow::Cow;8use std::path::{Path, PathBuf};9use std::process::{Command, Stdio};10use std::sync::{Arc, Mutex};1112use lazy_static::lazy_static;13use regex::Regex;1415use crate::exit_codes::ExitCode;1617use self::command::execute_command;18use self::input::{basename, dirname, remove_extension};19pub use self::job::{batch, job};20use self::token::Token;2122/// Execution mode of the command23#[derive(Debug, Clone, Copy, PartialEq)]24pub enum ExecutionMode {25    /// Command is executed for each search result26    OneByOne,27    /// Command is run for a batch of results at once28    Batch,29}3031/// Represents a template that is utilized to generate command strings.32///33/// The template is meant to be coupled with an input in order to generate a command. The34/// `generate_and_execute()` method will be used to generate a command and execute it.35#[derive(Debug, Clone, PartialEq)]36pub struct CommandTemplate {37    args: Vec<ArgumentTemplate>,38    mode: ExecutionMode,39}4041impl CommandTemplate {42    pub fn new<I, S>(input: I) -> CommandTemplate43    where44        I: IntoIterator<Item = S>,45        S: AsRef<str>,46    {47        Self::build(input, ExecutionMode::OneByOne)48    }4950    pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate, &'static str>51    where52        I: IntoIterator<Item = S>,53        S: AsRef<str>,54    {55        let cmd = Self::build(input, ExecutionMode::Batch);56        if cmd.number_of_tokens() > 1 {57            return Err("Only one placeholder allowed for batch commands");58        }59        if cmd.args[0].has_tokens() {60            return Err("First argument of exec-batch is expected to be a fixed executable");61        }62        Ok(cmd)63    }6465    fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate66    where67        I: IntoIterator<Item = S>,68        S: AsRef<str>,69    {70        lazy_static! {71            static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();72        }7374        let mut args = Vec::new();75        let mut has_placeholder = false;7677        for arg in input {78            let arg = arg.as_ref();7980            let mut tokens = Vec::new();81            let mut start = 0;8283            for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {84                // Leading text before the placeholder.85                if placeholder.start() > start {86                    tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));87                }8889                start = placeholder.end();9091                match placeholder.as_str() {92                    "{}" => tokens.push(Token::Placeholder),93                    "{.}" => tokens.push(Token::NoExt),94                    "{/}" => tokens.push(Token::Basename),95                    "{//}" => tokens.push(Token::Parent),96                    "{/.}" => tokens.push(Token::BasenameNoExt),97                    _ => panic!("Unhandled placeholder"),98                }99100                has_placeholder = true;101            }102103            // Without a placeholder, the argument is just fixed text.104            if tokens.is_empty() {105                args.push(ArgumentTemplate::Text(arg.to_owned()));106                continue;107            }108109            if start < arg.len() {110                // Trailing text after last placeholder.111                tokens.push(Token::Text(arg[start..].to_owned()));112            }113114            args.push(ArgumentTemplate::Tokens(tokens));115        }116117        // If a placeholder token was not supplied, append one at the end of the command.118        if !has_placeholder {119            args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));120        }121122        CommandTemplate { args, mode }123    }124125    fn number_of_tokens(&self) -> usize {126        self.args.iter().filter(|arg| arg.has_tokens()).count()127    }128129    fn prepare_path(input: &Path) -> String {130        input131            .strip_prefix(".")132            .unwrap_or(input)133            .to_string_lossy()134            .into_owned()135    }136137    /// Generates and executes a command.138    ///139    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be140    /// build. Once all arguments have been processed, the command is executed.141    pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) -> ExitCode {142        let input = Self::prepare_path(input);143144        let mut cmd = Command::new(self.args[0].generate(&input).as_ref());145        for arg in &self.args[1..] {146            cmd.arg(arg.generate(&input).as_ref());147        }148149        execute_command(cmd, &out_perm)150    }151152    pub fn in_batch_mode(&self) -> bool {153        self.mode == ExecutionMode::Batch154    }155156    pub fn generate_and_execute_batch<I>(&self, paths: I) -> ExitCode157    where158        I: Iterator<Item = PathBuf>,159    {160        let mut cmd = Command::new(self.args[0].generate("").as_ref());161        cmd.stdin(Stdio::inherit());162        cmd.stdout(Stdio::inherit());163        cmd.stderr(Stdio::inherit());164165        let mut paths: Vec<String> = paths.map(|p| Self::prepare_path(&p)).collect();166        let mut has_path = false;167168        for arg in &self.args[1..] {169            if arg.has_tokens() {170                paths.sort();171172                // A single `Tokens` is expected173                // So we can directly consume the iterator once and for all174                for path in &mut paths {175                    cmd.arg(arg.generate(&path).as_ref());176                    has_path = true;177                }178            } else {179                cmd.arg(arg.generate("").as_ref());180            }181        }182183        if has_path {184            execute_command(cmd, &Mutex::new(()))185        } else {186            ExitCode::Success187        }188    }189}190191/// Represents a template for a single command argument.192///193/// The argument is either a collection of `Token`s including at least one placeholder variant, or194/// a fixed text.195#[derive(Clone, Debug, PartialEq)]196enum ArgumentTemplate {197    Tokens(Vec<Token>),198    Text(String),199}200201impl ArgumentTemplate {202    pub fn has_tokens(&self) -> bool {203        match self {204            ArgumentTemplate::Tokens(_) => true,205            _ => false,206        }207    }208209    pub fn generate<'a>(&'a self, path: &str) -> Cow<'a, str> {210        use self::Token::*;211212        match *self {213            ArgumentTemplate::Tokens(ref tokens) => {214                let mut s = String::new();215                for token in tokens {216                    match *token {217                        Basename => s += basename(path),218                        BasenameNoExt => s += remove_extension(basename(path)),219                        NoExt => s += remove_extension(path),220                        Parent => s += dirname(path),221                        Placeholder => s += path,222                        Text(ref string) => s += string,223                    }224                }225                Cow::Owned(s)226            }227            ArgumentTemplate::Text(ref text) => Cow::Borrowed(text),228        }229    }230}231232#[cfg(test)]233mod tests {234    use super::*;235236    #[test]237    fn tokens_with_placeholder() {238        assert_eq!(239            CommandTemplate::new(&[&"echo", &"${SHELL}:"]),240            CommandTemplate {241                args: vec![242                    ArgumentTemplate::Text("echo".into()),243                    ArgumentTemplate::Text("${SHELL}:".into()),244                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),245                ],246                mode: ExecutionMode::OneByOne,247            }248        );249    }250251    #[test]252    fn tokens_with_no_extension() {253        assert_eq!(254            CommandTemplate::new(&["echo", "{.}"]),255            CommandTemplate {256                args: vec![257                    ArgumentTemplate::Text("echo".into()),258                    ArgumentTemplate::Tokens(vec![Token::NoExt]),259                ],260                mode: ExecutionMode::OneByOne,261            }262        );263    }264265    #[test]266    fn tokens_with_basename() {267        assert_eq!(268            CommandTemplate::new(&["echo", "{/}"]),269            CommandTemplate {270                args: vec![271                    ArgumentTemplate::Text("echo".into()),272                    ArgumentTemplate::Tokens(vec![Token::Basename]),273                ],274                mode: ExecutionMode::OneByOne,275            }276        );277    }278279    #[test]280    fn tokens_with_parent() {281        assert_eq!(282            CommandTemplate::new(&["echo", "{//}"]),283            CommandTemplate {284                args: vec![285                    ArgumentTemplate::Text("echo".into()),286                    ArgumentTemplate::Tokens(vec![Token::Parent]),287                ],288                mode: ExecutionMode::OneByOne,289            }290        );291    }292293    #[test]294    fn tokens_with_basename_no_extension() {295        assert_eq!(296            CommandTemplate::new(&["echo", "{/.}"]),297            CommandTemplate {298                args: vec![299                    ArgumentTemplate::Text("echo".into()),300                    ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),301                ],302                mode: ExecutionMode::OneByOne,303            }304        );305    }306307    #[test]308    fn tokens_multiple() {309        assert_eq!(310            CommandTemplate::new(&["cp", "{}", "{/.}.ext"]),311            CommandTemplate {312                args: vec![313                    ArgumentTemplate::Text("cp".into()),314                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),315                    ArgumentTemplate::Tokens(vec![316                        Token::BasenameNoExt,317                        Token::Text(".ext".into())318                    ]),319                ],320                mode: ExecutionMode::OneByOne,321            }322        );323    }324325    #[test]326    fn tokens_single_batch() {327        assert_eq!(328            CommandTemplate::new_batch(&["echo", "{.}"]).unwrap(),329            CommandTemplate {330                args: vec![331                    ArgumentTemplate::Text("echo".into()),332                    ArgumentTemplate::Tokens(vec![Token::NoExt]),333                ],334                mode: ExecutionMode::Batch,335            }336        );337    }338339    #[test]340    fn tokens_multiple_batch() {341        assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"]).is_err());342    }343}