Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

593 lines · 19.5 KiB · Rust

Last changed by

exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e

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::{Arc, Mutex};1314use anyhow::{bail, Result};15use argmax::Command;16use once_cell::sync::Lazy;17use regex::Regex;1819use crate::exit_codes::ExitCode;2021use self::command::{execute_commands, handle_cmd_error};22use self::input::{basename, dirname, remove_extension};23pub use self::job::{batch, job};24use self::token::Token;2526/// Execution mode of the command27#[derive(Debug, Clone, Copy, PartialEq)]28pub enum ExecutionMode {29    /// Command is executed for each search result30    OneByOne,31    /// Command is run for a batch of results at once32    Batch,33}3435#[derive(Debug, Clone, PartialEq)]36pub struct CommandSet {37    mode: ExecutionMode,38    path_separator: Option<String>,39    commands: Vec<CommandTemplate>,40}4142impl CommandSet {43    pub fn new<I, S>(input: I, path_separator: Option<String>) -> Result<CommandSet>44    where45        I: IntoIterator<Item = Vec<S>>,46        S: AsRef<str>,47    {48        Ok(CommandSet {49            mode: ExecutionMode::OneByOne,50            path_separator,51            commands: input52                .into_iter()53                .map(CommandTemplate::new)54                .collect::<Result<_>>()?,55        })56    }5758    pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandSet>59    where60        I: IntoIterator<Item = Vec<S>>,61        S: AsRef<str>,62    {63        Ok(CommandSet {64            mode: ExecutionMode::Batch,65            path_separator,66            commands: input67                .into_iter()68                .map(|args| {69                    let cmd = CommandTemplate::new(args)?;70                    if cmd.number_of_tokens() > 1 {71                        bail!("Only one placeholder allowed for batch commands");72                    }73                    if cmd.args[0].has_tokens() {74                        bail!("First argument of exec-batch is expected to be a fixed executable");75                    }76                    Ok(cmd)77                })78                .collect::<Result<Vec<_>>>()?,79        })80    }8182    pub fn in_batch_mode(&self) -> bool {83        self.mode == ExecutionMode::Batch84    }8586    pub fn execute(&self, input: &Path, out_perm: Arc<Mutex<()>>, buffer_output: bool) -> ExitCode {87        let path_separator = self.path_separator.as_deref();88        let commands = self89            .commands90            .iter()91            .map(|c| c.generate(input, path_separator));92        execute_commands(commands, &out_perm, buffer_output)93    }9495    pub fn execute_batch<I>(&self, paths: I, limit: usize) -> ExitCode96    where97        I: Iterator<Item = PathBuf>,98    {99        let path_separator = self.path_separator.as_deref();100101        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                ExitCode::Success124            }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}140141impl CommandBuilder {142    fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {143        let mut pre_args = vec![];144        let mut path_arg = None;145        let mut post_args = vec![];146147        for arg in &template.args {148            if arg.has_tokens() {149                path_arg = Some(arg.clone());150            } else if path_arg == None {151                pre_args.push(arg.generate("", None));152            } else {153                post_args.push(arg.generate("", None));154            }155        }156157        let cmd = Self::new_command(&pre_args)?;158159        Ok(Self {160            pre_args,161            path_arg: path_arg.unwrap(),162            post_args,163            cmd,164            count: 0,165            limit,166        })167    }168169    fn new_command(pre_args: &[OsString]) -> io::Result<Command> {170        let mut cmd = Command::new(&pre_args[0]);171        cmd.stdin(Stdio::inherit());172        cmd.stdout(Stdio::inherit());173        cmd.stderr(Stdio::inherit());174        cmd.try_args(&pre_args[1..])?;175        Ok(cmd)176    }177178    fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {179        if self.limit > 0 && self.count >= self.limit {180            self.finish()?;181        }182183        let arg = self.path_arg.generate(path, separator);184        if !self185            .cmd186            .args_would_fit(iter::once(&arg).chain(&self.post_args))187        {188            self.finish()?;189        }190191        self.cmd.try_arg(arg)?;192        self.count += 1;193        Ok(())194    }195196    fn finish(&mut self) -> io::Result<()> {197        if self.count > 0 {198            self.cmd.try_args(&self.post_args)?;199            self.cmd.status()?;200201            self.cmd = Self::new_command(&self.pre_args)?;202            self.count = 0;203        }204205        Ok(())206    }207}208209/// Represents a template that is utilized to generate command strings.210///211/// The template is meant to be coupled with an input in order to generate a command. The212/// `generate_and_execute()` method will be used to generate a command and execute it.213#[derive(Debug, Clone, PartialEq)]214struct CommandTemplate {215    args: Vec<ArgumentTemplate>,216}217218impl CommandTemplate {219    fn new<I, S>(input: I) -> Result<CommandTemplate>220    where221        I: IntoIterator<Item = S>,222        S: AsRef<str>,223    {224        static PLACEHOLDER_PATTERN: Lazy<Regex> =225            Lazy::new(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());226227        let mut args = Vec::new();228        let mut has_placeholder = false;229230        for arg in input {231            let arg = arg.as_ref();232233            let mut tokens = Vec::new();234            let mut start = 0;235236            for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {237                // Leading text before the placeholder.238                if placeholder.start() > start {239                    tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));240                }241242                start = placeholder.end();243244                match placeholder.as_str() {245                    "{}" => tokens.push(Token::Placeholder),246                    "{.}" => tokens.push(Token::NoExt),247                    "{/}" => tokens.push(Token::Basename),248                    "{//}" => tokens.push(Token::Parent),249                    "{/.}" => tokens.push(Token::BasenameNoExt),250                    _ => unreachable!("Unhandled placeholder"),251                }252253                has_placeholder = true;254            }255256            // Without a placeholder, the argument is just fixed text.257            if tokens.is_empty() {258                args.push(ArgumentTemplate::Text(arg.to_owned()));259                continue;260            }261262            if start < arg.len() {263                // Trailing text after last placeholder.264                tokens.push(Token::Text(arg[start..].to_owned()));265            }266267            args.push(ArgumentTemplate::Tokens(tokens));268        }269270        // We need to check that we have at least one argument, because if not271        // it will try to execute each file and directory it finds.272        //273        // Sadly, clap can't currently handle this for us, see274        // https://github.com/clap-rs/clap/issues/3542275        if args.is_empty() {276            bail!("No executable provided for --exec or --exec-batch");277        }278279        // If a placeholder token was not supplied, append one at the end of the command.280        if !has_placeholder {281            args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));282        }283284        Ok(CommandTemplate { args })285    }286287    fn number_of_tokens(&self) -> usize {288        self.args.iter().filter(|arg| arg.has_tokens()).count()289    }290291    /// Generates and executes a command.292    ///293    /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be294    /// build.295    fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {296        let mut cmd = Command::new(self.args[0].generate(&input, path_separator));297        for arg in &self.args[1..] {298            cmd.try_arg(arg.generate(&input, path_separator))?;299        }300        Ok(cmd)301    }302}303304/// Represents a template for a single command argument.305///306/// The argument is either a collection of `Token`s including at least one placeholder variant, or307/// a fixed text.308#[derive(Clone, Debug, PartialEq)]309enum ArgumentTemplate {310    Tokens(Vec<Token>),311    Text(String),312}313314impl ArgumentTemplate {315    pub fn has_tokens(&self) -> bool {316        matches!(self, ArgumentTemplate::Tokens(_))317    }318319    /// Generate an argument from this template. If path_separator is Some, then it will replace320    /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by321    /// path separator substitution.322    pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {323        use self::Token::*;324        let path = path.as_ref();325326        match *self {327            ArgumentTemplate::Tokens(ref tokens) => {328                let mut s = OsString::new();329                for token in tokens {330                    match *token {331                        Basename => s.push(Self::replace_separator(basename(path), path_separator)),332                        BasenameNoExt => s.push(Self::replace_separator(333                            &remove_extension(basename(path).as_ref()),334                            path_separator,335                        )),336                        NoExt => s.push(Self::replace_separator(337                            &remove_extension(path),338                            path_separator,339                        )),340                        Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),341                        Placeholder => {342                            s.push(Self::replace_separator(path.as_ref(), path_separator))343                        }344                        Text(ref string) => s.push(string),345                    }346                }347                s348            }349            ArgumentTemplate::Text(ref text) => OsString::from(text),350        }351    }352353    /// Replace the path separator in the input with the custom separator string. If path_separator354    /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is355    /// interpreted as a Path and its components are iterated through and re-joined into a new356    /// OsString.357    fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {358        // fast-path - no replacement necessary359        if path_separator.is_none() {360            return Cow::Borrowed(path);361        }362363        let path_separator = path_separator.unwrap();364        let mut out = OsString::with_capacity(path.len());365        let mut components = Path::new(path).components().peekable();366367        while let Some(comp) = components.next() {368            match comp {369                // Absolute paths on Windows are tricky.  A Prefix component is usually a drive370                // letter or UNC path, and is usually followed by RootDir. There are also371                // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to372                // ignore verbatim path prefixes here because they're very rare, might be373                // impossible to reach here, and there's no good way to deal with them. If users374                // are doing something advanced involving verbatim windows paths, they can do their375                // own output filtering with a tool like sed.376                Component::Prefix(prefix) => {377                    if let Prefix::UNC(server, share) = prefix.kind() {378                        // Prefix::UNC is a parsed version of '\\server\share'379                        out.push(path_separator);380                        out.push(path_separator);381                        out.push(server);382                        out.push(path_separator);383                        out.push(share);384                    } else {385                        // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for386                        // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,387                        // but they're not returned by directories fd can search anyway so we don't worry388                        // about them.389                        out.push(comp.as_os_str());390                    }391                }392393                // Root directory is always replaced with the custom separator.394                Component::RootDir => out.push(path_separator),395396                // Everything else is joined normally, with a trailing separator if we're not last397                _ => {398                    out.push(comp.as_os_str());399                    if components.peek().is_some() {400                        out.push(path_separator);401                    }402                }403            }404        }405        Cow::Owned(out)406    }407}408409#[cfg(test)]410mod tests {411    use super::*;412413    #[test]414    fn tokens_with_placeholder() {415        assert_eq!(416            CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]], None).unwrap(),417            CommandSet {418                commands: vec![CommandTemplate {419                    args: vec![420                        ArgumentTemplate::Text("echo".into()),421                        ArgumentTemplate::Text("${SHELL}:".into()),422                        ArgumentTemplate::Tokens(vec![Token::Placeholder]),423                    ]424                }],425                mode: ExecutionMode::OneByOne,426                path_separator: None,427            }428        );429    }430431    #[test]432    fn tokens_with_no_extension() {433        assert_eq!(434            CommandSet::new(vec![vec!["echo", "{.}"]], None).unwrap(),435            CommandSet {436                commands: vec![CommandTemplate {437                    args: vec![438                        ArgumentTemplate::Text("echo".into()),439                        ArgumentTemplate::Tokens(vec![Token::NoExt]),440                    ],441                }],442                mode: ExecutionMode::OneByOne,443                path_separator: None,444            }445        );446    }447448    #[test]449    fn tokens_with_basename() {450        assert_eq!(451            CommandSet::new(vec![vec!["echo", "{/}"]], None).unwrap(),452            CommandSet {453                commands: vec![CommandTemplate {454                    args: vec![455                        ArgumentTemplate::Text("echo".into()),456                        ArgumentTemplate::Tokens(vec![Token::Basename]),457                    ],458                }],459                mode: ExecutionMode::OneByOne,460                path_separator: None,461            }462        );463    }464465    #[test]466    fn tokens_with_parent() {467        assert_eq!(468            CommandSet::new(vec![vec!["echo", "{//}"]], None).unwrap(),469            CommandSet {470                commands: vec![CommandTemplate {471                    args: vec![472                        ArgumentTemplate::Text("echo".into()),473                        ArgumentTemplate::Tokens(vec![Token::Parent]),474                    ],475                }],476                mode: ExecutionMode::OneByOne,477                path_separator: None,478            }479        );480    }481482    #[test]483    fn tokens_with_basename_no_extension() {484        assert_eq!(485            CommandSet::new(vec![vec!["echo", "{/.}"]], None).unwrap(),486            CommandSet {487                commands: vec![CommandTemplate {488                    args: vec![489                        ArgumentTemplate::Text("echo".into()),490                        ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),491                    ],492                }],493                mode: ExecutionMode::OneByOne,494                path_separator: None,495            }496        );497    }498499    #[test]500    fn tokens_multiple() {501        assert_eq!(502            CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]], None).unwrap(),503            CommandSet {504                commands: vec![CommandTemplate {505                    args: vec![506                        ArgumentTemplate::Text("cp".into()),507                        ArgumentTemplate::Tokens(vec![Token::Placeholder]),508                        ArgumentTemplate::Tokens(vec![509                            Token::BasenameNoExt,510                            Token::Text(".ext".into())511                        ]),512                    ],513                }],514                mode: ExecutionMode::OneByOne,515                path_separator: None,516            }517        );518    }519520    #[test]521    fn tokens_single_batch() {522        assert_eq!(523            CommandSet::new_batch(vec![vec!["echo", "{.}"]], None).unwrap(),524            CommandSet {525                commands: vec![CommandTemplate {526                    args: vec![527                        ArgumentTemplate::Text("echo".into()),528                        ArgumentTemplate::Tokens(vec![Token::NoExt]),529                    ],530                }],531                mode: ExecutionMode::Batch,532                path_separator: None,533            }534        );535    }536537    #[test]538    fn tokens_multiple_batch() {539        assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]], None).is_err());540    }541542    #[test]543    fn template_no_args() {544        assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());545    }546547    #[test]548    fn command_set_no_args() {549        assert!(CommandSet::new(vec![vec!["echo"], vec![]], None).is_err());550    }551552    #[test]553    fn generate_custom_path_separator() {554        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);555        macro_rules! check {556            ($input:expr, $expected:expr) => {557                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));558            };559        }560561        check!("foo", "foo");562        check!("foo/bar", "foo#bar");563        check!("/foo/bar/baz", "#foo#bar#baz");564    }565566    #[cfg(windows)]567    #[test]568    fn generate_custom_path_separator_windows() {569        let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);570        macro_rules! check {571            ($input:expr, $expected:expr) => {572                assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));573            };574        }575576        // path starting with a drive letter577        check!(r"C:\foo\bar", "C:#foo#bar");578        // UNC path579        check!(r"\\server\share\path", "##server#share#path");580        // Drive Relative path - no separator after the colon omits the RootDir path component.581        // This is uncommon, but valid582        check!(r"C:foo\bar", "C:foo#bar");583584        // forward slashes should get normalized and interpreted as separators585        check!("C:/foo/bar", "C:#foo#bar");586        check!("C:foo/bar", "C:foo#bar");587588        // Rust does not interpret "//server/share" as a UNC path, but rather as a normal589        // absolute path that begins with RootDir, and the two slashes get combined together as590        // a single path separator during normalization.591        //check!("//server/share/path", "##server#share#path");592    }593}