Skip to content
Myr

command.rs

This file

Path

src/command.rs

511 lines · 15.6 KiB · Rust

Last changed by

Split range into range_step and commandsDavid Peterbefore adoption6db82cd

History of this file

Take it

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 1–2why, one step back
1use std::collections::BTreeMap;
2use std::fmt;

Split range into range_step and commandsDavid Peterbefore adoption6db82cd

line 3why, one step back
3use std::str::FromStr;

Flat directory/module structureDavid Peterbefore adoption30c381f

line 4why, one step back
4

Split range into range_step and commandsDavid Peterbefore adoption6db82cd

lines 5–8why, one step back
5use crate::{
6 error::{OptionsError, ParameterScanError},7 parameter::range_step::{Numeric, RangeStep},8};

Move build_commandsDavid Peterbefore adoptioncd38e9c

lines 9–11why, one step back
9
10use clap::ArgMatches;11

New parameter moduleDavid Peterbefore adoption47091a5

lines 12–13why, one step back
12use crate::parameter::tokenize::tokenize;
13use crate::parameter::ParameterValue;

Flat directory/module structureDavid Peterbefore adoption30c381f

line 14why, one step back
14

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 15why, one step back
15use anyhow::{bail, Result};

Split range into range_step and commandsDavid Peterbefore adoption6db82cd

lines 16–17why, one step back
16use clap::Values;
17use rust_decimal::Decimal;

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 18why, one step back
18

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 19–97why, one step back
19/// A command that should be benchmarked.
20#[derive(Debug, Clone, PartialEq, Eq)]21pub struct Command<'a> {22 /// The command name (without parameter substitution)23 name: Option<&'a str>,2425 /// The command that should be executed (without parameter substitution)26 expression: &'a str,2728 /// Zero or more parameter values.29 parameters: Vec<(&'a str, ParameterValue)>,30}3132impl<'a> Command<'a> {33 pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {34 Command {35 name,36 expression,37 parameters: Vec::new(),38 }39 }4041 pub fn new_parametrized(42 name: Option<&'a str>,43 expression: &'a str,44 parameters: Vec<(&'a str, ParameterValue)>,45 ) -> Command<'a> {46 Command {47 name,48 expression,49 parameters,50 }51 }5253 pub fn get_name(&self) -> String {54 self.name.map_or_else(55 || self.get_shell_command(),56 |name| self.replace_parameters_in(name),57 )58 }5960 pub fn get_shell_command(&self) -> String {61 self.replace_parameters_in(self.expression)62 }6364 pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {65 &self.parameters66 }6768 fn replace_parameters_in(&self, original: &str) -> String {69 let mut result = String::new();70 let mut replacements = BTreeMap::<String, String>::new();71 for (param_name, param_value) in &self.parameters {72 replacements.insert(73 format!("{{{param_name}}}", param_name = param_name),74 param_value.to_string(),75 );76 }77 let mut remaining = original;78 // Manually replace consecutive occurrences to avoid double-replacing: e.g.,79 //80 // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'81 //82 // should not ever run 'echo baz baz'. See `test_get_shell_command_nonoverlapping`.83 'outer: while let Some(head) = remaining.chars().next() {84 for (k, v) in &replacements {85 if remaining.starts_with(k.as_str()) {86 result.push_str(v);87 remaining = &remaining[k.len()..];88 continue 'outer;89 }90 }91 result.push(head);92 remaining = &remaining[head.len_utf8()..];93 }94 result95 }96}97

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 98–109why, one step back
98/// Finds all the strings that appear multiple times in the input iterator, returning them in
99/// sorted order. If no string appears more than once, the result is an empty vector.100fn find_duplicates<'a, I: IntoIterator<Item = &'a str>>(i: I) -> Vec<&'a str> {101 let mut counts = BTreeMap::<&'a str, usize>::new();102 for s in i {103 *counts.entry(s).or_default() += 1;104 }105 counts106 .into_iter()107 .filter_map(|(k, n)| if n > 1 { Some(k) } else { None })108 .collect()109}

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 110why, one step back
110

Split range into range_step and commandsDavid Peterbefore adoption6db82cd

