Run setup/cleanup commands in a shell (#990)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Peter · committed by GitHub · parent e4a3213 · Browse files · 6 files·+103 added−80 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+103 added−80 removed
- tests:+19 added−19 removed
- other:+84 added−61 removed
Provenance
- Commit
4a9e066- Tree
39dd85c- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
e4a3213
6 files changed+103 added−80 removed
modified:doc/hyperfine.1+6 added-4 removed
192 unmodified lines193 possible parameter combinations.194 .HP195 \fB\-\-shell\fR \fISHELL\fP196 .IP197-Set the shell to use for executing commands (default: none). This can be198-the name or the path to the shell executable, or a full command line197+Set the shell to use for executing benchmarked commands, including warmup runs198+(default: none). This can be the name or the path to the shell executable,199+or a full command line200 like "bash \fB\-\-norc\fR". It can also be set to "default" to explicitly201 select the platform shell (sh on Unix, cmd.exe on Windows). Finally, this can also be201-set to "none" to disable the shell. In this case, commands will be202+set to "none" to disable the shell. In this case, benchmarked commands will be203 executed directly. They can still have arguments, but more complex204 things like "sleep 0.1; sleep 0.2" are not possible without a shell.204-This option also applies to setup, prepare, conclude, and cleanup commands.205+Setup, prepare, conclude, and cleanup commands always use a shell: the selected206+shell, or the platform shell when this option is omitted or set to "none".207 .HP208 \fB\-S\fR209 .IP210 An alias for '\-\-shell=default' (sh on Unix, cmd.exe on Windows).182 unmodified linesmodified:src/benchmark/executor.rs+51 added-20 removed
3 unmodified lines4 5 use crate::benchmark::measurement::Measurement;6 use crate::benchmark::measurement::Measurements;7 use crate::command::Command;8-use crate::options::{9- CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell,10-};8+use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};9 use crate::output::progress_bar::get_progress_bar;10 use crate::quantity::{second, Information, Time, Zero};11 use crate::timer::execute_and_measure;12 use crate::util::randomized_environment_offset;26 unmodified lines39 command_failure_action: Option<CmdFailureAction>,40 output_policy: &CommandOutputPolicy,41 ) -> Result<Measurement>;42 43+ /// Run a lifecycle command through a shell, always treating failures as errors.44+ fn run_intermediate_command_and_measure(45+ &self,46+ command: &Command<'_>,47+ iteration: BenchmarkIteration,48+ output_policy: &CommandOutputPolicy,49+ ) -> Result<Measurement> {50+ self.run_command_and_measure(51+ command,52+ iteration,53+ Some(CmdFailureAction::RaiseError),54+ output_policy,55+ )56+ }57+58 /// Perform a calibration of this executor. For example,59 /// when running commands through a shell, we need to60 /// measure the shell spawning time separately in order61 /// to subtract it from the full runtime later.8 unmodified lines70 71 fn run_command_and_measure_common(72 mut command: std::process::Command,73 iteration: BenchmarkIteration,61- command_failure_action: CmdFailureAction,62- command_input_policy: &CommandInputPolicy,74+ command_failure_action: Option<CmdFailureAction>,75+ options: &Options,76 command_output_policy: &CommandOutputPolicy,77 command_name: &str,78 collect_hardware_counters: bool,79 ) -> Result<Measurement> {67- let stdin = command_input_policy.get_stdin()?;80+ let stdin = options.command_input_policy.get_stdin()?;81 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;82 command.stdin(stdin).stdout(stdout).stderr(stderr);83 84 command.env(10 unmodified lines95 96 if !measurement.exit_status.success() {97 use crate::util::exit_code::extract_exit_code;98 99+ let show_ignore_failure_hint = command_failure_action.is_none();86- let should_fail = match command_failure_action {100+ let should_fail = match command_failure_action101+ .as_ref()102+ .unwrap_or(&options.command_failure_action)103+ {104 CmdFailureAction::RaiseError => true,105 CmdFailureAction::IgnoreAllFailures => false,89- CmdFailureAction::IgnoreSpecificFailures(ref codes) => {106+ CmdFailureAction::IgnoreSpecificFailures(codes) => {107 // Only fail if the exit code is not in the list of codes to ignore108 if let Some(exit_code) = extract_exit_code(measurement.exit_status) {109 !codes.contains(&exit_code)110 } else {10 unmodified lines121 BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"),122 BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(),123 BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"),124 };108- bail!(109- "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \110- Alternatively, use the '--show-output' option to debug what went wrong.",111- cause=measurement.exit_status.code().map_or(112- "The process has been terminated by a signal".into(),113- |c| format!("Command terminated with non-zero exit code {c}")114-115- ),125+ let cause = measurement.exit_status.code().map_or_else(126+ || "was terminated by a signal".to_owned(),127+ |code| format!("terminated with non-zero exit code {code}"),128 );129+ let hint = if show_ignore_failure_hint {130+ " Use the '-i'/'--ignore-failure' option if you want to ignore this. \131+ Alternatively, use the '--show-output' option to debug what went wrong."132+ } else {133+ " Use the '--show-output' option to debug what went wrong."134+ };135+ bail!("Command '{command_name}' {cause} in {when}.{hint}");136 }137 }138 139 Ok(measurement)19 unmodified lines159 ) -> Result<Measurement> {160 run_command_and_measure_common(161 command.get_command()?,162 iteration,144- command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),145- &self.options.command_input_policy,163+ command_failure_action,164+ self.options,165 output_policy,166 &command.get_command_line(),167 matches!(iteration, BenchmarkIteration::Benchmark(_)),168 )169 }170 171+ fn run_intermediate_command_and_measure(172+ &self,173+ command: &Command<'_>,174+ iteration: BenchmarkIteration,175+ output_policy: &CommandOutputPolicy,176+ ) -> Result<Measurement> {177+ // Keep shell startup in the hook's duration: raw benchmarks have no178+ // calibrated shell overhead to add back when estimating the run count.179+ ShellExecutor::new(&Shell::platform_default(), self.options)180+ .run_intermediate_command_and_measure(command, iteration, output_policy)181+ }182+183 fn calibrate(&mut self) -> Result<()> {184 Ok(())185 }186 40 unmodified lines227 228 let mut measurement = run_command_and_measure_common(229 command_builder,230 iteration,200- command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),201- &self.options.command_input_policy,231+ command_failure_action,232+ self.options,233 output_policy,234 &command.get_command_line(),235 false,236 )?;164 unmodified linesmodified:src/benchmark/mod.rs+16 added-28 removed
9 unmodified lines10 use crate::benchmark::benchmark_result::Parameter;11 use crate::benchmark::executor::BenchmarkIteration;12 use crate::benchmark::measurement::{Measurement, Measurements};13 use crate::command::Command;14-use crate::options::{15- CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,16-};14+use crate::options::{CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption};15 use crate::outlier_detection::OUTLIER_THRESHOLD;16 use crate::output::console_writeln;17 use crate::output::progress_bar::{18 finish_initial_measurement, get_progress_bar, set_benchmark_header, start_initial_measurement,33 unmodified lines52 executor,53 }54 }55 58- /// Run setup, cleanup, or preparation commands56+ /// Run setup, cleanup, preparation, or conclusion commands57 fn run_intermediate_command(58 &self,59 command: &Command<'_>,62- error_output: &'static str,60+ kind: &'static str,61 output_policy: &CommandOutputPolicy,62 iteration: executor::BenchmarkIteration,63 ) -> Result<Measurement> {64 self.executor67- .run_command_and_measure(68- command,69- iteration,70- Some(CmdFailureAction::RaiseError),71- output_policy,72- )73- .map_err(|_| anyhow!(error_output))65+ .run_intermediate_command_and_measure(command, iteration, output_policy)66+ .map_err(|error| {67+ let hint = if cfg!(windows) {68+ "Append ' || exit /b 0' to the command if this failure can be ignored."69+ } else {70+ "Append ' || true' to the command if this failure can be ignored."71+ };72+ anyhow!("The {kind} command failed: {error:#} {hint}")73+ })74 }75 76 /// Run the command specified by `--setup`.77 fn run_setup_command(6 unmodified lines84 .setup_command85 .as_ref()86 .map(|setup_command| Command::new_parametrized(None, setup_command, parameters));87 88- let error_output = "The setup command terminated with a non-zero exit code. \89- Append ' || true' to the command if you are sure that this can be ignored.";90-88 Ok(command89 .map(|cmd| {90 self.run_intermediate_command(91 &cmd,95- error_output,92+ "setup",93 output_policy,94 BenchmarkIteration::NonBenchmarkRun,95 )96 })12 unmodified lines109 .cleanup_command110 .as_ref()111 .map(|cleanup_command| Command::new_parametrized(None, cleanup_command, parameters));112 116- let error_output = "The cleanup command terminated with a non-zero exit code. \117- Append ' || true' to the command if you are sure that this can be ignored.";118-113 Ok(command114 .map(|cmd| {115 self.run_intermediate_command(116 &cmd,123- error_output,117+ "cleanup",118 output_policy,119 BenchmarkIteration::NonBenchmarkRun,120 )121 })7 unmodified lines129 command: &Command<'_>,130 output_policy: &CommandOutputPolicy,131 iteration: executor::BenchmarkIteration,132 ) -> Result<Measurement> {139- let error_output = "The preparation command terminated with a non-zero exit code. \140- Append ' || true' to the command if you are sure that this can be ignored.";141-142- self.run_intermediate_command(command, error_output, output_policy, iteration)133+ self.run_intermediate_command(command, "preparation", output_policy, iteration)134 }135 136 /// Run the command specified by `--conclude`.137 fn run_conclusion_command(1 unmodified line139 command: &Command<'_>,140 output_policy: &CommandOutputPolicy,141 iteration: executor::BenchmarkIteration,142 ) -> Result<Measurement> {152- let error_output = "The conclusion command terminated with a non-zero exit code. \153- Append ' || true' to the command if you are sure that this can be ignored.";154-155- self.run_intermediate_command(command, error_output, output_policy, iteration)143+ self.run_intermediate_command(command, "conclusion", output_policy, iteration)144 }145 146 fn validate_measurement(&self, measurement: &Measurement) -> Result<()> {147 if self.options.skip_unavailable_metrics {316 unmodified linesmodified:src/cli.rs+6 added-5 removed
234 unmodified lines235 .action(ArgAction::Set)236 .value_name("SHELL")237 .overrides_with("shell")238 .value_hint(ValueHint::CommandString)239- .help("Set the shell to use for executing commands (default: none). This can be the \240- name or the path to the shell executable, or a full command line \239+ .help("Set the shell to use for executing benchmarked commands, including warmup runs \240+ (default: none). This can be the name or the path to the shell executable, or a full command line \241 like \"bash --norc\". It can also be set to \"default\" to explicitly select \242 the platform shell (sh on Unix, cmd.exe on Windows). It can also be set to \243- \"none\" to disable the shell. In this case, commands will be executed \243+ \"none\" to disable the shell. In this case, benchmarked commands will be executed \244 directly. They can still have arguments, but more complex things like \245- \"sleep 0.1; sleep 0.2\" are not possible without a shell. This option also \246- applies to setup, prepare, conclude, and cleanup commands.")245+ \"sleep 0.1; sleep 0.2\" are not possible without a shell. Setup, prepare, conclude, \246+ and cleanup commands always use a shell: the selected shell, or the platform \247+ shell when this option is omitted or set to \"none\".")248 )249 .arg(250 Arg::new("default-shell")251 .short('S')172 unmodified linesmodified:tests/integration_tests.rs+19 added-19 removed
273 unmodified lines274 .arg("some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")275 .assert()276 .failure()277 .stderr(predicate::str::contains(278- "Command terminated with non-zero exit code",278+ "Command 'some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577' terminated with non-zero exit code",279 ));280 }281 282 #[test]14 unmodified lines297 fn fails_for_failing_command_without_shell() {298 hyperfine()299 .arg("--shell=none")300 .arg("--runs=1")301- .arg("false")301+ .arg("--command-name=named benchmark")302+ .args(["--parameter-list", "status", "0,1"])303+ .arg("test {status} -eq 0")304 .assert()305 .failure()306 .stderr(predicate::str::contains(305- "Command terminated with non-zero exit code",306- ));307+ "Command 'test 1 -eq 0' terminated with non-zero exit code 1 in the first benchmark run.",308+ ))309+ .stderr(predicate::str::contains("--ignore-failure"));310 }311 312 #[test]313 fn fails_for_unknown_setup_command() {3 unmodified lines317 .arg("--setup=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")318 .arg("echo test")319 .assert()320 .failure()318- .stderr(predicate::str::contains(319- "The setup command terminated with a non-zero exit code.",320- ));321+ .stderr(predicate::str::contains("The setup command failed:"));322 }323 324 #[test]325 fn fails_for_unknown_cleanup_command() {3 unmodified lines329 .arg("--cleanup=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")330 .arg("echo test")331 .assert()332 .failure()332- .stderr(predicate::str::contains(333- "The cleanup command terminated with a non-zero exit code.",334- ));333+ .stderr(predicate::str::contains("The cleanup command failed:"));334 }335 336 #[test]337 fn fails_for_unknown_prepare_command() {2 unmodified lines340 .arg("--prepare=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")341 .arg("echo test")342 .assert()343 .failure()345- .stderr(predicate::str::contains(346- "The preparation command terminated with a non-zero exit code.",347- ));344+ .stderr(predicate::str::contains("The preparation command failed:"));345 }346 347 #[test]348 fn fails_for_unknown_conclude_command() {2 unmodified lines351 .arg("--conclude=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")352 .arg("echo test")353 .assert()354 .failure()358- .stderr(predicate::str::contains(359- "The conclusion command terminated with a non-zero exit code.",360- ));355+ .stderr(predicate::str::contains("The conclusion command failed:"));356 }357 358 #[cfg(unix)]359 #[test]2 unmodified lines362 .arg("false")363 .assert()364 .failure()365 .stderr(predicate::str::contains(371- "Command terminated with non-zero exit code",366+ "Command 'false' terminated with non-zero exit code",367 ));368 369 hyperfine()370 .arg("--runs=1")23 unmodified lines394 .arg("exit 2")395 .assert()396 .failure()397 .stderr(predicate::str::contains(403- "Command terminated with non-zero exit code 2",398+ "Command 'exit 2' terminated with non-zero exit code 2",399 ));400 }401 402 #[cfg(unix)]32 unmodified lines435 .arg("exit 4")436 .assert()437 .failure()438 .stderr(predicate::str::contains(444- "Command terminated with non-zero exit code 4",439+ "Command 'exit 4' terminated with non-zero exit code 4",440 ));441 }442 443 #[cfg(unix)]27 unmodified lines471 .arg("--runs=1")472 .arg("--show-output")473 .arg("--shell")474 .arg("echo 'custom_shell' '--shell-arg'")475+ .arg("--setup=echo setup")476+ .arg("--prepare=echo prepare")477+ .arg("--conclude=echo conclude")478+ .arg("--cleanup=echo cleanup")479 .arg("echo benchmark")480 .assert()481 .success()482+ .stdout(predicate::str::contains("custom_shell --shell-arg").count(5))483 .stdout(484 predicate::str::contains("custom_shell --shell-arg -c echo benchmark").or(485 predicate::str::contains("custom_shell --shell-arg /C echo benchmark"),486 ),788 unmodified linesmodified:README.md+5 added-4 removed
106 unmodified lines107 ```108 109 ### Intermediate shell110 111-By default, commands are executed directly, without an intermediate shell (`--shell=none`).111+By default, benchmarked commands, including warmup runs, are executed directly, without an intermediate shell (`--shell=none`).112 Arguments are split using shell-like quoting, so quoted arguments containing spaces are supported.113 Shell syntax such as pipes, redirections, environment-variable expansion, `*`, and `~` is not interpreted.114 This avoids shell startup overhead and the noise from correcting for it, especially for fast commands115 (< 5 ms).8 unmodified lines124 ```sh125 hyperfine --shell zsh 'for i in {1..10000}; do echo test; done'126 ```127 128-The shell setting applies to all commands, including `--setup`, `--prepare`, `--conclude`, and `--cleanup`.129-If any of these commands need shell syntax, enable a shell explicitly.128+The `--setup`, `--prepare`, `--conclude`, and `--cleanup` commands always run through a shell.129+They use the shell selected by `--shell`, or the platform shell (`sh` on Unix, `cmd.exe` on Windows)130+when `--shell` is omitted or set to `none`.131 131-When a shell is enabled, hyperfine *corrects for the shell spawning time*. It runs the shell with an132+When benchmarked commands use a shell, hyperfine *corrects for the shell spawning time*. It runs the shell with an133 empty command multiple times to measure its startup time, then subtracts this time from each134 time measurement.135 136 313 unmodified lines