Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

582 lines · 18.7 KiB · Rust

Last changed by

feat: Add a way to escape { and }in exec templates.Thayne McCombsbefore adoptiond9b69c8

History of this file

Take it

1mod command;2mod input;3mod job;4mod token;56use std::borrow::Cow;7use std::ffi::{OsStr, OsString};8use std::io;9use std::iter;10use std::path::{Component, Path, PathBuf, Prefix};11use std::process::Stdio;12use std::sync::Mutex;1314use anyhow::{bail, Result};15use argmax::Command;1617use crate::exit_codes::{merge_exitcodes, ExitCode};1819use self::command::{execute_commands, handle_cmd_error};20use self::input::{basename, dirname, remove_extension};21pub use self::job::{batch, job};22use self::token::{tokenize, Token};2324/// Execution mode of the command25#[derive(Debug, Clone, Copy, PartialEq, Eq)]26pub enum ExecutionMode {27    /// Command is executed for each search result28    OneByOne,29    /// Command is run for a batch of results at once30    Batch,31}3233#[derive(Debug, Clone, PartialEq)]34pub struct CommandSet {35    mode: ExecutionMode,36    commands: Vec<CommandTemplate>,37}3839impl CommandSet {40    pub fn new<I, T, S>(input: I) -> Result<CommandSet>41    where42        I: IntoIterator<Item = T>,43        T: IntoIterator<Item = S>,44        S: AsRef<str>,45    {46        Ok(CommandSet {47            mode: ExecutionMode::OneByOne,48            commands: input49                .into_iter()50                .map(CommandTemplate::new)51                .collect::<Result<_>>()?,52        })53    }5455    pub fn new_batch<I, T, S>(input: I) -> Result<CommandSet>56    where57        I: IntoIterator<Item = T>,58        T: IntoIterator<Item = S>,59        S: AsRef<str>,60    {61        Ok(CommandSet {62            mode: ExecutionMode::Batch,63            commands: input64                .into_iter()65                .map(|args| {66                    let cmd = CommandTemplate::new(args)?;67                    if cmd.number_of_tokens() > 1 {68                        bail!("Only one placeholder allowed for batch commands");69                    }70                    if cmd.args[0].has_tokens() {71                        bail!("First argument of exec-batch is expected to be a fixed executable");72                    }73                    Ok(cmd)74                })75                .collect::<Result<Vec<_>>>()?,76        })77    }7879    pub fn in_batch_mode(&self) -> bool {80        self.mode == ExecutionMode::Batch81    }8283    pub fn execute(84        &self,85        input: &Path,86        path_separator: Option<&str>,87        out_perm: &Mutex<()>,88        buffer_output: bool,89    ) -> ExitCode {90        let commands = self91            .commands92            .iter()93            .map(|c| c.generate(input, path_separator));94        execute_commands(commands, out_perm, buffer_output)95    }9697    pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode98    where99        I: Iterator<Item = PathBuf>,100    {101        let builders: io::Result<Vec<_>> = self102            .commands103            .iter()104            .map(|c| CommandBuilder::new(c, limit))105            .collect();106107        match builders {108            Ok(mut builders) => {109                for path in paths {110                    for builder in &mut builders {111                        if let Err(e) = builder.push(&path, path_separator) {112                            return handle_cmd_error(Some(&builder.cmd), e);113                        }114                    }115                }116117                for builder in &mut builders {118                    if let Err(e) = builder.finish() {119                        return handle_cmd_error(Some(&builder.cmd), e);120                    }121                }122123                merge_exitcodes(builders.iter().map(|b| b.exit_code()))124            }125            Err(e) => handle_cmd_error(None, e),126        }127    }128}129130/// Represents a multi-exec command as it is built.131#[derive(Debug)]132struct CommandBuilder {133    pre_args: Vec<OsString>,134    path_arg: ArgumentTemplate,135    post_args: Vec<OsString>,136    cmd: Command,137    count: usize,138    limit: usize,139    exit_code: ExitCode,140}141142impl CommandBuilder {143    fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {144        let mut pre_args = vec![];145        let mut path_arg = None;146        let mut post_args = vec![];147148        for arg in &template.args {149            if arg.has_tokens() {150                path_arg = Some(arg.clone());151            } else if path_arg.is_none() {152                pre_args.push(arg.generate("", None));153            } else {154                post_args.push(arg.generate("", None));155            }156        }157158        let cmd = Self::new_command(&pre_args)?;159160        Ok(Self {161            pre_args,162            path_arg: path_arg.unwrap(),163            post_args,164            cmd,165            count: 0,166            limit,167            exit_code: ExitCode::Success,168        })169    }170171    fn new_command(pre_args: &[OsString]) -> io::Result<Command> {172        let mut cmd = Command::new(&pre_args[0]);173        cmd.stdin(Stdio::inherit());174        cmd.stdout(Stdio::inherit());175        cmd.stderr(Stdio::inherit());176        cmd.try_args(&pre_args[1..])?;177        Ok(cmd)178    }179180    fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {181        if self.limit > 0 && self.count >= self.limit {182            self.finish()?;183        }184185        let arg = self.path_arg.generate(path, separator);186        if !self187            .cmd188            .args_would_fit(iter::once(&arg).chain(&self.post_args))189        {190            self.finish()?;191        }192193        self.cmd.try_arg(arg)?;194        self.count += 1;195        Ok(())196    }197198    fn finish(&mut self) -> io::Result<()> {199        if self.count > 0 {200            self.cmd.try_args(&self.post_args)?;201            if !self.cmd.status()?.success() {202                self.exit_code = ExitCode::GeneralError;203            }204205            self.cmd = Self::new_command(&self.pre_args)?;206            self.count = 0;207        }208209        Ok(())210    }211212    fn exit_code(&self) -> ExitCode {213        self.exit_code214    }215}216217/// Represents a template that is utilized to generate command strings.218///219/// The template is meant to be coupled with an input in order to generate a command. The220/// `generate_and_execute()` method will be used to generate a command and execute it.221#[derive(Debug, Clone, PartialEq)]222struct CommandTemplate {223    args: Vec<ArgumentTemplate>,224}225226impl CommandTemplate {227    fn new<I, S>(input: I) -> Result<CommandTemplate>228    where229        I: IntoIterator<Item = S>,230        S: AsRef<str>,231    {232        let mut args = Vec::new();233        let mut has_placeholder = false;234235        for arg in input {236            let arg = arg.as_ref();237238            let tmpl = tokenize(arg);239            has_placeholder |= tmpl.has_tokens();240            args.push(tmpl);241        }242243        // We need to check that we have at least one argument, because if not244        // it will try to execute each file and directory it finds.245        //246        // Sadly, clap can't currently handle this for us, see247        // https://github.com/clap-rs/clap/issues/3542248        if args.is_empty() {249            bail!("No executable provided for --exec or --exec-batch");250        }251252        // If a placeholder token was not supplied, append one at the end of the command.253        if !has_placeholder {254            args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));255        }256257        Ok(CommandTemplate { args })258    }259260    fn number_of_tokens(&self) -> usize {261        self.args.iter().filter(|arg| arg.has_tokens()).count()262    }263264    /// Generates and executes a command.265    ///266    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be267    /// build.268    fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {269        let mut cmd = Command::new(self.args[0].generate(input, path_separator));270        for arg in &self.args[1..] {271            cmd.try_arg(arg.generate(input, path_separator))?;272        }273        Ok(cmd)274    }275}276277/// Represents a template for a single command argument.278///279/// The argument is either a collection of `Token`s including at least one placeholder variant, or280/// a fixed text.281#[derive(Clone, Debug, PartialEq)]282enum ArgumentTemplate {283    Tokens(Vec<Token>),284    Text(String),285}286287impl ArgumentTemplate {288    pub fn has_tokens(&self) -> bool {289        matches!(self, ArgumentTemplate::Tokens(_))290    }291292    /// Generate an argument from this template. If path_separator is Some, then it will replace293    /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by294    /// path separator substitution.295    pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {296        use self::Token::*;297        let path = path.as_ref();298299        match *self {300            ArgumentTemplate::Tokens(ref tokens) => {301                let mut s = OsString::new();302                for token in tokens {303                    match *token {304                        Basename => s.push(Self::replace_separator(basename(path), path_separator)),305                        BasenameNoExt => s.push(Self::replace_separator(306                            &remove_extension(basename(path).as_ref()),307                            path_separator,308                        )),309                        NoExt => s.push(Self::replace_separator(310                            &remove_extension(path),311                            path_separator,312                        )),313                        Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),314                        Placeholder => {315                            s.push(Self::replace_separator(path.as_ref(), path_separator))316                        }317                        Text(ref string) => s.push(string),318                    }319                }320                s321            }322            ArgumentTemplate::Text(ref text) => OsString::from(text),323        }324    }325326    /// Replace the path separator in the input with the custom separator string. If path_separator327    /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is328    /// interpreted as a Path and its components are iterated through and re-joined into a new329    /// OsString.330    fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {331        // fast-path - no replacement necessary332        if path_separator.is_none() {333            return Cow::Borrowed(path);334        }335336        let path_separator = path_separator.unwrap();337        let mut out = OsString::with_capacity(path.len());338        let mut components = Path::new(path).components().peekable();339340        while let Some(comp) = components.next() {341            match comp {342                // Absolute paths on Windows are tricky.  A Prefix component is usually a drive343                // letter or UNC path, and is usually followed by RootDir. There are also344                // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to345                // ignore verbatim path prefixes here because they're very rare, might be346                // impossible to reach here, and there's no good way to deal with them. If users347                // are doing something advanced involving verbatim windows paths, they can do their348                // own output filtering with a tool like sed.349                Component::Prefix(prefix) => {350                    if let Prefix::UNC(server, share) = prefix.kind() {351                        // Prefix::UNC is a parsed version of '\\server\share'352                        out.push(path_separator);353                        out.push(path_separator);354                        out.push(server);355                        out.push(path_separator);356                        out.push(share);357                    } else {358                        // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for359                        // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,360                        // but they're not returned by directories fd can search anyway so we don't worry361                        // about them.362                        out.push(comp.as_os_str());363                    }364                }365366                // Root directory is always replaced with the custom separator.367                Component::RootDir => out.push(path_separator),368369                // Everything else is joined normally, with a trailing separator if we're not last370                _ => {371                    out.push(comp.as_os_str());372                    if components.peek().is_some() {373                        out.push(path_separator);374                    }375                }376            }377        }378        Cow::Owned(out)379    }380}381382#[cfg(test)]383mod tests {384    use super::*;385386    fn generate_str(template: &CommandTemplate, input: &str) -> Vec<String> {387        template388            .args389            .iter()390            .map(|arg| arg.generate(input, None).into_string().unwrap())391            .collect()392    }393394    #[test]395    fn tokens_with_placeholder() {396        assert_eq!(397            CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),398            CommandSet {399                commands: vec![CommandTemplate {400                    args: vec![401                        ArgumentTemplate::Text("echo".into()),402                        ArgumentTemplate::Text("${SHELL}:".into()),403                        ArgumentTemplate::Tokens(vec![Token::Placeholder]),404                    ]405                }],406                mode: ExecutionMode::OneByOne,407            }408        );409    }410411    #[test]412    fn tokens_with_no_extension() {413        assert_eq!(414            CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),415            CommandSet {416                commands: vec![CommandTemplate {417                    args: vec![418                        ArgumentTemplate::Text("echo".into()),419                        ArgumentTemplate::Tokens(vec![Token::NoExt]),420                    ],421                }],422                mode: ExecutionMode::OneByOne,423            }424        );425    }426427    #[test]428    fn tokens_with_basename() {429        assert_eq!(430            CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),431            CommandSet {432                commands: vec![CommandTemplate {433                    args: vec![434                        ArgumentTemplate::Text("echo".into()),435                        ArgumentTemplate::Tokens(vec![Token::Basename]),436                    ],437                }],438                mode: ExecutionMode::OneByOne,439            }440        );441    }442443    #[test]444    fn tokens_with_parent() {445        assert_eq!(446            CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),447            CommandSet {448                commands: vec![CommandTemplate {449                    args: vec![450                        ArgumentTemplate::Text("echo".into()),451                        ArgumentTemplate::Tokens(vec![Token::Parent]),452                    ],453                }],454                mode: ExecutionMode::OneByOne,455            }456        );457    }458459    #[test]460    fn tokens_with_basename_no_extension() {461        assert_eq!(462            CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),463            CommandSet {464                commands: vec![CommandTemplate {465                    args: vec![466                        ArgumentTemplate::Text("echo".into()),467                        ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),468                    ],469                }],470                mode: ExecutionMode::OneByOne,471            }472        );473    }474475    #[test]476    fn tokens_with_literal_braces() {477        let template = CommandTemplate::new(vec!["{{}}", "{{", "{.}}"]).unwrap();478        assert_eq!(479            generate_str(&template, "foo"),480            vec!["{}", "{", "{.}", "foo"]481        );482    }483484    #[test]485    fn tokens_with_literal_braces_and_placeholder() {486        let template = CommandTemplate::new(vec!["{{{},end}"]).unwrap();487        assert_eq!(generate_str(&template, "foo"), vec!["{foo,end}"]);488    }489490    #[test]491    fn tokens_multiple() {492        assert_eq!(493            CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),494            CommandSet {495                commands: vec![CommandTemplate {496                    args: vec![497                        ArgumentTemplate::Text("cp".into()),498                        ArgumentTemplate::Tokens(vec![Token::Placeholder]),499                        ArgumentTemplate::Tokens(vec![500                            Token::BasenameNoExt,501                            Token::Text(".ext".into())502                        ]),503                    ],504                }],505                mode: ExecutionMode::OneByOne,506            }507        );508    }509510    #[test]511    fn tokens_single_batch() {512        assert_eq!(513            CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),514            CommandSet {515                commands: vec![CommandTemplate {516                    args: vec![517                        ArgumentTemplate::Text("echo".into()),518                        ArgumentTemplate::Tokens(vec![Token::NoExt]),519                    ],520                }],521                mode: ExecutionMode::Batch,522            }523        );524    }525526    #[test]527    fn tokens_multiple_batch() {528        assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());529    }530531    #[test]532    fn template_no_args() {533        assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());534    }535536    #[test]537    fn command_set_no_args() {538        assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());539    }540541    #[test]542    fn generate_custom_path_separator() {543        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);544        macro_rules! check {545            ($input:expr, $expected:expr) => {546                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));547            };548        }549550        check!("foo", "foo");551        check!("foo/bar", "foo#bar");552        check!("/foo/bar/baz", "#foo#bar#baz");553    }554555    #[cfg(windows)]556    #[test]557    fn generate_custom_path_separator_windows() {558        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);559        macro_rules! check {560            ($input:expr, $expected:expr) => {561                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));562            };563        }564565        // path starting with a drive letter566        check!(r"C:\foo\bar", "C:#foo#bar");567        // UNC path568        check!(r"\\server\share\path", "##server#share#path");569        // Drive Relative path - no separator after the colon omits the RootDir path component.570        // This is uncommon, but valid571        check!(r"C:foo\bar", "C:foo#bar");572573        // forward slashes should get normalized and interpreted as separators574        check!("C:/foo/bar", "C:#foo#bar");575        check!("C:foo/bar", "C:foo#bar");576577        // Rust does not interpret "//server/share" as a UNC path, but rather as a normal578        // absolute path that begins with RootDir, and the two slashes get combined together as579        // a single path separator during normalization.580        //check!("//server/share/path", "##server#share#path");581    }582}