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
The walk stopped after 200 commits: lines older than ab5ae5f point at it.
Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
line 1why, one step back1use std::fs::{File, OpenOptions};Handle broken pipe errors on stdout gracefully (#932)jkbefore adoptionc0b3834
line 2why, one step back2use std::io::{self, Write};Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
lines 3–9why, one step back34mod asciidoc;5mod csv;6mod json;7mod markdown;8mod markup;9mod orgmode;Use insta for exporter testsDavid Peterbefore adoption7a9d04d
lines 10–11why, one step back10#[cfg(test)]11mod tests;Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
lines 12–19why, one step back1213use 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;Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
line 20why, one step back20use crate::metric::MetricSelection;Handle broken pipe errors on stdout gracefully (#932)jkbefore adoptionc0b3834
line 21why, one step back21use crate::output::console_writeln;Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
lines 22–47why, one step back2223use 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.Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
line 48why, one step back48 fn serialize(&self, results: &[BenchmarkResult], primary: MetricSelection) -> Result<Vec<u8>>;Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
lines 49–63why, one step back49}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>,Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
line 64why, one step back64 primary: MetricSelection,Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
lines 65–69why, one step back65}6667impl ExportManager {68 /// Build the ExportManager that will export the results specified69 /// in the given ArgMatchesAlternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
line 70why, one step back70 pub fn from_cli_arguments(matches: &ArgMatches, primary: MetricSelection) -> Result<Self> {Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
lines 71–72why, one step back71 let mut export_manager = Self {72 exporters: vec![],Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
line 73why, one step back73 primary,Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
lines 74–106why, one step back74 };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)style: simplify string interpolationHamir Mahalbefore adoptionef12632
line 107why, one step back107 .with_context(|| format!("Could not create export file '{filename}'"))?;Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
lines 108–120why, one step back108 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).Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
line 121why, one step back121 pub fn write_results(&self, results: &[BenchmarkResult], intermediate: bool) -> Result<()> {Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
line 122why, one step back122 for e in &self.exporters {Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
line 123why, one step back123 let content = || e.exporter.serialize(results, self.primary);Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
lines 124–132why, one step back124125 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 {Handle broken pipe errors on stdout gracefully (#932)jkbefore adoptionc0b3834
lines 133–135why, one step back133 let mut stdout = io::stdout().lock();134 console_writeln!(stdout)?;135 console_writeln!(stdout, "{}", String::from_utf8(content()?).unwrap())?;Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
lines 136–145why, one step back136 }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<()> {Merge pull request #970 from sharkdp/codex/truncate-export-rewritesDavid Peterbefore adoption4aa36c8
lines 146–150why, one step back146 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)?;Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
line 151why, one step back151 file.write_all(content)style: simplify string interpolationHamir Mahalbefore adoptionef12632
line 152why, one step back152 .with_context(|| format!("Failed to export results to '{filename}'"))Bump clap_complete from 4.2.0 to 4.2.1dependabot[bot]before adoptionab5ae5f
line 153why, one step back153}