Add new style option to disable coloring and progress bars (#24)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Steve Pentland · committed by David Peter · parent d5c21ec · Browse files · 5 files·+80 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+80 added−14 removed
- other:+80 added−14 removed
Provenance
- Commit
2e24ff0- Tree
be6f3da- Author
Steve Pentland <stevepentland@users.noreply.github.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
d5c21ec
5 files changed+80 added−14 removed
modified:src/hyperfine/benchmark.rs+15 added-6 removed
3 unmodified lines4 5 use colored::*;6 use statistical::{mean, standard_deviation};7 8-use hyperfine::internal::{get_progress_bar, max, min, CmdFailureAction, HyperfineOptions, Second,9- MIN_EXECUTION_TIME};8+use hyperfine::internal::{get_progress_bar, max, min, CmdFailureAction, HyperfineOptions,9+ OutputStyleOption, Second, MIN_EXECUTION_TIME};10 use hyperfine::warnings::Warnings;11 use hyperfine::format::{format_duration, format_duration_unit};12 use hyperfine::cputime::{cpu_time_interval, get_cpu_times};13 use hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};73 unmodified lines87 ))88 }89 90 /// Measure the average shell spawning time91-pub fn mean_shell_spawning_time() -> io::Result<TimingResult> {91+pub fn mean_shell_spawning_time(style: &OutputStyleOption) -> io::Result<TimingResult> {92 const COUNT: u64 = 200;93- let progress_bar = get_progress_bar(COUNT, "Measuring shell spawning time");93+ let progress_bar = get_progress_bar(COUNT, "Measuring shell spawning time", style);94 95 let mut times_real: Vec<Second> = vec![];96 let mut times_user: Vec<Second> = vec![];97 let mut times_system: Vec<Second> = vec![];63 unmodified lines161 let mut all_succeeded = true;162 163 // Warmup phase164 if options.warmup_count > 0 {165- let progress_bar = get_progress_bar(options.warmup_count, "Performing warmup runs");165+ let progress_bar = get_progress_bar(166+ options.warmup_count,167+ "Performing warmup runs",168+ &options.output_style,169+ );170 171 for _ in 0..options.warmup_count {172 let _ = time_shell_command(cmd, options.failure_action, None)?;173 progress_bar.inc(1);1 unmodified line175 progress_bar.finish_and_clear();176 }177 178 // Set up progress bar (and spinner for initial measurement)175- let progress_bar = get_progress_bar(options.min_runs, "Initial time measurement");179+ let progress_bar = get_progress_bar(180+ options.min_runs,181+ "Initial time measurement",182+ &options.output_style,183+ );184 185 // Run init / cleanup command186 run_preparation_command(&options.preparation_command)?;187 105 unmodified lines293 }294 295 if !warnings.is_empty() {296 eprintln!(" ");297+298 for warning in &warnings {299 eprintln!(" {}: {}", "Warning".yellow(), warning);300 }301 }5 unmodified linesmodified:src/hyperfine/internal.rs+25 added-5 removed
14 unmodified lines15 /// Simply ignore the non-zero exit code16 Ignore,17 }18 19+/// Output style type option20+#[derive(Debug, Clone, Copy, PartialEq)]21+pub enum OutputStyleOption {22+ /// Do not output with colors or any special formatting23+ Basic,24+25+ /// Output with full color and formatting26+ Full,27+}28+29 /// A set of options for hyperfine30 pub struct HyperfineOptions {31 /// Number of warmup runs32 pub warmup_count: u64,8 unmodified lines41 pub failure_action: CmdFailureAction,42 43 /// Command to run before each timing run44 pub preparation_command: Option<String>,45+46+ /// What color mode to use for output47+ pub output_style: OutputStyleOption,48 }49 50 impl Default for HyperfineOptions {51 fn default() -> HyperfineOptions {2 unmodified lines54 min_runs: 10,55 min_time_sec: 3.0,56 failure_action: CmdFailureAction::RaiseError,57 preparation_command: None,58+ output_style: OutputStyleOption::Full,59 }60 }61 }62 63 /// Return a pre-configured progress bar50-pub fn get_progress_bar(length: u64, msg: &str) -> ProgressBar {51- let progressbar_style = ProgressStyle::default_spinner()52- .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")53- .template(" {spinner} {msg:<30} {wide_bar} ETA {eta_precise}");64+pub fn get_progress_bar(length: u64, msg: &str, option: &OutputStyleOption) -> ProgressBar {65+ let progressbar_style = match option {66+ &OutputStyleOption::Basic => ProgressStyle::default_bar(),67+ &OutputStyleOption::Full => ProgressStyle::default_spinner()68+ .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")69+ .template(" {spinner} {msg:<30} {wide_bar} ETA {eta_precise}"),70+ };71 55- let progress_bar = ProgressBar::new(length);72+ let progress_bar = match option {73+ &OutputStyleOption::Basic => ProgressBar::hidden(),74+ &OutputStyleOption::Full => ProgressBar::new(length),75+ };76 progress_bar.set_style(progressbar_style.clone());77 progress_bar.enable_steady_tick(80);78 progress_bar.set_message(msg);79 25 unmodified linesmodified:src/main.rs+38 added-3 removed
1+extern crate atty;2+3 #[macro_use]4 extern crate clap;5 extern crate colored;6 extern crate indicatif;7 unmodified lines14 use std::cmp;15 use std::error::Error;16 use std::io;17 18+use atty::Stream;19 use colored::*;20 use clap::{App, AppSettings, Arg};21 22 mod hyperfine;23 21-use hyperfine::internal::{CmdFailureAction, HyperfineOptions};24+use hyperfine::internal::{CmdFailureAction, HyperfineOptions, OutputStyleOption};25 use hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};26 27 /// Print error message to stderr and terminate28 pub fn error(message: &str) -> ! {2 unmodified lines31 }32 33 /// Runs the benchmark for the given commands34 fn run(commands: &Vec<&str>, options: &HyperfineOptions) -> io::Result<()> {32- let shell_spawning_time = mean_shell_spawning_time()?;35+ let shell_spawning_time = mean_shell_spawning_time(&options.output_style)?;36 37 // Run the benchmarks38 for (num, cmd) in commands.iter().enumerate() {39 run_benchmark(num, cmd, shell_spawning_time, options)?;5 unmodified lines45 fn main() {46 // Process command line options47 let mut options = HyperfineOptions::default();48 49+ let clap_color_setting = if atty::is(Stream::Stdout) {50+ AppSettings::ColoredHelp51+ } else {52+ AppSettings::ColorNever53+ };54+55 let matches = App::new("hyperfine")56 .version(crate_version!())48- .setting(AppSettings::ColoredHelp)57+ .setting(clap_color_setting)58 .setting(AppSettings::DeriveDisplayOrder)59 .setting(AppSettings::UnifiedHelpMessage)60 .max_term_width(90)61 .about("A command-line benchmarking tool.")37 unmodified lines99 clearing disk caches, for example.",100 ),101 )102 .arg(103+ Arg::with_name("style")104+ .long("style")105+ .short("s")106+ .takes_value(true)107+ .value_name("TYPE")108+ .possible_values(&["auto", "basic", "full"])109+ .help(110+ "Set output style type. If set to 'basic', all colors and special \111+ formatting will be disabled. If set to 'auto' when output target is not \112+ a TTY, 'basic' is used (default: auto).",113+ ),114+ )115+ .arg(116 Arg::with_name("ignore-failure")117 .long("ignore-failure")118 .short("i")119 .help("Ignore non-zero exit codes."),15 unmodified lines135 }136 137 options.preparation_command = matches.value_of("prepare").map(String::from);138 139+ options.output_style = match matches.value_of("style") {140+ Some("full") => OutputStyleOption::Full,141+ Some("basic") => OutputStyleOption::Basic,142+ _ => if atty::is(Stream::Stdout) {143+ OutputStyleOption::Full144+ } else {145+ OutputStyleOption::Basic146+ },147+ };148+149+ if options.output_style == OutputStyleOption::Basic {150+ colored::control::set_override(false);151+ }152 if matches.is_present("ignore-failure") {153 options.failure_action = CmdFailureAction::Ignore;154 }155 7 unmodified linesmodified:Cargo.lock+1 added
96 unmodified lines97 name = "hyperfine"98 version = "0.3.0"99 dependencies = [100 "approx 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",101+ "atty 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",102 "clap 2.29.2 (registry+https://github.com/rust-lang/crates.io-index)",103 "colored 1.6.0 (registry+https://github.com/rust-lang/crates.io-index)",104 "indicatif 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",105 "libc 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)",358 unmodified linesmodified:Cargo.toml+1 added
12 unmodified lines1314151617181920214 unmodified lines12 unmodified linescolored = "1.6"indicatif = "0.9"statistical = "0.1"libc = "0.2"atty = "0.2.2"
[dependencies.clap]version = "2"default-features = false4 unmodified lines