Files
hyperfine/src/options.rs
T

352 lines
10 KiB
Rust
Raw Normal View History

2021-10-04 22:34:19 +09:00
use std::process::Command;
use std::{cmp, fmt};
2022-02-07 21:03:23 +01:00
use anyhow::ensure;
use atty::Stream;
use clap::ArgMatches;
2021-10-04 22:34:19 +09:00
2022-02-07 21:03:23 +01:00
use crate::command::Commands;
2021-10-04 22:34:19 +09:00
use crate::error::OptionsError;
2022-02-06 20:01:41 +01:00
use crate::util::units::{Second, Unit};
2021-08-22 19:04:22 +02:00
2022-02-07 21:03:23 +01:00
use anyhow::Result;
2021-08-22 19:04:22 +02:00
#[cfg(not(windows))]
pub const DEFAULT_SHELL: &str = "sh";
#[cfg(windows)]
pub const DEFAULT_SHELL: &str = "cmd.exe";
2021-08-22 17:53:08 +02:00
2021-10-04 22:34:19 +09:00
/// Shell to use for executing benchmarked commands
2021-10-04 22:49:37 +09:00
#[derive(Debug)]
2021-10-04 22:34:19 +09:00
pub enum Shell {
/// Default shell command
Default(&'static str),
2022-02-19 19:58:00 +01:00
2021-10-04 22:34:19 +09:00
/// Custom shell command specified via --shell
Custom(Vec<String>),
}
impl Default for Shell {
fn default() -> Self {
Shell::Default(DEFAULT_SHELL)
}
}
impl fmt::Display for Shell {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Shell::Default(cmd) => write!(f, "{}", cmd),
2021-10-04 22:49:37 +09:00
Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)),
2021-10-04 22:34:19 +09:00
}
}
}
impl Shell {
/// Parse given string as shell command line
2022-02-22 10:13:06 +01:00
pub fn parse_from_str<'a>(s: &str) -> Result<Self, OptionsError<'a>> {
2021-10-04 23:07:38 +09:00
let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?;
2021-10-04 22:49:37 +09:00
if v.is_empty() || v[0].is_empty() {
2021-10-04 22:34:19 +09:00
return Err(OptionsError::EmptyShell);
}
Ok(Shell::Custom(v))
}
pub fn command(&self) -> Command {
match self {
Shell::Default(cmd) => Command::new(cmd),
Shell::Custom(cmdline) => {
let mut c = Command::new(&cmdline[0]);
c.args(&cmdline[1..]);
c
}
}
}
}
2021-08-22 17:53:08 +02:00
/// Action to take when an executed command fails.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CmdFailureAction {
/// Exit with an error message
RaiseError,
/// Simply ignore the non-zero exit code
Ignore,
}
/// Output style type option
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum OutputStyleOption {
/// Do not output with colors or any special formatting
Basic,
/// Output with full color and formatting
Full,
/// Keep elements such as progress bar, but use no coloring
NoColor,
/// Keep coloring, but use no progress bar
Color,
/// Disable all the output
Disabled,
}
2022-02-19 20:01:49 +01:00
/// Bounds for the number of benchmark runs
pub struct RunBounds {
2021-08-22 17:53:08 +02:00
/// Minimum number of benchmark runs
pub min: u64,
/// Maximum number of benchmark runs
pub max: Option<u64>,
}
2022-02-19 20:01:49 +01:00
impl Default for RunBounds {
2022-02-20 13:15:54 +01:00
fn default() -> Self {
2022-02-19 20:01:49 +01:00
RunBounds { min: 10, max: None }
2021-08-22 17:53:08 +02:00
}
}
2022-02-20 13:15:54 +01:00
/// How to handle the output of benchmarked commands
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CommandOutputPolicy {
/// Discard all output
Discard,
2021-08-22 17:53:08 +02:00
2022-02-20 13:15:54 +01:00
/// Show command output on the terminal
Forward,
}
impl Default for CommandOutputPolicy {
fn default() -> Self {
CommandOutputPolicy::Discard
}
}
2022-02-22 08:36:56 +01:00
pub enum ExecutorKind {
Shell(Shell),
2022-02-22 08:58:57 +01:00
Mock(Option<String>),
2022-02-22 08:36:56 +01:00
}
impl Default for ExecutorKind {
fn default() -> Self {
ExecutorKind::Shell(Shell::default())
}
}
2022-02-20 13:15:54 +01:00
/// The main settings for a hyperfine benchmark session
pub struct Options {
2022-02-19 20:01:49 +01:00
/// Upper and lower bound for the number of benchmark runs
pub run_bounds: RunBounds,
2021-08-22 17:53:08 +02:00
2022-02-20 13:15:54 +01:00
/// Number of warmup runs
pub warmup_count: u64,
2021-08-22 17:53:08 +02:00
/// Minimum benchmarking time
2022-02-20 13:15:54 +01:00
pub min_benchmarking_time: Second,
2021-08-22 17:53:08 +02:00
/// Whether or not to ignore non-zero exit codes
2022-02-20 13:15:54 +01:00
pub command_failure_action: CmdFailureAction,
2022-02-20 13:19:23 +01:00
/// Command(s) to run before each timing run
2021-08-22 17:53:08 +02:00
pub preparation_command: Option<Vec<String>>,
2022-02-20 13:15:54 +01:00
/// Command to run before each *batch* of timing runs, i.e. before each individual benchmark
pub setup_command: Option<String>,
/// Command to run after each *batch* of timing runs, i.e. after each individual benchmark
2021-08-22 17:53:08 +02:00
pub cleanup_command: Option<String>,
2022-02-20 13:15:54 +01:00
/// What color mode to use for the terminal output
2021-08-22 17:53:08 +02:00
pub output_style: OutputStyleOption,
2022-02-22 08:36:56 +01:00
/// Determines how we run commands
pub executor_kind: ExecutorKind,
2021-08-22 17:53:08 +02:00
2022-02-20 13:15:54 +01:00
/// What to do with the output of the benchmarked command
pub command_output_policy: CommandOutputPolicy,
2021-08-22 17:53:08 +02:00
2022-02-20 13:23:54 +01:00
/// Which time unit to use when displaying resuls
2021-08-22 17:53:08 +02:00
pub time_unit: Option<Unit>,
}
2022-02-06 18:20:38 +01:00
impl Default for Options {
fn default() -> Options {
Options {
2022-02-19 20:01:49 +01:00
run_bounds: RunBounds::default(),
2022-02-20 13:23:54 +01:00
warmup_count: 0,
2022-02-20 13:15:54 +01:00
min_benchmarking_time: 3.0,
command_failure_action: CmdFailureAction::RaiseError,
2021-08-22 17:53:08 +02:00
preparation_command: None,
2022-02-20 13:23:54 +01:00
setup_command: None,
2021-08-22 17:53:08 +02:00
cleanup_command: None,
output_style: OutputStyleOption::Full,
2022-02-22 08:36:56 +01:00
executor_kind: ExecutorKind::default(),
2022-02-20 13:15:54 +01:00
command_output_policy: CommandOutputPolicy::Discard,
2021-08-22 17:53:08 +02:00
time_unit: None,
}
}
}
2021-10-04 22:49:37 +09:00
2022-02-06 18:20:38 +01:00
impl Options {
pub fn from_cli_arguments<'a>(matches: &ArgMatches) -> Result<Self, OptionsError<'a>> {
let mut options = Self::default();
let param_to_u64 = |param| {
matches
.value_of(param)
.map(|n| {
n.parse::<u64>()
.map_err(|e| OptionsError::NumericParsingError(param, e))
})
.transpose()
};
options.warmup_count = param_to_u64("warmup")?.unwrap_or(options.warmup_count);
let mut min_runs = param_to_u64("min-runs")?;
let mut max_runs = param_to_u64("max-runs")?;
if let Some(runs) = param_to_u64("runs")? {
min_runs = Some(runs);
max_runs = Some(runs);
}
match (min_runs, max_runs) {
(Some(min), None) => {
2022-02-19 20:01:49 +01:00
options.run_bounds.min = min;
}
(None, Some(max)) => {
// Since the minimum was not explicit we lower it if max is below the default min.
2022-02-19 20:01:49 +01:00
options.run_bounds.min = cmp::min(options.run_bounds.min, max);
options.run_bounds.max = Some(max);
}
(Some(min), Some(max)) if min > max => {
return Err(OptionsError::EmptyRunsRange);
}
(Some(min), Some(max)) => {
2022-02-19 20:01:49 +01:00
options.run_bounds.min = min;
options.run_bounds.max = Some(max);
}
(None, None) => {}
};
options.setup_command = matches.value_of("setup").map(String::from);
options.preparation_command = matches
.values_of("prepare")
.map(|values| values.map(String::from).collect::<Vec<String>>());
options.cleanup_command = matches.value_of("cleanup").map(String::from);
2022-02-20 13:15:54 +01:00
options.command_output_policy = if matches.is_present("show-output") {
CommandOutputPolicy::Forward
} else {
CommandOutputPolicy::Discard
};
options.output_style = match matches.value_of("style") {
Some("full") => OutputStyleOption::Full,
Some("basic") => OutputStyleOption::Basic,
Some("nocolor") => OutputStyleOption::NoColor,
Some("color") => OutputStyleOption::Color,
Some("none") => OutputStyleOption::Disabled,
_ => {
2022-02-20 13:15:54 +01:00
if options.command_output_policy == CommandOutputPolicy::Discard
&& atty::is(Stream::Stdout)
{
OutputStyleOption::Full
} else {
OutputStyleOption::Basic
}
}
};
match options.output_style {
OutputStyleOption::Basic | OutputStyleOption::NoColor => {
colored::control::set_override(false)
}
OutputStyleOption::Full | OutputStyleOption::Color => {
colored::control::set_override(true)
}
OutputStyleOption::Disabled => {}
};
2022-02-22 08:36:56 +01:00
options.executor_kind = match (matches.is_present("debug-mode"), matches.value_of("shell"))
{
2022-02-22 10:13:06 +01:00
(false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?),
2022-02-22 08:36:56 +01:00
(false, None) => ExecutorKind::Shell(Shell::default()),
2022-02-22 08:58:57 +01:00
(true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())),
(true, None) => ExecutorKind::Mock(None),
2022-02-22 08:36:56 +01:00
};
if matches.is_present("ignore-failure") {
2022-02-20 13:15:54 +01:00
options.command_failure_action = CmdFailureAction::Ignore;
}
options.time_unit = match matches.value_of("time-unit") {
Some("millisecond") => Some(Unit::MilliSecond),
Some("second") => Some(Unit::Second),
_ => None,
};
Ok(options)
}
2022-02-07 21:03:23 +01:00
pub fn validate_against_command_list(&self, commands: &Commands) -> Result<()> {
if let Some(preparation_command) = &self.preparation_command {
ensure!(
2022-02-19 19:58:00 +01:00
preparation_command.len() <= 1
|| commands.num_commands() == preparation_command.len(),
2022-02-07 21:03:23 +01:00
"The '--prepare' option has to be provided just once or N times, where N is the \
number of benchmark commands."
);
}
Ok(())
}
}
2021-10-04 22:49:37 +09:00
#[test]
2022-02-20 13:31:49 +01:00
fn test_default_shell() {
2021-10-04 22:49:37 +09:00
let shell = Shell::default();
let s = format!("{}", shell);
assert_eq!(&s, DEFAULT_SHELL);
let cmd = shell.command();
2022-02-20 13:25:50 +01:00
assert_eq!(cmd.get_program(), DEFAULT_SHELL);
2021-10-04 22:49:37 +09:00
}
#[test]
2022-02-20 13:19:23 +01:00
fn test_can_parse_shell_command_line_from_str() {
2022-02-22 10:13:06 +01:00
let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap();
2021-10-04 22:49:37 +09:00
let s = format!("{}", shell);
assert_eq!(&s, "shell -x 'aaa bbb'");
let cmd = shell.command();
2022-02-05 22:14:06 +01:00
assert_eq!(cmd.get_program().to_string_lossy(), "shell");
assert_eq!(
cmd.get_args()
.map(|a| a.to_string_lossy())
.collect::<Vec<_>>(),
vec!["-x", "aaa bbb"]
);
2021-10-04 22:49:37 +09:00
// Error cases
2022-02-05 22:14:06 +01:00
assert!(matches!(
2022-02-22 10:13:06 +01:00
Shell::parse_from_str("shell 'foo").unwrap_err(),
2022-02-05 22:14:06 +01:00
OptionsError::ShellParseError(_)
));
2021-10-04 22:49:37 +09:00
2022-02-06 17:56:59 +01:00
assert!(matches!(
2022-02-22 10:13:06 +01:00
Shell::parse_from_str("").unwrap_err(),
2022-02-06 17:56:59 +01:00
OptionsError::EmptyShell
));
2021-10-04 22:49:37 +09:00
2022-02-06 17:56:59 +01:00
assert!(matches!(
2022-02-22 10:13:06 +01:00
Shell::parse_from_str("''").unwrap_err(),
2022-02-06 17:56:59 +01:00
OptionsError::EmptyShell
));
2021-10-04 22:49:37 +09:00
}