Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

351 lines · 10.5 KiB · Rust

Last changed by

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

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 crate::exit_codes::ExitCode;2425use self::command::execute_command;26use self::input::{basename, dirname, remove_extension};27pub use self::job::{batch, job};28use self::token::Token;2930/// Execution mode of the command31#[derive(Debug, Clone, Copy, PartialEq)]32pub enum ExecutionMode {33    /// Command is executed for each search result34    OneByOne,35    /// Command is run for a batch of results at once36    Batch,37}3839/// Represents a template that is utilized to generate command strings.40///41/// The template is meant to be coupled with an input in order to generate a command. The42/// `generate_and_execute()` method will be used to generate a command and execute it.43#[derive(Debug, Clone, PartialEq)]44pub struct CommandTemplate {45    args: Vec<ArgumentTemplate>,46    mode: ExecutionMode,47}4849impl CommandTemplate {50    pub fn new<I, S>(input: I) -> CommandTemplate51    where52        I: IntoIterator<Item = S>,53        S: AsRef<str>,54    {55        Self::build(input, ExecutionMode::OneByOne)56    }5758    pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate, &'static str>59    where60        I: IntoIterator<Item = S>,61        S: AsRef<str>,62    {63        let cmd = Self::build(input, ExecutionMode::Batch);64        if cmd.number_of_tokens() > 1 {65            return Err("Only one placeholder allowed for batch commands");66        }67        if cmd.args[0].has_tokens() {68            return Err("First argument of exec-batch is expected to be a fixed executable");69        }70        Ok(cmd)71    }7273    fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate74    where75        I: IntoIterator<Item = S>,76        S: AsRef<str>,77    {78        lazy_static! {79            static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();80        }8182        let mut args = Vec::new();83        let mut has_placeholder = false;8485        for arg in input {86            let arg = arg.as_ref();8788            let mut tokens = Vec::new();89            let mut start = 0;9091            for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {92                // Leading text before the placeholder.93                if placeholder.start() > start {94                    tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));95                }9697                start = placeholder.end();9899                match placeholder.as_str() {100                    "{}" => tokens.push(Token::Placeholder),101                    "{.}" => tokens.push(Token::NoExt),102                    "{/}" => tokens.push(Token::Basename),103                    "{//}" => tokens.push(Token::Parent),104                    "{/.}" => tokens.push(Token::BasenameNoExt),105                    _ => panic!("Unhandled placeholder"),106                }107108                has_placeholder = true;109            }110111            // Without a placeholder, the argument is just fixed text.112            if tokens.is_empty() {113                args.push(ArgumentTemplate::Text(arg.to_owned()));114                continue;115            }116117            if start < arg.len() {118                // Trailing text after last placeholder.119                tokens.push(Token::Text(arg[start..].to_owned()));120            }121122            args.push(ArgumentTemplate::Tokens(tokens));123        }124125        // If a placeholder token was not supplied, append one at the end of the command.126        if !has_placeholder {127            args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));128        }129130        CommandTemplate { args, mode }131    }132133    fn number_of_tokens(&self) -> usize {134        self.args.iter().filter(|arg| arg.has_tokens()).count()135    }136137    fn prepare_path(input: &Path) -> String {138        input139            .strip_prefix(".")140            .unwrap_or(input)141            .to_string_lossy()142            .into_owned()143    }144145    /// Generates and executes a command.146    ///147    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be148    /// build. Once all arguments have been processed, the command is executed.149    pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) {150        let input = Self::prepare_path(input);151152        let mut cmd = Command::new(self.args[0].generate(&input).as_ref());153        for arg in &self.args[1..] {154            cmd.arg(arg.generate(&input).as_ref());155        }156157        execute_command(cmd, &out_perm);158    }159160    pub fn in_batch_mode(&self) -> bool {161        self.mode == ExecutionMode::Batch162    }163164    pub fn generate_and_execute_batch<I>(&self, paths: I) -> ExitCode165    where166        I: Iterator<Item = PathBuf>,167    {168        let mut cmd = Command::new(self.args[0].generate("").as_ref());169        cmd.stdin(Stdio::inherit());170        cmd.stdout(Stdio::inherit());171        cmd.stderr(Stdio::inherit());172173        let mut paths: Vec<String> = paths.map(|p| Self::prepare_path(&p)).collect();174        let mut has_path = false;175176        for arg in &self.args[1..] {177            if arg.has_tokens() {178                paths.sort();179180                // A single `Tokens` is expected181                // So we can directly consume the iterator once and for all182                for path in &mut paths {183                    cmd.arg(arg.generate(&path).as_ref());184                    has_path = true;185                }186            } else {187                cmd.arg(arg.generate("").as_ref());188            }189        }190191        if has_path {192            execute_command(cmd, &Mutex::new(()))193        } else {194            ExitCode::Success195        }196    }197}198199/// Represents a template for a single command argument.200///201/// The argument is either a collection of `Token`s including at least one placeholder variant, or202/// a fixed text.203#[derive(Clone, Debug, PartialEq)]204enum ArgumentTemplate {205    Tokens(Vec<Token>),206    Text(String),207}208209impl ArgumentTemplate {210    pub fn has_tokens(&self) -> bool {211        match self {212            ArgumentTemplate::Tokens(_) => true,213            _ => false,214        }215    }216217    pub fn generate<'a>(&'a self, path: &str) -> Cow<'a, str> {218        use self::Token::*;219220        match *self {221            ArgumentTemplate::Tokens(ref tokens) => {222                let mut s = String::new();223                for token in tokens {224                    match *token {225                        Basename => s += basename(path),226                        BasenameNoExt => s += remove_extension(basename(path)),227                        NoExt => s += remove_extension(path),228                        Parent => s += dirname(path),229                        Placeholder => s += path,230                        Text(ref string) => s += string,231                    }232                }233                Cow::Owned(s)234            }235            ArgumentTemplate::Text(ref text) => Cow::Borrowed(text),236        }237    }238}239240#[cfg(test)]241mod tests {242    use super::*;243244    #[test]245    fn tokens_with_placeholder() {246        assert_eq!(247            CommandTemplate::new(&[&"echo", &"${SHELL}:"]),248            CommandTemplate {249                args: vec![250                    ArgumentTemplate::Text("echo".into()),251                    ArgumentTemplate::Text("${SHELL}:".into()),252                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),253                ],254                mode: ExecutionMode::OneByOne,255            }256        );257    }258259    #[test]260    fn tokens_with_no_extension() {261        assert_eq!(262            CommandTemplate::new(&["echo", "{.}"]),263            CommandTemplate {264                args: vec![265                    ArgumentTemplate::Text("echo".into()),266                    ArgumentTemplate::Tokens(vec![Token::NoExt]),267                ],268                mode: ExecutionMode::OneByOne,269            }270        );271    }272273    #[test]274    fn tokens_with_basename() {275        assert_eq!(276            CommandTemplate::new(&["echo", "{/}"]),277            CommandTemplate {278                args: vec![279                    ArgumentTemplate::Text("echo".into()),280                    ArgumentTemplate::Tokens(vec![Token::Basename]),281                ],282                mode: ExecutionMode::OneByOne,283            }284        );285    }286287    #[test]288    fn tokens_with_parent() {289        assert_eq!(290            CommandTemplate::new(&["echo", "{//}"]),291            CommandTemplate {292                args: vec![293                    ArgumentTemplate::Text("echo".into()),294                    ArgumentTemplate::Tokens(vec![Token::Parent]),295                ],296                mode: ExecutionMode::OneByOne,297            }298        );299    }300301    #[test]302    fn tokens_with_basename_no_extension() {303        assert_eq!(304            CommandTemplate::new(&["echo", "{/.}"]),305            CommandTemplate {306                args: vec![307                    ArgumentTemplate::Text("echo".into()),308                    ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),309                ],310                mode: ExecutionMode::OneByOne,311            }312        );313    }314315    #[test]316    fn tokens_multiple() {317        assert_eq!(318            CommandTemplate::new(&["cp", "{}", "{/.}.ext"]),319            CommandTemplate {320                args: vec![321                    ArgumentTemplate::Text("cp".into()),322                    ArgumentTemplate::Tokens(vec![Token::Placeholder]),323                    ArgumentTemplate::Tokens(vec![324                        Token::BasenameNoExt,325                        Token::Text(".ext".into())326                    ]),327                ],328                mode: ExecutionMode::OneByOne,329            }330        );331    }332333    #[test]334    fn tokens_single_batch() {335        assert_eq!(336            CommandTemplate::new_batch(&["echo", "{.}"]).unwrap(),337            CommandTemplate {338                args: vec![339                    ArgumentTemplate::Text("echo".into()),340                    ArgumentTemplate::Tokens(vec![Token::NoExt]),341                ],342                mode: ExecutionMode::Batch,343            }344        );345    }346347    #[test]348    fn tokens_multiple_batch() {349        assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"]).is_err());350    }351}