Skip to content
Myr

Add option to export JSON, change file handling

Before adoption: this commit came in with the history the project adopted, so no landing records it.

No longer serialize into strings, instead use Vec<u8> as it is what we're writing to the files. Fixup comments

authored by Steve Pentland · committed by David Peter · parent ce79d81 · Browse files · 6 files+130 added−32 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+130 added−32 removed

  • other:+130 added−32 removed

6 files+130 added−32 removed

modified:src/hyperfine/export/csv.rs+11 added-11 removed
1use super::{ExportEntry, ResultExporter};23use csv::WriterBuilder;4use std::io::Result;4use std::io::{Error, ErrorKind, Result};56pub struct CsvExporter {7 out_file: String,8}6pub struct CsvExporter {}78impl ResultExporter for CsvExporter {11 fn write(&self, results: &Vec<ExportEntry>) -> Result<()> {12 let mut writer = WriterBuilder::new().from_path(&self.out_file)?;9 fn write(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>> {10 let mut writer = WriterBuilder::new().from_writer(vec![]);11 for res in results {12 writer.serialize(res)?;13 }16 Ok(())1415 if let Ok(inner) = writer.into_inner() {16 return Ok(inner);17 }18 Err(Error::new(ErrorKind::Other, "Error serializing to CSV"))19 }20}2122impl CsvExporter {21 pub fn new(file_name: String) -> Self {22 CsvExporter {23 out_file: file_name,24 }23 pub fn new() -> Self {24 CsvExporter {}25 }26}
added:src/hyperfine/export/json.rs+29 added
1use super::{ExportEntry, ResultExporter};23use std::io::{Error, ErrorKind, Result};45use serde_json::to_vec_pretty;67#[derive(Serialize, Debug)]8struct HyperfineSummary<'a> {9 results: &'a Vec<ExportEntry>,10}1112pub struct JsonExporter {}1314impl ResultExporter for JsonExporter {15 fn write(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>> {16 let serialized = to_vec_pretty(&HyperfineSummary { results });1718 match serialized {19 Ok(file_content) => Ok(file_content),20 Err(e) => Err(Error::new(ErrorKind::Other, format!("{:?}", e))),21 }22 }23}2425impl JsonExporter {26 pub fn new() -> Self {27 JsonExporter {}28 }29}
modified:src/hyperfine/export/mod.rs+29 added-10 removed
1mod csv;2mod json;34use self::csv::CsvExporter;5use self::json::JsonExporter;65use std::io::Result;7use std::io::{Result, Write};8use std::fs::File;910use hyperfine::internal::Second;1112/// The ExportEntry is the main set of values that will
40 unmodified lines
53}5455/// The ResultExportType enum is used to denote the desired form56/// of exporter to use for a given file.57#[derive(Clone)]58pub enum ResultExportType {59 /// Export to a csv file with the provided name60 Csv(String),61 /// Export to a JSON file62 Json(String),63}6465/// A ResultExporter is responsible for writing all results to the66/// appropriate file67trait ResultExporter {68 /// Write all entries to the target destination63 fn write(&self, values: &Vec<ExportEntry>) -> Result<()>;69 fn write(&self, values: &Vec<ExportEntry>) -> Result<Vec<u8>>;70}7172/// Create a new ExportManager73pub fn create_export_manager() -> ExportManager {
1 unmodified line
75 exporters: Vec::new(),76 }77}7873/// The Exporter is the internal implementation of the ExportManager79/// The ExportManager handles the management of multiple file80/// exporters.81pub struct ExportManager {75 exporters: Vec<Box<ResultExporter>>,82 exporters: Vec<ResultExportType>,83}8485impl ExportManager {79 pub fn add_exporter(&mut self, for_type: &ResultExportType) {80 match for_type {81 &ResultExportType::Csv(ref file_name) => self.exporters82 .push(Box::from(CsvExporter::new(file_name.clone()))),83 };86 /// Add an additional exporter to the ExportManager87 pub fn add_exporter(&mut self, for_type: ResultExportType) {88 self.exporters.push(for_type);89 }9091 /// Write the given results to all Exporters contained within this manager92 pub fn write_results(&self, to_write: Vec<ExportEntry>) -> Result<()> {93 for exp in &self.exporters {88 exp.write(&to_write)?;94 let (exporter, filename): (Box<ResultExporter>, &str) = match exp {95 &ResultExportType::Csv(ref file) => (Box::from(CsvExporter::new()), file),96 &ResultExportType::Json(ref file) => (Box::from(JsonExporter::new()), file),97 };9899 let file_content = exporter.write(&to_write)?;100 write_to_file(filename, file_content)?;101 }102 Ok(())103 }104}105106/// Write the given content to a file with the specified name107fn write_to_file(filename: &str, content: Vec<u8>) -> Result<()> {108 let mut file = File::create(filename)?;109 file.write_all(&content)?;110 Ok(())111}
modified:src/main.rs+35 added-11 removed
10 unmodified lines
11extern crate serde;1213#[macro_use]14extern crate serde_derive;15extern crate serde_json;16extern crate statistical;1718cfg_if! {19 if #[cfg(windows)] {
18 unmodified lines
38mod hyperfine;3940use hyperfine::internal::{CmdFailureAction, HyperfineOptions, OutputStyleOption};41use hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};41use hyperfine::export::{create_export_manager, ExportEntry, ResultExportType};42use hyperfine::export::{create_export_manager, ExportEntry, ExportManager, ResultExportType};4344/// Print error message to stderr and terminate45pub fn error(message: &str) -> ! {46 eprintln!("{} {}", "Error:".red(), message);
97 unmodified lines
144 .takes_value(true)145 .value_name("FILE")146 .help("Export the timing results to the given file in csv format."),147 )148 .arg(149 Arg::with_name("export-json")150 .long("export-json")151 .takes_value(true)152 .value_name("FILE")153 .help("Export the timing results to the given file in JSON format."),154 )155 .help_message("Print this help message.")156 .version_message("Show version information.")157 .get_matches();158
21 unmodified lines
180 OutputStyleOption::Basic181 },182 };183176 // Initial impl since we're only doing csv files, expand once we have multiple177 // export types. Simplest probably to do the same for each, but check for178 // None manager on later additions (JSON, Markdown, etc.)179 let export_manager = match matches.value_of("export-csv") {180 Some(filename) => {181 let mut export_manager = create_export_manager();182 export_manager.add_exporter(&ResultExportType::Csv(filename.to_string()));183 Some(export_manager)184 }185 None => None,184 let export_targets = ExportTargetList {185 json_file: matches.value_of("export-json"),186 csv_file: matches.value_of("export-csv"),187 };188 let export_manager = create_exporter(export_targets);189190 // We default Windows to NoColor if full had been specified.191 if cfg!(windows) && options.output_style == OutputStyleOption::Full {192 options.output_style = OutputStyleOption::NoColor;
18 unmodified lines
211 }212 Err(e) => error(e.description()),213 }214}215216struct ExportTargetList<'a> {217 json_file: Option<&'a str>,218 csv_file: Option<&'a str>,219}220221fn create_exporter(targets: ExportTargetList) -> Option<ExportManager> {222 if targets.json_file.is_none() && targets.csv_file.is_none() {223 return None;224 }225226 let mut export_manager = create_export_manager();227228 if let Some(filename) = targets.json_file {229 export_manager.add_exporter(ResultExportType::Json(filename.to_string()));230 }231232 if let Some(filename) = targets.csv_file {233 export_manager.add_exporter(ResultExportType::Csv(filename.to_string()));234 }235 Some(export_manager)236}
modified:Cargo.lock+25 added
100 unmodified lines
101 "memchr 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)",102]103104[[package]]105name = "dtoa"106version = "0.4.2"107source = "registry+https://github.com/rust-lang/crates.io-index"108109[[package]]110name = "fuchsia-zircon"111version = "0.3.3"112source = "registry+https://github.com/rust-lang/crates.io-index"113dependencies = [
19 unmodified lines
133 "indicatif 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",134 "libc 0.2.37 (registry+https://github.com/rust-lang/crates.io-index)",135 "serde 1.0.33 (registry+https://github.com/rust-lang/crates.io-index)",136 "serde_derive 1.0.33 (registry+https://github.com/rust-lang/crates.io-index)",137 "serde_json 1.0.11 (registry+https://github.com/rust-lang/crates.io-index)",138 "statistical 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",139 "winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",140]141
8 unmodified lines
150 "regex 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",151]152153[[package]]154name = "itoa"155version = "0.3.4"156source = "registry+https://github.com/rust-lang/crates.io-index"157158[[package]]159name = "kernel32-sys"160version = "0.2.2"161source = "registry+https://github.com/rust-lang/crates.io-index"162dependencies = [
214 unmodified lines
377 "syn 0.12.14 (registry+https://github.com/rust-lang/crates.io-index)",378]379380[[package]]381name = "serde_json"382version = "1.0.11"383source = "registry+https://github.com/rust-lang/crates.io-index"384dependencies = [385 "dtoa 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",386 "itoa 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",387 "num-traits 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",388 "serde 1.0.33 (registry+https://github.com/rust-lang/crates.io-index)",389]390391[[package]]392name = "smallvec"393version = "0.6.0"394source = "registry+https://github.com/rust-lang/crates.io-index"395
141 unmodified lines
537"checksum colored 1.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b0aa3473e85a3161b59845d6096b289bb577874cafeaf75ea1b1beaa6572c7fc"538"checksum console 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7649ca90478264b9686aac8d269fcb014f14c2bed7c79a7e51b9f6afd4d783eb"539"checksum csv 1.0.0-beta.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e7a9e063dcebdb56c306f23e672bfd31df3da8ec5f6d696b35f2c29c2a9572f0"540"checksum csv-core 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "4dd8e6d86f7ba48b4276ef1317edc8cc36167546d8972feb4a2b5fec0b374105"541"checksum dtoa 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "09c3753c3db574d215cba4ea76018483895d7bff25a31b49ba45db21c48e50ab"542"checksum fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82"543"checksum fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7"544"checksum indicatif 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a29b2fa6f00010c268bface64c18bb0310aaa70d46a195d5382d288c477fb016"545"checksum itoa 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8324a32baf01e2ae060e9de58ed0bc2320c9a2833491ee36cd3b4c414de4db8c"546"checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"547"checksum lazy_static 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "76f033c7ad61445c5b347c7382dd1237847eb1bce590fe50365dcb33d546be73"548"checksum lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c8f31047daa365f19be14b47c29df4f7c3b581832407daabe6ae77397619237d"549"checksum libc 0.2.37 (registry+https://github.com/rust-lang/crates.io-index)" = "56aebce561378d99a0bb578f8cb15b6114d2a1814a6c7949bbe646d968bb4fa9"
19 unmodified lines
569"checksum rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)" = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda"570"checksum serde 1.0.33 (registry+https://github.com/rust-lang/crates.io-index)" = "4fe95aa0d46f04ce5c3a88bdcd4114ecd6144ed0b2725ebca2f1127744357807"571"checksum serde_derive 1.0.33 (registry+https://github.com/rust-lang/crates.io-index)" = "23b163a6ce7e1aa897919f9d8e40bd1f8a6f95342ed57727ae31387a01a7a356"572"checksum serde_derive_internals 0.21.0 (registry+https://github.com/rust-lang/crates.io-index)" = "370aa477297975243dc914d0b0e1234927520ec311de507a560fbd1c80f7ab8c"573"checksum serde_json 1.0.11 (registry+https://github.com/rust-lang/crates.io-index)" = "fab6c4d75bedcf880711c85e39ebf8ccc70d0eba259899047ec5d7436643ee17"574"checksum smallvec 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "44db0ecb22921ef790d17ae13a3f6d15784183ff5f2a01aa32098c7498d2b4b9"575"checksum stable_deref_trait 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "15132e0e364248108c5e2c02e3ab539be8d6f5d52a01ca9bbf27ed657316f02b"576"checksum statistical 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c139942f46d96c53b28420a2cdfb374629f122656bd9daef7fc221ed4d8ec228"577"checksum strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4f380125926a99e52bc279241539c018323fab05ad6368b56f93d9369ff550"
16 unmodified lines
modified:Cargo.toml+1 added