lines 111–197why, one step back
111fn build_parameterized_commands<'a, T: Numeric>(
112 param_min: T,113 param_max: T,114 step: T,115 command_names: Vec<&'a str>,116 command_strings: Vec<&'a str>,117 param_name: &'a str,118) -> Result<Vec<Command<'a>>, ParameterScanError> {119 let param_range = RangeStep::new(param_min, param_max, step)?;120 let param_count = param_range.size_hint().1.unwrap();121 let command_name_count = command_names.len();122123 // `--command-name` should appear exactly once or exactly B times,124 // where B is the total number of benchmarks.125 if command_name_count > 1 && command_name_count != param_count {126 return Err(ParameterScanError::UnexpectedCommandNameCount(127 command_name_count,128 param_count,129 ));130 }131132 let mut i = 0;133 let mut commands = vec![];134 for value in param_range {135 for cmd in &command_strings {136 let name = command_names137 .get(i)138 .or_else(|| command_names.get(0))139 .copied();140 commands.push(Command::new_parametrized(141 name,142 cmd,143 vec![(param_name, ParameterValue::Numeric(value.into()))],144 ));145 i += 1;146 }147 }148 Ok(commands)149}150151fn get_parameterized_commands<'a>(152 command_names: Option<Values<'a>>,153 command_strings: Values<'a>,154 mut vals: clap::Values<'a>,155 step: Option<&str>,156) -> Result<Vec<Command<'a>>, ParameterScanError> {157 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());158 let command_strings = command_strings.collect::<Vec<&str>>();159 let param_name = vals.next().unwrap();160 let param_min = vals.next().unwrap();161 let param_max = vals.next().unwrap();162163 // attempt to parse as integers164 if let (Ok(param_min), Ok(param_max), Ok(step)) = (165 param_min.parse::<i32>(),166 param_max.parse::<i32>(),167 step.unwrap_or("1").parse::<i32>(),168 ) {169 return build_parameterized_commands(170 param_min,171 param_max,172 step,173 command_names,174 command_strings,175 param_name,176 );177 }178179 // try parsing them as decimals180 let param_min = Decimal::from_str(param_min)?;181 let param_max = Decimal::from_str(param_max)?;182183 if step.is_none() {184 return Err(ParameterScanError::StepRequired);185 }186187 let step = Decimal::from_str(step.unwrap())?;188 build_parameterized_commands(189 param_min,190 param_max,191 step,192 command_names,193 command_strings,194 param_name,195 )196}197

Introduce Commands structDavid Peterbefore adoptiona6baf49

line 198why, one step back
198pub struct Commands<'a>(Vec<Command<'a>>);

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 199why, one step back
199

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 200–230why, one step back
200impl<'a> Commands<'a> {
201 pub fn from_cli_arguments(matches: &'a ArgMatches) -> Result<Commands> {202 let command_names = matches.values_of("command-name");203 let command_strings = matches.values_of("command").unwrap();204205 if let Some(args) = matches.values_of("parameter-scan") {206 let step_size = matches.value_of("parameter-step-size");207 Ok(Self(get_parameterized_commands(208 command_names,209 command_strings,210 args,211 step_size,212 )?))213 } else if let Some(args) = matches.values_of("parameter-list") {214 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());215216 let args: Vec<_> = args.collect();217 let param_names_and_values: Vec<(&str, Vec<String>)> = args218 .chunks_exact(2)219 .map(|pair| {220 let name = pair[0];221 let list_str = pair[1];222 (name, tokenize(list_str))223 })224 .collect();225 {226 let duplicates =227 find_duplicates(param_names_and_values.iter().map(|(name, _)| *name));228 if !duplicates.is_empty() {229 bail!("Duplicate parameter names: {}", &duplicates.join(", "));230 }

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 231why, one step back
231 }

Introduce Commands structDavid Peterbefore adoptiona6baf49

line 232why, one step back
232 let command_list = command_strings.collect::<Vec<&str>>();

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 233why, one step back
233

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 234–244why, one step back
234 let dimensions: Vec<usize> = std::iter::once(command_list.len())
235 .chain(236 param_names_and_values237 .iter()238 .map(|(_, values)| values.len()),239 )240 .collect();241 let param_space_size = dimensions.iter().product();242 if param_space_size == 0 {243 return Ok(Self(Vec::new()));244 }

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 245why, one step back
245

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 246–255why, one step back
246 // `--command-name` should appear exactly once or exactly B times,
247 // where B is the total number of benchmarks.248 let command_name_count = command_names.len();249 if command_name_count > 1 && command_name_count != param_space_size {250 return Err(OptionsError::UnexpectedCommandNameCount(251 command_name_count,252 param_space_size,253 )254 .into());255 }

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 256why, one step back
256

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 257–265why, one step back
257 let mut i = 0;
258 let mut commands = Vec::with_capacity(param_space_size);259 let mut index = vec![0usize; dimensions.len()];260 'outer: loop {261 let name = command_names262 .get(i)263 .or_else(|| command_names.get(0))264 .copied();265 i += 1;

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 266why, one step back
266

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 267–277why, one step back
267 let (command_index, params_indices) = index.split_first().unwrap();
268 let parameters = param_names_and_values269 .iter()270 .zip(params_indices)271 .map(|((name, values), i)| (*name, ParameterValue::Text(values[*i].clone())))272 .collect();273 commands.push(Command::new_parametrized(274 name,275 command_list[*command_index],276 parameters,277 ));

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 278why, one step back
278

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 279–286why, one step back
279 // Increment index, exiting loop on overflow.
280 for (i, n) in index.iter_mut().zip(dimensions.iter()) {281 *i += 1;282 if *i < *n {283 continue 'outer;284 } else {285 *i = 0;286 }

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 287why, one step back
287 }

Introduce Commands structDavid Peterbefore adoptiona6baf49

line 288why, one step back
288 break 'outer;

Move build_commandsDavid Peterbefore adoptioncd38e9c

lines 289–290why, one step back
289 }
290

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 291–296why, one step back
291 Ok(Self(commands))
292 } else {293 let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());294 if command_names.len() > command_strings.len() {295 return Err(OptionsError::TooManyCommandNames(command_strings.len()).into());296 }

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 297why, one step back
297

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 298–303why, one step back
298 let command_list = command_strings.collect::<Vec<&str>>();
299 let mut commands = Vec::with_capacity(command_list.len());300 for (i, s) in command_list.iter().enumerate() {301 commands.push(Command::new(command_names.get(i).copied(), s));302 }303 Ok(Self(commands))

