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
Provenance
- Commit
2040810- Tree
033fad1- Author
David Peter <mail@david-peter.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
34dabcb
10 files changed+95 added−101 removed
modified:src/export/asciidoc.rs+4 added-5 removed
1-use std::io::{Error, ErrorKind, Result};2-1 use crate::benchmark_result::BenchmarkResult;2 use crate::format::format_duration_value;3 use crate::relative_speed::{self, BenchmarkResultWithRelativeSpeed};4 use crate::units::Unit;5 6 use super::Exporter;7 8+use anyhow::{anyhow, Result};9+10 #[derive(Default)]11 pub struct AsciidocExporter {}12 13 impl Exporter for AsciidocExporter {21 unmodified lines35 res.append(&mut table_startend());36 37 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 linesmodified:src/export/csv.rs+3 added-4 removed
1 use std::borrow::Cow;2-use std::io::{Error, ErrorKind, Result};2 3 use csv::WriterBuilder;4 5 use super::Exporter;6 use crate::benchmark_result::BenchmarkResult;7 use crate::units::Unit;8 9+use anyhow::Result;10+11 #[derive(Default)]12 pub struct CsvExporter {}13 14 impl Exporter for CsvExporter {34 unmodified lines49 }50 writer.write_record(fields)?;51 }52 52- writer53- .into_inner()54- .map_err(|e| Error::new(ErrorKind::Other, e))53+ Ok(writer.into_inner()?)54 }55 }56 57 #[test]53 unmodified linesmodified:src/export/json.rs+3 added-3 removed
1-use std::io::{Error, ErrorKind, Result};2-1 use serde::*;2 use serde_json::to_vec_pretty;3 4 use super::Exporter;5 use crate::benchmark_result::BenchmarkResult;6 use crate::units::Unit;7 8+use anyhow::Result;9+10 #[derive(Serialize, Debug)]11 struct HyperfineSummary<'a> {12 results: &'a [BenchmarkResult],13 }7 unmodified lines21 for content in output.iter_mut() {22 content.push(b'\n');23 }24 25- output.map_err(|e| Error::new(ErrorKind::Other, e))25+ Ok(output?)26 }27 }modified:src/export/markdown.rs+4 added-5 removed
1-use std::io::{Error, ErrorKind, Result};2-1 use super::Exporter;2 use crate::benchmark_result::BenchmarkResult;3 use crate::format::format_duration_value;4 use crate::relative_speed::{self, BenchmarkResultWithRelativeSpeed};5 use crate::units::Unit;6 7+use anyhow::{anyhow, Result};8+9 #[derive(Default)]10 pub struct MarkdownExporter {}11 12 impl Exporter for MarkdownExporter {17 unmodified lines30 }31 32 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 linesmodified:src/export/mod.rs+6 added-2 removed
1 use std::fs::{File, OpenOptions};2-use std::io::{Result, Write};2+use std::io::Write;3 4 mod asciidoc;5 mod csv;6 mod json;6 unmodified lines13 14 use crate::benchmark_result::BenchmarkResult;15 use crate::units::Unit;16 17+use anyhow::{Context, Result};18+19 /// The desired form of exporter to use for a given file.20 #[derive(Clone)]21 pub enum ExportType {22 /// Asciidoc Table28 unmodified lines51 52 impl 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}'"))?;57 58 let exporter: Box<dyn Exporter> = match export_type {59 ExportType::Asciidoc => Box::new(AsciidocExporter::default()),60 ExportType::Csv => Box::new(CsvExporter::default()),21 unmodified lines82 /// Write the given content to a file with the specified name83 fn 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
1 use std::cmp;2-use std::io;2 use std::process::{ExitStatus, Stdio};3 4 use colored::*;5 use statistical::{mean, median, standard_deviation};10 unmodified lines16 use crate::timer::{TimerStart, TimerStop};17 use crate::units::Second;18 use crate::warnings::Warnings;19 20+use anyhow::{bail, Result};21+22 /// Threshold for warning about fast execution time23 pub const MIN_EXECUTION_TIME: Second = 5e-3;24 25 /// Results from timing a single shell command24 unmodified lines50 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 lines65 let mut time_user = result.user_time;66 let mut time_system = result.system_time;67 68 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 }78 79 // Correct for shell spawning time80 if let Some(spawning_time) = shell_spawning_time {16 unmodified lines97 pub 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 lines131 } else {132 format!("{} -c \"\"", shell)133 };134 138- 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 lines164 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 lines182 fn 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.";189 190 run_intermediate_command(shell, command, show_output, error_output)3 unmodified lines194 fn 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.";201 202 run_intermediate_command(shell, command, show_output, error_output)3 unmodified lines206 fn 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.";213 214 run_intermediate_command(shell, command, show_output, error_output)25 unmodified lines240 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 linesmodified:src/main.rs+39 added-49 removed
1 use std::cmp;2 use std::collections::BTreeMap;3 use std::env;4-use std::io;4 5 use atty::Stream;6 use clap::ArgMatches;7 use colored::*;29 unmodified lines37 use tokenize::tokenize;38 use types::ParameterValue;39 use units::Unit;40 42-/// Print error message to stderr and terminate43-pub fn error(message: &str) -> ! {44- eprintln!("{} {}", "Error:".red(), message);45- std::process::exit(1);46-}41+use anyhow::{bail, Result};42 43 pub fn write_benchmark_comparison(results: &[BenchmarkResult]) {44 if results.len() < 2 {45 return;31 unmodified lines77 );78 }79 }80 86-/// Runs the benchmark for the given commands87-fn run(81+fn 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)?;88 89 let mut timing_results = vec![];90 91 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 line101 for (num, cmd) in commands.iter().enumerate() {102 timing_results.push(run_benchmark(num, cmd, shell_spawning_time, options)?);103 104 // 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 }107 108 // Print relative speed comparison109 if options.output_style != OutputStyleOption::Disabled {2 unmodified lines112 113 Ok(())114 }115 128-fn main() {116+fn 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)?;121 137- 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+}124 125+fn 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 }134 135 /// Build the HyperfineOptions that correspond to the given ArgMatches93 unmodified lines229 }230 231 /// Build the ExportManager that will export the results specified232 /// in the given ArgMatches246-fn build_export_manager(matches: &ArgMatches) -> io::Result<ExportManager> {233+fn 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 lines253 let command_strings = matches.values_of("command").unwrap();254 255 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>>());265 266 let args: Vec<_> = args.collect();7 unmodified lines274 .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 lines288 )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 }294 295 // `--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 }305 306 let mut i = 0;307 let mut commands = Vec::with_capacity(param_space_size);28 unmodified lines336 }337 break 'outer;338 }339 349- 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 }346 347 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 }355 356 /// Finds all the strings that appear multiple times in the input iterator, returning them in21 unmodified lines378 "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();383 384 // 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 lines412 "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 lines434 "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 linesmodified:src/shell.rs+7 added-5 removed
1-use std::io;1 use std::process::{ExitStatus, Stdio};2 3 use crate::options::Shell;4 use crate::timer::get_cpu_timer;5 6+use anyhow::{Context, Result};7+8 /// Used to indicate the result of running a command9 #[derive(Debug, Copy, Clone)]10 pub struct ExecuteResult {11 /// The amount of user time the process used12 unmodified lines24 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 lines44 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();50 51 let status = run_shell_command(stdout, stderr, command, shell)?;52 12 unmodified lines65 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 lines78 .stdin(Stdio::null())79 .stdout(stdout)80 .stderr(stderr)81 .status()82+ .with_context(|| format!("Failed to run command '{}'", command))83 }84 85 /// Run a Windows shell command using `cmd.exe /C`86 #[cfg(windows)]1 unmodified line88 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 linesmodified:Cargo.lock+7 added
10 unmodified lines11 "memchr",12 ]13 14 [[package]]15+name = "anyhow"16+version = "1.0.53"17+source = "registry+https://github.com/rust-lang/crates.io-index"18+checksum = "94a45b455c14666b85fc40a019e8ab9eb75e3a124e05494f5397122bc9eb06e0"19+20+[[package]]21 name = "approx"22 version = "0.5.1"23 source = "registry+https://github.com/rust-lang/crates.io-index"24 checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"226 unmodified lines251 [[package]]252 name = "hyperfine"253 version = "1.12.0"254 dependencies = [255+ "anyhow",256 "approx",257 "assert_cmd",258 "atty",259 "clap",641 unmodified linesmodified:Cargo.toml+1 added
21 unmodified lines22 rust_decimal = "1.19"23 rand = "0.8"24 shell-words = "1.0"25 thiserror = "1.0"26+anyhow = "1.0"27 28 [target.'cfg(not(windows))'.dependencies]29 libc = "0.2"30 21 unmodified lines