Skip to content
Myr

options.rs

This file

Path

src/options.rs

525 lines · 16.5 KiB · Rust

Last changed by

Basic scheduler testDavid Peterbefore adoption0705d6c

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::util::units::{Second, Unit};1314use anyhow::Result;1516#[cfg(not(windows))]17pub const DEFAULT_SHELL: &str = "sh";1819#[cfg(windows)]20pub const DEFAULT_SHELL: &str = "cmd.exe";2122/// Shell to use for executing benchmarked commands23#[derive(Debug, PartialEq)]24pub enum Shell {25    /// Default shell command26    Default(&'static str),2728    /// Custom shell command specified via --shell29    Custom(Vec<String>),30}3132impl Default for Shell {33    fn default() -> Self {34        Shell::Default(DEFAULT_SHELL)35    }36}3738impl fmt::Display for Shell {39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {40        match self {41            Shell::Default(cmd) => write!(f, "{cmd}"),42            Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)),43        }44    }45}4647impl Shell {48    /// 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, Copy, PartialEq, Eq)]71pub enum CmdFailureAction {72    /// Exit with an error message73    RaiseError,7475    /// Simply ignore the non-zero exit code76    Ignore,77}7879/// Output style type option80#[derive(Debug, Clone, Copy, PartialEq, Eq)]81pub enum OutputStyleOption {82    /// Do not output with colors or any special formatting83    Basic,8485    /// Output with full color and formatting86    Full,8788    /// Keep elements such as progress bar, but use no coloring89    NoColor,9091    /// Keep coloring, but use no progress bar92    Color,9394    /// Disable all the output95    Disabled,96}9798#[derive(Debug, Clone, Copy, PartialEq, Eq)]99pub enum SortOrder {100    Command,101    MeanTime,102}103104/// Bounds for the number of benchmark runs105pub struct RunBounds {106    /// Minimum number of benchmark runs107    pub min: u64,108109    /// Maximum number of benchmark runs110    pub max: Option<u64>,111}112113impl Default for RunBounds {114    fn default() -> Self {115        RunBounds { min: 10, max: None }116    }117}118119#[derive(Debug, Default, Clone, PartialEq)]120pub enum CommandInputPolicy {121    /// Read from the null device122    #[default]123    Null,124125    /// Read input from a file126    File(PathBuf),127}128129impl CommandInputPolicy {130    pub fn get_stdin(&self) -> io::Result<Stdio> {131        let stream: Stdio = match self {132            CommandInputPolicy::Null => Stdio::null(),133134            CommandInputPolicy::File(path) => {135                let file: File = File::open(path)?;136                Stdio::from(file)137            }138        };139140        Ok(stream)141    }142}143144/// How to handle the output of benchmarked commands145#[derive(Debug, Clone, PartialEq, Eq, Default)]146pub enum CommandOutputPolicy {147    /// Redirect output to the null device148    #[default]149    Null,150151    /// Feed output through a pipe before discarding it152    Pipe,153154    /// Redirect output to a file155    File(PathBuf),156157    /// Show command output on the terminal158    Inherit,159}160161impl CommandOutputPolicy {162    pub fn get_stdout_stderr(&self) -> io::Result<(Stdio, Stdio)> {163        let streams = match self {164            CommandOutputPolicy::Null => (Stdio::null(), Stdio::null()),165166            // Typically only stdout is performance-relevant, so just pipe that167            CommandOutputPolicy::Pipe => (Stdio::piped(), Stdio::null()),168169            CommandOutputPolicy::File(path) => {170                let file = File::create(path)?;171                (file.into(), Stdio::null())172            }173174            CommandOutputPolicy::Inherit => (Stdio::inherit(), Stdio::inherit()),175        };176177        Ok(streams)178    }179}180181#[derive(Debug, PartialEq)]182pub enum ExecutorKind {183    Raw,184    Shell(Shell),185    Mock(Option<String>),186}187188impl Default for ExecutorKind {189    fn default() -> Self {190        ExecutorKind::Shell(Shell::default())191    }192}193194/// The main settings for a hyperfine benchmark session195pub struct Options {196    /// Upper and lower bound for the number of benchmark runs197    pub run_bounds: RunBounds,198199    /// Number of warmup runs200    pub warmup_count: u64,201202    /// Minimum benchmarking time203    pub min_benchmarking_time: Second,204205    /// Whether or not to ignore non-zero exit codes206    pub command_failure_action: CmdFailureAction,207208    // Command to use as a reference for relative speed comparison209    pub reference_command: Option<String>,210211    /// Command(s) to run before each timing run212    pub preparation_command: Option<Vec<String>>,213214    /// Command(s) to run after each timing run215    pub conclusion_command: Option<Vec<String>>,216217    /// Command to run before each *batch* of timing runs, i.e. before each individual benchmark218    pub setup_command: Option<String>,219220    /// Command to run after each *batch* of timing runs, i.e. after each individual benchmark221    pub cleanup_command: Option<String>,222223    /// What color mode to use for the terminal output224    pub output_style: OutputStyleOption,225226    /// How to order benchmarks in the relative speed comparison227    pub sort_order_speed_comparison: SortOrder,228229    /// How to order benchmarks in the markup format exports230    pub sort_order_exports: SortOrder,231232    /// Determines how we run commands233    pub executor_kind: ExecutorKind,234235    /// Where input to the benchmarked command comes from236    pub command_input_policy: CommandInputPolicy,237238    /// What to do with the output of the benchmarked commands239    pub command_output_policies: Vec<CommandOutputPolicy>,240241    /// Which time unit to use when displaying results242    pub time_unit: Option<Unit>,243}244245impl Default for Options {246    fn default() -> Options {247        Options {248            run_bounds: RunBounds::default(),249            warmup_count: 0,250            min_benchmarking_time: 3.0,251            command_failure_action: CmdFailureAction::RaiseError,252            reference_command: None,253            preparation_command: None,254            conclusion_command: None,255            setup_command: None,256            cleanup_command: None,257            output_style: OutputStyleOption::Full,258            sort_order_speed_comparison: SortOrder::MeanTime,259            sort_order_exports: SortOrder::Command,260            executor_kind: ExecutorKind::default(),261            command_output_policies: vec![CommandOutputPolicy::Null],262            time_unit: None,263            command_input_policy: CommandInputPolicy::Null,264        }265    }266}267268impl Options {269    pub fn from_cli_arguments<'a>(matches: &ArgMatches) -> Result<Self, OptionsError<'a>> {270        let mut options = Self::default();271        let param_to_u64 = |param| {272            matches273                .get_one::<String>(param)274                .map(|n| {275                    n.parse::<u64>()276                        .map_err(|e| OptionsError::IntParsingError(param, e))277                })278                .transpose()279        };280281        options.warmup_count = param_to_u64("warmup")?.unwrap_or(options.warmup_count);282283        let mut min_runs = param_to_u64("min-runs")?;284        let mut max_runs = param_to_u64("max-runs")?;285286        if let Some(runs) = param_to_u64("runs")? {287            min_runs = Some(runs);288            max_runs = Some(runs);289        }290291        match (min_runs, max_runs) {292            (Some(min), None) => {293                options.run_bounds.min = min;294            }295            (None, Some(max)) => {296                // Since the minimum was not explicit we lower it if max is below the default min.297                options.run_bounds.min = cmp::min(options.run_bounds.min, max);298                options.run_bounds.max = Some(max);299            }300            (Some(min), Some(max)) if min > max => {301                return Err(OptionsError::EmptyRunsRange);302            }303            (Some(min), Some(max)) => {304                options.run_bounds.min = min;305                options.run_bounds.max = Some(max);306            }307            (None, None) => {}308        };309310        options.setup_command = matches.get_one::<String>("setup").map(String::from);311312        options.reference_command = matches.get_one::<String>("reference").map(String::from);313314        options.preparation_command = matches315            .get_many::<String>("prepare")316            .map(|values| values.map(String::from).collect::<Vec<String>>());317318        options.conclusion_command = matches319            .get_many::<String>("conclude")320            .map(|values| values.map(String::from).collect::<Vec<String>>());321322        options.cleanup_command = matches.get_one::<String>("cleanup").map(String::from);323324        options.command_output_policies = if matches.get_flag("show-output") {325            vec![CommandOutputPolicy::Inherit]326        } else if let Some(output_values) = matches.get_many::<String>("output") {327            let mut policies = vec![];328            for value in output_values {329                let policy = match value.as_str() {330                    "null" => CommandOutputPolicy::Null,331                    "pipe" => CommandOutputPolicy::Pipe,332                    "inherit" => CommandOutputPolicy::Inherit,333                    arg => {334                        let path = PathBuf::from(arg);335                        if path.components().count() <= 1 {336                            return Err(OptionsError::UnknownOutputPolicy(arg.to_string()));337                        }338                        CommandOutputPolicy::File(path)339                    }340                };341                policies.push(policy);342            }343            policies344        } else {345            vec![CommandOutputPolicy::Null]346        };347348        options.output_style = match matches.get_one::<String>("style").map(|s| s.as_str()) {349            Some("full") => OutputStyleOption::Full,350            Some("basic") => OutputStyleOption::Basic,351            Some("nocolor") => OutputStyleOption::NoColor,352            Some("color") => OutputStyleOption::Color,353            Some("none") => OutputStyleOption::Disabled,354            _ => {355                if options356                    .command_output_policies357                    .iter()358                    .any(|policy| *policy == CommandOutputPolicy::Inherit)359                    || !io::stdout().is_terminal()360                {361                    OutputStyleOption::Basic362                } else if env::var_os("TERM")363                    .map(|t| t == "unknown" || t == "dumb")364                    .unwrap_or(!cfg!(target_os = "windows"))365                    || env::var_os("NO_COLOR")366                        .map(|t| !t.is_empty())367                        .unwrap_or(false)368                {369                    OutputStyleOption::NoColor370                } else {371                    OutputStyleOption::Full372                }373            }374        };375376        match options.output_style {377            OutputStyleOption::Basic | OutputStyleOption::NoColor => {378                colored::control::set_override(false)379            }380            OutputStyleOption::Full | OutputStyleOption::Color => {381                colored::control::set_override(true)382            }383            OutputStyleOption::Disabled => {}384        };385386        (387            options.sort_order_speed_comparison,388            options.sort_order_exports,389        ) = match matches.get_one::<String>("sort").map(|s| s.as_str()) {390            None | Some("auto") => (SortOrder::MeanTime, SortOrder::Command),391            Some("command") => (SortOrder::Command, SortOrder::Command),392            Some("mean-time") => (SortOrder::MeanTime, SortOrder::MeanTime),393            Some(_) => unreachable!("Unknown sort order"),394        };395396        options.executor_kind = if matches.get_flag("no-shell") {397            ExecutorKind::Raw398        } else {399            match (400                matches.get_flag("debug-mode"),401                matches.get_one::<String>("shell"),402            ) {403                (false, Some(shell)) if shell == "default" => ExecutorKind::Shell(Shell::default()),404                (false, Some(shell)) if shell == "none" => ExecutorKind::Raw,405                (false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?),406                (false, None) => ExecutorKind::Shell(Shell::default()),407                (true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())),408                (true, None) => ExecutorKind::Mock(None),409            }410        };411412        if matches.get_flag("ignore-failure") {413            options.command_failure_action = CmdFailureAction::Ignore;414        }415416        options.time_unit = match matches.get_one::<String>("time-unit").map(|s| s.as_str()) {417            Some("microsecond") => Some(Unit::MicroSecond),418            Some("millisecond") => Some(Unit::MilliSecond),419            Some("second") => Some(Unit::Second),420            _ => None,421        };422423        if let Some(time) = matches.get_one::<String>("min-benchmarking-time") {424            options.min_benchmarking_time = time425                .parse::<f64>()426                .map_err(|e| OptionsError::FloatParsingError("min-benchmarking-time", e))?;427        }428429        options.command_input_policy = if let Some(path_str) = matches.get_one::<String>("input") {430            if path_str == "null" {431                CommandInputPolicy::Null432            } else {433                let path = PathBuf::from(path_str);434                if !path.exists() {435                    return Err(OptionsError::StdinDataFileDoesNotExist(436                        path_str.to_string(),437                    ));438                }439                CommandInputPolicy::File(path)440            }441        } else {442            CommandInputPolicy::Null443        };444445        Ok(options)446    }447448    pub fn validate_against_command_list(&mut self, commands: &Commands) -> Result<()> {449        let has_reference_command = self.reference_command.is_some();450        let num_commands = commands.num_commands(has_reference_command);451452        if let Some(preparation_command) = &self.preparation_command {453            ensure!(454                preparation_command.len() <= 1 || num_commands == preparation_command.len(),455                "The '--prepare' option has to be provided just once or N times, where N={num_commands} is the \456                 number of benchmark commands (including a potential reference)."457            );458        }459460        if let Some(conclusion_command) = &self.conclusion_command {461            ensure!(462                conclusion_command.len() <= 1 || num_commands == conclusion_command.len(),463                "The '--conclude' option has to be provided just once or N times, where N={num_commands} is the \464                 number of benchmark commands (including a potential reference)."465            );466        }467468        if self.command_output_policies.len() == 1 {469            self.command_output_policies =470                vec![self.command_output_policies[0].clone(); num_commands];471        } else {472            ensure!(473                self.command_output_policies.len() == num_commands,474                "The '--output' option has to be provided just once or N times, where N={num_commands} is the \475                 number of benchmark commands (including a potential reference)."476            );477        }478479        Ok(())480    }481}482483#[test]484fn test_default_shell() {485    let shell = Shell::default();486487    let s = format!("{shell}");488    assert_eq!(&s, DEFAULT_SHELL);489490    let cmd = shell.command();491    assert_eq!(cmd.get_program(), DEFAULT_SHELL);492}493494#[test]495fn test_can_parse_shell_command_line_from_str() {496    let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap();497498    let s = format!("{shell}");499    assert_eq!(&s, "shell -x 'aaa bbb'");500501    let cmd = shell.command();502    assert_eq!(cmd.get_program().to_string_lossy(), "shell");503    assert_eq!(504        cmd.get_args()505            .map(|a| a.to_string_lossy())506            .collect::<Vec<_>>(),507        vec!["-x", "aaa bbb"]508    );509510    // Error cases511    assert!(matches!(512        Shell::parse_from_str("shell 'foo").unwrap_err(),513        OptionsError::ShellParseError(_)514    ));515516    assert!(matches!(517        Shell::parse_from_str("").unwrap_err(),518        OptionsError::EmptyShell519    ));520521    assert!(matches!(522        Shell::parse_from_str("''").unwrap_err(),523        OptionsError::EmptyShell524    ));525}