Move build_commandsDavid Peterbefore adoptioncd38e9c

lines 304–306why, one step back
304 }
305 }306

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 307–308why, one step back
307 pub fn iter(&self) -> impl Iterator<Item = &Command<'a>> {
308 self.0.iter()

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 309why, one step back
309 }

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 310–313why, one step back
310
311 pub fn len(&self) -> usize {312 self.0.len()313 }

Move build_commandsDavid Peterbefore adoptioncd38e9c

lines 314–315why, one step back
314}
315

Flat directory/module structureDavid Peterbefore adoption30c381f

lines 316–345why, one step back
316#[test]
317fn test_get_shell_command_nonoverlapping() {318 let cmd = Command::new_parametrized(319 None,320 "echo {foo} {bar}",321 vec![322 ("foo", ParameterValue::Text("{bar} baz".into())),323 ("bar", ParameterValue::Text("quux".into())),324 ],325 );326 assert_eq!(cmd.get_shell_command(), "echo {bar} baz quux");327}328329#[test]330fn test_get_parameterized_command_name() {331 let cmd = Command::new_parametrized(332 Some("name-{bar}-{foo}"),333 "echo {foo} {bar}",334 vec![335 ("foo", ParameterValue::Text("baz".into())),336 ("bar", ParameterValue::Text("quux".into())),337 ],338 );339 assert_eq!(cmd.get_name(), "name-quux-baz");340}341342impl<'a> fmt::Display for Command<'a> {343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {344 write!(f, "{}", self.get_shell_command())345 }

Move build_commandsDavid Peterbefore adoptioncd38e9c

lines 346–349why, one step back
346}
347348#[test]349fn test_build_commands_cross_product() {

Introduce Commands structDavid Peterbefore adoptiona6baf49

line 350why, one step back
350 use crate::app::get_cli_arguments;

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 351why, one step back
351

Introduce Commands structDavid Peterbefore adoptiona6baf49

line 352why, one step back
352 let matches = get_cli_arguments(vec![

Move build_commandsDavid Peterbefore adoptioncd38e9c

lines 353–362why, one step back
353 "hyperfine",
354 "-L",355 "par1",356 "a,b",357 "-L",358 "par2",359 "z,y",360 "echo {par1} {par2}",361 "printf '%s\n' {par1} {par2}",362 ]);

Introduce Commands structDavid Peterbefore adoptiona6baf49

line 363why, one step back
363 let result = Commands::from_cli_arguments(&matches).unwrap().0;

Move build_commandsDavid Peterbefore adoptioncd38e9c

lines 364–387why, one step back
364
365 // Iteration order: command list first, then parameters in listed order (here, "par1" before366 // "par2", which is distinct from their sorted order), with parameter values in listed order.367 let pv = |s: &str| ParameterValue::Text(s.to_string());368 let cmd = |cmd: usize, par1: &str, par2: &str| {369 let expression = ["echo {par1} {par2}", "printf '%s\n' {par1} {par2}"][cmd];370 let params = vec![("par1", pv(par1)), ("par2", pv(par2))];371 Command::new_parametrized(None, expression, params)372 };373 let expected = vec![374 cmd(0, "a", "z"),375 cmd(1, "a", "z"),376 cmd(0, "b", "z"),377 cmd(1, "b", "z"),378 cmd(0, "a", "y"),379 cmd(1, "a", "y"),380 cmd(0, "b", "y"),381 cmd(1, "b", "y"),382 ];383 assert_eq!(result, expected);384}385386#[test]387fn test_build_parameter_list_commands() {

Introduce Commands structDavid Peterbefore adoptiona6baf49

line 388why, one step back
388 use crate::app::get_cli_arguments;

