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
Provenance
- Commit
40b368e- Tree
b396b4d- Author
Tavian Barnes <tavianator@tavianator.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
16acdeb
6 files changed+215 added−81 removed
modified:src/exec/command.rs+20 added-11 removed
1 use std::io;2 use std::io::Write;3-use std::process::Command;3 use std::sync::Mutex;4 5+use argmax::Command;6+7 use crate::error::print_error;8 use crate::exit_codes::ExitCode;9 10 struct Outputs {39 unmodified lines50 }51 }52 53 /// Executes a command.53-pub fn execute_commands<I: Iterator<Item = Command>>(54+pub 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+ };65+66 // Spawn the supplied command.67 let output = if enable_output_buffering {68 cmd.output()69 } else {14 unmodified lines84 }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 }95 90-pub 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::GeneralError96+pub 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 lines61 }62 None63 }64 });65- if limit == 0 {66- // no limit67- return cmd.execute_batch(paths);68- }65 70- 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 lines4 mod token;5 6 use std::borrow::Cow;7 use std::ffi::{OsStr, OsString};8+use std::io;9+use std::iter;10 use std::path::{Component, Path, PathBuf, Prefix};9-use std::process::{Command, Stdio};11+use std::process::Stdio;12 use std::sync::{Arc, Mutex};13 14 use anyhow::{bail, Result};15+use argmax::Command;16 use once_cell::sync::Lazy;17 use regex::Regex;18 19 use crate::exit_codes::ExitCode;71 unmodified lines91 .map(|c| c.generate(input, path_separator));92 execute_commands(commands, &out_perm, buffer_output)93 }94 92- 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;100+101+ let builders: io::Result<Vec<_>> = self102+ .commands103+ .iter()104+ .map(|c| CommandBuilder::new(c, limit))105+ .collect();106+107+ 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+ }116+117+ for builder in &mut builders {118+ if let Err(e) = builder.finish() {119+ return handle_cmd_error(Some(&builder.cmd), e);120+ }121+ }122+123+ ExitCode::Success124 }125+ Err(e) => handle_cmd_error(None, e),126 }105- ExitCode::Success127 }128 }129 130+/// Represents a multi-exec command as it is built.131+#[derive(Debug)]132+struct 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+}140+141+impl 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![];146+147+ 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+ }156+157+ let cmd = Self::new_command(&pre_args)?;158+159+ Ok(Self {160+ pre_args,161+ path_arg: path_arg.unwrap(),162+ post_args,163+ cmd,164+ count: 0,165+ limit,166+ })167+ }168+169+ 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+ }177+178+ fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {179+ if self.limit > 0 && self.count >= self.limit {180+ self.finish()?;181+ }182+183+ 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+ }190+191+ self.cmd.try_arg(arg)?;192+ self.count += 1;193+ Ok(())194+ }195+196+ fn finish(&mut self) -> io::Result<()> {197+ if self.count > 0 {198+ self.cmd.try_args(&self.post_args)?;199+ self.cmd.status()?;200+201+ self.cmd = Self::new_command(&self.pre_args)?;202+ self.count = 0;203+ }204+205+ Ok(())206+ }207+}208+209 /// 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 lines291 /// 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 }202-203- 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());212-213- let mut has_path = false;214-215- 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- }225-226- 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 }303 304 /// Represents a template for a single command argument.305 ///288 unmodified linesmodified:tests/tests.rs+43 added-9 removed
1490 unmodified lines1491 return;1492 }1493 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);1494 1495- 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();1517+1518+ 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 }1540 1541 #[test]1542 fn test_exec_batch_with_limit() {3 unmodified lines1546 }1547 1548 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);1549 1511- 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- );1515-1550 let output = te.assert_success_and_get_output(1551 ".",1552 &["foo", "--batch-size=2", "--exec-batch", "echo", "{}"],1553 );563 unmodified linesmodified:Cargo.lock+38 added-4 removed
25 unmodified lines26 source = "registry+https://github.com/rust-lang/crates.io-index"27 checksum = "08f9b8508dccb7687a1d6c4ce66b2b0ecef467c94667de27d8d7fe1f8d2a9cdc"28 29 [[package]]30+name = "argmax"31+version = "0.3.0"32+source = "registry+https://github.com/rust-lang/crates.io-index"33+checksum = "932fb17af6e53a41ce7312f1ae1ba2a6f3f613fe36f38ad655b212906eb9657f"34+dependencies = [35+ "lazy_static",36+ "libc",37+ "nix 0.23.1",38+]39+40+[[package]]41 name = "atty"42 version = "0.2.14"43 source = "registry+https://github.com/rust-lang/crates.io-index"44 checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"99 unmodified lines144 version = "3.2.2"145 source = "registry+https://github.com/rust-lang/crates.io-index"146 checksum = "b37feaa84e6861e00a1f5e5aa8da3ee56d605c9992d33e082786754828e20865"147 dependencies = [137- "nix",148+ "nix 0.24.1",149 "winapi",150 ]151 152 [[package]]28 unmodified lines181 version = "8.3.2"182 dependencies = [183 "ansi_term",184 "anyhow",185+ "argmax",186 "atty",187 "chrono",188 "clap",189 "clap_complete",6 unmodified lines196 "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 lines340 checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"341 342 [[package]]343 name = "libc"332-version = "0.2.125"344+version = "0.2.126"345 source = "registry+https://github.com/rust-lang/crates.io-index"334-checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b"346+checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836"347 348 [[package]]349 name = "log"350 version = "0.4.14"18 unmodified lines369 source = "registry+https://github.com/rust-lang/crates.io-index"370 checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"371 372 [[package]]373+name = "memoffset"374+version = "0.6.5"375+source = "registry+https://github.com/rust-lang/crates.io-index"376+checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce"377+dependencies = [378+ "autocfg",379+]380+381+[[package]]382 name = "nix"383+version = "0.23.1"384+source = "registry+https://github.com/rust-lang/crates.io-index"385+checksum = "9f866317acbd3a240710c63f065ffb1e4fd466259045ccb504130b7f668f35c6"386+dependencies = [387+ "bitflags",388+ "cc",389+ "cfg-if",390+ "libc",391+ "memoffset",392+]393+394+[[package]]395+name = "nix"396 version = "0.24.1"397 source = "registry+https://github.com/rust-lang/crates.io-index"398 checksum = "8f17df307904acd05aa8e32e97bb20f2a0df1728bbc2d771ae8f9a90463441e9"399 dependencies = [344 unmodified linesmodified:Cargo.toml+1 added
34 unmodified lines35363738394041424341 unmodified lines34 unmodified linesversion_check = "0.9"
[dependencies]ansi_term = "0.12"argmax = "0.3.0"atty = "0.2"ignore = "0.4.3"num_cpus = "1.13"regex = "1.5.5"41 unmodified lines