Skip to content
Myr

options.rs

This file

Path

src/options.rs

538 lines · 17.3 KiB · Rust

Last changed by

Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9

History of this file

Take it

1use std::fs::File;2use std::io::IsTerminal;3use std::path::PathBuf;4use std::process::{Command, Stdio};5use std::{cmp, env, fmt, io};67use anyhow::ensure;8use clap::ArgMatches;910use crate::command::Commands;11use crate::error::OptionsError;12use crate::metric::{Metric, MetricSelection};13use crate::quantity::{second, Time};1415use anyhow::Result;1617#[cfg(not(windows))]18pub const DEFAULT_SHELL: &str = "sh";1920#[cfg(windows)]21pub const DEFAULT_SHELL: &str = "cmd.exe";2223/// Shell to use for executing benchmarked commands24#[derive(Debug, PartialEq)]25pub enum Shell {26    /// Default shell command27    Default(&'static str),2829    /// Custom shell command specified via --shell30    Custom(Vec<String>),31}3233impl fmt::Display for Shell {34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {35        match self {36            Shell::Default(cmd) => write!(f, "{cmd}"),37            Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)),38        }39    }40}4142impl Shell {43    /// Select the platform shell (sh on Unix, cmd.exe on Windows).44    pub fn platform_default() -> Self {45        Shell::Default(DEFAULT_SHELL)46    }4748    /// Parse given string as shell command line49    pub fn parse_from_str<'a>(s: &str) -> Result<Self, OptionsError<'a>> {50        let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?;51        if v.is_empty() || v[0].is_empty() {52            return Err(OptionsError::EmptyShell);53        }54        Ok(Shell::Custom(v))55    }5657    pub fn command(&self) -> Command {58        match self {59            Shell::Default(cmd) => Command::new(cmd),60            Shell::Custom(cmdline) => {61                let mut c = Command::new(&cmdline[0]);62                c.args(&cmdline[1..]);63                c64            }65        }66    }67}6869/// Action to take when an executed command fails.70#[derive(Debug, Clone, PartialEq, Eq)]71pub enum CmdFailureAction {72    /// Exit with an error message73    RaiseError,7475    /// Ignore all non-zero exit codes76    IgnoreAllFailures,7778    /// Ignore specific exit codes79    IgnoreSpecificFailures(Vec<i32>),80}8182/// Output style type option83#[derive(Debug, Clone, Copy, PartialEq, Eq)]84pub enum OutputStyleOption {85    /// Do not output with colors or any special formatting86    Basic,8788    /// Output with full color and formatting89    Full,9091    /// Keep elements such as progress bar, but use no coloring92    NoColor,9394    /// Keep coloring, but use no progress bar95    Color,9697    /// Disable all the output98    Disabled,99}100101/// Bounds for the number of benchmark runs102pub struct RunBounds {103    /// Minimum number of benchmark runs104    pub min: u64,105106    /// Maximum number of benchmark runs107    pub max: Option<u64>,108}109110impl Default for RunBounds {111    fn default() -> Self {112        RunBounds { min: 10, max: None }113    }114}115116#[derive(Debug, Default, Clone, PartialEq)]117pub enum CommandInputPolicy {118    /// Read from the null device119    #[default]120    Null,121122    /// Read input from a file123    File(PathBuf),124}125126impl CommandInputPolicy {127    pub fn get_stdin(&self) -> io::Result<Stdio> {128        let stream: Stdio = match self {129            CommandInputPolicy::Null => Stdio::null(),130131            CommandInputPolicy::File(path) => {132                let file: File = File::open(path)?;133                Stdio::from(file)134            }135        };136137        Ok(stream)138    }139}140141/// How to handle the output of benchmarked commands142#[derive(Debug, Clone, PartialEq, Eq, Default)]143pub enum CommandOutputPolicy {144    /// Redirect output to the null device145    #[default]146    Null,147148    /// Feed output through a pipe before discarding it149    Pipe,150151    /// Redirect output to a file152    File(PathBuf),153154    /// Show command output on the terminal155    Inherit,156}157158impl CommandOutputPolicy {159    pub fn get_stdout_stderr(&self) -> io::Result<(Stdio, Stdio)> {160        let streams = match self {161            CommandOutputPolicy::Null => (Stdio::null(), Stdio::null()),162163            // Typically only stdout is performance-relevant, so just pipe that164            CommandOutputPolicy::Pipe => (Stdio::piped(), Stdio::null()),165166            CommandOutputPolicy::File(path) => {167                let file = File::create(path)?;168                (file.into(), Stdio::null())169            }170171            CommandOutputPolicy::Inherit => (Stdio::inherit(), Stdio::inherit()),172        };173174        Ok(streams)175    }176}177178#[derive(Debug, Default, PartialEq)]179pub enum ExecutorKind {180    #[default]181    Raw,182    Shell(Shell),183    Mock(Option<String>),184}185186/// The main settings for a hyperfine benchmark session187pub struct Options {188    /// Upper and lower bound for the number of benchmark runs189    pub run_bounds: RunBounds,190191    /// Number of warmup runs192    pub warmup_count: u64,193194    /// Minimum benchmarking time195    pub min_benchmarking_time: Time,196197    /// Whether or not to ignore non-zero exit codes198    pub command_failure_action: CmdFailureAction,199200    /// Command(s) to run before each benchmark run201    pub preparation_command: Option<Vec<String>>,202203    /// Command(s) to run after each benchmark run204    pub conclusion_command: Option<Vec<String>>,205206    /// Command to run before each *batch* of benchmark runs, i.e. before each individual benchmark207    pub setup_command: Option<String>,208209    /// Command to run after each *batch* of benchmark runs, i.e. after each individual benchmark210    pub cleanup_command: Option<String>,211212    /// What color mode to use for the terminal output213    pub output_style: OutputStyleOption,214215    /// Determines how we run commands216    pub executor_kind: ExecutorKind,217218    /// Where input to the benchmarked command comes from219    pub command_input_policy: CommandInputPolicy,220221    /// What to do with the output of the benchmarked commands222    pub command_output_policies: Vec<CommandOutputPolicy>,223224    /// Displayed metrics, with the primary metric first.225    pub metrics: Vec<MetricSelection>,226227    /// The `all` preset displays only metrics with complete measurements.228    pub skip_unavailable_metrics: bool,229}230231impl Default for Options {232    fn default() -> Options {233        Options {234            run_bounds: RunBounds::default(),235            warmup_count: 0,236            min_benchmarking_time: Time::new::<second>(3.0),237            command_failure_action: CmdFailureAction::RaiseError,238            preparation_command: None,239            conclusion_command: None,240            setup_command: None,241            cleanup_command: None,242            output_style: OutputStyleOption::Full,243            executor_kind: ExecutorKind::default(),244            command_output_policies: vec![CommandOutputPolicy::Null],245            metrics: MetricSelection::parse_list(crate::cli::DEFAULT_METRICS)246                .expect("valid default metrics"),247            skip_unavailable_metrics: false,248            command_input_policy: CommandInputPolicy::Null,249        }250    }251}252253impl Options {254    pub fn from_cli_arguments<'a>(matches: &ArgMatches) -> Result<Self, OptionsError<'a>> {255        let mut options = Self::default();256        options.warmup_count = matches257            .get_one::<u64>("warmup")258            .copied()259            .unwrap_or(options.warmup_count);260261        let mut min_runs = matches.get_one::<u64>("min-runs").copied();262        let mut max_runs = matches.get_one::<u64>("max-runs").copied();263264        if let Some(&runs) = matches.get_one::<u64>("runs") {265            min_runs = Some(runs);266            max_runs = Some(runs);267        }268269        match (min_runs, max_runs) {270            (Some(min), None) => {271                options.run_bounds.min = min;272            }273            (None, Some(max)) => {274                // Since the minimum was not explicit we lower it if max is below the default min.275                options.run_bounds.min = cmp::min(options.run_bounds.min, max);276                options.run_bounds.max = Some(max);277            }278            (Some(min), Some(max)) if min > max => {279                return Err(OptionsError::EmptyRunsRange);280            }281            (Some(min), Some(max)) => {282                options.run_bounds.min = min;283                options.run_bounds.max = Some(max);284            }285            (None, None) => {}286        };287288        options.setup_command = matches.get_one::<String>("setup").map(String::from);289290        options.preparation_command = matches291            .get_many::<String>("prepare")292            .map(|values| values.map(String::from).collect::<Vec<String>>());293294        options.conclusion_command = matches295            .get_many::<String>("conclude")296            .map(|values| values.map(String::from).collect::<Vec<String>>());297298        options.cleanup_command = matches.get_one::<String>("cleanup").map(String::from);299300        options.command_output_policies = if matches.get_flag("show-output") {301            vec![CommandOutputPolicy::Inherit]302        } else if let Some(output_values) = matches.get_many::<String>("output") {303            let mut policies = vec![];304            for value in output_values {305                let policy = match value.as_str() {306                    "null" => CommandOutputPolicy::Null,307                    "pipe" => CommandOutputPolicy::Pipe,308                    "inherit" => CommandOutputPolicy::Inherit,309                    arg => {310                        let path = PathBuf::from(arg);311                        if path.components().count() <= 1 {312                            return Err(OptionsError::UnknownOutputPolicy(arg.to_string()));313                        }314                        CommandOutputPolicy::File(path)315                    }316                };317                policies.push(policy);318            }319            policies320        } else {321            vec![CommandOutputPolicy::Null]322        };323324        options.output_style = match matches.get_one::<String>("style").map(|s| s.as_str()) {325            Some("full") => OutputStyleOption::Full,326            Some("basic") => OutputStyleOption::Basic,327            Some("nocolor") => OutputStyleOption::NoColor,328            Some("color") => OutputStyleOption::Color,329            Some("none") => OutputStyleOption::Disabled,330            _ => {331                if options332                    .command_output_policies333                    .contains(&CommandOutputPolicy::Inherit)334                    || !io::stdout().is_terminal()335                {336                    OutputStyleOption::Basic337                } else if env::var_os("TERM")338                    .map(|t| t == "unknown" || t == "dumb")339                    .unwrap_or(!cfg!(target_os = "windows"))340                    || env::var_os("NO_COLOR")341                        .map(|t| !t.is_empty())342                        .unwrap_or(false)343                {344                    OutputStyleOption::NoColor345                } else {346                    OutputStyleOption::Full347                }348            }349        };350351        match options.output_style {352            OutputStyleOption::Basic | OutputStyleOption::NoColor => {353                colored::control::set_override(false)354            }355            OutputStyleOption::Full | OutputStyleOption::Color => {356                colored::control::set_override(true)357            }358            OutputStyleOption::Disabled => {}359        };360361        options.executor_kind = if matches.get_flag("no-shell") {362            ExecutorKind::Raw363        } else if matches.get_flag("default-shell") {364            ExecutorKind::Shell(Shell::platform_default())365        } else {366            match (367                matches.get_flag("debug-mode"),368                matches.get_one::<String>("shell"),369            ) {370                (false, Some(shell)) if shell == "default" => {371                    ExecutorKind::Shell(Shell::platform_default())372                }373                (false, Some(shell)) if shell == "none" => ExecutorKind::Raw,374                (false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?),375                (false, None) => ExecutorKind::default(),376                (true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())),377                (true, None) => ExecutorKind::Mock(None),378            }379        };380381        if let Some(mode) = matches.get_one::<String>("ignore-failure") {382            options.command_failure_action = match mode.as_str() {383                "all-non-zero" | "" => CmdFailureAction::IgnoreAllFailures,384                codes => {385                    let exit_codes: Result<Vec<i32>, _> = codes386                        .split(',')387                        .map(|s| {388                            s.trim()389                                .parse::<i32>()390                                .map_err(|e| OptionsError::IntParsingError("ignore-failure", e))391                        })392                        .collect();393                    CmdFailureAction::IgnoreSpecificFailures(exit_codes?)394                }395            };396        }397398        match matches.get_one::<String>("metrics").unwrap().as_str() {399            "default" => {}400            "time" => {401                options.metrics = [402                    Metric::TimeWallClock,403                    Metric::TimeCpu,404                    Metric::TimeUser,405                    Metric::TimeSystem,406                ]407                .map(|metric| MetricSelection { metric, unit: None })408                .to_vec();409            }410            "all" => {411                let shell = matches!(412                    options.executor_kind,413                    ExecutorKind::Shell(_) | ExecutorKind::Mock(Some(_))414                );415                options.metrics = Metric::ALL416                    .iter()417                    .copied()418                    .filter(|metric| metric.ensure_available(shell).is_ok())419                    .map(|metric| MetricSelection { metric, unit: None })420                    .collect();421                options.skip_unavailable_metrics = true;422            }423            list => {424                options.metrics = MetricSelection::parse_list(list)425                    .map_err(|error| OptionsError::InvalidMetrics(error.to_string()))?;426            }427        }428429        if let Some(time) = matches.get_one::<String>("min-benchmarking-time") {430            options.min_benchmarking_time = Time::new::<second>(431                time.parse::<f64>()432                    .map_err(|e| OptionsError::FloatParsingError("min-benchmarking-time", e))?,433            );434        }435436        options.command_input_policy = if let Some(path_str) = matches.get_one::<String>("input") {437            if path_str == "null" {438                CommandInputPolicy::Null439            } else {440                let path = PathBuf::from(path_str);441                if !path.exists() {442                    return Err(OptionsError::StdinDataFileDoesNotExist(443                        path_str.to_string(),444                    ));445                }446                CommandInputPolicy::File(path)447            }448        } else {449            CommandInputPolicy::Null450        };451452        Ok(options)453    }454455    pub fn validate_against_command_list(&mut self, commands: &Commands) -> Result<()> {456        if !matches!(self.executor_kind, ExecutorKind::Mock(_)) {457            for selection in &self.metrics {458                selection459                    .metric460                    .ensure_available(matches!(self.executor_kind, ExecutorKind::Shell(_)))?;461            }462        }463        let num_commands = commands.num_commands();464465        if let Some(preparation_command) = &self.preparation_command {466            ensure!(467                preparation_command.len() <= 1 || num_commands == preparation_command.len(),468                "The '--prepare' option has to be provided just once or N times, where N={num_commands} is the \469                 number of benchmark commands."470            );471        }472473        if let Some(conclusion_command) = &self.conclusion_command {474            ensure!(475                conclusion_command.len() <= 1 || num_commands == conclusion_command.len(),476                "The '--conclude' option has to be provided just once or N times, where N={num_commands} is the \477                 number of benchmark commands."478            );479        }480481        if self.command_output_policies.len() == 1 {482            self.command_output_policies =483                vec![self.command_output_policies[0].clone(); num_commands];484        } else {485            ensure!(486                self.command_output_policies.len() == num_commands,487                "The '--output' option has to be provided just once or N times, where N={num_commands} is the \488                 number of benchmark commands."489            );490        }491492        Ok(())493    }494}495496#[test]497fn test_platform_default_shell() {498    let shell = Shell::platform_default();499500    let s = format!("{shell}");501    assert_eq!(&s, DEFAULT_SHELL);502503    let cmd = shell.command();504    assert_eq!(cmd.get_program(), DEFAULT_SHELL);505}506507#[test]508fn test_can_parse_shell_command_line_from_str() {509    let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap();510511    let s = format!("{shell}");512    assert_eq!(&s, "shell -x 'aaa bbb'");513514    let cmd = shell.command();515    assert_eq!(cmd.get_program().to_string_lossy(), "shell");516    assert_eq!(517        cmd.get_args()518            .map(|a| a.to_string_lossy())519            .collect::<Vec<_>>(),520        vec!["-x", "aaa bbb"]521    );522523    // Error cases524    assert!(matches!(525        Shell::parse_from_str("shell 'foo").unwrap_err(),526        OptionsError::ShellParseError(_)527    ));528529    assert!(matches!(530        Shell::parse_from_str("").unwrap_err(),531        OptionsError::EmptyShell532    ));533534    assert!(matches!(535        Shell::parse_from_str("''").unwrap_err(),536        OptionsError::EmptyShell537    ));538}