Move build_commandsDavid Peterbefore adoptioncd38e9c

line 389why, one step back
389

Introduce Commands structDavid Peterbefore adoptiona6baf49

line 390why, one step back
390 let matches = get_cli_arguments(vec![

Move build_commandsDavid Peterbefore adoptioncd38e9c

lines 391–398why, one step back
391 "hyperfine",
392 "echo {foo}",393 "--parameter-list",394 "foo",395 "1,2",396 "--command-name",397 "name-{foo}",398 ]);

Introduce Commands structDavid Peterbefore adoptiona6baf49

line 399why, one step back
399 let commands = Commands::from_cli_arguments(&matches).unwrap().0;

Move build_commandsDavid Peterbefore adoptioncd38e9c

lines 400–408why, one step back
400 assert_eq!(commands.len(), 2);
401 assert_eq!(commands[0].get_name(), "name-1");402 assert_eq!(commands[1].get_name(), "name-2");403 assert_eq!(commands[0].get_shell_command(), "echo 1");404 assert_eq!(commands[1].get_shell_command(), "echo 2");405}406407#[test]408fn test_build_parameter_range_commands() {

Introduce Commands structDavid Peterbefore adoptiona6baf49

lines 409–410why, one step back
409 use crate::app::get_cli_arguments;
410 let matches = get_cli_arguments(vec![

Move build_commandsDavid Peterbefore adoptioncd38e9c

lines 411–421why, one step back
411 "hyperfine",
412 "echo {val}",413 "--parameter-scan",414 "val",415 "1",416 "2",417 "--parameter-step-size",418 "1",419 "--command-name",420 "name-{val}",421 ]);

Introduce Commands structDavid Peterbefore adoptiona6baf49

line 422why, one step back
422 let commands = Commands::from_cli_arguments(&matches).unwrap().0;

Move build_commandsDavid Peterbefore adoptioncd38e9c

lines 423–427why, one step back
423 assert_eq!(commands.len(), 2);
424 assert_eq!(commands[0].get_name(), "name-1");425 assert_eq!(commands[1].get_name(), "name-2");426 assert_eq!(commands[0].get_shell_command(), "echo 1");427 assert_eq!(commands[1].get_shell_command(), "echo 2");

Split range into range_step and commandsDavid Peterbefore adoption6db82cd

lines 428–510why, one step back
428}
429430#[test]431fn test_get_parameterized_commands_int() {432 let commands =433 build_parameterized_commands(1i32, 7i32, 3i32, vec![], vec!["echo {val}"], "val").unwrap();434 assert_eq!(commands.len(), 3);435 assert_eq!(commands[2].get_name(), "echo 7");436 assert_eq!(commands[2].get_shell_command(), "echo 7");437}438439#[test]440fn test_get_parameterized_commands_decimal() {441 let param_min = Decimal::from_str("0").unwrap();442 let param_max = Decimal::from_str("1").unwrap();443 let step = Decimal::from_str("0.33").unwrap();444445 let commands = build_parameterized_commands(446 param_min,447 param_max,448 step,449 vec![],450 vec!["echo {val}"],451 "val",452 )453 .unwrap();454 assert_eq!(commands.len(), 4);455 assert_eq!(commands[3].get_name(), "echo 0.99");456 assert_eq!(commands[3].get_shell_command(), "echo 0.99");457}458459#[test]460fn test_get_parameterized_command_names() {461 let commands = build_parameterized_commands(462 1i32,463 3i32,464 1i32,465 vec!["name-{val}"],466 vec!["echo {val}"],467 "val",468 )469 .unwrap();470 assert_eq!(commands.len(), 3);471 let command_names = commands472 .iter()473 .map(|c| c.get_name())474 .collect::<Vec<String>>();475 assert_eq!(command_names, vec!["name-1", "name-2", "name-3"]);476}477478#[test]479fn test_get_specified_command_names() {480 let commands = build_parameterized_commands(481 1i32,482 3i32,483 1i32,484 vec!["name-a", "name-b", "name-c"],485 vec!["echo {val}"],486 "val",487 )488 .unwrap();489 assert_eq!(commands.len(), 3);490 let command_names = commands491 .iter()492 .map(|c| c.get_name())493 .collect::<Vec<String>>();494 assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]);495}496497#[test]498fn test_different_command_name_count_with_parameters() {499 let result = build_parameterized_commands(500 1i32,501 3i32,502 1i32,503 vec!["name-1", "name-2"],504 vec!["echo {val}"],505 "val",506 );507 assert_eq!(508 format!("{}", result.unwrap_err()),509 "'--command-name' has been specified 2 times. It has to appear exactly once, or exactly 3 times (number of benchmarks)"510 );

Flat directory/module structureDavid Peterbefore adoption30c381f

line 511why, one step back
511}