options.rs
This file
Path
src/options.rs
322 lines · 8.9 KiB · Rust
Last changed by
New Scheduler structDavid Peterbefore adoption72d2772
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–38why, one step back22pub enum Shell {23 /// Default shell command24 Default(&'static str),25 /// Custom shell command specified via --shell26 Custom(Vec<String>),27}2829impl Default for Shell {30 fn default() -> Self {31 Shell::Default(DEFAULT_SHELL)32 }33}3435impl fmt::Display for Shell {36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {37 match self {38 Shell::Default(cmd) => write!(f, "{}", cmd),Add tests for options::Shellrhysdbefore adoption1b7d139
line 39why, one step back39 Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)),Parse --shell option value as shell commandrhysdbefore adoptione2fdace
lines 40–46why, one step back40 }41 }42}4344impl Shell {45 /// Parse given string as shell command line46 pub fn parse<'a>(s: &str) -> Result<Self, OptionsError<'a>> {Fix clippy warningsrhysdbefore adoptionf2bfedd
line 47why, one step back47 let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?;Add tests for options::Shellrhysdbefore adoption1b7d139
line 48why, one step back48 if v.is_empty() || v[0].is_empty() {Parse --shell option value as shell commandrhysdbefore adoptione2fdace
lines 49–65why, one step back49 return Err(OptionsError::EmptyShell);50 }51 Ok(Shell::Custom(v))52 }5354 pub fn command(&self) -> Command {55 match self {56 Shell::Default(cmd) => Command::new(cmd),57 Shell::Custom(cmdline) => {58 let mut c = Command::new(&cmdline[0]);59 c.args(&cmdline[1..]);60 c61 }62 }63 }64}65Flat directory/module structureDavid Peterbefore adoption30c381f
lines 66–110why, one step back66/// Action to take when an executed command fails.67#[derive(Debug, Clone, Copy, PartialEq)]68pub enum CmdFailureAction {69 /// Exit with an error message70 RaiseError,7172 /// Simply ignore the non-zero exit code73 Ignore,74}7576/// Output style type option77#[derive(Debug, Clone, Copy, PartialEq)]78pub enum OutputStyleOption {79 /// Do not output with colors or any special formatting80 Basic,8182 /// Output with full color and formatting83 Full,8485 /// Keep elements such as progress bar, but use no coloring86 NoColor,8788 /// Keep coloring, but use no progress bar89 Color,9091 /// Disable all the output92 Disabled,93}9495/// Number of runs for a benchmark96pub struct Runs {97 /// Minimum number of benchmark runs98 pub min: u64,99100 /// Maximum number of benchmark runs101 pub max: Option<u64>,102}103104impl Default for Runs {105 fn default() -> Runs {106 Runs { min: 10, max: None }107 }108}109110/// A set of options for hyperfineRename to OptionsDavid Peterbefore adoptionb54b2f8
line 111why, one step back111pub struct Options {Flat directory/module structureDavid Peterbefore adoption30c381f
lines 112–123why, one step back112 /// Number of warmup runs113 pub warmup_count: u64,114115 /// Number of benchmark runs116 pub runs: Runs,117118 /// Minimum benchmarking time119 pub min_time_sec: Second,120121 /// Whether or not to ignore non-zero exit codes122 pub failure_action: CmdFailureAction,123Add --setup (-s) option, like --prepare but runs once per batchÆvar Arnfjörð Bjarmasonbefore adoption017d55a
lines 124–126why, one step back124 /// Command to run before each batch of timing runs125 pub setup_command: Option<String>,126Flat directory/module structureDavid Peterbefore adoption30c381f
lines 127–136why, one step back127 /// Command to run before each timing run128 pub preparation_command: Option<Vec<String>>,129130 /// Command to run after each benchmark131 pub cleanup_command: Option<String>,132133 /// What color mode to use for output134 pub output_style: OutputStyleOption,135136 /// The shell to use for executing commands.Parse --shell option value as shell commandrhysdbefore adoptione2fdace
line 137why, one step back137 pub shell: Shell,Flat directory/module structureDavid Peterbefore adoption30c381f
lines 138–150why, one step back138139 /// Forward benchmark's stdout to hyperfine's stdout140 pub show_output: bool,141142 /// Which time unit to use for CLI & Markdown output143 pub time_unit: Option<Unit>,144145 /// A list of custom command names that, if defined,146 /// will be used instead of the command itself in147 /// benchmark outputs.148 pub names: Option<Vec<String>>,149}150Rename to OptionsDavid Peterbefore adoptionb54b2f8
lines 151–153why, one step back151impl Default for Options {152 fn default() -> Options {153 Options {Flat directory/module structureDavid Peterbefore adoption30c381f
lines 154–158why, one step back154 names: None,155 warmup_count: 0,156 runs: Runs::default(),157 min_time_sec: 3.0,158 failure_action: CmdFailureAction::RaiseError,Add --setup (-s) option, like --prepare but runs once per batchÆvar Arnfjörð Bjarmasonbefore adoption017d55a
line 159why, one step back159 setup_command: None,Flat directory/module structureDavid Peterbefore adoption30c381f
lines 160–162why, one step back160 preparation_command: None,161 cleanup_command: None,162 output_style: OutputStyleOption::Full,Parse --shell option value as shell commandrhysdbefore adoptione2fdace
line 163why, one step back163 shell: Shell::default(),Flat directory/module structureDavid Peterbefore adoption30c381f
lines 164–166why, one step back164 show_output: false,165 time_unit: None,166 }Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 167–169why, one step back167 }168}169Rename to OptionsDavid Peterbefore adoptionb54b2f8
line 170why, one step back170impl Options {Move convert_cli_arguments_to_options to HyperfineOptionsDavid Peterbefore adoption39a85b8
lines 171–261why, one step back171 pub fn from_cli_arguments<'a>(matches: &ArgMatches) -> Result<Self, OptionsError<'a>> {172 let mut options = Self::default();173 let param_to_u64 = |param| {174 matches175 .value_of(param)176 .map(|n| {177 n.parse::<u64>()178 .map_err(|e| OptionsError::NumericParsingError(param, e))179 })180 .transpose()181 };182183 options.warmup_count = param_to_u64("warmup")?.unwrap_or(options.warmup_count);184185 let mut min_runs = param_to_u64("min-runs")?;186 let mut max_runs = param_to_u64("max-runs")?;187188 if let Some(runs) = param_to_u64("runs")? {189 min_runs = Some(runs);190 max_runs = Some(runs);191 }192193 match (min_runs, max_runs) {194 (Some(min), None) => {195 options.runs.min = min;196 }197 (None, Some(max)) => {198 // Since the minimum was not explicit we lower it if max is below the default min.199 options.runs.min = cmp::min(options.runs.min, max);200 options.runs.max = Some(max);201 }202 (Some(min), Some(max)) if min > max => {203 return Err(OptionsError::EmptyRunsRange);204 }205 (Some(min), Some(max)) => {206 options.runs.min = min;207 options.runs.max = Some(max);208 }209 (None, None) => {}210 };211212 options.setup_command = matches.value_of("setup").map(String::from);213214 options.preparation_command = matches215 .values_of("prepare")216 .map(|values| values.map(String::from).collect::<Vec<String>>());217218 options.cleanup_command = matches.value_of("cleanup").map(String::from);219220 options.show_output = matches.is_present("show-output");221222 options.output_style = match matches.value_of("style") {223 Some("full") => OutputStyleOption::Full,224 Some("basic") => OutputStyleOption::Basic,225 Some("nocolor") => OutputStyleOption::NoColor,226 Some("color") => OutputStyleOption::Color,227 Some("none") => OutputStyleOption::Disabled,228 _ => {229 if !options.show_output && atty::is(Stream::Stdout) {230 OutputStyleOption::Full231 } else {232 OutputStyleOption::Basic233 }234 }235 };236237 match options.output_style {238 OutputStyleOption::Basic | OutputStyleOption::NoColor => {239 colored::control::set_override(false)240 }241 OutputStyleOption::Full | OutputStyleOption::Color => {242 colored::control::set_override(true)243 }244 OutputStyleOption::Disabled => {}245 };246247 if let Some(shell) = matches.value_of("shell") {248 options.shell = Shell::parse(shell)?;249 }250251 if matches.is_present("ignore-failure") {252 options.failure_action = CmdFailureAction::Ignore;253 }254255 options.time_unit = match matches.value_of("time-unit") {256 Some("millisecond") => Some(Unit::MilliSecond),257 Some("second") => Some(Unit::Second),258 _ => None,259 };260261 Ok(options)New Scheduler structDavid Peterbefore adoption72d2772
lines 262–273why, one step back262 }263264 pub fn validate_against_command_list(&self, commands: &Commands) -> Result<()> {265 if let Some(preparation_command) = &self.preparation_command {266 ensure!(267 preparation_command.len() <= 1 || commands.len() == preparation_command.len(),268 "The '--prepare' option has to be provided just once or N times, where N is the \269 number of benchmark commands."270 );271 }272273 Ok(())Add tests for options::Shellrhysdbefore adoption1b7d139
lines 274–298why, one step back274 }275}276277#[test]278fn test_shell_default_command() {279 let shell = Shell::default();280281 let s = format!("{}", shell);282 assert_eq!(&s, DEFAULT_SHELL);283284 let cmd = shell.command();285 // Command::get_program is not yet available in stable channel.286 // https://doc.rust-lang.org/std/process/struct.Command.html#method.get_program287 let s = format!("{:?}", cmd);288 assert_eq!(s, format!("\"{}\"", DEFAULT_SHELL));289}290291#[test]292fn test_shell_parse_command() {293 let shell = Shell::parse("shell -x 'aaa bbb'").unwrap();294295 let s = format!("{}", shell);296 assert_eq!(&s, "shell -x 'aaa bbb'");297298 let cmd = shell.command();Fix clippy suggestionsDavid Peterbefore adoptionf5de548
lines 299–305why, one step back299 assert_eq!(cmd.get_program().to_string_lossy(), "shell");300 assert_eq!(301 cmd.get_args()302 .map(|a| a.to_string_lossy())303 .collect::<Vec<_>>(),304 vec!["-x", "aaa bbb"]305 );Add tests for options::Shellrhysdbefore adoption1b7d139
lines 306–307why, one step back306307 // Error casesFix clippy suggestionsDavid Peterbefore adoptionf5de548
lines 308–311why, one step back308 assert!(matches!(309 Shell::parse("shell 'foo").unwrap_err(),310 OptionsError::ShellParseError(_)311 ));Add tests for options::Shellrhysdbefore adoption1b7d139
line 312why, one step back312Fix formattingDavid Peterbefore adoptiona35e7e2
lines 313–316why, one step back313 assert!(matches!(314 Shell::parse("").unwrap_err(),315 OptionsError::EmptyShell316 ));Add tests for options::Shellrhysdbefore adoption1b7d139
line 317why, one step back317Fix formattingDavid Peterbefore adoptiona35e7e2
lines 318–321why, one step back318 assert!(matches!(319 Shell::parse("''").unwrap_err(),320 OptionsError::EmptyShell321 ));Flat directory/module structureDavid Peterbefore adoption30c381f
line 322why, one step back322}