Skip to content
Myr

mod.rs

This file

Path

src/export/mod.rs

157 lines · 5.0 KiB · Rust

Last changed by

Export selected metrics side by side in CSVDavid Peterbefore adoption067ee70

History of this file

Take 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 using a nonempty list of selected metrics, primary first.48    fn serialize(49        &self,50        results: &[BenchmarkResult],51        metrics: &[MetricSelection],52    ) -> Result<Vec<u8>>;53}5455pub enum ExportTarget {56    File(String),57    Stdout,58}5960struct ExporterWithTarget {61    exporter: Box<dyn Exporter>,62    target: ExportTarget,63}6465/// Handles the management of multiple file exporters.66pub struct ExportManager {67    exporters: Vec<ExporterWithTarget>,68    metrics: Vec<MetricSelection>,69}7071impl ExportManager {72    /// Build the ExportManager that will export the results specified73    /// in the given ArgMatches74    pub fn from_cli_arguments(matches: &ArgMatches, metrics: &[MetricSelection]) -> Result<Self> {75        let mut export_manager = Self {76            exporters: vec![],77            metrics: metrics.to_vec(),78        };79        {80            let mut add_exporter = |flag, exporttype| -> Result<()> {81                if let Some(filename) = matches.get_one::<String>(flag) {82                    export_manager.add_exporter(exporttype, filename)?;83                }84                Ok(())85            };86            add_exporter("export-asciidoc", ExportType::Asciidoc)?;87            add_exporter("export-json", ExportType::Json)?;88            add_exporter("export-csv", ExportType::Csv)?;89            add_exporter("export-markdown", ExportType::Markdown)?;90            add_exporter("export-orgmode", ExportType::Orgmode)?;91        }92        Ok(export_manager)93    }9495    /// Add an additional exporter to the ExportManager96    pub fn add_exporter(&mut self, export_type: ExportType, filename: &str) -> Result<()> {97        let exporter: Box<dyn Exporter> = match export_type {98            ExportType::Asciidoc => Box::<AsciidocExporter>::default(),99            ExportType::Csv => Box::<CsvExporter>::default(),100            ExportType::Json => Box::<JsonExporter>::default(),101            ExportType::Markdown => Box::<MarkdownExporter>::default(),102            ExportType::Orgmode => Box::<OrgmodeExporter>::default(),103        };104105        self.exporters.push(ExporterWithTarget {106            exporter,107            target: if filename == "-" {108                ExportTarget::Stdout109            } else {110                let _ = File::create(filename)111                    .with_context(|| format!("Could not create export file '{filename}'"))?;112                ExportTarget::File(filename.to_string())113            },114        });115116        Ok(())117    }118119    /// Write the given results to all Exporters. The 'intermediate' flag specifies120    /// whether this is being called while still performing benchmarks, or if this121    /// is the final call after all benchmarks have been finished. In the former case,122    /// results are written to all file targets (to always have them up to date, even123    /// if a benchmark fails). In the latter case, we only print to stdout targets (in124    /// order not to clutter the output of hyperfine with intermediate results).125    pub fn write_results(&self, results: &[BenchmarkResult], intermediate: bool) -> Result<()> {126        for e in &self.exporters {127            let content = || e.exporter.serialize(results, &self.metrics);128129            match e.target {130                ExportTarget::File(ref filename) => {131                    if intermediate {132                        write_to_file(filename, &content()?)?133                    }134                }135                ExportTarget::Stdout => {136                    if !intermediate {137                        let mut stdout = io::stdout().lock();138                        console_writeln!(stdout)?;139                        console_writeln!(stdout, "{}", String::from_utf8(content()?).unwrap())?;140                    }141                }142            }143        }144        Ok(())145    }146}147148/// Write the given content to a file with the specified name149fn write_to_file(filename: &str, content: &[u8]) -> Result<()> {150    let mut file = OpenOptions::new()151        .write(true)152        // Avoid leaving trailing bytes when the new export is shorter.153        .truncate(true)154        .open(filename)?;155    file.write_all(content)156        .with_context(|| format!("Failed to export results to '{filename}'"))157}