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

Parse --shell option value as shell commandrhysdbefore adoptione2fdace

line 1why, one step back
1use std::process::Command;

Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8

line 2why, one step back
2use std::{cmp, fmt};

Parse --shell option value as shell commandrhysdbefore adoptione2fdace

line 3why, one step back
3

New Scheduler structDavid Peterbefore adoption72d2772

line 4why, one step back
4use anyhow::ensure;

Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8

lines 5–7why, one step back
5use atty::Stream;
6use clap::ArgMatches;7

New Scheduler structDavid Peterbefore adoption72d2772

line 8why, one step back
8use crate::command::Commands;

Parse --shell option value as shell commandrhysdbefore adoptione2fdace

line 9why, one step back
9use crate::error::OptionsError;

Move a few modules to utilDavid Peterbefore adoption5c634c9

line 10why, one step back
10use crate::util::units::{Second, Unit};

Flat directory/module structureDavid Peterbefore adoption30c381f

line 11why, one step back
11

New Scheduler structDavid Peterbefore adoption72d2772

lines 12–13why, one step back
12use anyhow::Result;
13

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 14–19why, one step back
14#[cfg(not(windows))]
15pub const DEFAULT_SHELL: &str = "sh";1617#[cfg(windows)]18pub const DEFAULT_SHELL: &str = "cmd.exe";19

Parse --shell option value as shell commandrhysdbefore adoptione2fdace

line 20why, one step back
20/// Shell to use for executing benchmarked commands

Add tests for options::Shellrhysdbefore adoption1b7d139

line 21why, one step back
21#[derive(Debug)]

Parse --shell option value as shell commandrhysdbefore adoptione2fdace

lines 22–24why, one step back
22pub enum Shell {
23 /// Default shell command24 Default(&'static str),

Fix clippy warningDavid Peterbefore adoption250db61

line 25why, one step back
25

Parse --shell option value as shell commandrhysdbefore adoptione2fdace

lines 26–39why, one step back
26 /// Custom shell command specified via --shell
27 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 back
40 Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)),

Parse --shell option value as shell commandrhysdbefore adoptione2fdace

