Skip to content
Myr

Unified error handling

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

authored by David Peter · committed by David Peter · parent 34dabcb · Browse files · 10 files+95 added−101 removed
This commit

State

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

Diff stats

10 files+95 added−101 removed

  • other:+95 added−101 removed

10 files+95 added−101 removed

modified:src/export/asciidoc.rs+4 added-5 removed
1use std::io::{Error, ErrorKind, Result};21use crate::benchmark_result::BenchmarkResult;2use crate::format::format_duration_value;3use crate::relative_speed::{self, BenchmarkResultWithRelativeSpeed};4use crate::units::Unit;56use super::Exporter;78use anyhow::{anyhow, Result};910#[derive(Default)]11pub struct AsciidocExporter {}1213impl Exporter for AsciidocExporter {
21 unmodified lines
35 res.append(&mut table_startend());3637 Ok(res)38 } else {39 Err(Error::new(40 ErrorKind::Other,41 "Relative speed comparison is not available for Asciidoctor export.",39 Err(anyhow!(40 "Relative speed comparison is not available for Asciidoctor export."41 ))42 }43 }44}
229 unmodified lines
modified:src/export/csv.rs+3 added-4 removed
1use std::borrow::Cow;2use std::io::{Error, ErrorKind, Result};23use csv::WriterBuilder;45use super::Exporter;6use crate::benchmark_result::BenchmarkResult;7use crate::units::Unit;89use anyhow::Result;1011#[derive(Default)]12pub struct CsvExporter {}1314impl Exporter for CsvExporter {
34 unmodified lines
49 }50 writer.write_record(fields)?;51 }5252 writer53 .into_inner()54 .map_err(|e| Error::new(ErrorKind::Other, e))53 Ok(writer.into_inner()?)54 }55}5657#[test]
53 unmodified lines
modified:src/export/json.rs+3 added-3 removed
1use std::io::{Error, ErrorKind, Result};21use serde::*;2use serde_json::to_vec_pretty;34use super::Exporter;5use crate::benchmark_result::BenchmarkResult;6use crate::units::Unit;78use anyhow::Result;910#[derive(Serialize, Debug)]11struct HyperfineSummary<'a> {12 results: &'a [BenchmarkResult],13}
7 unmodified lines
21 for content in output.iter_mut() {22 content.push(b'\n');23 }2425 output.map_err(|e| Error::new(ErrorKind::Other, e))25 Ok(output?)26 }27}
modified:src/export/markdown.rs+4 added-5 removed
1use std::io::{Error, ErrorKind, Result};21use super::Exporter;2use crate::benchmark_result::BenchmarkResult;3use crate::format::format_duration_value;4use crate::relative_speed::{self, BenchmarkResultWithRelativeSpeed};5use crate::units::Unit;67use anyhow::{anyhow, Result};89#[derive(Default)]10pub struct MarkdownExporter {}1112impl Exporter for MarkdownExporter {
17 unmodified lines
30 }3132 Ok(destination)33 } else {34 Err(Error::new(35 ErrorKind::Other,36 "Relative speed comparison is not available for Markdown export.",34 Err(anyhow!(35 "Relative speed comparison is not available for Markdown export."36 ))37 }38 }39}
254 unmodified lines
modified:src/export/mod.rs+6 added-2 removed
1use std::fs::{File, OpenOptions};2use std::io::{Result, Write};2use std::io::Write;34mod asciidoc;5mod csv;6mod json;
6 unmodified lines
1314use crate::benchmark_result::BenchmarkResult;15use crate::units::Unit;1617use anyhow::{Context, Result};1819/// The desired form of exporter to use for a given file.20#[derive(Clone)]21pub enum ExportType {22 /// Asciidoc Table
28 unmodified lines
5152impl ExportManager {53 /// Add an additional exporter to the ExportManager54 pub fn add_exporter(&mut self, export_type: ExportType, filename: &str) -> Result<()> {53 let _ = File::create(filename)?;55 let _ = File::create(filename)56 .with_context(|| format!("Could not create export file '{filename}'"))?;5758 let exporter: Box<dyn Exporter> = match export_type {59 ExportType::Asciidoc => Box::new(AsciidocExporter::default()),60 ExportType::Csv => Box::new(CsvExporter::default()),
21 unmodified lines
82/// Write the given content to a file with the specified name83fn write_to_file(filename: &str, content: &[u8]) -> Result<()> {84 let mut file = OpenOptions::new().write(true).open(filename)?;85 file.write_all(content)86 .with_context(|| format!("Failed to export results to '{}'", filename))87}
modified:src/benchmark.rs+21 added-28 removed
1use std::cmp;2use std::io;2use std::process::{ExitStatus, Stdio};34use colored::*;5use statistical::{mean, median, standard_deviation};
10 unmodified lines
16use crate::timer::{TimerStart, TimerStop};17use crate::units::Second;18use crate::warnings::Warnings;1920use anyhow::{bail, Result};2122/// Threshold for warning about fast execution time23pub const MIN_EXECUTION_TIME: Second = 5e-3;2425/// Results from timing a single shell command
24 unmodified lines
50 command: &Command<'_>,51 show_output: bool,52 failure_action: CmdFailureAction,53 shell_spawning_time: Option<TimingResult>,53) -> io::Result<(TimingResult, ExitStatus)> {54) -> Result<(TimingResult, ExitStatus)> {55 let (stdout, stderr) = if show_output {56 (Stdio::inherit(), Stdio::inherit())57 } else {58 (Stdio::null(), Stdio::null())
6 unmodified lines
65 let mut time_user = result.user_time;66 let mut time_system = result.system_time;6768 if failure_action == CmdFailureAction::RaiseError && !result.status.success() {68 return Err(io::Error::new(69 io::ErrorKind::Other,70 format!(71 "{}. \72 Use the '-i'/'--ignore-failure' option if you want to ignore this. \69 bail!(70 "{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \71 Alternatively, use the '--show-output' option to debug what went wrong.",74 result.status.code().map_or(75 "The process has been terminated by a signal".into(),76 |c| format!("Command terminated with non-zero exit code: {}", c)77 )78 ),79 ));72 result.status.code().map_or(73 "The process has been terminated by a signal".into(),74 |c| format!("Command terminated with non-zero exit code: {}", c)75 )76 );77 }7879 // Correct for shell spawning time80 if let Some(spawning_time) = shell_spawning_time {
16 unmodified lines
97pub fn mean_shell_spawning_time(98 shell: &Shell,99 style: OutputStyleOption,100 show_output: bool,104) -> io::Result<TimingResult> {101) -> Result<TimingResult> {102 const COUNT: u64 = 50;103 let progress_bar = if style != OutputStyleOption::Disabled {104 Some(get_progress_bar(105 COUNT,
25 unmodified lines
131 } else {132 format!("{} -c \"\"", shell)133 };134138 return Err(io::Error::new(139 io::ErrorKind::Other,140 format!(141 "Could not measure shell execution time. \142 Make sure you can run '{}'.",143 shell_cmd144 ),145 ));135 bail!(136 "Could not measure shell execution time. Make sure you can run '{}'.",137 shell_cmd138 );139 }140 Ok((r, _)) => {141 times_real.push(r.time_real);142 times_user.push(r.time_user);
21 unmodified lines
164 shell: &Shell,165 command: &Option<Command<'_>>,166 show_output: bool,167 error_output: &'static str,175) -> io::Result<TimingResult> {168) -> Result<TimingResult> {169 if let Some(ref cmd) = command {170 let res = time_shell_command(shell, cmd, show_output, CmdFailureAction::RaiseError, None);171 if res.is_err() {179 return Err(io::Error::new(io::ErrorKind::Other, error_output));172 bail!(error_output);173 }174 return res.map(|r| r.0);175 }176 Ok(TimingResult {
5 unmodified lines
182fn run_setup_command(183 shell: &Shell,184 command: &Option<Command<'_>>,185 show_output: bool,193) -> io::Result<TimingResult> {186) -> Result<TimingResult> {187 let error_output = "The setup command terminated with a non-zero exit code. \188 Append ' || true' to the command if you are sure that this can be ignored.";189190 run_intermediate_command(shell, command, show_output, error_output)
3 unmodified lines
194fn run_preparation_command(195 shell: &Shell,196 command: &Option<Command<'_>>,197 show_output: bool,205) -> io::Result<TimingResult> {198) -> Result<TimingResult> {199 let error_output = "The preparation command terminated with a non-zero exit code. \200 Append ' || true' to the command if you are sure that this can be ignored.";201202 run_intermediate_command(shell, command, show_output, error_output)
3 unmodified lines
206fn run_cleanup_command(207 shell: &Shell,208 command: &Option<Command<'_>>,209 show_output: bool,217) -> io::Result<TimingResult> {210) -> Result<TimingResult> {211 let error_output = "The cleanup command terminated with a non-zero exit code. \212 Append ' || true' to the command if you are sure that this can be ignored.";213214 run_intermediate_command(shell, command, show_output, error_output)
25 unmodified lines
240 num: usize,241 cmd: &Command<'_>,242 shell_spawning_time: TimingResult,243 options: &HyperfineOptions,251) -> io::Result<BenchmarkResult> {244) -> Result<BenchmarkResult> {245 let command_name = cmd.get_name();246 if options.output_style != OutputStyleOption::Disabled {247 println!(248 "{}{}: {}",
268 unmodified lines
modified:src/main.rs+39 added-49 removed
1use std::cmp;2use std::collections::BTreeMap;3use std::env;4use std::io;45use atty::Stream;6use clap::ArgMatches;7use colored::*;
29 unmodified lines
37use tokenize::tokenize;38use types::ParameterValue;39use units::Unit;4042/// Print error message to stderr and terminate43pub fn error(message: &str) -> ! {44 eprintln!("{} {}", "Error:".red(), message);45 std::process::exit(1);46}41use anyhow::{bail, Result};4243pub fn write_benchmark_comparison(results: &[BenchmarkResult]) {44 if results.len() < 2 {45 return;
31 unmodified lines
77 );78 }79}8086/// Runs the benchmark for the given commands87fn run(81fn run_benchmarks_and_print_comparison(82 commands: &[Command<'_>],83 options: &HyperfineOptions,84 export_manager: &ExportManager,91) -> io::Result<()> {85) -> Result<()> {86 let shell_spawning_time =87 mean_shell_spawning_time(&options.shell, options.output_style, options.show_output)?;8889 let mut timing_results = vec![];9091 if let Some(preparation_command) = &options.preparation_command {92 if preparation_command.len() > 1 && commands.len() != preparation_command.len() {99 error(93 bail!(94 "The '--prepare' option has to be provided just once or N times, where N is the \101 number of benchmark commands.",95 number of benchmark commands."96 );97 }98 }99
1 unmodified line
101 for (num, cmd) in commands.iter().enumerate() {102 timing_results.push(run_benchmark(num, cmd, shell_spawning_time, options)?);103104 // Export (intermediate) results111 let ans = export_manager.write_results(&timing_results, options.time_unit);112 if let Err(e) = ans {113 error(&format!(114 "The following error occurred while exporting: {}",115 e116 ));117 }105 export_manager.write_results(&timing_results, options.time_unit)?;106 }107108 // Print relative speed comparison109 if options.output_style != OutputStyleOption::Disabled {
2 unmodified lines
112113 Ok(())114}115128fn main() {116fn run() -> Result<()> {117 let matches = get_arg_matches(env::args_os());130 let options = build_hyperfine_options(&matches);131 let commands = build_commands(&matches);132 let export_manager = match build_export_manager(&matches) {133 Ok(export_manager) => export_manager,134 Err(ref e) => error(&e.to_string()),135 };118 let options = build_hyperfine_options(&matches)?;119 let commands = build_commands(&matches)?;120 let export_manager = build_export_manager(&matches)?;121137 let res = match options {138 Ok(ref opts) => run(&commands, opts, &export_manager),139 Err(ref e) => error(&e.to_string()),140 };122 run_benchmarks_and_print_comparison(&commands, &options, &export_manager)123}124125fn main() {142 match res {126 match run() {127 Ok(_) => {}144 Err(e) => error(&e.to_string()),128 Err(e) => {129 eprintln!("{} {:#}", "Error:".red(), e);130 std::process::exit(1);131 }132 }133}134135/// Build the HyperfineOptions that correspond to the given ArgMatches
93 unmodified lines
229}230231/// Build the ExportManager that will export the results specified232/// in the given ArgMatches246fn build_export_manager(matches: &ArgMatches) -> io::Result<ExportManager> {233fn build_export_manager(matches: &ArgMatches) -> Result<ExportManager> {234 let mut export_manager = ExportManager::default();235 {249 let mut add_exporter = |flag, exporttype| -> io::Result<()> {236 let mut add_exporter = |flag, exporttype| -> Result<()> {237 if let Some(filename) = matches.value_of(flag) {238 export_manager.add_exporter(exporttype, filename)?;239 }240 Ok(())
12 unmodified lines
253 let command_strings = matches.values_of("command").unwrap();254255 if let Some(args) = matches.values_of("parameter-scan") {256 let step_size = matches.value_of("parameter-step-size");270 match get_parameterized_commands(command_names, command_strings, args, step_size) {271 Ok(commands) => commands,272 Err(e) => error(&e.to_string()),273 }257 Ok(get_parameterized_commands(258 command_names,259 command_strings,260 args,261 step_size,262 )?)263 } else if let Some(args) = matches.values_of("parameter-list") {264 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());265266 let args: Vec<_> = args.collect();
7 unmodified lines
274 .collect();275 {276 let dupes = find_dupes(param_names_and_values.iter().map(|(name, _)| *name));277 if !dupes.is_empty() {289 error(&format!("duplicate parameter names: {}", &dupes.join(", ")))278 bail!("Duplicate parameter names: {}", &dupes.join(", "));279 }280 }281 let command_list = command_strings.collect::<Vec<&str>>();282
5 unmodified lines
288 )289 .collect();290 let param_space_size = dimensions.iter().product();291 if param_space_size == 0 {303 return Vec::new();292 return Ok(Vec::new());293 }294295 // `--command-name` should appear exactly once or exactly B times,296 // where B is the total number of benchmarks.297 let command_name_count = command_names.len();298 if command_name_count > 1 && command_name_count != param_space_size {310 let err =311 OptionsError::UnexpectedCommandNameCount(command_name_count, param_space_size);312 error(&err.to_string());299 return Err(OptionsError::UnexpectedCommandNameCount(300 command_name_count,301 param_space_size,302 )303 .into());304 }305306 let mut i = 0;307 let mut commands = Vec::with_capacity(param_space_size);
28 unmodified lines
336 }337 break 'outer;338 }339349 commands340 Ok(commands)341 } else {342 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());343 if command_names.len() > command_strings.len() {353 let err = OptionsError::TooManyCommandNames(command_strings.len());354 error(&err.to_string());344 return Err(OptionsError::TooManyCommandNames(command_strings.len()).into());345 }346347 let command_list = command_strings.collect::<Vec<&str>>();348 let mut commands = Vec::with_capacity(command_list.len());349 for (i, s) in command_list.iter().enumerate() {350 commands.push(Command::new(command_names.get(i).copied(), s));351 }362 commands352 Ok(commands)353 }354}355356/// Finds all the strings that appear multiple times in the input iterator, returning them in
21 unmodified lines
378 "z,y",379 "echo {par1} {par2}",380 "printf '%s\n' {par1} {par2}",381 ]);392 let result = build_commands(&matches);382 let result = build_commands(&matches).unwrap();383384 // Iteration order: command list first, then parameters in listed order (here, "par1" before385 // "par2", which is distinct from their sorted order), with parameter values in listed order.386 let pv = |s: &str| ParameterValue::Text(s.to_string());
25 unmodified lines
412 "1,2",413 "--command-name",414 "name-{foo}",415 ]);426 let commands = build_commands(&matches);416 let commands = build_commands(&matches).unwrap();417 assert_eq!(commands.len(), 2);418 assert_eq!(commands[0].get_name(), "name-1");419 assert_eq!(commands[1].get_name(), "name-2");420 assert_eq!(commands[0].get_shell_command(), "echo 1");
13 unmodified lines
434 "1",435 "--command-name",436 "name-{val}",437 ]);448 let commands = build_commands(&matches);438 let commands = build_commands(&matches).unwrap();439 assert_eq!(commands.len(), 2);440 assert_eq!(commands[0].get_name(), "name-1");441 assert_eq!(commands[1].get_name(), "name-2");442 assert_eq!(commands[0].get_shell_command(), "echo 1");
2 unmodified lines
modified:src/shell.rs+7 added-5 removed
1use std::io;1use std::process::{ExitStatus, Stdio};23use crate::options::Shell;4use crate::timer::get_cpu_timer;56use anyhow::{Context, Result};78/// Used to indicate the result of running a command9#[derive(Debug, Copy, Clone)]10pub struct ExecuteResult {11 /// The amount of user time the process used
12 unmodified lines
24 stdout: Stdio,25 stderr: Stdio,26 command: &str,27 shell: &Shell,27) -> io::Result<ExecuteResult> {28) -> Result<ExecuteResult> {29 let mut child = run_shell_command(stdout, stderr, command, shell)?;30 let cpu_timer = get_cpu_timer(&child);31 let status = child.wait()?;32
11 unmodified lines
44 stdout: Stdio,45 stderr: Stdio,46 command: &str,47 shell: &Shell,47) -> io::Result<ExecuteResult> {48) -> Result<ExecuteResult> {49 let cpu_timer = get_cpu_timer();5051 let status = run_shell_command(stdout, stderr, command, shell)?;52
12 unmodified lines
65 stdout: Stdio,66 stderr: Stdio,67 command: &str,68 shell: &Shell,68) -> io::Result<std::process::ExitStatus> {69) -> Result<std::process::ExitStatus> {70 shell71 .command()72 .arg("-c")73 .arg(command)
4 unmodified lines
78 .stdin(Stdio::null())79 .stdout(stdout)80 .stderr(stderr)81 .status()82 .with_context(|| format!("Failed to run command '{}'", command))83}8485/// Run a Windows shell command using `cmd.exe /C`86#[cfg(windows)]
1 unmodified line
88 stdout: Stdio,89 stderr: Stdio,90 command: &str,91 shell: &Shell,90) -> io::Result<std::process::Child> {92) -> Result<std::process::Child> {93 shell94 .command()95 .arg("/C")96 .arg(command)
5 unmodified lines
modified:Cargo.lock+7 added
10 unmodified lines
11 "memchr",12]1314[[package]]15name = "anyhow"16version = "1.0.53"17source = "registry+https://github.com/rust-lang/crates.io-index"18checksum = "94a45b455c14666b85fc40a019e8ab9eb75e3a124e05494f5397122bc9eb06e0"1920[[package]]21name = "approx"22version = "0.5.1"23source = "registry+https://github.com/rust-lang/crates.io-index"24checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
226 unmodified lines
251[[package]]252name = "hyperfine"253version = "1.12.0"254dependencies = [255 "anyhow",256 "approx",257 "assert_cmd",258 "atty",259 "clap",
641 unmodified lines
modified:Cargo.toml+1 added
21 unmodified lines
22rust_decimal = "1.19"23rand = "0.8"24shell-words = "1.0"25thiserror = "1.0"26anyhow = "1.0"2728[target.'cfg(not(windows))'.dependencies]29libc = "0.2"30
21 unmodified lines