Skip to content
Myr

options.rs

This file

Path

src/options.rs

543 lines · 17.4 KiB · Rust

Last changed by

Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24

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::quantity::{second, Time, TimeUnit};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, 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]102pub enum SortOrder {103    Command,104    MeanTime,105}106107/// Bounds for the number of benchmark runs108pub struct RunBounds {109    /// Minimum number of benchmark runs110    pub min: u64,111112    /// Maximum number of benchmark runs113    pub max: Option<u64>,114}115116impl Default for RunBounds {117    fn default() -> Self {118        RunBounds { min: 10, max: None }119    }120}121122#[derive(Debug, Default, Clone, PartialEq)]123pub enum CommandInputPolicy {124    /// Read from the null device125    #[default]126    Null,127128    /// Read input from a file129    File(PathBuf),130}131132impl CommandInputPolicy {133    pub fn get_stdin(&self) -> io::Result<Stdio> {134        let stream: Stdio = match self {135            CommandInputPolicy::Null => Stdio::null(),136137            CommandInputPolicy::File(path) => {138                let file: File = File::open(path)?;139                Stdio::from(file)140            }141        };142143        Ok(stream)144    }145}146147/// How to handle the output of benchmarked commands148#[derive(Debug, Clone, PartialEq, Eq, Default)]149pub enum CommandOutputPolicy {150    /// Redirect output to the null device151    #[default]152    Null,153154    /// Feed output through a pipe before discarding it155    Pipe,156157    /// Redirect output to a file158    File(PathBuf),159160    /// Show command output on the terminal161    Inherit,162}163164impl CommandOutputPolicy {165    pub fn get_stdout_stderr(&self) -> io::Result<(Stdio, Stdio)> {166        let streams = match self {167            CommandOutputPolicy::Null => (Stdio::null(), Stdio::null()),168169            // Typically only stdout is performance-relevant, so just pipe that170            CommandOutputPolicy::Pipe => (Stdio::piped(), Stdio::null()),171172            CommandOutputPolicy::File(path) => {173                let file = File::create(path)?;174                (file.into(), Stdio::null())175            }176177            CommandOutputPolicy::Inherit => (Stdio::inherit(), Stdio::inherit()),178        };179180        Ok(streams)181    }182}183184#[derive(Debug, PartialEq)]185pub enum ExecutorKind {186    Raw,187    Shell(Shell),188    Mock(Option<String>),189}190191impl Default for ExecutorKind {192    fn default() -> Self {193        ExecutorKind::Shell(Shell::default())194    }195}196197/// The main settings for a hyperfine benchmark session198pub struct Options {199    /// Upper and lower bound for the number of benchmark runs200    pub run_bounds: RunBounds,201202    /// Number of warmup runs203    pub warmup_count: u64,204205    /// Minimum benchmarking time206    pub min_benchmarking_time: Time,207208    /// Whether or not to ignore non-zero exit codes209    pub command_failure_action: CmdFailureAction,210211    // Command to use as a reference for relative speed comparison212    pub reference_command: Option<String>,213214    // Name of the reference command215    pub reference_name: Option<String>,216217    /// Command(s) to run before each timing run218    pub preparation_command: Option<Vec<String>>,219220    /// Command(s) to run after each timing run221    pub conclusion_command: Option<Vec<String>>,222223    /// Command to run before each *batch* of timing runs, i.e. before each individual benchmark224    pub setup_command: Option<String>,225226    /// Command to run after each *batch* of timing runs, i.e. after each individual benchmark227    pub cleanup_command: Option<String>,228229    /// What color mode to use for the terminal output230    pub output_style: OutputStyleOption,231232    /// How to order benchmarks in the relative speed comparison233    pub sort_order_speed_comparison: SortOrder,234235    /// How to order benchmarks in the markup format exports236    pub sort_order_exports: SortOrder,237238    /// Determines how we run commands239    pub executor_kind: ExecutorKind,240241    /// Where input to the benchmarked command comes from242    pub command_input_policy: CommandInputPolicy,243244    /// What to do with the output of the benchmarked commands245    pub command_output_policies: Vec<CommandOutputPolicy>,246247    /// Which time unit to use when displaying results248    pub time_unit: Option<TimeUnit>,249}250251impl Default for Options {252    fn default() -> Options {253        Options {254            run_bounds: RunBounds::default(),255            warmup_count: 0,256            min_benchmarking_time: Time::new::<second>(3.0),257            command_failure_action: CmdFailureAction::RaiseError,258            reference_command: None,259            reference_name: None,260            preparation_command: None,261            conclusion_command: None,262            setup_command: None,263            cleanup_command: None,264            output_style: OutputStyleOption::Full,265            sort_order_speed_comparison: SortOrder::MeanTime,266            sort_order_exports: SortOrder::Command,267            executor_kind: ExecutorKind::default(),268            command_output_policies: vec![CommandOutputPolicy::Null],269            time_unit: None,270            command_input_policy: CommandInputPolicy::Null,271        }272    }273}274275impl Options {276    pub fn from_cli_arguments<'a>(matches: &ArgMatches) -> Result<Self, OptionsError<'a>> {277        let mut options = Self::default();278        options.warmup_count = matches279            .get_one::<u64>("warmup")280            .copied()281            .unwrap_or(options.warmup_count);282283        let mut min_runs = matches.get_one::<u64>("min-runs").copied();284        let mut max_runs = matches.get_one::<u64>("max-runs").copied();285286        if let Some(&runs) = matches.get_one::<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);313        options.reference_name = matches314            .get_one::<String>("reference-name")315            .map(String::from);316317        options.preparation_command = matches318            .get_many::<String>("prepare")319            .map(|values| values.map(String::from).collect::<Vec<String>>());320321        options.conclusion_command = matches322            .get_many::<String>("conclude")323            .map(|values| values.map(String::from).collect::<Vec<String>>());324325        options.cleanup_command = matches.get_one::<String>("cleanup").map(String::from);326327        options.command_output_policies = if matches.get_flag("show-output") {328            vec![CommandOutputPolicy::Inherit]329        } else if let Some(output_values) = matches.get_many::<String>("output") {330            let mut policies = vec![];331            for value in output_values {332                let policy = match value.as_str() {333                    "null" => CommandOutputPolicy::Null,334                    "pipe" => CommandOutputPolicy::Pipe,335                    "inherit" => CommandOutputPolicy::Inherit,336                    arg => {337                        let path = PathBuf::from(arg);338                        if path.components().count() <= 1 {339                            return Err(OptionsError::UnknownOutputPolicy(arg.to_string()));340                        }341                        CommandOutputPolicy::File(path)342                    }343                };344                policies.push(policy);345            }346            policies347        } else {348            vec![CommandOutputPolicy::Null]349        };350351        options.output_style = match matches.get_one::<String>("style").map(|s| s.as_str()) {352            Some("full") => OutputStyleOption::Full,353            Some("basic") => OutputStyleOption::Basic,354            Some("nocolor") => OutputStyleOption::NoColor,355            Some("color") => OutputStyleOption::Color,356            Some("none") => OutputStyleOption::Disabled,357            _ => {358                if options359                    .command_output_policies360                    .contains(&CommandOutputPolicy::Inherit)361                    || !io::stdout().is_terminal()362                {363                    OutputStyleOption::Basic364                } else if env::var_os("TERM")365                    .map(|t| t == "unknown" || t == "dumb")366                    .unwrap_or(!cfg!(target_os = "windows"))367                    || env::var_os("NO_COLOR")368                        .map(|t| !t.is_empty())369                        .unwrap_or(false)370                {371                    OutputStyleOption::NoColor372                } else {373                    OutputStyleOption::Full374                }375            }376        };377378        match options.output_style {379            OutputStyleOption::Basic | OutputStyleOption::NoColor => {380                colored::control::set_override(false)381            }382            OutputStyleOption::Full | OutputStyleOption::Color => {383                colored::control::set_override(true)384            }385            OutputStyleOption::Disabled => {}386        };387388        (389            options.sort_order_speed_comparison,390            options.sort_order_exports,391        ) = match matches.get_one::<String>("sort").map(|s| s.as_str()) {392            None | Some("auto") => (SortOrder::MeanTime, SortOrder::Command),393            Some("command") => (SortOrder::Command, SortOrder::Command),394            Some("mean-time") => (SortOrder::MeanTime, SortOrder::MeanTime),395            Some(_) => unreachable!("Unknown sort order"),396        };397398        options.executor_kind = if matches.get_flag("no-shell") {399            ExecutorKind::Raw400        } else {401            match (402                matches.get_flag("debug-mode"),403                matches.get_one::<String>("shell"),404            ) {405                (false, Some(shell)) if shell == "default" => ExecutorKind::Shell(Shell::default()),406                (false, Some(shell)) if shell == "none" => ExecutorKind::Raw,407                (false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?),408                (false, None) => ExecutorKind::Shell(Shell::default()),409                (true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())),410                (true, None) => ExecutorKind::Mock(None),411            }412        };413414        if let Some(mode) = matches.get_one::<String>("ignore-failure") {415            options.command_failure_action = match mode.as_str() {416                "all-non-zero" | "" => CmdFailureAction::IgnoreAllFailures,417                codes => {418                    let exit_codes: Result<Vec<i32>, _> = codes419                        .split(',')420                        .map(|s| {421                            s.trim()422                                .parse::<i32>()423                                .map_err(|e| OptionsError::IntParsingError("ignore-failure", e))424                        })425                        .collect();426                    CmdFailureAction::IgnoreSpecificFailures(exit_codes?)427                }428            };429        }430431        options.time_unit = match matches.get_one::<String>("time-unit").map(|s| s.as_str()) {432            Some("µs" | "us" | "microsecond" | "microseconds") => Some(TimeUnit::MicroSecond),433            Some("ms" | "millisecond" | "milliseconds") => Some(TimeUnit::MilliSecond),434            Some("s" | "second" | "seconds") => Some(TimeUnit::Second),435            Some("min" | "minute" | "minutes") => Some(TimeUnit::Minute),436            Some("h" | "hour" | "hours") => Some(TimeUnit::Hour),437            _ => None,438        };439440        if let Some(time) = matches.get_one::<String>("min-benchmarking-time") {441            options.min_benchmarking_time = Time::new::<second>(442                time.parse::<f64>()443                    .map_err(|e| OptionsError::FloatParsingError("min-benchmarking-time", e))?,444            );445        }446447        options.command_input_policy = if let Some(path_str) = matches.get_one::<String>("input") {448            if path_str == "null" {449                CommandInputPolicy::Null450            } else {451                let path = PathBuf::from(path_str);452                if !path.exists() {453                    return Err(OptionsError::StdinDataFileDoesNotExist(454                        path_str.to_string(),455                    ));456                }457                CommandInputPolicy::File(path)458            }459        } else {460            CommandInputPolicy::Null461        };462463        Ok(options)464    }465466    pub fn validate_against_command_list(&mut self, commands: &Commands) -> Result<()> {467        let has_reference_command = self.reference_command.is_some();468        let num_commands = commands.num_commands(has_reference_command);469470        if let Some(preparation_command) = &self.preparation_command {471            ensure!(472                preparation_command.len() <= 1 || num_commands == preparation_command.len(),473                "The '--prepare' option has to be provided just once or N times, where N={num_commands} is the \474                 number of benchmark commands (including a potential reference)."475            );476        }477478        if let Some(conclusion_command) = &self.conclusion_command {479            ensure!(480                conclusion_command.len() <= 1 || num_commands == conclusion_command.len(),481                "The '--conclude' option has to be provided just once or N times, where N={num_commands} is the \482                 number of benchmark commands (including a potential reference)."483            );484        }485486        if self.command_output_policies.len() == 1 {487            self.command_output_policies =488                vec![self.command_output_policies[0].clone(); num_commands];489        } else {490            ensure!(491                self.command_output_policies.len() == num_commands,492                "The '--output' option has to be provided just once or N times, where N={num_commands} is the \493                 number of benchmark commands (including a potential reference)."494            );495        }496497        Ok(())498    }499}500501#[test]502fn test_default_shell() {503    let shell = Shell::default();504505    let s = format!("{shell}");506    assert_eq!(&s, DEFAULT_SHELL);507508    let cmd = shell.command();509    assert_eq!(cmd.get_program(), DEFAULT_SHELL);510}511512#[test]513fn test_can_parse_shell_command_line_from_str() {514    let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap();515516    let s = format!("{shell}");517    assert_eq!(&s, "shell -x 'aaa bbb'");518519    let cmd = shell.command();520    assert_eq!(cmd.get_program().to_string_lossy(), "shell");521    assert_eq!(522        cmd.get_args()523            .map(|a| a.to_string_lossy())524            .collect::<Vec<_>>(),525        vec!["-x", "aaa bbb"]526    );527528    // Error cases529    assert!(matches!(530        Shell::parse_from_str("shell 'foo").unwrap_err(),531        OptionsError::ShellParseError(_)532    ));533534    assert!(matches!(535        Shell::parse_from_str("").unwrap_err(),536        OptionsError::EmptyShell537    ));538539    assert!(matches!(540        Shell::parse_from_str("''").unwrap_err(),541        OptionsError::EmptyShell542    ));543}