Skip to content
Myr

mod.rs

This file

Path

src/export/mod.rs

157 lines · 4.8 KiB · Rust

Last changed by

Add new --sort optionDavid Peterbefore adoptionac617c8

History of this file

Take it

1use std::fs::{File, OpenOptions};2use std::io::Write;34mod asciidoc;5mod csv;6mod json;7mod markdown;8mod markup;9mod orgmode;1011use self::asciidoc::AsciidocExporter;12use self::csv::CsvExporter;13use self::json::JsonExporter;14use self::markdown::MarkdownExporter;15use self::orgmode::OrgmodeExporter;1617use crate::benchmark::benchmark_result::BenchmarkResult;18use crate::options::SortOrder;19use crate::util::units::Unit;2021use anyhow::{Context, Result};22use clap::ArgMatches;2324/// The desired form of exporter to use for a given file.25#[derive(Clone)]26pub enum ExportType {27    /// Asciidoc Table28    Asciidoc,2930    /// CSV (comma separated values) format31    Csv,3233    /// JSON format34    Json,3536    /// Markdown table37    Markdown,3839    /// Emacs org-mode tables40    Orgmode,41}4243/// Interface for different exporters.44trait Exporter {45    /// Export the given entries in the serialized form.46    fn serialize(47        &self,48        results: &[BenchmarkResult],49        unit: Option<Unit>,50        sort_order: SortOrder,51    ) -> Result<Vec<u8>>;52}5354pub enum ExportTarget {55    File(String),56    Stdout,57}5859struct ExporterWithTarget {60    exporter: Box<dyn Exporter>,61    target: ExportTarget,62}6364/// Handles the management of multiple file exporters.65#[derive(Default)]66pub struct ExportManager {67    exporters: Vec<ExporterWithTarget>,68    time_unit: Option<Unit>,69}7071impl ExportManager {72    /// Build the ExportManager that will export the results specified73    /// in the given ArgMatches74    pub fn from_cli_arguments(matches: &ArgMatches, time_unit: Option<Unit>) -> Result<Self> {75        let mut export_manager = Self {76            exporters: vec![],77            time_unit,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(126        &self,127        results: &[BenchmarkResult],128        sort_order: SortOrder,129        intermediate: bool,130    ) -> Result<()> {131        for e in &self.exporters {132            let content = || e.exporter.serialize(results, self.time_unit, sort_order);133134            match e.target {135                ExportTarget::File(ref filename) => {136                    if intermediate {137                        write_to_file(filename, &content()?)?138                    }139                }140                ExportTarget::Stdout => {141                    if !intermediate {142                        println!();143                        println!("{}", String::from_utf8(content()?).unwrap());144                    }145                }146            }147        }148        Ok(())149    }150}151152/// Write the given content to a file with the specified name153fn write_to_file(filename: &str, content: &[u8]) -> Result<()> {154    let mut file = OpenOptions::new().write(true).open(filename)?;155    file.write_all(content)156        .with_context(|| format!("Failed to export results to '{}'", filename))157}