Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

485 lines · 14.3 KiB · Rust

Last changed by

apply strict filtercurious-rabbitbefore adoptionaeecb5d

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                    Ok(cmd)67                })68                .collect::<Result<Vec<_>>>()?,69        })70    }7172    pub fn in_batch_mode(&self) -> bool {73        self.mode == ExecutionMode::Batch74    }7576    pub fn execute(77        &self,78        input: &Path,79        path_separator: Option<&str>,80        null_separator: bool,81        buffer_output: bool,82    ) -> ExitCode {83        let commands = self84            .commands85            .iter()86            .map(|c| c.generate(input, path_separator));87        execute_commands(commands, OutputBuffer::new(null_separator), buffer_output)88    }8990    pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode91    where92        I: Iterator<Item = PathBuf>,93    {94        let builders: io::Result<Vec<_>> = self95            .commands96            .iter()97            .map(|c| CommandBuilder::new(c, limit))98            .collect();99100        match builders {101            Ok(mut builders) => {102                for path in paths {103                    for builder in &mut builders {104                        if let Err(e) = builder.push(&path, path_separator) {105                            return handle_cmd_error(Some(&builder.cmd), e);106                        }107                    }108                }109110                for builder in &mut builders {111                    if let Err(e) = builder.finish() {112                        return handle_cmd_error(Some(&builder.cmd), e);113                    }114                }115116                merge_exitcodes(builders.iter().map(|b| b.exit_code()))117            }118            Err(e) => handle_cmd_error(None, e),119        }120    }121}122123/// Represents a multi-exec command as it is built.124#[derive(Debug)]125struct CommandBuilder {126    pre_args: Vec<OsString>,127    path_arg: FormatTemplate,128    post_args: Vec<OsString>,129    cmd: Command,130    count: usize,131    limit: usize,132    exit_code: ExitCode,133}134135impl CommandBuilder {136    fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {137        let mut pre_args = vec![];138        let mut path_arg = None;139        let mut post_args = vec![];140141        for arg in &template.args {142            if arg.has_tokens() {143                path_arg = Some(arg.clone());144            } else if path_arg.is_none() {145                pre_args.push(arg.generate("", None));146            } else {147                post_args.push(arg.generate("", None));148            }149        }150151        let cmd = Self::new_command(&pre_args)?;152153        Ok(Self {154            pre_args,155            path_arg: path_arg.unwrap(),156            post_args,157            cmd,158            count: 0,159            limit,160            exit_code: ExitCode::Success,161        })162    }163164    fn new_command(pre_args: &[OsString]) -> io::Result<Command> {165        let mut cmd = Command::new(&pre_args[0]);166        cmd.stdin(Stdio::inherit());167        cmd.stdout(Stdio::inherit());168        cmd.stderr(Stdio::inherit());169        cmd.try_args(&pre_args[1..])?;170        Ok(cmd)171    }172173    fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {174        if self.limit > 0 && self.count >= self.limit {175            self.finish()?;176        }177178        let arg = self.path_arg.generate(path, separator);179        if !self180            .cmd181            .args_would_fit(iter::once(&arg).chain(&self.post_args))182        {183            self.finish()?;184        }185186        self.cmd.try_arg(arg)?;187        self.count += 1;188        Ok(())189    }190191    fn finish(&mut self) -> io::Result<()> {192        if self.count > 0 {193            self.cmd.try_args(&self.post_args)?;194            if !self.cmd.status()?.success() {195                self.exit_code = ExitCode::GeneralError;196            }197198            self.cmd = Self::new_command(&self.pre_args)?;199            self.count = 0;200        }201202        Ok(())203    }204205    fn exit_code(&self) -> ExitCode {206        self.exit_code207    }208}209210/// Represents a template that is utilized to generate command strings.211///212/// The template is meant to be coupled with an input in order to generate a command. The213/// `generate_and_execute()` method will be used to generate a command and execute it.214#[derive(Debug, Clone, PartialEq)]215struct CommandTemplate {216    args: Vec<FormatTemplate>,217}218219impl CommandTemplate {220    fn new<I, S>(input: I) -> Result<CommandTemplate>221    where222        I: IntoIterator<Item = S>,223        S: AsRef<str>,224    {225        let mut args = Vec::new();226        let mut has_placeholder = false;227228        for arg in input {229            let arg = arg.as_ref();230231            let tmpl = FormatTemplate::parse(arg);232            has_placeholder |= tmpl.has_tokens();233            args.push(tmpl);234        }235236        // We need to check that we have at least one argument, because if not237        // it will try to execute each file and directory it finds.238        //239        // Sadly, clap can't currently handle this for us, see240        // https://github.com/clap-rs/clap/issues/3542241        if args.is_empty() {242            bail!("No executable provided for --exec or --exec-batch");243        }244245        // Reject placeholder-as-executable for both --exec and --exec-batch246        // (was previously checked only for --exec-batch).247        if args[0].has_tokens() {248            bail!(249                "First argument of --exec/--exec-batch must be a fixed executable, not a placeholder"250            );251        }252253        // If a placeholder token was not supplied, append one at the end of the command.254        if !has_placeholder {255            args.push(FormatTemplate::Tokens(vec![Token::Placeholder]));256        }257258        Ok(CommandTemplate { args })259    }260261    fn number_of_tokens(&self) -> usize {262        self.args.iter().filter(|arg| arg.has_tokens()).count()263    }264265    /// Generates and executes a command.266    ///267    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be268    /// build.269    fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {270        let mut cmd = Command::new(self.args[0].generate(input, path_separator));271        for arg in &self.args[1..] {272            cmd.try_arg(arg.generate(input, path_separator))?;273        }274        Ok(cmd)275    }276}277278#[cfg(test)]279mod tests {280    use super::*;281282    fn generate_str(template: &CommandTemplate, input: &str) -> Vec<String> {283        template284            .args285            .iter()286            .map(|arg| arg.generate(input, None).into_string().unwrap())287            .collect()288    }289290    #[test]291    fn tokens_with_placeholder() {292        assert_eq!(293            CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),294            CommandSet {295                commands: vec![CommandTemplate {296                    args: vec![297                        FormatTemplate::Text("echo".into()),298                        FormatTemplate::Text("${SHELL}:".into()),299                        FormatTemplate::Tokens(vec![Token::Placeholder]),300                    ]301                }],302                mode: ExecutionMode::OneByOne,303            }304        );305    }306307    #[test]308    fn tokens_with_no_extension() {309        assert_eq!(310            CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),311            CommandSet {312                commands: vec![CommandTemplate {313                    args: vec![314                        FormatTemplate::Text("echo".into()),315                        FormatTemplate::Tokens(vec![Token::NoExt]),316                    ],317                }],318                mode: ExecutionMode::OneByOne,319            }320        );321    }322323    #[test]324    fn tokens_with_basename() {325        assert_eq!(326            CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),327            CommandSet {328                commands: vec![CommandTemplate {329                    args: vec![330                        FormatTemplate::Text("echo".into()),331                        FormatTemplate::Tokens(vec![Token::Basename]),332                    ],333                }],334                mode: ExecutionMode::OneByOne,335            }336        );337    }338339    #[test]340    fn tokens_with_parent() {341        assert_eq!(342            CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),343            CommandSet {344                commands: vec![CommandTemplate {345                    args: vec![346                        FormatTemplate::Text("echo".into()),347                        FormatTemplate::Tokens(vec![Token::Parent]),348                    ],349                }],350                mode: ExecutionMode::OneByOne,351            }352        );353    }354355    #[test]356    fn tokens_with_basename_no_extension() {357        assert_eq!(358            CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),359            CommandSet {360                commands: vec![CommandTemplate {361                    args: vec![362                        FormatTemplate::Text("echo".into()),363                        FormatTemplate::Tokens(vec![Token::BasenameNoExt]),364                    ],365                }],366                mode: ExecutionMode::OneByOne,367            }368        );369    }370371    #[test]372    fn tokens_with_literal_braces() {373        let template = CommandTemplate::new(vec!["{{}}", "{{", "{.}}"]).unwrap();374        assert_eq!(375            generate_str(&template, "foo"),376            vec!["{}", "{", "{.}", "foo"]377        );378    }379380    #[test]381    fn tokens_with_literal_braces_and_placeholder() {382        let template = CommandTemplate::new(vec!["echo", "{{{},end}"]).unwrap();383        assert_eq!(generate_str(&template, "foo"), vec!["echo", "{foo,end}"]);384    }385386    #[test]387    fn tokens_multiple() {388        assert_eq!(389            CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),390            CommandSet {391                commands: vec![CommandTemplate {392                    args: vec![393                        FormatTemplate::Text("cp".into()),394                        FormatTemplate::Tokens(vec![Token::Placeholder]),395                        FormatTemplate::Tokens(vec![396                            Token::BasenameNoExt,397                            Token::Text(".ext".into())398                        ]),399                    ],400                }],401                mode: ExecutionMode::OneByOne,402            }403        );404    }405406    #[test]407    fn tokens_single_batch() {408        assert_eq!(409            CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),410            CommandSet {411                commands: vec![CommandTemplate {412                    args: vec![413                        FormatTemplate::Text("echo".into()),414                        FormatTemplate::Tokens(vec![Token::NoExt]),415                    ],416                }],417                mode: ExecutionMode::Batch,418            }419        );420    }421422    #[test]423    fn tokens_multiple_batch() {424        assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());425    }426427    #[test]428    fn template_no_args() {429        assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());430    }431432    #[test]433    fn command_set_no_args() {434        assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());435    }436437    #[test]438    fn placeholder_as_executable_rejected() {439        assert!(CommandSet::new(vec![vec!["{}"]]).is_err());440        assert!(CommandSet::new(vec![vec!["{/}", "arg"]]).is_err());441        assert!(CommandSet::new_batch(vec![vec!["{}"]]).is_err());442    }443444    #[test]445    fn generate_custom_path_separator() {446        let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);447        macro_rules! check {448            ($input:expr, $expected:expr) => {449                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));450            };451        }452453        check!("foo", "foo");454        check!("foo/bar", "foo#bar");455        check!("/foo/bar/baz", "#foo#bar#baz");456    }457458    #[cfg(windows)]459    #[test]460    fn generate_custom_path_separator_windows() {461        let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);462        macro_rules! check {463            ($input:expr, $expected:expr) => {464                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));465            };466        }467468        // path starting with a drive letter469        check!(r"C:\foo\bar", "C:#foo#bar");470        // UNC path471        check!(r"\\server\share\path", "##server#share#path");472        // Drive Relative path - no separator after the colon omits the RootDir path component.473        // This is uncommon, but valid474        check!(r"C:foo\bar", "C:foo#bar");475476        // forward slashes should get normalized and interpreted as separators477        check!("C:/foo/bar", "C:#foo#bar");478        check!("C:foo/bar", "C:foo#bar");479480        // Rust does not interpret "//server/share" as a UNC path, but rather as a normal481        // absolute path that begins with RootDir, and the two slashes get combined together as482        // a single path separator during normalization.483        //check!("//server/share/path", "##server#share#path");484    }485}