Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

486 lines · 14.5 KiB · Rust

Last changed by

Merge pull request #1976 from curious-rabbit/masterThayne McCombsbefore adoptionb126064

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(|args| CommandTemplate::new(args, ExecutionMode::OneByOne))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, ExecutionMode::Batch)?;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, mode: ExecutionMode) -> 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        // A placeholder as the executable is meaningful for `--exec` but never for `--exec-batch`.246        if mode == ExecutionMode::Batch && args[0].has_tokens() {247            bail!("First argument of --exec-batch must be a fixed executable, not a placeholder");248        }249250        // If a placeholder token was not supplied, append one at the end of the command.251        if !has_placeholder {252            args.push(FormatTemplate::Tokens(vec![Token::Placeholder]));253        }254255        Ok(CommandTemplate { args })256    }257258    fn number_of_tokens(&self) -> usize {259        self.args.iter().filter(|arg| arg.has_tokens()).count()260    }261262    /// Generates and executes a command.263    ///264    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be265    /// build.266    fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {267        let mut cmd = Command::new(self.args[0].generate(input, path_separator));268        for arg in &self.args[1..] {269            cmd.try_arg(arg.generate(input, path_separator))?;270        }271        Ok(cmd)272    }273}274275#[cfg(test)]276mod tests {277    use super::*;278279    fn generate_str(template: &CommandTemplate, input: &str) -> Vec<String> {280        template281            .args282            .iter()283            .map(|arg| arg.generate(input, None).into_string().unwrap())284            .collect()285    }286287    #[test]288    fn tokens_with_placeholder() {289        assert_eq!(290            CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),291            CommandSet {292                commands: vec![CommandTemplate {293                    args: vec![294                        FormatTemplate::Text("echo".into()),295                        FormatTemplate::Text("${SHELL}:".into()),296                        FormatTemplate::Tokens(vec![Token::Placeholder]),297                    ]298                }],299                mode: ExecutionMode::OneByOne,300            }301        );302    }303304    #[test]305    fn tokens_with_no_extension() {306        assert_eq!(307            CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),308            CommandSet {309                commands: vec![CommandTemplate {310                    args: vec![311                        FormatTemplate::Text("echo".into()),312                        FormatTemplate::Tokens(vec![Token::NoExt]),313                    ],314                }],315                mode: ExecutionMode::OneByOne,316            }317        );318    }319320    #[test]321    fn tokens_with_basename() {322        assert_eq!(323            CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),324            CommandSet {325                commands: vec![CommandTemplate {326                    args: vec![327                        FormatTemplate::Text("echo".into()),328                        FormatTemplate::Tokens(vec![Token::Basename]),329                    ],330                }],331                mode: ExecutionMode::OneByOne,332            }333        );334    }335336    #[test]337    fn tokens_with_parent() {338        assert_eq!(339            CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),340            CommandSet {341                commands: vec![CommandTemplate {342                    args: vec![343                        FormatTemplate::Text("echo".into()),344                        FormatTemplate::Tokens(vec![Token::Parent]),345                    ],346                }],347                mode: ExecutionMode::OneByOne,348            }349        );350    }351352    #[test]353    fn tokens_with_basename_no_extension() {354        assert_eq!(355            CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),356            CommandSet {357                commands: vec![CommandTemplate {358                    args: vec![359                        FormatTemplate::Text("echo".into()),360                        FormatTemplate::Tokens(vec![Token::BasenameNoExt]),361                    ],362                }],363                mode: ExecutionMode::OneByOne,364            }365        );366    }367368    #[test]369    fn tokens_with_literal_braces() {370        let template =371            CommandTemplate::new(vec!["{{}}", "{{", "{.}}"], ExecutionMode::OneByOne).unwrap();372        assert_eq!(373            generate_str(&template, "foo"),374            vec!["{}", "{", "{.}", "foo"]375        );376    }377378    #[test]379    fn tokens_with_literal_braces_and_placeholder() {380        let template =381            CommandTemplate::new(vec!["echo", "{{{},end}"], ExecutionMode::OneByOne).unwrap();382        assert_eq!(generate_str(&template, "foo"), vec!["echo", "{foo,end}"]);383    }384385    #[test]386    fn tokens_multiple() {387        assert_eq!(388            CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),389            CommandSet {390                commands: vec![CommandTemplate {391                    args: vec![392                        FormatTemplate::Text("cp".into()),393                        FormatTemplate::Tokens(vec![Token::Placeholder]),394                        FormatTemplate::Tokens(vec![395                            Token::BasenameNoExt,396                            Token::Text(".ext".into())397                        ]),398                    ],399                }],400                mode: ExecutionMode::OneByOne,401            }402        );403    }404405    #[test]406    fn tokens_single_batch() {407        assert_eq!(408            CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),409            CommandSet {410                commands: vec![CommandTemplate {411                    args: vec![412                        FormatTemplate::Text("echo".into()),413                        FormatTemplate::Tokens(vec![Token::NoExt]),414                    ],415                }],416                mode: ExecutionMode::Batch,417            }418        );419    }420421    #[test]422    fn tokens_multiple_batch() {423        assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());424    }425426    #[test]427    fn template_no_args() {428        assert!(429            CommandTemplate::new::<Vec<_>, &'static str>(vec![], ExecutionMode::OneByOne).is_err()430        );431    }432433    #[test]434    fn command_set_no_args() {435        assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());436    }437438    #[test]439    fn placeholder_as_executable_rejected() {440        assert!(CommandSet::new(vec![vec!["{}"]]).is_ok());441        assert!(CommandSet::new(vec![vec!["{/}", "arg"]]).is_ok());442        assert!(CommandSet::new_batch(vec![vec!["{}"]]).is_err());443    }444445    #[test]446    fn generate_custom_path_separator() {447        let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);448        macro_rules! check {449            ($input:expr, $expected:expr) => {450                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));451            };452        }453454        check!("foo", "foo");455        check!("foo/bar", "foo#bar");456        check!("/foo/bar/baz", "#foo#bar#baz");457    }458459    #[cfg(windows)]460    #[test]461    fn generate_custom_path_separator_windows() {462        let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);463        macro_rules! check {464            ($input:expr, $expected:expr) => {465                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));466            };467        }468469        // path starting with a drive letter470        check!(r"C:\foo\bar", "C:#foo#bar");471        // UNC path472        check!(r"\\server\share\path", "##server#share#path");473        // Drive Relative path - no separator after the colon omits the RootDir path component.474        // This is uncommon, but valid475        check!(r"C:foo\bar", "C:foo#bar");476477        // forward slashes should get normalized and interpreted as separators478        check!("C:/foo/bar", "C:#foo#bar");479        check!("C:foo/bar", "C:foo#bar");480481        // Rust does not interpret "//server/share" as a UNC path, but rather as a normal482        // absolute path that begins with RootDir, and the two slashes get combined together as483        // a single path separator during normalization.484        //check!("//server/share/path", "##server#share#path");485    }486}