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 fileTake it
Parse --shell option value as shell commandrhysdbefore adoptione2fdace
line 1why, one step back1use std::process::Command;Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
line 2why, one step back2use std::{cmp, fmt};Parse --shell option value as shell commandrhysdbefore adoptione2fdace
line 3why, one step back3New Scheduler structDavid Peterbefore adoption72d2772
line 4why, one step back4use anyhow::ensure;Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 5–7why, one step back5use atty::Stream;6use clap::ArgMatches;7New Scheduler structDavid Peterbefore adoption72d2772
line 8why, one step back8use crate::command::Commands;Parse --shell option value as shell commandrhysdbefore adoptione2fdace
line 9why, one step back9use crate::error::OptionsError;Move a few modules to utilDavid Peterbefore adoption5c634c9
line 10why, one step back10use crate::util::units::{Second, Unit};Flat directory/module structureDavid Peterbefore adoption30c381f
line 11why, one step back11New Scheduler structDavid Peterbefore adoption72d2772
lines 12–13why, one step back12use anyhow::Result;13Flat directory/module structureDavid Peterbefore adoption30c381f
lines 14–19why, one step back14#[cfg(not(windows))]15pub const DEFAULT_SHELL: &str = "sh";1617#[cfg(windows)]18pub const DEFAULT_SHELL: &str = "cmd.exe";19Parse --shell option value as shell commandrhysdbefore adoptione2fdace
line 20why, one step back20/// Shell to use for executing benchmarked commandsAdd tests for options::Shellrhysdbefore adoption1b7d139
line 21why, one step back21#[derive(Debug)]Parse --shell option value as shell commandrhysdbefore adoptione2fdace
lines 22–24why, one step back22pub enum Shell {23 /// Default shell command24 Default(&'static str),Fix clippy warningDavid Peterbefore adoption250db61
line 25why, one step back25Parse --shell option value as shell commandrhysdbefore adoptione2fdace
lines 26–39why, one step back26 /// 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),Add tests for options::Shellrhysdbefore adoption1b7d139
line 40why, one step back40 Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)),Parse --shell option value as shell commandrhysdbefore adoptione2fdace
lines 41–46why, one step back41 }42 }43}4445impl Shell {46 /// Parse given string as shell command lineFix clippy warningsDavid Peterbefore adoptionf029a46
line 47why, one step back47 pub fn parse_from_str<'a>(s: &str) -> Result<Self, OptionsError<'a>> {Fix clippy warningsrhysdbefore adoptionf2bfedd
line 48why, one step back48 let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?;Add tests for options::Shellrhysdbefore adoption1b7d139
line 49why, one step back49 if v.is_empty() || v[0].is_empty() {Parse --shell option value as shell commandrhysdbefore adoptione2fdace
lines 50–66why, one step back50 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}66Flat directory/module structureDavid Peterbefore adoption30c381f
lines 67–95why, one step back67/// 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}95Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa
lines 96–97why, one step back96/// Bounds for the number of benchmark runs97pub struct RunBounds {Flat directory/module structureDavid Peterbefore adoption30c381f
lines 98–104why, one step back98 /// Minimum number of benchmark runs99 pub min: u64,100101 /// Maximum number of benchmark runs102 pub max: Option<u64>,103}104Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa
line 105why, one step back105impl Default for RunBounds {Turn show_output into enumDavid Peterbefore adoption0ebd76d
line 106why, one step back106 fn default() -> Self {Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa
line 107why, one step back107 RunBounds { min: 10, max: None }Flat directory/module structureDavid Peterbefore adoption30c381f
lines 108–110why, one step back108 }109}110Turn show_output into enumDavid Peterbefore adoption0ebd76d
lines 111–115why, one step back111/// How to handle the output of benchmarked commands112#[derive(Debug, Clone, Copy, PartialEq)]113pub enum CommandOutputPolicy {114 /// Discard all output115 Discard,Flat directory/module structureDavid Peterbefore adoption30c381f
line 116why, one step back116Turn show_output into enumDavid Peterbefore adoption0ebd76d
lines 117–126why, one step back117 /// Show command output on the terminal118 Forward,119}120121impl Default for CommandOutputPolicy {122 fn default() -> Self {123 CommandOutputPolicy::Discard124 }125}126Add debug/mock modeDavid Peterbefore adoption6f51232
lines 127–128why, one step back127pub enum ExecutorKind {128 Shell(Shell),Proper shell overhead computationDavid Peterbefore adoption6887835
line 129why, one step back129 Mock(Option<String>),Add debug/mock modeDavid Peterbefore adoption6f51232
lines 130–137why, one step back130}131132impl Default for ExecutorKind {133 fn default() -> Self {134 ExecutorKind::Shell(Shell::default())135 }136}137Turn show_output into enumDavid Peterbefore adoption0ebd76d
lines 138–139why, one step back138/// The main settings for a hyperfine benchmark session139pub struct Options {Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa
lines 140–141why, one step back140 /// Upper and lower bound for the number of benchmark runs141 pub run_bounds: RunBounds,Flat directory/module structureDavid Peterbefore adoption30c381f
line 142why, one step back142Turn show_output into enumDavid Peterbefore adoption0ebd76d
lines 143–145why, one step back143 /// Number of warmup runs144 pub warmup_count: u64,145Flat directory/module structureDavid Peterbefore adoption30c381f
line 146why, one step back146 /// Minimum benchmarking timeTurn show_output into enumDavid Peterbefore adoption0ebd76d
line 147why, one step back147 pub min_benchmarking_time: Second,Flat directory/module structureDavid Peterbefore adoption30c381f
lines 148–149why, one step back148149 /// Whether or not to ignore non-zero exit codesTurn show_output into enumDavid Peterbefore adoption0ebd76d
line 150why, one step back150 pub command_failure_action: CmdFailureAction,Flat directory/module structureDavid Peterbefore adoption30c381f
line 151why, one step back151Rename parse to from_strDavid Peterbefore adoptionf9e62e5
line 152why, one step back152 /// Command(s) to run before each timing runFlat directory/module structureDavid Peterbefore adoption30c381f
lines 153–154why, one step back153 pub preparation_command: Option<Vec<String>>,154Turn show_output into enumDavid Peterbefore adoption0ebd76d
lines 155–158why, one step back155 /// 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 benchmarkFlat directory/module structureDavid Peterbefore adoption30c381f
lines 159–160why, one step back159 pub cleanup_command: Option<String>,160Turn show_output into enumDavid Peterbefore adoption0ebd76d
line 161why, one step back161 /// What color mode to use for the terminal outputFlat directory/module structureDavid Peterbefore adoption30c381f
lines 162–163why, one step back162 pub output_style: OutputStyleOption,163Add debug/mock modeDavid Peterbefore adoption6f51232
lines 164–165why, one step back164 /// Determines how we run commands165 pub executor_kind: ExecutorKind,Flat directory/module structureDavid Peterbefore adoption30c381f
line 166why, one step back166Turn show_output into enumDavid Peterbefore adoption0ebd76d
lines 167–168why, one step back167 /// What to do with the output of the benchmarked command168 pub command_output_policy: CommandOutputPolicy,Flat directory/module structureDavid Peterbefore adoption30c381f
line 169why, one step back169Remove unused optionDavid Peterbefore adoption21f76a3
line 170why, one step back170 /// Which time unit to use when displaying resulsFlat directory/module structureDavid Peterbefore adoption30c381f
lines 171–173why, one step back171 pub time_unit: Option<Unit>,172}173Rename to OptionsDavid Peterbefore adoptionb54b2f8
lines 174–176why, one step back174impl Default for Options {175 fn default() -> Options {176 Options {Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa
line 177why, one step back177 run_bounds: RunBounds::default(),Remove unused optionDavid Peterbefore adoption21f76a3
line 178why, one step back178 warmup_count: 0,Turn show_output into enumDavid Peterbefore adoption0ebd76d
lines 179–180why, one step back179 min_benchmarking_time: 3.0,180 command_failure_action: CmdFailureAction::RaiseError,Flat directory/module structureDavid Peterbefore adoption30c381f
line 181why, one step back181 preparation_command: None,Remove unused optionDavid Peterbefore adoption21f76a3
line 182why, one step back182 setup_command: None,Flat directory/module structureDavid Peterbefore adoption30c381f
lines 183–184why, one step back183 cleanup_command: None,184 output_style: OutputStyleOption::Full,Add debug/mock modeDavid Peterbefore adoption6f51232
line 185why, one step back185 executor_kind: ExecutorKind::default(),Turn show_output into enumDavid Peterbefore adoption0ebd76d
line 186why, one step back186 command_output_policy: CommandOutputPolicy::Discard,Flat directory/module structureDavid Peterbefore adoption30c381f
lines 187–188why, one step back187 time_unit: None,188 }Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 189–191why, one step back189 }190}191Rename to OptionsDavid Peterbefore adoptionb54b2f8
line 192why, one step back192impl Options {Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 193–216why, one step back193 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) => {Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa
line 217why, one step back217 options.run_bounds.min = min;Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 218–220why, one step back218 }219 (None, Some(max)) => {220 // Since the minimum was not explicit we lower it if max is below the default min.Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa
lines 221–222why, one step back221 options.run_bounds.min = cmp::min(options.run_bounds.min, max);222 options.run_bounds.max = Some(max);Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 223–227why, one step back223 }224 (Some(min), Some(max)) if min > max => {225 return Err(OptionsError::EmptyRunsRange);226 }227 (Some(min), Some(max)) => {Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa
lines 228–229why, one step back228 options.run_bounds.min = min;229 options.run_bounds.max = Some(max);Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 230–241why, one step back230 }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);241Turn show_output into enumDavid Peterbefore adoption0ebd76d
lines 242–246why, one step back242 options.command_output_policy = if matches.is_present("show-output") {243 CommandOutputPolicy::Forward244 } else {245 CommandOutputPolicy::Discard246 };Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 247–254why, one step back247248 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 _ => {Turn show_output into enumDavid Peterbefore adoption0ebd76d
lines 255–257why, one step back255 if options.command_output_policy == CommandOutputPolicy::Discard256 && atty::is(Stream::Stdout)257 {Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 258–274why, one step back258 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 };274Add debug/mock modeDavid Peterbefore adoption6f51232
lines 275–276why, one step back275 options.executor_kind = match (matches.is_present("debug-mode"), matches.value_of("shell"))276 {Fix clippy warningsDavid Peterbefore adoptionf029a46
line 277why, one step back277 (false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?),Add debug/mock modeDavid Peterbefore adoption6f51232
line 278why, one step back278 (false, None) => ExecutorKind::Shell(Shell::default()),Proper shell overhead computationDavid Peterbefore adoption6887835
lines 279–280why, one step back279 (true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())),280 (true, None) => ExecutorKind::Mock(None),Add debug/mock modeDavid Peterbefore adoption6f51232
line 281why, one step back281 };Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 282–283why, one step back282283 if matches.is_present("ignore-failure") {Turn show_output into enumDavid Peterbefore adoption0ebd76d
line 284why, one step back284 options.command_failure_action = CmdFailureAction::Ignore;Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 285–293why, one step back285 }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)New Scheduler structDavid Peterbefore adoption72d2772
lines 294–298why, one step back294 }295296 pub fn validate_against_command_list(&self, commands: &Commands) -> Result<()> {297 if let Some(preparation_command) = &self.preparation_command {298 ensure!(Fix clippy warningDavid Peterbefore adoption250db61
lines 299–300why, one step back299 preparation_command.len() <= 1300 || commands.num_commands() == preparation_command.len(),New Scheduler structDavid Peterbefore adoption72d2772
lines 301–306why, one step back301 "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(())Add tests for options::Shellrhysdbefore adoption1b7d139
lines 307–310why, one step back307 }308}309310#[test]Rename testDavid Peterbefore adoption811e6b5
line 311why, one step back311fn test_default_shell() {Add tests for options::Shellrhysdbefore adoption1b7d139
lines 312–317why, one step back312 let shell = Shell::default();313314 let s = format!("{}", shell);315 assert_eq!(&s, DEFAULT_SHELL);316317 let cmd = shell.command();Use get_programDavid Peterbefore adoption6645fa1
line 318why, one step back318 assert_eq!(cmd.get_program(), DEFAULT_SHELL);Add tests for options::Shellrhysdbefore adoption1b7d139
lines 319–321why, one step back319}320321#[test]Rename parse to from_strDavid Peterbefore adoptionf9e62e5
line 322why, one step back322fn test_can_parse_shell_command_line_from_str() {Fix clippy warningsDavid Peterbefore adoptionf029a46
line 323why, one step back323 let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap();Add tests for options::Shellrhysdbefore adoption1b7d139
lines 324–328why, one step back324325 let s = format!("{}", shell);326 assert_eq!(&s, "shell -x 'aaa bbb'");327328 let cmd = shell.command();Fix clippy suggestionsDavid Peterbefore adoptionf5de548
lines 329–335why, one step back329 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 );Add tests for options::Shellrhysdbefore adoption1b7d139
lines 336–337why, one step back336337 // Error casesFix clippy suggestionsDavid Peterbefore adoptionf5de548
line 338why, one step back338 assert!(matches!(Fix clippy warningsDavid Peterbefore adoptionf029a46
line 339why, one step back339 Shell::parse_from_str("shell 'foo").unwrap_err(),Fix clippy suggestionsDavid Peterbefore adoptionf5de548
lines 340–341why, one step back340 OptionsError::ShellParseError(_)341 ));Add tests for options::Shellrhysdbefore adoption1b7d139
line 342why, one step back342Fix formattingDavid Peterbefore adoptiona35e7e2
line 343why, one step back343 assert!(matches!(Fix clippy warningsDavid Peterbefore adoptionf029a46
line 344why, one step back344 Shell::parse_from_str("").unwrap_err(),Fix formattingDavid Peterbefore adoptiona35e7e2
lines 345–346why, one step back345 OptionsError::EmptyShell346 ));Add tests for options::Shellrhysdbefore adoption1b7d139
line 347why, one step back347Fix formattingDavid Peterbefore adoptiona35e7e2
line 348why, one step back348 assert!(matches!(Fix clippy warningsDavid Peterbefore adoptionf029a46
line 349why, one step back349 Shell::parse_from_str("''").unwrap_err(),Fix formattingDavid Peterbefore adoptiona35e7e2
lines 350–351why, one step back350 OptionsError::EmptyShell351 ));Flat directory/module structureDavid Peterbefore adoption30c381f
line 352why, one step back352}