Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

345 lines · 10.3 KiB · Rust

Last changed by

[2018 edition] remove all extern crate lines from sourcesAlexandru Macoveibefore adoption051ff59

History of this file

Take it

1// Copyright (c) 2017 fd developers2// Licensed under the Apache License, Version 2.03// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>4// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,5// at your option. All files in the project carrying such6// notice may not be copied, modified, or distributed except7// according to those terms.89// TODO: Possible optimization could avoid pushing characters on a buffer.10mod command;11mod input;12mod job;13mod token;1415use std::borrow::Cow;16use std::path::{Path, PathBuf};17use std::process::{Command, Stdio};18use std::sync::{Arc, Mutex};1920use lazy_static::lazy_static;21use regex::Regex;2223use self::command::execute_command;24use self::input::{basename, dirname, remove_extension};25pub use self::job::{batch, job};26use self::token::Token;2728/// Execution mode of the command29#[derive(Debug, Clone, Copy, PartialEq)]30pub enum ExecutionMode {31    /// Command is executed for each search result32    OneByOne,33    /// Command is run for a batch of results at once34    Batch,35}3637/// Represents a template that is utilized to generate command strings.38///39/// The template is meant to be coupled with an input in order to generate a command. The40/// `generate_and_execute()` method will be used to generate a command and execute it.41#[derive(Debug, Clone, PartialEq)]42pub struct CommandTemplate {43    args: Vec<ArgumentTemplate>,44    mode: ExecutionMode,45}4647impl CommandTemplate {48    pub fn new<I, S>(input: I) -> CommandTemplate49    where50        I: IntoIterator<Item = S>,51        S: AsRef<str>,52    {53        Self::build(input, ExecutionMode::OneByOne)54    }5556    pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate, &'static str>57    where58        I: IntoIterator<Item = S>,59        S: AsRef<str>,60    {61        let cmd = Self::build(input, ExecutionMode::Batch);62        if cmd.number_of_tokens() > 1 {63            return Err("Only one placeholder allowed for batch commands");64        }65        if cmd.args[0].has_tokens() {66            return Err("First argument of exec-batch is expected to be a fixed executable");67        }68        Ok(cmd)69    }7071    fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate72    where73        I: IntoIterator<Item = S>,74        S: AsRef<str>,75    {76        lazy_static! {77            static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();78        }7980        let mut args = Vec::new();81        let mut has_placeholder = false;8283        for arg in input {84            let arg = arg.as_ref();8586            let mut tokens = Vec::new();87            let mut start = 0;8889            for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {90                // Leading text before the placeholder.91                if placeholder.start() > start {92                    tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));93                }9495                start = placeholder.end();9697                match placeholder.as_str() {98                    "{}" => tokens.push(Token::Placeholder),99                    "{.}" => tokens.push(Token::NoExt),100                    "{/}" => tokens.push(Token::Basename),101                    "{//}" => tokens.push(Token::Parent),102                    "{/.}" => tokens.push(Token::BasenameNoExt),103                    _ => panic!("Unhandled placeholder"),104                }105106                has_placeholder = true;107            }108109            // Without a placeholder, the argument is just fixed text.110            if tokens.is_empty() {111                args.push(ArgumentTemplate::Text(arg.to_owned()));112                continue;113            }114115            if start < arg.len() {116                // Trailing text after last placeholder.117                tokens.push(Token::Text(arg[start..].to_owned()));118            }119120            args.push(ArgumentTemplate::Tokens(tokens));121        }122123        // If a placeholder token was not supplied, append one at the end of the command.124        if !has_placeholder {125            args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));126        }127128        CommandTemplate { args, mode }129    }130131    fn number_of_tokens(&self) -> usize {132        self.args.iter().filter(|arg| arg.has_tokens()).count()133    }134135    fn prepare_path(input: &Path) -> String {136        input137            .strip_prefix(".")138            .unwrap_or(input)139            .to_string_lossy()140            .into_owned()141    }142143    /// Generates and executes a command.144    ///145    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be146    /// build. Once all arguments have been processed, the command is executed.147    pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) {148        let input = Self::prepare_path(input);149150        let mut cmd = Command::new(self.args[0].generate(&input).as_ref());151        for arg in &self.args[1..] {152            cmd.arg(arg.generate(&input).as_ref());153        }154155        execute_command(cmd, &out_perm)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)163    where164        I: Iterator<Item = PathBuf>,165    {166        let mut cmd = Command::new(self.args[0].generate("").as_ref());167        cmd.stdin(Stdio::inherit());168        cmd.stdout(Stdio::inherit());169        cmd.stderr(Stdio::inherit());170171        let mut paths = paths.map(|p| Self::prepare_path(&p));172        let mut has_path = false;173174        for arg in &self.args[1..] {175            if arg.has_tokens() {176                // A single `Tokens` is expected177                // So we can directy consume the iterator once and for all178                for path in &mut paths {179                    cmd.arg(arg.generate(&path).as_ref());180                    has_path = true;181                }182            } else {183                cmd.arg(arg.generate("").as_ref());184            }185        }186187        if has_path {188            execute_command(cmd, &Mutex::new(()));189        }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}