Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

345 lines · 10.1 KiB · Rust

Last changed by

Remove irrelevant TODOsharkdpbefore adoptionf9372b5

History of this file

Take it

1mod command;2mod input;3mod job;4mod token;56use std::borrow::Cow;7use std::path::{Path, PathBuf};8use std::process::{Command, Stdio};9use std::sync::{Arc, Mutex};1011use anyhow::{anyhow, Result};12use 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>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(anyhow!("Only one placeholder allowed for batch commands"));58        }59        if cmd.args[0].has_tokens() {60            return Err(anyhow!(61                "First argument of exec-batch is expected to be a fixed executable"62            ));63        }64        Ok(cmd)65    }6667    fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate68    where69        I: IntoIterator<Item = S>,70        S: AsRef<str>,71    {72        lazy_static! {73            static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();74        }7576        let mut args = Vec::new();77        let mut has_placeholder = false;7879        for arg in input {80            let arg = arg.as_ref();8182            let mut tokens = Vec::new();83            let mut start = 0;8485            for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {86                // Leading text before the placeholder.87                if placeholder.start() > start {88                    tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));89                }9091                start = placeholder.end();9293                match placeholder.as_str() {94                    "{}" => tokens.push(Token::Placeholder),95                    "{.}" => tokens.push(Token::NoExt),96                    "{/}" => tokens.push(Token::Basename),97                    "{//}" => tokens.push(Token::Parent),98                    "{/.}" => tokens.push(Token::BasenameNoExt),99                    _ => panic!("Unhandled placeholder"),100                }101102                has_placeholder = true;103            }104105            // Without a placeholder, the argument is just fixed text.106            if tokens.is_empty() {107                args.push(ArgumentTemplate::Text(arg.to_owned()));108                continue;109            }110111            if start < arg.len() {112                // Trailing text after last placeholder.113                tokens.push(Token::Text(arg[start..].to_owned()));114            }115116            args.push(ArgumentTemplate::Tokens(tokens));117        }118119        // If a placeholder token was not supplied, append one at the end of the command.120        if !has_placeholder {121            args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));122        }123124        CommandTemplate { args, mode }125    }126127    fn number_of_tokens(&self) -> usize {128        self.args.iter().filter(|arg| arg.has_tokens()).count()129    }130131    fn prepare_path(input: &Path) -> String {132        input133            .strip_prefix(".")134            .unwrap_or(input)135            .to_string_lossy()136            .into_owned()137    }138139    /// Generates and executes a command.140    ///141    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be142    /// build. Once all arguments have been processed, the command is executed.143    pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) -> ExitCode {144        let input = Self::prepare_path(input);145146        let mut cmd = Command::new(self.args[0].generate(&input).as_ref());147        for arg in &self.args[1..] {148            cmd.arg(arg.generate(&input).as_ref());149        }150151        execute_command(cmd, &out_perm)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) -> ExitCode159    where160        I: Iterator<Item = PathBuf>,161    {162        let mut cmd = Command::new(self.args[0].generate("").as_ref());163        cmd.stdin(Stdio::inherit());164        cmd.stdout(Stdio::inherit());165        cmd.stderr(Stdio::inherit());166167        let mut paths: Vec<String> = paths.map(|p| Self::prepare_path(&p)).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).as_ref());178                    has_path = true;179                }180            } else {181                cmd.arg(arg.generate("").as_ref());182            }183        }184185        if has_path {186            execute_command(cmd, &Mutex::new(()))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        match self {206            ArgumentTemplate::Tokens(_) => true,207            _ => false,208        }209    }210211    pub fn generate<'a>(&'a self, path: &str) -> Cow<'a, str> {212        use self::Token::*;213214        match *self {215            ArgumentTemplate::Tokens(ref tokens) => {216                let mut s = String::new();217                for token in tokens {218                    match *token {219                        Basename => s += basename(path),220                        BasenameNoExt => s += remove_extension(basename(path)),221                        NoExt => s += remove_extension(path),222                        Parent => s += dirname(path),223                        Placeholder => s += path,224                        Text(ref string) => s += string,225                    }226                }227                Cow::Owned(s)228            }229            ArgumentTemplate::Text(ref text) => Cow::Borrowed(text),230        }231    }232}233234#[cfg(test)]235mod tests {236    use super::*;237238    #[test]239    fn tokens_with_placeholder() {240        assert_eq!(241            CommandTemplate::new(&[&"echo", &"${SHELL}:"]),242            CommandTemplate {243                args: vec![244                    ArgumentTemplate::Text("echo".into()),245                    ArgumentTemplate::Text("${SHELL}:".into()),246                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),247                ],248                mode: ExecutionMode::OneByOne,249            }250        );251    }252253    #[test]254    fn tokens_with_no_extension() {255        assert_eq!(256            CommandTemplate::new(&["echo", "{.}"]),257            CommandTemplate {258                args: vec![259                    ArgumentTemplate::Text("echo".into()),260                    ArgumentTemplate::Tokens(vec![Token::NoExt]),261                ],262                mode: ExecutionMode::OneByOne,263            }264        );265    }266267    #[test]268    fn tokens_with_basename() {269        assert_eq!(270            CommandTemplate::new(&["echo", "{/}"]),271            CommandTemplate {272                args: vec![273                    ArgumentTemplate::Text("echo".into()),274                    ArgumentTemplate::Tokens(vec![Token::Basename]),275                ],276                mode: ExecutionMode::OneByOne,277            }278        );279    }280281    #[test]282    fn tokens_with_parent() {283        assert_eq!(284            CommandTemplate::new(&["echo", "{//}"]),285            CommandTemplate {286                args: vec![287                    ArgumentTemplate::Text("echo".into()),288                    ArgumentTemplate::Tokens(vec![Token::Parent]),289                ],290                mode: ExecutionMode::OneByOne,291            }292        );293    }294295    #[test]296    fn tokens_with_basename_no_extension() {297        assert_eq!(298            CommandTemplate::new(&["echo", "{/.}"]),299            CommandTemplate {300                args: vec![301                    ArgumentTemplate::Text("echo".into()),302                    ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),303                ],304                mode: ExecutionMode::OneByOne,305            }306        );307    }308309    #[test]310    fn tokens_multiple() {311        assert_eq!(312            CommandTemplate::new(&["cp", "{}", "{/.}.ext"]),313            CommandTemplate {314                args: vec![315                    ArgumentTemplate::Text("cp".into()),316                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),317                    ArgumentTemplate::Tokens(vec![318                        Token::BasenameNoExt,319                        Token::Text(".ext".into())320                    ]),321                ],322                mode: ExecutionMode::OneByOne,323            }324        );325    }326327    #[test]328    fn tokens_single_batch() {329        assert_eq!(330            CommandTemplate::new_batch(&["echo", "{.}"]).unwrap(),331            CommandTemplate {332                args: vec![333                    ArgumentTemplate::Text("echo".into()),334                    ArgumentTemplate::Tokens(vec![Token::NoExt]),335                ],336                mode: ExecutionMode::Batch,337            }338        );339    }340341    #[test]342    fn tokens_multiple_batch() {343        assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"]).is_err());344    }345}