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 fileTake it
The walk stopped after 200 commits: lines older than 13a93e5 point at it.
Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 1–3why, one step back1mod command;2mod job;3Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
line 4why, one step back4use std::ffi::OsString;Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 5–6why, one step back5use std::io;6use std::iter;Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
line 7why, one step back7use std::path::{Path, PathBuf};Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 8–9why, one step back8use std::process::Stdio;9Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06
line 10why, one step back10use anyhow::{Result, bail};Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 11–12why, one step back11use argmax::Command;12Merge pull request #1805 from tmccombs/exec-nulsThayne McCombsbefore adoption5558e40
line 13why, one step back13use crate::exec::command::OutputBuffer;Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06
line 14why, one step back14use crate::exit_codes::{ExitCode, merge_exitcodes};Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
line 15why, one step back15use crate::fmt::{FormatTemplate, Token};Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 16–82why, one step back1617use 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>,Merge pull request #1805 from tmccombs/exec-nulsThayne McCombsbefore adoption5558e40
line 83why, one step back83 null_separator: bool,Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 84–89why, one step back84 buffer_output: bool,85 ) -> ExitCode {86 let commands = self87 .commands88 .iter()89 .map(|c| c.generate(input, path_separator));Merge pull request #1805 from tmccombs/exec-nulsThayne McCombsbefore adoption5558e40
line 90why, one step back90 execute_commands(commands, OutputBuffer::new(null_separator), buffer_output)Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 91–129why, one step back91 }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>,Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
line 130why, one step back130 path_arg: FormatTemplate,Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 131–218why, one step back131 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 {Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
line 219why, one step back219 args: Vec<FormatTemplate>,Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 220–233why, one step back220}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();233Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
line 234why, one step back234 let tmpl = FormatTemplate::parse(arg);Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 235–249why, one step back235 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 {Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
line 250why, one step back250 args.push(FormatTemplate::Tokens(vec![Token::Placeholder]));Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 251–291why, one step back251 }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![Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
lines 292–294why, one step back292 FormatTemplate::Text("echo".into()),293 FormatTemplate::Text("${SHELL}:".into()),294 FormatTemplate::Tokens(vec![Token::Placeholder]),Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 295–308why, one step back295 ]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![Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
lines 309–310why, one step back309 FormatTemplate::Text("echo".into()),310 FormatTemplate::Tokens(vec![Token::NoExt]),Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 311–324why, one step back311 ],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![Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
lines 325–326why, one step back325 FormatTemplate::Text("echo".into()),326 FormatTemplate::Tokens(vec![Token::Basename]),Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 327–340why, one step back327 ],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![Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
lines 341–342why, one step back341 FormatTemplate::Text("echo".into()),342 FormatTemplate::Tokens(vec![Token::Parent]),Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 343–356why, one step back343 ],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![Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
lines 357–358why, one step back357 FormatTemplate::Text("echo".into()),358 FormatTemplate::Tokens(vec![Token::BasenameNoExt]),Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 359–387why, one step back359 ],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![Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
lines 388–390why, one step back388 FormatTemplate::Text("cp".into()),389 FormatTemplate::Tokens(vec![Token::Placeholder]),390 FormatTemplate::Tokens(vec![Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 391–407why, one step back391 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![Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
lines 408–409why, one step back408 FormatTemplate::Text("echo".into()),409 FormatTemplate::Tokens(vec![Token::NoExt]),Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 410–433why, one step back410 ],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() {Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
line 434why, one step back434 let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 435–448why, one step back435 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() {Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd
line 449why, one step back449 let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);Add new unreleased sectionDavid Peterbefore adoption13a93e5
lines 450–473why, one step back450 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}