Skip to content
Myr

options.rs

This file

Path

src/options.rs

352 lines · 10.0 KiB · Rust

Last changed by

Fix clippy warningsDavid Peterbefore adoptionf029a46

History of this file

Take it

1use std::process::Command;2use std::{cmp, fmt};34use anyhow::ensure;5use atty::Stream;6use clap::ArgMatches;78use crate::command::Commands;9use crate::error::OptionsError;10use crate::util::units::{Second, Unit};1112use anyhow::Result;1314#[cfg(not(windows))]15pub const DEFAULT_SHELL: &str = "sh";1617#[cfg(windows)]18pub const DEFAULT_SHELL: &str = "cmd.exe";1920/// Shell to use for executing benchmarked commands21#[derive(Debug)]22pub enum Shell {23    /// Default shell command24    Default(&'static str),2526    /// Custom shell command specified via --shell27    Custom(Vec<String>),28}2930impl Default for Shell {31    fn default() -> Self {32        Shell::Default(DEFAULT_SHELL)33    }34}3536impl fmt::Display for Shell {37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {38        match self {39            Shell::Default(cmd) => write!(f, "{}", cmd),40            Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)),41        }42    }43}4445impl Shell {46    /// Parse given string as shell command line47    pub fn parse_from_str<'a>(s: &str) -> Result<Self, OptionsError<'a>> {48        let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?;49        if v.is_empty() || v[0].is_empty() {50            return Err(OptionsError::EmptyShell);51        }52        Ok(Shell::Custom(v))53    }5455    pub fn command(&self) -> Command {56        match self {57            Shell::Default(cmd) => Command::new(cmd),58            Shell::Custom(cmdline) => {59                let mut c = Command::new(&cmdline[0]);60                c.args(&cmdline[1..]);61                c62            }63        }64    }65}6667/// Action to take when an executed command fails.68#[derive(Debug, Clone, Copy, PartialEq)]69pub enum CmdFailureAction {70    /// Exit with an error message71    RaiseError,7273    /// Simply ignore the non-zero exit code74    Ignore,75}7677/// Output style type option78#[derive(Debug, Clone, Copy, PartialEq)]79pub enum OutputStyleOption {80    /// Do not output with colors or any special formatting81    Basic,8283    /// Output with full color and formatting84    Full,8586    /// Keep elements such as progress bar, but use no coloring87    NoColor,8889    /// Keep coloring, but use no progress bar90    Color,9192    /// Disable all the output93    Disabled,94}9596/// Bounds for the number of benchmark runs97pub struct RunBounds {98    /// Minimum number of benchmark runs99    pub min: u64,100101    /// Maximum number of benchmark runs102    pub max: Option<u64>,103}104105impl Default for RunBounds {106    fn default() -> Self {107        RunBounds { min: 10, max: None }108    }109}110111/// How to handle the output of benchmarked commands112#[derive(Debug, Clone, Copy, PartialEq)]113pub enum CommandOutputPolicy {114    /// Discard all output115    Discard,116117    /// Show command output on the terminal118    Forward,119}120121impl Default for CommandOutputPolicy {122    fn default() -> Self {123        CommandOutputPolicy::Discard124    }125}126127pub enum ExecutorKind {128    Shell(Shell),129    Mock(Option<String>),130}131132impl Default for ExecutorKind {133    fn default() -> Self {134        ExecutorKind::Shell(Shell::default())135    }136}137138/// The main settings for a hyperfine benchmark session139pub struct Options {140    /// Upper and lower bound for the number of benchmark runs141    pub run_bounds: RunBounds,142143    /// Number of warmup runs144    pub warmup_count: u64,145146    /// Minimum benchmarking time147    pub min_benchmarking_time: Second,148149    /// Whether or not to ignore non-zero exit codes150    pub command_failure_action: CmdFailureAction,151152    /// Command(s) to run before each timing run153    pub preparation_command: Option<Vec<String>>,154155    /// Command to run before each *batch* of timing runs, i.e. before each individual benchmark156    pub setup_command: Option<String>,157158    /// Command to run after each *batch* of timing runs, i.e. after each individual benchmark159    pub cleanup_command: Option<String>,160161    /// What color mode to use for the terminal output162    pub output_style: OutputStyleOption,163164    /// Determines how we run commands165    pub executor_kind: ExecutorKind,166167    /// What to do with the output of the benchmarked command168    pub command_output_policy: CommandOutputPolicy,169170    /// Which time unit to use when displaying resuls171    pub time_unit: Option<Unit>,172}173174impl Default for Options {175    fn default() -> Options {176        Options {177            run_bounds: RunBounds::default(),178            warmup_count: 0,179            min_benchmarking_time: 3.0,180            command_failure_action: CmdFailureAction::RaiseError,181            preparation_command: None,182            setup_command: None,183            cleanup_command: None,184            output_style: OutputStyleOption::Full,185            executor_kind: ExecutorKind::default(),186            command_output_policy: CommandOutputPolicy::Discard,187            time_unit: None,188        }189    }190}191192impl Options {193    pub fn from_cli_arguments<'a>(matches: &ArgMatches) -> Result<Self, OptionsError<'a>> {194        let mut options = Self::default();195        let param_to_u64 = |param| {196            matches197                .value_of(param)198                .map(|n| {199                    n.parse::<u64>()200                        .map_err(|e| OptionsError::NumericParsingError(param, e))201                })202                .transpose()203        };204205        options.warmup_count = param_to_u64("warmup")?.unwrap_or(options.warmup_count);206207        let mut min_runs = param_to_u64("min-runs")?;208        let mut max_runs = param_to_u64("max-runs")?;209210        if let Some(runs) = param_to_u64("runs")? {211            min_runs = Some(runs);212            max_runs = Some(runs);213        }214215        match (min_runs, max_runs) {216            (Some(min), None) => {217                options.run_bounds.min = min;218            }219            (None, Some(max)) => {220                // Since the minimum was not explicit we lower it if max is below the default min.221                options.run_bounds.min = cmp::min(options.run_bounds.min, max);222                options.run_bounds.max = Some(max);223            }224            (Some(min), Some(max)) if min > max => {225                return Err(OptionsError::EmptyRunsRange);226            }227            (Some(min), Some(max)) => {228                options.run_bounds.min = min;229                options.run_bounds.max = Some(max);230            }231            (None, None) => {}232        };233234        options.setup_command = matches.value_of("setup").map(String::from);235236        options.preparation_command = matches237            .values_of("prepare")238            .map(|values| values.map(String::from).collect::<Vec<String>>());239240        options.cleanup_command = matches.value_of("cleanup").map(String::from);241242        options.command_output_policy = if matches.is_present("show-output") {243            CommandOutputPolicy::Forward244        } else {245            CommandOutputPolicy::Discard246        };247248        options.output_style = match matches.value_of("style") {249            Some("full") => OutputStyleOption::Full,250            Some("basic") => OutputStyleOption::Basic,251            Some("nocolor") => OutputStyleOption::NoColor,252            Some("color") => OutputStyleOption::Color,253            Some("none") => OutputStyleOption::Disabled,254            _ => {255                if options.command_output_policy == CommandOutputPolicy::Discard256                    && atty::is(Stream::Stdout)257                {258                    OutputStyleOption::Full259                } else {260                    OutputStyleOption::Basic261                }262            }263        };264265        match options.output_style {266            OutputStyleOption::Basic | OutputStyleOption::NoColor => {267                colored::control::set_override(false)268            }269            OutputStyleOption::Full | OutputStyleOption::Color => {270                colored::control::set_override(true)271            }272            OutputStyleOption::Disabled => {}273        };274275        options.executor_kind = match (matches.is_present("debug-mode"), matches.value_of("shell"))276        {277            (false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?),278            (false, None) => ExecutorKind::Shell(Shell::default()),279            (true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())),280            (true, None) => ExecutorKind::Mock(None),281        };282283        if matches.is_present("ignore-failure") {284            options.command_failure_action = CmdFailureAction::Ignore;285        }286287        options.time_unit = match matches.value_of("time-unit") {288            Some("millisecond") => Some(Unit::MilliSecond),289            Some("second") => Some(Unit::Second),290            _ => None,291        };292293        Ok(options)294    }295296    pub fn validate_against_command_list(&self, commands: &Commands) -> Result<()> {297        if let Some(preparation_command) = &self.preparation_command {298            ensure!(299                preparation_command.len() <= 1300                    || commands.num_commands() == preparation_command.len(),301                "The '--prepare' option has to be provided just once or N times, where N is the \302             number of benchmark commands."303            );304        }305306        Ok(())307    }308}309310#[test]311fn test_default_shell() {312    let shell = Shell::default();313314    let s = format!("{}", shell);315    assert_eq!(&s, DEFAULT_SHELL);316317    let cmd = shell.command();318    assert_eq!(cmd.get_program(), DEFAULT_SHELL);319}320321#[test]322fn test_can_parse_shell_command_line_from_str() {323    let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap();324325    let s = format!("{}", shell);326    assert_eq!(&s, "shell -x 'aaa bbb'");327328    let cmd = shell.command();329    assert_eq!(cmd.get_program().to_string_lossy(), "shell");330    assert_eq!(331        cmd.get_args()332            .map(|a| a.to_string_lossy())333            .collect::<Vec<_>>(),334        vec!["-x", "aaa bbb"]335    );336337    // Error cases338    assert!(matches!(339        Shell::parse_from_str("shell 'foo").unwrap_err(),340        OptionsError::ShellParseError(_)341    ));342343    assert!(matches!(344        Shell::parse_from_str("").unwrap_err(),345        OptionsError::EmptyShell346    ));347348    assert!(matches!(349        Shell::parse_from_str("''").unwrap_err(),350        OptionsError::EmptyShell351    ));352}