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

The walk stopped after 200 commits: lines older than 8c7a84e point at it.

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 1–3why, one step back
1mod command;
2mod job;3

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

line 4why, one step back
4use std::ffi::OsString;

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 5–6why, one step back
5use std::io;
6use std::iter;

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

line 7why, one step back
7use std::path::{Path, PathBuf};

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 8–9why, one step back
8use std::process::Stdio;
9

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

line 10why, one step back
10use anyhow::{Result, bail};

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 11–12why, one step back
11use argmax::Command;
12

Merge pull request #1805 from tmccombs/exec-nulsThayne McCombsbefore adoption5558e40

line 13why, one step back
13use crate::exec::command::OutputBuffer;

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

line 14why, one step back
14use crate::exit_codes::{ExitCode, merge_exitcodes};

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

line 15why, one step back
15use crate::fmt::{FormatTemplate, Token};

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 16–79why, one step back
16
17use 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>,

Merge pull request #1805 from tmccombs/exec-nulsThayne McCombsbefore adoption5558e40

line 80why, one step back
80 null_separator: bool,

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 81–86why, one step back
81 buffer_output: bool,
82 ) -> ExitCode {83 let commands = self84 .commands85 .iter()86 .map(|c| c.generate(input, path_separator));

Merge pull request #1805 from tmccombs/exec-nulsThayne McCombsbefore adoption5558e40

line 87why, one step back
87 execute_commands(commands, OutputBuffer::new(null_separator), buffer_output)

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 88–126why, one step back
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>,

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

line 127why, one step back
127 path_arg: FormatTemplate,

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 128–177why, one step back
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 }177

improve patchcurious-rabbitbefore adoption63a7d85

line 178why, one step back
178 let arg = self.path_arg.generate(path, separator);

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 179–215why, one step back
179 if !self
180 .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 {

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

line 216why, one step back
216 args: Vec<FormatTemplate>,

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 217–230why, one step back
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();230

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

line 231why, one step back
231 let tmpl = FormatTemplate::parse(arg);

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 232–244why, one step back
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 }244

apply strict filtercurious-rabbitbefore adoptionaeecb5d

lines 245–246why, one step back
245 // Reject placeholder-as-executable for both --exec and --exec-batch
246 // (was previously checked only for --exec-batch).

fix: sanitize escape sequence injectioncurious-rabbitbefore adoption92c54d3

line 247why, one step back
247 if args[0].has_tokens() {

formattingcurious-rabbitbefore adoption825f308

lines 248–250why, one step back
248 bail!(
249 "First argument of --exec/--exec-batch must be a fixed executable, not a placeholder"250 );

fix: sanitize escape sequence injectioncurious-rabbitbefore adoption92c54d3

lines 251–252why, one step back
251 }
252

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 253–254why, one step back
253 // If a placeholder token was not supplied, append one at the end of the command.
254 if !has_placeholder {

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

line 255why, one step back
255 args.push(FormatTemplate::Tokens(vec![Token::Placeholder]));

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 256–269why, one step back
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> {

improve patchcurious-rabbitbefore adoption63a7d85

line 270why, one step back
270 let mut cmd = Command::new(self.args[0].generate(input, path_separator));

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

line 271why, one step back
271 for arg in &self.args[1..] {

improve patchcurious-rabbitbefore adoption63a7d85

line 272why, one step back
272 cmd.try_arg(arg.generate(input, path_separator))?;

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 273–296why, one step back
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![

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

lines 297–299why, one step back
297 FormatTemplate::Text("echo".into()),
298 FormatTemplate::Text("${SHELL}:".into()),299 FormatTemplate::Tokens(vec![Token::Placeholder]),

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 300–313why, one step back
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![

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

lines 314–315why, one step back
314 FormatTemplate::Text("echo".into()),
315 FormatTemplate::Tokens(vec![Token::NoExt]),

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 316–329why, one step back
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![

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

lines 330–331why, one step back
330 FormatTemplate::Text("echo".into()),
331 FormatTemplate::Tokens(vec![Token::Basename]),

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 332–345why, one step back
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![

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

lines 346–347why, one step back
346 FormatTemplate::Text("echo".into()),
347 FormatTemplate::Tokens(vec![Token::Parent]),

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 348–361why, one step back
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![

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

lines 362–363why, one step back
362 FormatTemplate::Text("echo".into()),
363 FormatTemplate::Tokens(vec![Token::BasenameNoExt]),

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 364–381why, one step back
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() {

fix: sanitize escape sequence injectioncurious-rabbitbefore adoption92c54d3

lines 382–383why, one step back
382 let template = CommandTemplate::new(vec!["echo", "{{{},end}"]).unwrap();
383 assert_eq!(generate_str(&template, "foo"), vec!["echo", "{foo,end}"]);

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 384–392why, one step back
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![

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

lines 393–395why, one step back
393 FormatTemplate::Text("cp".into()),
394 FormatTemplate::Tokens(vec![Token::Placeholder]),395 FormatTemplate::Tokens(vec![

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 396–412why, one step back
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![

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

lines 413–414why, one step back
413 FormatTemplate::Text("echo".into()),
414 FormatTemplate::Tokens(vec![Token::NoExt]),

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 415–434why, one step back
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());

fix: sanitize escape sequence injectioncurious-rabbitbefore adoption92c54d3

lines 435–441why, one step back
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());

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 442–445why, one step back
442 }
443444 #[test]445 fn generate_custom_path_separator() {

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

line 446why, one step back
446 let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 447–460why, one step back
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() {

Merge pull request #1043 from tmccombs/format-optionThayne McCombsbefore adoptionea22cbd

line 461why, one step back
461 let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);

Merge pull request #1534 from tmccombs/msrv-updateThayne McCombsbefore adoption8c7a84e

lines 462–485why, one step back
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}