Skip to content
Myr

exec: Execute batches before they get too long

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fixes #410.

authored by Tavian Barnes · committed by David Peter · parent 16acdeb · Browse files · 6 files+215 added−81 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+215 added−81 removed

  • tests:+43 added−9 removed
  • other:+172 added−72 removed

6 files+215 added−81 removed

modified:src/exec/command.rs+20 added-11 removed
1use std::io;2use std::io::Write;3use std::process::Command;3use std::sync::Mutex;45use argmax::Command;67use crate::error::print_error;8use crate::exit_codes::ExitCode;910struct Outputs {
39 unmodified lines
50 }51}5253/// Executes a command.53pub fn execute_commands<I: Iterator<Item = Command>>(54pub fn execute_commands<I: Iterator<Item = io::Result<Command>>>(55 cmds: I,56 out_perm: &Mutex<()>,57 enable_output_buffering: bool,58) -> ExitCode {59 let mut output_buffer = OutputBuffer::new(out_perm);59 for mut cmd in cmds {60 for result in cmds {61 let mut cmd = match result {62 Ok(cmd) => cmd,63 Err(e) => return handle_cmd_error(None, e),64 };6566 // Spawn the supplied command.67 let output = if enable_output_buffering {68 cmd.output()69 } else {
14 unmodified lines
84 }85 }86 Err(why) => {87 output_buffer.write();82 return handle_cmd_error(&cmd, why);88 return handle_cmd_error(Some(&cmd), why);89 }90 }91 }92 output_buffer.write();93 ExitCode::Success94}9590pub fn handle_cmd_error(cmd: &Command, err: io::Error) -> ExitCode {91 if err.kind() == io::ErrorKind::NotFound {92 print_error(format!("Command not found: {:?}", cmd));93 ExitCode::GeneralError94 } else {95 print_error(format!("Problem while executing command: {}", err));96 ExitCode::GeneralError96pub fn handle_cmd_error(cmd: Option<&Command>, err: io::Error) -> ExitCode {97 match (cmd, err) {98 (Some(cmd), err) if err.kind() == io::ErrorKind::NotFound => {99 print_error(format!("Command not found: {:?}", cmd));100 ExitCode::GeneralError101 }102 (_, err) => {103 print_error(format!("Problem while executing command: {}", err));104 ExitCode::GeneralError105 }106 }107}
modified:src/exec/job.rs+1 added-12 removed
60 unmodified lines
61 }62 None63 }64 });65 if limit == 0 {66 // no limit67 return cmd.execute_batch(paths);68 }6570 let mut exit_codes = Vec::new();71 let mut peekable = paths.peekable();72 while peekable.peek().is_some() {73 let limited = peekable.by_ref().take(limit);74 let exit_code = cmd.execute_batch(limited);75 exit_codes.push(exit_code);76 }77 merge_exitcodes(exit_codes)66 cmd.execute_batch(paths, limit)67}
modified:src/exec/mod.rs+112 added-45 removed
3 unmodified lines
4mod token;56use std::borrow::Cow;7use std::ffi::{OsStr, OsString};8use std::io;9use std::iter;10use std::path::{Component, Path, PathBuf, Prefix};9use std::process::{Command, Stdio};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;
71 unmodified lines
91 .map(|c| c.generate(input, path_separator));92 execute_commands(commands, &out_perm, buffer_output)93 }9492 pub fn execute_batch<I>(&self, paths: I) -> ExitCode95 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();97 let mut paths = paths.collect::<Vec<_>>();98 paths.sort();99 for cmd in &self.commands {100 let exit = cmd.generate_and_execute_batch(&paths, path_separator);101 if exit != ExitCode::Success {102 return exit;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 }105 ExitCode::Success127 }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.
78 unmodified lines
291 /// Generates and executes a command.292 ///293 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be294 /// build.195 fn generate(&self, input: &Path, path_separator: Option<&str>) -> Command {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..] {198 cmd.arg(arg.generate(&input, path_separator));298 cmd.try_arg(arg.generate(&input, path_separator))?;299 }200 cmd300 Ok(cmd)301 }202203 fn generate_and_execute_batch(204 &self,205 paths: &[PathBuf],206 path_separator: Option<&str>,207 ) -> ExitCode {208 let mut cmd = Command::new(self.args[0].generate("", None));209 cmd.stdin(Stdio::inherit());210 cmd.stdout(Stdio::inherit());211 cmd.stderr(Stdio::inherit());212213 let mut has_path = false;214215 for arg in &self.args[1..] {216 if arg.has_tokens() {217 for path in paths {218 cmd.arg(arg.generate(path, path_separator));219 has_path = true;220 }221 } else {222 cmd.arg(arg.generate("", None));223 }224 }225226 if has_path {227 match cmd.spawn().and_then(|mut c| c.wait()) {228 Ok(_) => ExitCode::Success,229 Err(e) => handle_cmd_error(&cmd, e),230 }231 } else {232 ExitCode::Success233 }234 }302}303304/// Represents a template for a single command argument.305///
288 unmodified lines
modified:tests/tests.rs+43 added-9 removed
1490 unmodified lines
1491 return;1492 }1493 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);14941495 te.assert_output(1496 &["foo", "--exec-batch", "echo", "{}", ";", "--exec-batch", "echo", "{/}"],1497 "./a.foo ./one/b.foo ./one/two/C.Foo2 ./one/two/c.foo ./one/two/three/d.foo ./one/two/three/directory_foo1498 a.foo b.foo C.Foo2 c.foo d.foo directory_foo",1495 let output = te.assert_success_and_get_output(1496 ".",1497 &[1498 "foo",1499 "--exec-batch",1500 "echo",1501 "{}",1502 ";",1503 "--exec-batch",1504 "echo",1505 "{/}",1506 ],1507 );1508 let stdout = std::str::from_utf8(&output.stdout).unwrap();1509 let lines: Vec<_> = stdout1510 .lines()1511 .map(|l| {1512 let mut words: Vec<_> = l.split_whitespace().collect();1513 words.sort();1514 words1515 })1516 .collect();15171518 assert_eq!(1519 lines,1520 &[1521 [1522 "./a.foo",1523 "./one/b.foo",1524 "./one/two/C.Foo2",1525 "./one/two/c.foo",1526 "./one/two/three/d.foo",1527 "./one/two/three/directory_foo"1528 ],1529 [1530 "C.Foo2",1531 "a.foo",1532 "b.foo",1533 "c.foo",1534 "d.foo",1535 "directory_foo"1536 ],1537 ]1538 );1539}15401541#[test]1542fn test_exec_batch_with_limit() {
3 unmodified lines
1546 }15471548 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);15491511 te.assert_output(1512 &["foo", "--batch-size", "0", "--exec-batch", "echo", "{}"],1513 "./a.foo ./one/b.foo ./one/two/C.Foo2 ./one/two/c.foo ./one/two/three/d.foo ./one/two/three/directory_foo",1514 );15151550 let output = te.assert_success_and_get_output(1551 ".",1552 &["foo", "--batch-size=2", "--exec-batch", "echo", "{}"],1553 );
563 unmodified lines
modified:Cargo.lock+38 added-4 removed
25 unmodified lines
26source = "registry+https://github.com/rust-lang/crates.io-index"27checksum = "08f9b8508dccb7687a1d6c4ce66b2b0ecef467c94667de27d8d7fe1f8d2a9cdc"2829[[package]]30name = "argmax"31version = "0.3.0"32source = "registry+https://github.com/rust-lang/crates.io-index"33checksum = "932fb17af6e53a41ce7312f1ae1ba2a6f3f613fe36f38ad655b212906eb9657f"34dependencies = [35 "lazy_static",36 "libc",37 "nix 0.23.1",38]3940[[package]]41name = "atty"42version = "0.2.14"43source = "registry+https://github.com/rust-lang/crates.io-index"44checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
99 unmodified lines
144version = "3.2.2"145source = "registry+https://github.com/rust-lang/crates.io-index"146checksum = "b37feaa84e6861e00a1f5e5aa8da3ee56d605c9992d33e082786754828e20865"147dependencies = [137 "nix",148 "nix 0.24.1",149 "winapi",150]151152[[package]]
28 unmodified lines
181version = "8.3.2"182dependencies = [183 "ansi_term",184 "anyhow",185 "argmax",186 "atty",187 "chrono",188 "clap",189 "clap_complete",
6 unmodified lines
196 "ignore",197 "jemallocator",198 "libc",199 "lscolors",188 "nix",200 "nix 0.24.1",201 "normpath",202 "num_cpus",203 "once_cell",204 "regex",
135 unmodified lines
340checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"341342[[package]]343name = "libc"332version = "0.2.125"344version = "0.2.126"345source = "registry+https://github.com/rust-lang/crates.io-index"334checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b"346checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836"347348[[package]]349name = "log"350version = "0.4.14"
18 unmodified lines
369source = "registry+https://github.com/rust-lang/crates.io-index"370checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"371372[[package]]373name = "memoffset"374version = "0.6.5"375source = "registry+https://github.com/rust-lang/crates.io-index"376checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce"377dependencies = [378 "autocfg",379]380381[[package]]382name = "nix"383version = "0.23.1"384source = "registry+https://github.com/rust-lang/crates.io-index"385checksum = "9f866317acbd3a240710c63f065ffb1e4fd466259045ccb504130b7f668f35c6"386dependencies = [387 "bitflags",388 "cc",389 "cfg-if",390 "libc",391 "memoffset",392]393394[[package]]395name = "nix"396version = "0.24.1"397source = "registry+https://github.com/rust-lang/crates.io-index"398checksum = "8f17df307904acd05aa8e32e97bb20f2a0df1728bbc2d771ae8f9a90463441e9"399dependencies = [
344 unmodified lines
modified:Cargo.toml+1 added