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
Provenance
- Commit
c59110d- Tree
a8fbb76- Author
Steve Pentland <stevepentland@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
ce79d81
6 files changed+130 added−32 removed
modified:src/hyperfine/export/csv.rs+11 added-11 removed
1 use super::{ExportEntry, ResultExporter};2 3 use csv::WriterBuilder;4-use std::io::Result;4+use std::io::{Error, ErrorKind, Result};5 6-pub struct CsvExporter {7- out_file: String,8-}6+pub struct CsvExporter {}7 8 impl 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(())14+15+ if let Ok(inner) = writer.into_inner() {16+ return Ok(inner);17+ }18+ Err(Error::new(ErrorKind::Other, "Error serializing to CSV"))19 }20 }21 22 impl 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
1+use super::{ExportEntry, ResultExporter};2+3+use std::io::{Error, ErrorKind, Result};4+5+use serde_json::to_vec_pretty;6+7+#[derive(Serialize, Debug)]8+struct HyperfineSummary<'a> {9+ results: &'a Vec<ExportEntry>,10+}11+12+pub struct JsonExporter {}13+14+impl ResultExporter for JsonExporter {15+ fn write(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>> {16+ let serialized = to_vec_pretty(&HyperfineSummary { results });17+18+ match serialized {19+ Ok(file_content) => Ok(file_content),20+ Err(e) => Err(Error::new(ErrorKind::Other, format!("{:?}", e))),21+ }22+ }23+}24+25+impl JsonExporter {26+ pub fn new() -> Self {27+ JsonExporter {}28+ }29+}modified:src/hyperfine/export/mod.rs+29 added-10 removed
1 mod csv;2+mod json;3 4 use self::csv::CsvExporter;5+use self::json::JsonExporter;6 5-use std::io::Result;7+use std::io::{Result, Write};8+use std::fs::File;9 10 use hyperfine::internal::Second;11 12 /// The ExportEntry is the main set of values that will40 unmodified lines53 }54 55 /// The ResultExportType enum is used to denote the desired form56 /// of exporter to use for a given file.57+#[derive(Clone)]58 pub enum ResultExportType {59 /// Export to a csv file with the provided name60 Csv(String),61+ /// Export to a JSON file62+ Json(String),63 }64 65 /// A ResultExporter is responsible for writing all results to the66 /// appropriate file67 trait 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 }71 72 /// Create a new ExportManager73 pub fn create_export_manager() -> ExportManager {1 unmodified line75 exporters: Vec::new(),76 }77 }78 73-/// The Exporter is the internal implementation of the ExportManager79+/// The ExportManager handles the management of multiple file80+/// exporters.81 pub struct ExportManager {75- exporters: Vec<Box<ResultExporter>>,82+ exporters: Vec<ResultExportType>,83 }84 85 impl 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 }90 91+ /// 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+ };98+99+ let file_content = exporter.write(&to_write)?;100+ write_to_file(filename, file_content)?;101 }102 Ok(())103 }104 }105+106+/// Write the given content to a file with the specified name107+fn 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 lines11 extern crate serde;12 13 #[macro_use]14 extern crate serde_derive;15+extern crate serde_json;16 extern crate statistical;17 18 cfg_if! {19 if #[cfg(windows)] {18 unmodified lines38 mod hyperfine;39 40 use hyperfine::internal::{CmdFailureAction, HyperfineOptions, OutputStyleOption};41 use hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};41-use hyperfine::export::{create_export_manager, ExportEntry, ResultExportType};42+use hyperfine::export::{create_export_manager, ExportEntry, ExportManager, ResultExportType};43 44 /// Print error message to stderr and terminate45 pub fn error(message: &str) -> ! {46 eprintln!("{} {}", "Error:".red(), message);97 unmodified lines144 .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 lines180 OutputStyleOption::Basic181 },182 };183 176- // 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);189 190 // 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 lines211 }212 Err(e) => error(e.description()),213 }214 }215+216+struct ExportTargetList<'a> {217+ json_file: Option<&'a str>,218+ csv_file: Option<&'a str>,219+}220+221+fn create_exporter(targets: ExportTargetList) -> Option<ExportManager> {222+ if targets.json_file.is_none() && targets.csv_file.is_none() {223+ return None;224+ }225+226+ let mut export_manager = create_export_manager();227+228+ if let Some(filename) = targets.json_file {229+ export_manager.add_exporter(ResultExportType::Json(filename.to_string()));230+ }231+232+ 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 lines101 "memchr 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)",102 ]103 104 [[package]]105+name = "dtoa"106+version = "0.4.2"107+source = "registry+https://github.com/rust-lang/crates.io-index"108+109+[[package]]110 name = "fuchsia-zircon"111 version = "0.3.3"112 source = "registry+https://github.com/rust-lang/crates.io-index"113 dependencies = [19 unmodified lines133 "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 lines150 "regex 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",151 ]152 153 [[package]]154+name = "itoa"155+version = "0.3.4"156+source = "registry+https://github.com/rust-lang/crates.io-index"157+158+[[package]]159 name = "kernel32-sys"160 version = "0.2.2"161 source = "registry+https://github.com/rust-lang/crates.io-index"162 dependencies = [214 unmodified lines377 "syn 0.12.14 (registry+https://github.com/rust-lang/crates.io-index)",378 ]379 380 [[package]]381+name = "serde_json"382+version = "1.0.11"383+source = "registry+https://github.com/rust-lang/crates.io-index"384+dependencies = [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+]390+391+[[package]]392 name = "smallvec"393 version = "0.6.0"394 source = "registry+https://github.com/rust-lang/crates.io-index"395 141 unmodified lines537 "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 lines569 "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 linesmodified:Cargo.toml+1 added
16 unmodified lines17181920212223242510 unmodified lines16 unmodified linescfg-if = "0.1.2"csv = "1.0.0-beta.5"serde = "1.0.33"serde_derive = "1.0.33"serde_json = "1.0.11"
[target.'cfg(not(windows))'.dependencies]libc = "0.2"
10 unmodified lines