Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

473 lines · 13.9 KiB · Rust

Last changed by

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

History of this file

Take it

1mod command;2mod job;34use std::ffi::OsString;5use std::io;6use std::iter;7use std::path::{Path, PathBuf};8use std::process::Stdio;910use anyhow::{Result, bail};11use argmax::Command;1213use crate::exec::command::OutputBuffer;14use crate::exit_codes::{ExitCode, merge_exitcodes};15use crate::fmt::{FormatTemplate, Token};1617use self::command::{execute_commands, handle_cmd_error};18pub use self::job::{batch, job};1920/// Execution mode of the command21#[derive(Debug, Clone, Copy, PartialEq, Eq)]22pub enum ExecutionMode {23    /// Command is executed for each search result24    OneByOne,25    /// Command is run for a batch of results at once26    Batch,27}2829#[derive(Debug, Clone, PartialEq)]30pub struct CommandSet {31    mode: ExecutionMode,32    commands: Vec<CommandTemplate>,33}3435impl CommandSet {36    pub fn new<I, T, S>(input: I) -> Result<CommandSet>37    where38        I: IntoIterator<Item = T>,39        T: IntoIterator<Item = S>,40        S: AsRef<str>,41    {42        Ok(CommandSet {43            mode: ExecutionMode::OneByOne,44            commands: input45                .into_iter()46                .map(CommandTemplate::new)47                .collect::<Result<_>>()?,48        })49    }5051    pub fn new_batch<I, T, S>(input: I) -> Result<CommandSet>52    where53        I: IntoIterator<Item = T>,54        T: IntoIterator<Item = S>,55        S: AsRef<str>,56    {57        Ok(CommandSet {58            mode: ExecutionMode::Batch,59            commands: input60                .into_iter()61                .map(|args| {62                    let cmd = CommandTemplate::new(args)?;63                    if cmd.number_of_tokens() > 1 {64                        bail!("Only one placeholder allowed for batch commands");65                    }66                    if cmd.args[0].has_tokens() {67                        bail!("First argument of exec-batch is expected to be a fixed executable");68                    }69                    Ok(cmd)70                })71                .collect::<Result<Vec<_>>>()?,72        })73    }7475    pub fn in_batch_mode(&self) -> bool {76        self.mode == ExecutionMode::Batch77    }7879    pub fn execute(80        &self,81        input: &Path,82        path_separator: Option<&str>,83        null_separator: bool,84        buffer_output: bool,85    ) -> ExitCode {86        let commands = self87            .commands88            .iter()89            .map(|c| c.generate(input, path_separator));90        execute_commands(commands, OutputBuffer::new(null_separator), buffer_output)91    }9293    pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode94    where95        I: Iterator<Item = PathBuf>,96    {97        let builders: io::Result<Vec<_>> = self98            .commands99            .iter()100            .map(|c| CommandBuilder::new(c, limit))101            .collect();102103        match builders {104            Ok(mut builders) => {105                for path in paths {106                    for builder in &mut builders {107                        if let Err(e) = builder.push(&path, path_separator) {108                            return handle_cmd_error(Some(&builder.cmd), e);109                        }110                    }111                }112113                for builder in &mut builders {114                    if let Err(e) = builder.finish() {115                        return handle_cmd_error(Some(&builder.cmd), e);116                    }117                }118119                merge_exitcodes(builders.iter().map(|b| b.exit_code()))120            }121            Err(e) => handle_cmd_error(None, e),122        }123    }124}125126/// Represents a multi-exec command as it is built.127#[derive(Debug)]128struct CommandBuilder {129    pre_args: Vec<OsString>,130    path_arg: FormatTemplate,131    post_args: Vec<OsString>,132    cmd: Command,133    count: usize,134    limit: usize,135    exit_code: ExitCode,136}137138impl CommandBuilder {139    fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {140        let mut pre_args = vec![];141        let mut path_arg = None;142        let mut post_args = vec![];143144        for arg in &template.args {145            if arg.has_tokens() {146                path_arg = Some(arg.clone());147            } else if path_arg.is_none() {148                pre_args.push(arg.generate("", None));149            } else {150                post_args.push(arg.generate("", None));151            }152        }153154        let cmd = Self::new_command(&pre_args)?;155156        Ok(Self {157            pre_args,158            path_arg: path_arg.unwrap(),159            post_args,160            cmd,161            count: 0,162            limit,163            exit_code: ExitCode::Success,164        })165    }166167    fn new_command(pre_args: &[OsString]) -> io::Result<Command> {168        let mut cmd = Command::new(&pre_args[0]);169        cmd.stdin(Stdio::inherit());170        cmd.stdout(Stdio::inherit());171        cmd.stderr(Stdio::inherit());172        cmd.try_args(&pre_args[1..])?;173        Ok(cmd)174    }175176    fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {177        if self.limit > 0 && self.count >= self.limit {178            self.finish()?;179        }180181        let arg = self.path_arg.generate(path, separator);182        if !self183            .cmd184            .args_would_fit(iter::once(&arg).chain(&self.post_args))185        {186            self.finish()?;187        }188189        self.cmd.try_arg(arg)?;190        self.count += 1;191        Ok(())192    }193194    fn finish(&mut self) -> io::Result<()> {195        if self.count > 0 {196            self.cmd.try_args(&self.post_args)?;197            if !self.cmd.status()?.success() {198                self.exit_code = ExitCode::GeneralError;199            }200201            self.cmd = Self::new_command(&self.pre_args)?;202            self.count = 0;203        }204205        Ok(())206    }207208    fn exit_code(&self) -> ExitCode {209        self.exit_code210    }211}212213/// Represents a template that is utilized to generate command strings.214///215/// The template is meant to be coupled with an input in order to generate a command. The216/// `generate_and_execute()` method will be used to generate a command and execute it.217#[derive(Debug, Clone, PartialEq)]218struct CommandTemplate {219    args: Vec<FormatTemplate>,220}221222impl CommandTemplate {223    fn new<I, S>(input: I) -> Result<CommandTemplate>224    where225        I: IntoIterator<Item = S>,226        S: AsRef<str>,227    {228        let mut args = Vec::new();229        let mut has_placeholder = false;230231        for arg in input {232            let arg = arg.as_ref();233234            let tmpl = FormatTemplate::parse(arg);235            has_placeholder |= tmpl.has_tokens();236            args.push(tmpl);237        }238239        // We need to check that we have at least one argument, because if not240        // it will try to execute each file and directory it finds.241        //242        // Sadly, clap can't currently handle this for us, see243        // https://github.com/clap-rs/clap/issues/3542244        if args.is_empty() {245            bail!("No executable provided for --exec or --exec-batch");246        }247248        // If a placeholder token was not supplied, append one at the end of the command.249        if !has_placeholder {250            args.push(FormatTemplate::Tokens(vec![Token::Placeholder]));251        }252253        Ok(CommandTemplate { args })254    }255256    fn number_of_tokens(&self) -> usize {257        self.args.iter().filter(|arg| arg.has_tokens()).count()258    }259260    /// Generates and executes a command.261    ///262    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be263    /// build.264    fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {265        let mut cmd = Command::new(self.args[0].generate(input, path_separator));266        for arg in &self.args[1..] {267            cmd.try_arg(arg.generate(input, path_separator))?;268        }269        Ok(cmd)270    }271}272273#[cfg(test)]274mod tests {275    use super::*;276277    fn generate_str(template: &CommandTemplate, input: &str) -> Vec<String> {278        template279            .args280            .iter()281            .map(|arg| arg.generate(input, None).into_string().unwrap())282            .collect()283    }284285    #[test]286    fn tokens_with_placeholder() {287        assert_eq!(288            CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),289            CommandSet {290                commands: vec![CommandTemplate {291                    args: vec![292                        FormatTemplate::Text("echo".into()),293                        FormatTemplate::Text("${SHELL}:".into()),294                        FormatTemplate::Tokens(vec![Token::Placeholder]),295                    ]296                }],297                mode: ExecutionMode::OneByOne,298            }299        );300    }301302    #[test]303    fn tokens_with_no_extension() {304        assert_eq!(305            CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),306            CommandSet {307                commands: vec![CommandTemplate {308                    args: vec![309                        FormatTemplate::Text("echo".into()),310                        FormatTemplate::Tokens(vec![Token::NoExt]),311                    ],312                }],313                mode: ExecutionMode::OneByOne,314            }315        );316    }317318    #[test]319    fn tokens_with_basename() {320        assert_eq!(321            CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),322            CommandSet {323                commands: vec![CommandTemplate {324                    args: vec![325                        FormatTemplate::Text("echo".into()),326                        FormatTemplate::Tokens(vec![Token::Basename]),327                    ],328                }],329                mode: ExecutionMode::OneByOne,330            }331        );332    }333334    #[test]335    fn tokens_with_parent() {336        assert_eq!(337            CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),338            CommandSet {339                commands: vec![CommandTemplate {340                    args: vec![341                        FormatTemplate::Text("echo".into()),342                        FormatTemplate::Tokens(vec![Token::Parent]),343                    ],344                }],345                mode: ExecutionMode::OneByOne,346            }347        );348    }349350    #[test]351    fn tokens_with_basename_no_extension() {352        assert_eq!(353            CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),354            CommandSet {355                commands: vec![CommandTemplate {356                    args: vec![357                        FormatTemplate::Text("echo".into()),358                        FormatTemplate::Tokens(vec![Token::BasenameNoExt]),359                    ],360                }],361                mode: ExecutionMode::OneByOne,362            }363        );364    }365366    #[test]367    fn tokens_with_literal_braces() {368        let template = CommandTemplate::new(vec!["{{}}", "{{", "{.}}"]).unwrap();369        assert_eq!(370            generate_str(&template, "foo"),371            vec!["{}", "{", "{.}", "foo"]372        );373    }374375    #[test]376    fn tokens_with_literal_braces_and_placeholder() {377        let template = CommandTemplate::new(vec!["{{{},end}"]).unwrap();378        assert_eq!(generate_str(&template, "foo"), vec!["{foo,end}"]);379    }380381    #[test]382    fn tokens_multiple() {383        assert_eq!(384            CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),385            CommandSet {386                commands: vec![CommandTemplate {387                    args: vec![388                        FormatTemplate::Text("cp".into()),389                        FormatTemplate::Tokens(vec![Token::Placeholder]),390                        FormatTemplate::Tokens(vec![391                            Token::BasenameNoExt,392                            Token::Text(".ext".into())393                        ]),394                    ],395                }],396                mode: ExecutionMode::OneByOne,397            }398        );399    }400401    #[test]402    fn tokens_single_batch() {403        assert_eq!(404            CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),405            CommandSet {406                commands: vec![CommandTemplate {407                    args: vec![408                        FormatTemplate::Text("echo".into()),409                        FormatTemplate::Tokens(vec![Token::NoExt]),410                    ],411                }],412                mode: ExecutionMode::Batch,413            }414        );415    }416417    #[test]418    fn tokens_multiple_batch() {419        assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());420    }421422    #[test]423    fn template_no_args() {424        assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());425    }426427    #[test]428    fn command_set_no_args() {429        assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());430    }431432    #[test]433    fn generate_custom_path_separator() {434        let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);435        macro_rules! check {436            ($input:expr, $expected:expr) => {437                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));438            };439        }440441        check!("foo", "foo");442        check!("foo/bar", "foo#bar");443        check!("/foo/bar/baz", "#foo#bar#baz");444    }445446    #[cfg(windows)]447    #[test]448    fn generate_custom_path_separator_windows() {449        let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);450        macro_rules! check {451            ($input:expr, $expected:expr) => {452                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));453            };454        }455456        // path starting with a drive letter457        check!(r"C:\foo\bar", "C:#foo#bar");458        // UNC path459        check!(r"\\server\share\path", "##server#share#path");460        // Drive Relative path - no separator after the colon omits the RootDir path component.461        // This is uncommon, but valid462        check!(r"C:foo\bar", "C:foo#bar");463464        // forward slashes should get normalized and interpreted as separators465        check!("C:/foo/bar", "C:#foo#bar");466        check!("C:foo/bar", "C:foo#bar");467468        // Rust does not interpret "//server/share" as a UNC path, but rather as a normal469        // absolute path that begins with RootDir, and the two slashes get combined together as470        // a single path separator during normalization.471        //check!("//server/share/path", "##server#share#path");472    }473}