lines 41–46why, one step back
41 }
42 }43}4445impl Shell {46 /// Parse given string as shell command line

Fix clippy warningsDavid Peterbefore adoptionf029a46

line 47why, one step back
47 pub fn parse_from_str<'a>(s: &str) -> Result<Self, OptionsError<'a>> {

Fix clippy warningsrhysdbefore adoptionf2bfedd

line 48why, one step back
48 let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?;

Add tests for options::Shellrhysdbefore adoption1b7d139

line 49why, one step back
49 if v.is_empty() || v[0].is_empty() {

Parse --shell option value as shell commandrhysdbefore adoptione2fdace

lines 50–66why, one step back
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}66

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 67–95why, one step back
67/// 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}95

Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa

lines 96–97why, one step back
96/// Bounds for the number of benchmark runs
97pub struct RunBounds {

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 98–104why, one step back
98 /// Minimum number of benchmark runs
99 pub min: u64,100101 /// Maximum number of benchmark runs102 pub max: Option<u64>,103}104

Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa

line 105why, one step back
105impl Default for RunBounds {

Turn show_output into enumDavid Peterbefore adoption0ebd76d

line 106why, one step back
106 fn default() -> Self {

Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa

line 107why, one step back
107 RunBounds { min: 10, max: None }

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 108–110why, one step back
108 }
109}110

Turn show_output into enumDavid Peterbefore adoption0ebd76d

lines 111–115why, one step back
111/// How to handle the output of benchmarked commands
112#[derive(Debug, Clone, Copy, PartialEq)]113pub enum CommandOutputPolicy {114 /// Discard all output115 Discard,

Flat directory/module structureDavid Peterbefore adoption30c381f

line 116why, one step back
116

Turn show_output into enumDavid Peterbefore adoption0ebd76d

lines 117–126why, one step back
117 /// Show command output on the terminal
118 Forward,119}120121impl Default for CommandOutputPolicy {122 fn default() -> Self {123 CommandOutputPolicy::Discard124 }125}126

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 127–128why, one step back
127pub enum ExecutorKind {
128 Shell(Shell),

Proper shell overhead computationDavid Peterbefore adoption6887835

line 129why, one step back
129 Mock(Option<String>),

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 130–137why, one step back
130}
131132impl Default for ExecutorKind {133 fn default() -> Self {134 ExecutorKind::Shell(Shell::default())135 }136}137

Turn show_output into enumDavid Peterbefore adoption0ebd76d

lines 138–139why, one step back
138/// The main settings for a hyperfine benchmark session
139pub struct Options {

Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa

lines 140–141why, one step back
140 /// Upper and lower bound for the number of benchmark runs
141 pub run_bounds: RunBounds,

Flat directory/module structureDavid Peterbefore adoption30c381f

line 142why, one step back
142

Turn show_output into enumDavid Peterbefore adoption0ebd76d

lines 143–145why, one step back
143 /// Number of warmup runs
144 pub warmup_count: u64,145

Flat directory/module structureDavid Peterbefore adoption30c381f

line 146why, one step back
146 /// Minimum benchmarking time

Turn show_output into enumDavid Peterbefore adoption0ebd76d

line 147why, one step back
147 pub min_benchmarking_time: Second,

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 148–149why, one step back
148
149 /// Whether or not to ignore non-zero exit codes

Turn show_output into enumDavid Peterbefore adoption0ebd76d

line 150why, one step back
150 pub command_failure_action: CmdFailureAction,

Flat directory/module structureDavid Peterbefore adoption30c381f

line 151why, one step back
151

Rename parse to from_strDavid Peterbefore adoptionf9e62e5

line 152why, one step back
152 /// Command(s) to run before each timing run

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 153–154why, one step back
153 pub preparation_command: Option<Vec<String>>,
154

Turn show_output into enumDavid Peterbefore adoption0ebd76d

lines 155–158why, one step back
155 /// Command to run before each *batch* of timing runs, i.e. before each individual benchmark
156 pub setup_command: Option<String>,157158 /// Command to run after each *batch* of timing runs, i.e. after each individual benchmark

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 159–160why, one step back
159 pub cleanup_command: Option<String>,
160

Turn show_output into enumDavid Peterbefore adoption0ebd76d

line 161why, one step back
161 /// What color mode to use for the terminal output

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 162–163why, one step back
162 pub output_style: OutputStyleOption,
163

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 164–165why, one step back
164 /// Determines how we run commands
165 pub executor_kind: ExecutorKind,

Flat directory/module structureDavid Peterbefore adoption30c381f

line 166why, one step back
166

Turn show_output into enumDavid Peterbefore adoption0ebd76d

lines 167–168why, one step back
167 /// What to do with the output of the benchmarked command
168 pub command_output_policy: CommandOutputPolicy,

Flat directory/module structureDavid Peterbefore adoption30c381f

line 169why, one step back
169

Remove unused optionDavid Peterbefore adoption21f76a3

line 170why, one step back
170 /// Which time unit to use when displaying resuls

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 171–173why, one step back
171 pub time_unit: Option<Unit>,
172}173

Rename to OptionsDavid Peterbefore adoptionb54b2f8

lines 174–176why, one step back
174impl Default for Options {
175 fn default() -> Options {176 Options {

Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa

line 177why, one step back
177 run_bounds: RunBounds::default(),

Remove unused optionDavid Peterbefore adoption21f76a3

line 178why, one step back
178 warmup_count: 0,

Turn show_output into enumDavid Peterbefore adoption0ebd76d

lines 179–180why, one step back
179 min_benchmarking_time: 3.0,
180 command_failure_action: CmdFailureAction::RaiseError,

Flat directory/module structureDavid Peterbefore adoption30c381f

line 181why, one step back
181 preparation_command: None,

Remove unused optionDavid Peterbefore adoption21f76a3

line 182why, one step back
182 setup_command: None,

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 183–184why, one step back
183 cleanup_command: None,
184 output_style: OutputStyleOption::Full,

Add debug/mock modeDavid Peterbefore adoption6f51232

line 185why, one step back
185 executor_kind: ExecutorKind::default(),

Turn show_output into enumDavid Peterbefore adoption0ebd76d

line 186why, one step back
186 command_output_policy: CommandOutputPolicy::Discard,

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 187–188why, one step back
187 time_unit: None,
188 }

Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8

lines 189–191why, one step back
189 }
190}191

Rename to OptionsDavid Peterbefore adoptionb54b2f8

line 192why, one step back
192impl Options {

Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8

lines 193–216why, one step back
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) => {

Rename Runs to RunBoundsDavid Peterbefore adoptionbea0cfa

line 217why, one step back
217 options.run_bounds.min = min;

Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8

lines 218–220why, one step back
218 }
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 back
221 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 back
223 }
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 back
228 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 back
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);241

