command.rs
This file
Path
src/command.rs
545 lines · 17.0 KiB · Rust
Last changed by
remove unneeded varBenjamin Rombautbefore adoption781a681
History of this fileTake it
The walk stopped after 200 commits: lines older than 6645fa1 point at it.
Use get_programDavid Peterbefore adoption6645fa1
lines 1–6why, one step back1use std::collections::BTreeMap;2use std::fmt;3use std::str::FromStr;45use crate::{6 error::{OptionsError, ParameterScanError},Move functions into SchedulerDavid Peterbefore adoption39c7736
lines 7–10why, one step back7 parameter::{8 range_step::{Numeric, RangeStep},9 ParameterNameAndValue,10 },Use get_programDavid Peterbefore adoption6645fa1
lines 11–12why, one step back11};12chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3
line 13why, one step back13use clap::{parser::ValuesRef, ArgMatches};Use get_programDavid Peterbefore adoption6645fa1
lines 14–17why, one step back1415use crate::parameter::tokenize::tokenize;16use crate::parameter::ParameterValue;17Use raw executor by default, skip intermediate shellDavid Peterbefore adoptiond9418e0
line 18why, one step back18use anyhow::{bail, Context, Result};Use get_programDavid Peterbefore adoption6645fa1
lines 19–30why, one step back19use rust_decimal::Decimal;2021/// A command that should be benchmarked.22#[derive(Debug, Clone, PartialEq, Eq)]23pub struct Command<'a> {24 /// The command name (without parameter substitution)25 name: Option<&'a str>,2627 /// The command that should be executed (without parameter substitution)28 expression: &'a str,2930 /// Zero or more parameter values.Move functions into SchedulerDavid Peterbefore adoption39c7736
line 31why, one step back31 parameters: Vec<ParameterNameAndValue<'a>>,Use get_programDavid Peterbefore adoption6645fa1
lines 32–45why, one step back32}3334impl<'a> Command<'a> {35 pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {36 Command {37 name,38 expression,39 parameters: Vec::new(),40 }41 }4243 pub fn new_parametrized(44 name: Option<&'a str>,45 expression: &'a str,Move functions into SchedulerDavid Peterbefore adoption39c7736
line 46why, one step back46 parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,Use get_programDavid Peterbefore adoption6645fa1
lines 47–50why, one step back47 ) -> Command<'a> {48 Command {49 name,50 expression,Move functions into SchedulerDavid Peterbefore adoption39c7736
line 51why, one step back51 parameters: parameters.into_iter().collect(),Use get_programDavid Peterbefore adoption6645fa1
lines 52–56why, one step back52 }53 }5455 pub fn get_name(&self) -> String {56 self.name.map_or_else(Rename to get_command_lineDavid Peterbefore adoption826449b
line 57why, one step back57 || self.get_command_line(),Use get_programDavid Peterbefore adoption6645fa1
lines 58–61why, one step back58 |name| self.replace_parameters_in(name),59 )60 }61Rename to get_command_lineDavid Peterbefore adoption826449b
line 62why, one step back62 pub fn get_command_line(&self) -> String {Use get_programDavid Peterbefore adoption6645fa1
line 63why, one step back63 self.replace_parameters_in(self.expression)Use raw executor by default, skip intermediate shellDavid Peterbefore adoptiond9418e0
lines 64–78why, one step back64 }6566 pub fn get_command(&self) -> Result<std::process::Command> {67 let command_line = self.get_command_line();68 let mut tokens = shell_words::split(&command_line)69 .with_context(|| format!("Failed to parse command '{}'", command_line))?70 .into_iter();7172 if let Some(program_name) = tokens.next() {73 let mut command_builder = std::process::Command::new(program_name);74 command_builder.args(tokens);75 Ok(command_builder)76 } else {77 bail!("Can not execute empty command")78 }Use get_programDavid Peterbefore adoption6645fa1
lines 79–80why, one step back79 }80Move functions into SchedulerDavid Peterbefore adoption39c7736
line 81why, one step back81 pub fn get_parameters(&self) -> &[(&'a str, ParameterValue)] {Use get_programDavid Peterbefore adoption6645fa1
lines 82–98why, one step back82 &self.parameters83 }8485 fn replace_parameters_in(&self, original: &str) -> String {86 let mut result = String::new();87 let mut replacements = BTreeMap::<String, String>::new();88 for (param_name, param_value) in &self.parameters {89 replacements.insert(90 format!("{{{param_name}}}", param_name = param_name),91 param_value.to_string(),92 );93 }94 let mut remaining = original;95 // Manually replace consecutive occurrences to avoid double-replacing: e.g.,96 //97 // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'98 //Rename to get_command_lineDavid Peterbefore adoption826449b
line 99why, one step back99 // should not ever run 'echo baz baz'. See `test_get_command_line_nonoverlapping`.Use get_programDavid Peterbefore adoption6645fa1
lines 100–119why, one step back100 'outer: while let Some(head) = remaining.chars().next() {101 for (k, v) in &replacements {102 if remaining.starts_with(k.as_str()) {103 result.push_str(v);104 remaining = &remaining[k.len()..];105 continue 'outer;106 }107 }108 result.push(head);109 remaining = &remaining[head.len_utf8()..];110 }111 result112 }113}114115/// A collection of commands that should be benchmarked116pub struct Commands<'a>(Vec<Command<'a>>);117118impl<'a> Commands<'a> {119 pub fn from_cli_arguments(matches: &'a ArgMatches) -> Result<Commands> {update to clap 4Benjamin Rombautbefore adoption8d38ef3
line 120why, one step back120 let command_names = matches.get_many::<String>("command-name");chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3
lines 121–125why, one step back121 let command_strings = matches122 .get_many::<String>("command")123 .unwrap_or_default()124 .map(|v| v.as_str())125 .collect::<Vec<_>>();Use get_programDavid Peterbefore adoption6645fa1
line 126why, one step back126update to clap 4Benjamin Rombautbefore adoption8d38ef3
line 127why, one step back127 if let Some(args) = matches.get_many::<String>("parameter-scan") {chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3
lines 128–130why, one step back128 let step_size = matches129 .get_one::<String>("parameter-step-size")130 .map(|s| s.as_str());Use get_programDavid Peterbefore adoption6645fa1
lines 131–136why, one step back131 Ok(Self(Self::get_parameter_scan_commands(132 command_names,133 command_strings,134 args,135 step_size,136 )?))update to clap 4Benjamin Rombautbefore adoption8d38ef3
line 137why, one step back137 } else if let Some(args) = matches.get_many::<String>("parameter-list") {chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3
lines 138–140why, one step back138 let command_names = command_names.map_or(vec![], |names| {139 names.map(|v| v.as_str()).collect::<Vec<_>>()140 });update to clap 4Benjamin Rombautbefore adoption8d38ef3
line 141why, one step back141 let args: Vec<_> = args.map(|v| v.as_str()).collect::<Vec<_>>();Use get_programDavid Peterbefore adoption6645fa1
lines 142–157why, one step back142 let param_names_and_values: Vec<(&str, Vec<String>)> = args143 .chunks_exact(2)144 .map(|pair| {145 let name = pair[0];146 let list_str = pair[1];147 (name, tokenize(list_str))148 })149 .collect();150 {151 let duplicates =152 Self::find_duplicates(param_names_and_values.iter().map(|(name, _)| *name));153 if !duplicates.is_empty() {154 bail!("Duplicate parameter names: {}", &duplicates.join(", "));155 }156 }157remove unneeded varBenjamin Rombautbefore adoptiona2e85a2
line 158why, one step back158 let dimensions: Vec<usize> = std::iter::once(command_strings.len())Use get_programDavid Peterbefore adoption6645fa1
lines 159–186why, one step back159 .chain(160 param_names_and_values161 .iter()162 .map(|(_, values)| values.len()),163 )164 .collect();165 let param_space_size = dimensions.iter().product();166 if param_space_size == 0 {167 return Ok(Self(Vec::new()));168 }169170 // `--command-name` should appear exactly once or exactly B times,171 // where B is the total number of benchmarks.172 let command_name_count = command_names.len();173 if command_name_count > 1 && command_name_count != param_space_size {174 return Err(OptionsError::UnexpectedCommandNameCount(175 command_name_count,176 param_space_size,177 )178 .into());179 }180181 let mut i = 0;182 let mut commands = Vec::with_capacity(param_space_size);183 let mut index = vec![0usize; dimensions.len()];184 'outer: loop {185 let name = command_names186 .get(i)Fix clippy suggestionsDavid Peterbefore adoptionc7e5694
line 187why, one step back187 .or_else(|| command_names.first())Use get_programDavid Peterbefore adoption6645fa1
lines 188–191why, one step back188 .copied();189 i += 1;190191 let (command_index, params_indices) = index.split_first().unwrap();Move functions into SchedulerDavid Peterbefore adoption39c7736
line 192why, one step back192 let parameters: Vec<_> = param_names_and_valuesUse get_programDavid Peterbefore adoption6645fa1
lines 193–198why, one step back193 .iter()194 .zip(params_indices)195 .map(|((name, values), i)| (*name, ParameterValue::Text(values[*i].clone())))196 .collect();197 commands.push(Command::new_parametrized(198 name,remove unneeded varBenjamin Rombautbefore adoptiona2e85a2
line 199why, one step back199 command_strings[*command_index],Use get_programDavid Peterbefore adoption6645fa1
lines 200–216why, one step back200 parameters,201 ));202203 // Increment index, exiting loop on overflow.204 for (i, n) in index.iter_mut().zip(dimensions.iter()) {205 *i += 1;206 if *i < *n {207 continue 'outer;208 } else {209 *i = 0;210 }211 }212 break 'outer;213 }214215 Ok(Self(commands))216 } else {chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3
lines 217–219why, one step back217 let command_names = command_names.map_or(vec![], |names| {218 names.map(|v| v.as_str()).collect::<Vec<_>>()219 });Use get_programDavid Peterbefore adoption6645fa1
lines 220–223why, one step back220 if command_names.len() > command_strings.len() {221 return Err(OptionsError::TooManyCommandNames(command_strings.len()).into());222 }223remove unneeded varBenjamin Rombautbefore adoption781a681
lines 224–225why, one step back224 let mut commands = Vec::with_capacity(command_strings.len());225 for (i, s) in command_strings.iter().enumerate() {Use get_programDavid Peterbefore adoption6645fa1
lines 226–279why, one step back226 commands.push(Command::new(command_names.get(i).copied(), s));227 }228 Ok(Self(commands))229 }230 }231232 pub fn iter(&self) -> impl Iterator<Item = &Command<'a>> {233 self.0.iter()234 }235236 pub fn num_commands(&self) -> usize {237 self.0.len()238 }239240 /// Finds all the strings that appear multiple times in the input iterator, returning them in241 /// sorted order. If no string appears more than once, the result is an empty vector.242 fn find_duplicates<'b, I: IntoIterator<Item = &'b str>>(i: I) -> Vec<&'b str> {243 let mut counts = BTreeMap::<&'b str, usize>::new();244 for s in i {245 *counts.entry(s).or_default() += 1;246 }247 counts248 .into_iter()249 .filter_map(|(k, n)| if n > 1 { Some(k) } else { None })250 .collect()251 }252253 fn build_parameter_scan_commands<'b, T: Numeric>(254 param_name: &'b str,255 param_min: T,256 param_max: T,257 step: T,258 command_names: Vec<&'b str>,259 command_strings: Vec<&'b str>,260 ) -> Result<Vec<Command<'b>>, ParameterScanError> {261 let param_range = RangeStep::new(param_min, param_max, step)?;262 let param_count = param_range.size_hint().1.unwrap();263 let command_name_count = command_names.len();264265 // `--command-name` should appear exactly once or exactly B times,266 // where B is the total number of benchmarks.267 if command_name_count > 1 && command_name_count != param_count {268 return Err(ParameterScanError::UnexpectedCommandNameCount(269 command_name_count,270 param_count,271 ));272 }273274 let mut i = 0;275 let mut commands = vec![];276 for value in param_range {277 for cmd in &command_strings {278 let name = command_names279 .get(i)Fix clippy suggestionsDavid Peterbefore adoptionc7e5694
line 280why, one step back280 .or_else(|| command_names.first())Use get_programDavid Peterbefore adoption6645fa1
lines 281–293why, one step back281 .copied();282 commands.push(Command::new_parametrized(283 name,284 cmd,285 vec![(param_name, ParameterValue::Numeric(value.into()))],286 ));287 i += 1;288 }289 }290 Ok(commands)291 }292293 fn get_parameter_scan_commands<'b>(update to clap 4Benjamin Rombautbefore adoption8d38ef3
lines 294–296why, one step back294 command_names: Option<ValuesRef<'b, String>>,295 command_strings: Vec<&'b str>,296 mut vals: ValuesRef<'b, String>,Use get_programDavid Peterbefore adoption6645fa1
lines 297–298why, one step back297 step: Option<&str>,298 ) -> Result<Vec<Command<'b>>, ParameterScanError> {chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3
lines 299–301why, one step back299 let command_names = command_names.map_or(vec![], |names| {300 names.map(|v| v.as_str()).collect::<Vec<_>>()301 });update to clap 4Benjamin Rombautbefore adoption8d38ef3
lines 302–305why, one step back302 let command_strings = command_strings;303 let param_name = vals.next().unwrap().as_str();304 let param_min = vals.next().unwrap().as_str();305 let param_max = vals.next().unwrap().as_str();Use get_programDavid Peterbefore adoption6645fa1
lines 306–343why, one step back306307 // attempt to parse as integers308 if let (Ok(param_min), Ok(param_max), Ok(step)) = (309 param_min.parse::<i32>(),310 param_max.parse::<i32>(),311 step.unwrap_or("1").parse::<i32>(),312 ) {313 return Self::build_parameter_scan_commands(314 param_name,315 param_min,316 param_max,317 step,318 command_names,319 command_strings,320 );321 }322323 // try parsing them as decimals324 let param_min = Decimal::from_str(param_min)?;325 let param_max = Decimal::from_str(param_max)?;326327 if step.is_none() {328 return Err(ParameterScanError::StepRequired);329 }330331 let step = Decimal::from_str(step.unwrap())?;332 Self::build_parameter_scan_commands(333 param_name,334 param_min,335 param_max,336 step,337 command_names,338 command_strings,339 )340 }341}342343#[test]Rename to get_command_lineDavid Peterbefore adoption826449b
line 344why, one step back344fn test_get_command_line_nonoverlapping() {Use get_programDavid Peterbefore adoption6645fa1
lines 345–352why, one step back345 let cmd = Command::new_parametrized(346 None,347 "echo {foo} {bar}",348 vec![349 ("foo", ParameterValue::Text("{bar} baz".into())),350 ("bar", ParameterValue::Text("quux".into())),351 ],352 );Rename to get_command_lineDavid Peterbefore adoption826449b
line 353why, one step back353 assert_eq!(cmd.get_command_line(), "echo {bar} baz quux");Use get_programDavid Peterbefore adoption6645fa1
lines 354–370why, one step back354}355356#[test]357fn test_get_parameterized_command_name() {358 let cmd = Command::new_parametrized(359 Some("name-{bar}-{foo}"),360 "echo {foo} {bar}",361 vec![362 ("foo", ParameterValue::Text("baz".into())),363 ("bar", ParameterValue::Text("quux".into())),364 ],365 );366 assert_eq!(cmd.get_name(), "name-quux-baz");367}368369impl<'a> fmt::Display for Command<'a> {370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {Rename to get_command_lineDavid Peterbefore adoption826449b
line 371why, one step back371 write!(f, "{}", self.get_command_line())Use get_programDavid Peterbefore adoption6645fa1
lines 372–376why, one step back372 }373}374375#[test]376fn test_build_commands_cross_product() {Update dependenciesDavid Peterbefore adoptionf2f1dd9
line 377why, one step back377 use crate::cli::get_cli_arguments;Use get_programDavid Peterbefore adoption6645fa1
lines 378–414why, one step back378379 let matches = get_cli_arguments(vec![380 "hyperfine",381 "-L",382 "par1",383 "a,b",384 "-L",385 "par2",386 "z,y",387 "echo {par1} {par2}",388 "printf '%s\n' {par1} {par2}",389 ]);390 let result = Commands::from_cli_arguments(&matches).unwrap().0;391392 // Iteration order: command list first, then parameters in listed order (here, "par1" before393 // "par2", which is distinct from their sorted order), with parameter values in listed order.394 let pv = |s: &str| ParameterValue::Text(s.to_string());395 let cmd = |cmd: usize, par1: &str, par2: &str| {396 let expression = ["echo {par1} {par2}", "printf '%s\n' {par1} {par2}"][cmd];397 let params = vec![("par1", pv(par1)), ("par2", pv(par2))];398 Command::new_parametrized(None, expression, params)399 };400 let expected = vec![401 cmd(0, "a", "z"),402 cmd(1, "a", "z"),403 cmd(0, "b", "z"),404 cmd(1, "b", "z"),405 cmd(0, "a", "y"),406 cmd(1, "a", "y"),407 cmd(0, "b", "y"),408 cmd(1, "b", "y"),409 ];410 assert_eq!(result, expected);411}412413#[test]414fn test_build_parameter_list_commands() {Update dependenciesDavid Peterbefore adoptionf2f1dd9
line 415why, one step back415 use crate::cli::get_cli_arguments;Use get_programDavid Peterbefore adoption6645fa1
lines 416–429why, one step back416417 let matches = get_cli_arguments(vec![418 "hyperfine",419 "echo {foo}",420 "--parameter-list",421 "foo",422 "1,2",423 "--command-name",424 "name-{foo}",425 ]);426 let commands = Commands::from_cli_arguments(&matches).unwrap().0;427 assert_eq!(commands.len(), 2);428 assert_eq!(commands[0].get_name(), "name-1");429 assert_eq!(commands[1].get_name(), "name-2");Rename to get_command_lineDavid Peterbefore adoption826449b
lines 430–431why, one step back430 assert_eq!(commands[0].get_command_line(), "echo 1");431 assert_eq!(commands[1].get_command_line(), "echo 2");Use get_programDavid Peterbefore adoption6645fa1
lines 432–435why, one step back432}433434#[test]435fn test_build_parameter_scan_commands() {Update dependenciesDavid Peterbefore adoptionf2f1dd9
line 436why, one step back436 use crate::cli::get_cli_arguments;Use get_programDavid Peterbefore adoption6645fa1
lines 437–452why, one step back437 let matches = get_cli_arguments(vec![438 "hyperfine",439 "echo {val}",440 "--parameter-scan",441 "val",442 "1",443 "2",444 "--parameter-step-size",445 "1",446 "--command-name",447 "name-{val}",448 ]);449 let commands = Commands::from_cli_arguments(&matches).unwrap().0;450 assert_eq!(commands.len(), 2);451 assert_eq!(commands[0].get_name(), "name-1");452 assert_eq!(commands[1].get_name(), "name-2");Rename to get_command_lineDavid Peterbefore adoption826449b
lines 453–454why, one step back453 assert_eq!(commands[0].get_command_line(), "echo 1");454 assert_eq!(commands[1].get_command_line(), "echo 2");Use get_programDavid Peterbefore adoption6645fa1
lines 455–469why, one step back455}456457#[test]458fn test_parameter_scan_commands_int() {459 let commands = Commands::build_parameter_scan_commands(460 "val",461 1i32,462 7i32,463 3i32,464 vec![],465 vec!["echo {val}"],466 )467 .unwrap();468 assert_eq!(commands.len(), 3);469 assert_eq!(commands[2].get_name(), "echo 7");Rename to get_command_lineDavid Peterbefore adoption826449b
line 470why, one step back470 assert_eq!(commands[2].get_command_line(), "echo 7");Use get_programDavid Peterbefore adoption6645fa1
lines 471–489why, one step back471}472473#[test]474fn test_parameter_scan_commands_decimal() {475 let param_min = Decimal::from_str("0").unwrap();476 let param_max = Decimal::from_str("1").unwrap();477 let step = Decimal::from_str("0.33").unwrap();478479 let commands = Commands::build_parameter_scan_commands(480 "val",481 param_min,482 param_max,483 step,484 vec![],485 vec!["echo {val}"],486 )487 .unwrap();488 assert_eq!(commands.len(), 4);489 assert_eq!(commands[3].get_name(), "echo 0.99");Rename to get_command_lineDavid Peterbefore adoption826449b
line 490why, one step back490 assert_eq!(commands[3].get_command_line(), "echo 0.99");Use get_programDavid Peterbefore adoption6645fa1
lines 491–493why, one step back491}492493#[test]Fix typo in unit test.Sendhil Panchadsarambefore adoption8c2ef10
line 494why, one step back494fn test_parameter_scan_commands_names() {Use get_programDavid Peterbefore adoption6645fa1
lines 495–545why, one step back495 let commands = Commands::build_parameter_scan_commands(496 "val",497 1i32,498 3i32,499 1i32,500 vec!["name-{val}"],501 vec!["echo {val}"],502 )503 .unwrap();504 assert_eq!(commands.len(), 3);505 let command_names = commands506 .iter()507 .map(|c| c.get_name())508 .collect::<Vec<String>>();509 assert_eq!(command_names, vec!["name-1", "name-2", "name-3"]);510}511512#[test]513fn test_get_specified_command_names() {514 let commands = Commands::build_parameter_scan_commands(515 "val",516 1i32,517 3i32,518 1i32,519 vec!["name-a", "name-b", "name-c"],520 vec!["echo {val}"],521 )522 .unwrap();523 assert_eq!(commands.len(), 3);524 let command_names = commands525 .iter()526 .map(|c| c.get_name())527 .collect::<Vec<String>>();528 assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]);529}530531#[test]532fn test_different_command_name_count_with_parameters() {533 let result = Commands::build_parameter_scan_commands(534 "val",535 1i32,536 3i32,537 1i32,538 vec!["name-1", "name-2"],539 vec!["echo {val}"],540 );541 assert!(matches!(542 result.unwrap_err(),543 ParameterScanError::UnexpectedCommandNameCount(2, 3)544 ));545}