mod.rs
This file
Path
src/export/mod.rs
153 lines · 4.9 KiB · Rust
Last changed by
Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
History of this fileTake it
1use std::fs::{File, OpenOptions};2use std::io::{self, Write};34mod asciidoc;5mod csv;6mod json;7mod markdown;8mod markup;9mod orgmode;10#[cfg(test)]11mod tests;1213use self::asciidoc::AsciidocExporter;14use self::csv::CsvExporter;15use self::json::JsonExporter;16use self::markdown::MarkdownExporter;17use self::orgmode::OrgmodeExporter;1819use crate::benchmark::benchmark_result::BenchmarkResult;20use crate::metric::MetricSelection;21use crate::output::console_writeln;2223use anyhow::{Context, Result};24use clap::ArgMatches;2526/// The desired form of exporter to use for a given file.27#[derive(Clone)]28pub enum ExportType {29 /// Asciidoc Table30 Asciidoc,3132 /// CSV (comma separated values) format33 Csv,3435 /// JSON format36 Json,3738 /// Markdown table39 Markdown,4041 /// Emacs org-mode tables42 Orgmode,43}4445/// Interface for different exporters.46trait Exporter {47 /// Export the given entries in the serialized form.48 fn serialize(&self, results: &[BenchmarkResult], primary: MetricSelection) -> Result<Vec<u8>>;49}5051pub enum ExportTarget {52 File(String),53 Stdout,54}5556struct ExporterWithTarget {57 exporter: Box<dyn Exporter>,58 target: ExportTarget,59}6061/// Handles the management of multiple file exporters.62pub struct ExportManager {63 exporters: Vec<ExporterWithTarget>,64 primary: MetricSelection,65}6667impl ExportManager {68 /// Build the ExportManager that will export the results specified69 /// in the given ArgMatches70 pub fn from_cli_arguments(matches: &ArgMatches, primary: MetricSelection) -> Result<Self> {71 let mut export_manager = Self {72 exporters: vec![],73 primary,74 };75 {76 let mut add_exporter = |flag, exporttype| -> Result<()> {77 if let Some(filename) = matches.get_one::<String>(flag) {78 export_manager.add_exporter(exporttype, filename)?;79 }80 Ok(())81 };82 add_exporter("export-asciidoc", ExportType::Asciidoc)?;83 add_exporter("export-json", ExportType::Json)?;84 add_exporter("export-csv", ExportType::Csv)?;85 add_exporter("export-markdown", ExportType::Markdown)?;86 add_exporter("export-orgmode", ExportType::Orgmode)?;87 }88 Ok(export_manager)89 }9091 /// Add an additional exporter to the ExportManager92 pub fn add_exporter(&mut self, export_type: ExportType, filename: &str) -> Result<()> {93 let exporter: Box<dyn Exporter> = match export_type {94 ExportType::Asciidoc => Box::<AsciidocExporter>::default(),95 ExportType::Csv => Box::<CsvExporter>::default(),96 ExportType::Json => Box::<JsonExporter>::default(),97 ExportType::Markdown => Box::<MarkdownExporter>::default(),98 ExportType::Orgmode => Box::<OrgmodeExporter>::default(),99 };100101 self.exporters.push(ExporterWithTarget {102 exporter,103 target: if filename == "-" {104 ExportTarget::Stdout105 } else {106 let _ = File::create(filename)107 .with_context(|| format!("Could not create export file '{filename}'"))?;108 ExportTarget::File(filename.to_string())109 },110 });111112 Ok(())113 }114115 /// Write the given results to all Exporters. The 'intermediate' flag specifies116 /// whether this is being called while still performing benchmarks, or if this117 /// is the final call after all benchmarks have been finished. In the former case,118 /// results are written to all file targets (to always have them up to date, even119 /// if a benchmark fails). In the latter case, we only print to stdout targets (in120 /// order not to clutter the output of hyperfine with intermediate results).121 pub fn write_results(&self, results: &[BenchmarkResult], intermediate: bool) -> Result<()> {122 for e in &self.exporters {123 let content = || e.exporter.serialize(results, self.primary);124125 match e.target {126 ExportTarget::File(ref filename) => {127 if intermediate {128 write_to_file(filename, &content()?)?129 }130 }131 ExportTarget::Stdout => {132 if !intermediate {133 let mut stdout = io::stdout().lock();134 console_writeln!(stdout)?;135 console_writeln!(stdout, "{}", String::from_utf8(content()?).unwrap())?;136 }137 }138 }139 }140 Ok(())141 }142}143144/// Write the given content to a file with the specified name145fn write_to_file(filename: &str, content: &[u8]) -> Result<()> {146 let mut file = OpenOptions::new()147 .write(true)148 // Avoid leaving trailing bytes when the new export is shorter.149 .truncate(true)150 .open(filename)?;151 file.write_all(content)152 .with_context(|| format!("Failed to export results to '{filename}'"))153}