Turn show_output into enumDavid Peterbefore adoption0ebd76d

lines 242–246why, one step back
242 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 back
247
248 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 back
255 if options.command_output_policy == CommandOutputPolicy::Discard
256 && atty::is(Stream::Stdout)257 {

Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8

lines 258–274why, one step back
258 OutputStyleOption::Full
259 } 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 };274

Add debug/mock modeDavid Peterbefore adoption6f51232

lines 275–276why, one step back
275 options.executor_kind = match (matches.is_present("debug-mode"), matches.value_of("shell"))
276 {

Fix clippy warningsDavid Peterbefore adoptionf029a46

line 277why, one step back
277 (false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?),

Add debug/mock modeDavid Peterbefore adoption6f51232

line 278why, one step back
278 (false, None) => ExecutorKind::Shell(Shell::default()),

Proper shell overhead computationDavid Peterbefore adoption6887835

lines 279–280why, one step back
279 (true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())),
280 (true, None) => ExecutorKind::Mock(None),

Add debug/mock modeDavid Peterbefore adoption6f51232

line 281why, one step back
281 };

Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8

lines 282–283why, one step back
282
283 if matches.is_present("ignore-failure") {

Turn show_output into enumDavid Peterbefore adoption0ebd76d

line 284why, one step back
284 options.command_failure_action = CmdFailureAction::Ignore;

Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8

lines 285–293why, one step back
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)

New Scheduler structDavid Peterbefore adoption72d2772

lines 294–298why, one step back
294 }
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 back
299 preparation_command.len() <= 1
300 || commands.num_commands() == preparation_command.len(),

New Scheduler structDavid Peterbefore adoption72d2772

lines 301–306why, one step back
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(())

Add tests for options::Shellrhysdbefore adoption1b7d139

lines 307–310why, one step back
307 }
308}309310#[test]

Rename testDavid Peterbefore adoption811e6b5

line 311why, one step back
311fn test_default_shell() {

Add tests for options::Shellrhysdbefore adoption1b7d139

lines 312–317why, one step back
312 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 back
318 assert_eq!(cmd.get_program(), DEFAULT_SHELL);

Add tests for options::Shellrhysdbefore adoption1b7d139

lines 319–321why, one step back
319}
320321#[test]

Rename parse to from_strDavid Peterbefore adoptionf9e62e5

line 322why, one step back
322fn test_can_parse_shell_command_line_from_str() {

Fix clippy warningsDavid Peterbefore adoptionf029a46

line 323why, one step back
323 let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap();

Add tests for options::Shellrhysdbefore adoption1b7d139

lines 324–328why, one step back
324
325 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 back
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 );

Add tests for options::Shellrhysdbefore adoption1b7d139

lines 336–337why, one step back
336
337 // Error cases

Fix clippy suggestionsDavid Peterbefore adoptionf5de548

line 338why, one step back
338 assert!(matches!(

Fix clippy warningsDavid Peterbefore adoptionf029a46

line 339why, one step back
339 Shell::parse_from_str("shell 'foo").unwrap_err(),

Fix clippy suggestionsDavid Peterbefore adoptionf5de548

lines 340–341why, one step back
340 OptionsError::ShellParseError(_)
341 ));

Add tests for options::Shellrhysdbefore adoption1b7d139

line 342why, one step back
342

Fix formattingDavid Peterbefore adoptiona35e7e2

line 343why, one step back
343 assert!(matches!(

Fix clippy warningsDavid Peterbefore adoptionf029a46

line 344why, one step back
344 Shell::parse_from_str("").unwrap_err(),

Fix formattingDavid Peterbefore adoptiona35e7e2

lines 345–346why, one step back
345 OptionsError::EmptyShell
346 ));

Add tests for options::Shellrhysdbefore adoption1b7d139

line 347why, one step back
347

Fix formattingDavid Peterbefore adoptiona35e7e2

line 348why, one step back
348 assert!(matches!(

Fix clippy warningsDavid Peterbefore adoptionf029a46

line 349why, one step back
349 Shell::parse_from_str("''").unwrap_err(),

Fix formattingDavid Peterbefore adoptiona35e7e2

lines 350–351why, one step back
350 OptionsError::EmptyShell
351 ));

Flat directory/module structureDavid Peterbefore adoption30c381f

line 352why, one step back
352}