Skip to content
Myr

mod.rs

This file

Path

src/export/mod.rs

168 lines · 5.2 KiB · Rust

Last changed by

Merge pull request #970 from sharkdp/codex/truncate-export-rewritesDavid Peterbefore adoption4aa36c8

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::options::SortOrder;21use crate::output::console_writeln;22use crate::quantity::TimeUnit;2324use anyhow::{Context, Result};25use clap::ArgMatches;2627/// The desired form of exporter to use for a given file.28#[derive(Clone)]29pub enum ExportType {30    /// Asciidoc Table31    Asciidoc,3233    /// CSV (comma separated values) format34    Csv,3536    /// JSON format37    Json,3839    /// Markdown table40    Markdown,4142    /// Emacs org-mode tables43    Orgmode,44}4546/// Interface for different exporters.47trait Exporter {48    /// Export the given entries in the serialized form.49    fn serialize(50        &self,51        results: &[BenchmarkResult],52        unit: Option<TimeUnit>,53        sort_order: SortOrder,54    ) -> Result<Vec<u8>>;55}5657pub enum ExportTarget {58    File(String),59    Stdout,60}6162struct ExporterWithTarget {63    exporter: Box<dyn Exporter>,64    target: ExportTarget,65}6667/// Handles the management of multiple file exporters.68pub struct ExportManager {69    exporters: Vec<ExporterWithTarget>,70    time_unit: Option<TimeUnit>,71    sort_order: SortOrder,72}7374impl ExportManager {75    /// Build the ExportManager that will export the results specified76    /// in the given ArgMatches77    pub fn from_cli_arguments(78        matches: &ArgMatches,79        time_unit: Option<TimeUnit>,80        sort_order: SortOrder,81    ) -> Result<Self> {82        let mut export_manager = Self {83            exporters: vec![],84            time_unit,85            sort_order,86        };87        {88            let mut add_exporter = |flag, exporttype| -> Result<()> {89                if let Some(filename) = matches.get_one::<String>(flag) {90                    export_manager.add_exporter(exporttype, filename)?;91                }92                Ok(())93            };94            add_exporter("export-asciidoc", ExportType::Asciidoc)?;95            add_exporter("export-json", ExportType::Json)?;96            add_exporter("export-csv", ExportType::Csv)?;97            add_exporter("export-markdown", ExportType::Markdown)?;98            add_exporter("export-orgmode", ExportType::Orgmode)?;99        }100        Ok(export_manager)101    }102103    /// Add an additional exporter to the ExportManager104    pub fn add_exporter(&mut self, export_type: ExportType, filename: &str) -> Result<()> {105        let exporter: Box<dyn Exporter> = match export_type {106            ExportType::Asciidoc => Box::<AsciidocExporter>::default(),107            ExportType::Csv => Box::<CsvExporter>::default(),108            ExportType::Json => Box::<JsonExporter>::default(),109            ExportType::Markdown => Box::<MarkdownExporter>::default(),110            ExportType::Orgmode => Box::<OrgmodeExporter>::default(),111        };112113        self.exporters.push(ExporterWithTarget {114            exporter,115            target: if filename == "-" {116                ExportTarget::Stdout117            } else {118                let _ = File::create(filename)119                    .with_context(|| format!("Could not create export file '{filename}'"))?;120                ExportTarget::File(filename.to_string())121            },122        });123124        Ok(())125    }126127    /// Write the given results to all Exporters. The 'intermediate' flag specifies128    /// whether this is being called while still performing benchmarks, or if this129    /// is the final call after all benchmarks have been finished. In the former case,130    /// results are written to all file targets (to always have them up to date, even131    /// if a benchmark fails). In the latter case, we only print to stdout targets (in132    /// order not to clutter the output of hyperfine with intermediate results).133    pub fn write_results(&self, results: &[BenchmarkResult], intermediate: bool) -> Result<()> {134        for e in &self.exporters {135            let content = || {136                e.exporter137                    .serialize(results, self.time_unit, self.sort_order)138            };139140            match e.target {141                ExportTarget::File(ref filename) => {142                    if intermediate {143                        write_to_file(filename, &content()?)?144                    }145                }146                ExportTarget::Stdout => {147                    if !intermediate {148                        let mut stdout = io::stdout().lock();149                        console_writeln!(stdout)?;150                        console_writeln!(stdout, "{}", String::from_utf8(content()?).unwrap())?;151                    }152                }153            }154        }155        Ok(())156    }157}158159/// Write the given content to a file with the specified name160fn write_to_file(filename: &str, content: &[u8]) -> Result<()> {161    let mut file = OpenOptions::new()162        .write(true)163        // Avoid leaving trailing bytes when the new export is shorter.164        .truncate(true)165        .open(filename)?;166    file.write_all(content)167        .with_context(|| format!("Failed to export results to '{filename}'"))168}