Skip to content
Myr

command.rs

This file

Path

src/command.rs

562 lines · 17.7 KiB · Rust

Last changed by

Multiple output policiesDavid Peterbefore adoption99d24b7

History of this file

Take it

The walk stopped after 200 commits: lines older than 2e8ce30 point at it.

Shrink unsafe blockcactterbefore adoption2e8ce30

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

Show unused parameters in command namesDavid Peterbefore adoptiona875276

lines 5–6why, one step back
5use crate::parameter::tokenize::tokenize;
6use crate::parameter::ParameterValue;

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 7–14why, one step back
7use crate::{
8 error::{OptionsError, ParameterScanError},9 parameter::{10 range_step::{Numeric, RangeStep},11 ParameterNameAndValue,12 },13};14

chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3

line 15why, one step back
15use clap::{parser::ValuesRef, ArgMatches};

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 16–60why, one step back
16
17use anyhow::{bail, Context, Result};18use rust_decimal::Decimal;1920/// A command that should be benchmarked.21#[derive(Debug, Clone, PartialEq, Eq)]22pub struct Command<'a> {23 /// The command name (without parameter substitution)24 name: Option<&'a str>,2526 /// The command that should be executed (without parameter substitution)27 expression: &'a str,2829 /// Zero or more parameter values.30 parameters: Vec<ParameterNameAndValue<'a>>,31}3233impl<'a> Command<'a> {34 pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {35 Command {36 name,37 expression,38 parameters: Vec::new(),39 }40 }4142 pub fn new_parametrized(43 name: Option<&'a str>,44 expression: &'a str,45 parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,46 ) -> Command<'a> {47 Command {48 name,49 expression,50 parameters: parameters.into_iter().collect(),51 }52 }5354 pub fn get_name(&self) -> String {55 self.name.map_or_else(56 || self.get_command_line(),57 |name| self.replace_parameters_in(name),58 )59 }60

Show unused parameters in command namesDavid Peterbefore adoptiona875276

line 61why, one step back
61 pub fn get_name_with_unused_parameters(&self) -> String {

refactor: Optimize code based on cargo clippy suggestionsone230sixbefore adoptionc092135

lines 62–64why, one step back
62 let parameters = self
63 .get_unused_parameters()64 .fold(String::new(), |output, (parameter, value)| {

style: simplify string interpolationHamir Mahalbefore adoptionef12632

line 65why, one step back
65 output + &format!("{parameter} = {value}, ")

refactor: Optimize code based on cargo clippy suggestionsone230sixbefore adoptionc092135

line 66why, one step back
66 });

Show unused parameters in command namesDavid Peterbefore adoptiona875276

lines 67–70why, one step back
67 let parameters = parameters.trim_end_matches(", ");
68 let parameters = if parameters.is_empty() {69 "".into()70 } else {

style: simplify string interpolationHamir Mahalbefore adoptionef12632

line 71why, one step back
71 format!(" ({parameters})")

Show unused parameters in command namesDavid Peterbefore adoptiona875276

lines 72–76why, one step back
72 };
7374 format!("{}{}", self.get_name(), parameters)75 }76

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 77–83why, one step back
77 pub fn get_command_line(&self) -> String {
78 self.replace_parameters_in(self.expression)79 }8081 pub fn get_command(&self) -> Result<std::process::Command> {82 let command_line = self.get_command_line();83 let mut tokens = shell_words::split(&command_line)

style: simplify string interpolationHamir Mahalbefore adoptionef12632

line 84why, one step back
84 .with_context(|| format!("Failed to parse command '{command_line}'"))?

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 85–97why, one step back
85 .into_iter();
8687 if let Some(program_name) = tokens.next() {88 let mut command_builder = std::process::Command::new(program_name);89 command_builder.args(tokens);90 Ok(command_builder)91 } else {92 bail!("Can not execute empty command")93 }94 }9596 pub fn get_parameters(&self) -> &[(&'a str, ParameterValue)] {97 &self.parameters

Show unused parameters in command namesDavid Peterbefore adoptiona875276

lines 98–102why, one step back
98 }
99100 pub fn get_unused_parameters(&self) -> impl Iterator<Item = &(&'a str, ParameterValue)> {101 self.parameters102 .iter()

style: simplify string interpolationHamir Mahalbefore adoptionef12632

line 103why, one step back
103 .filter(move |(parameter, _)| !self.expression.contains(&format!("{{{parameter}}}")))

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 104–109why, one step back
104 }
105106 fn replace_parameters_in(&self, original: &str) -> String {107 let mut result = String::new();108 let mut replacements = BTreeMap::<String, String>::new();109 for (param_name, param_value) in &self.parameters {

fix: formatting in `src/command.rs`Hamir Mahalbefore adoption981db9d

line 110why, one step back
110 replacements.insert(format!("{{{param_name}}}"), param_value.to_string());

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 111–136why, one step back
111 }
112 let mut remaining = original;113 // Manually replace consecutive occurrences to avoid double-replacing: e.g.,114 //115 // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'116 //117 // should not ever run 'echo baz baz'. See `test_get_command_line_nonoverlapping`.118 'outer: while let Some(head) = remaining.chars().next() {119 for (k, v) in &replacements {120 if remaining.starts_with(k.as_str()) {121 result.push_str(v);122 remaining = &remaining[k.len()..];123 continue 'outer;124 }125 }126 result.push(head);127 remaining = &remaining[head.len_utf8()..];128 }129 result130 }131}132133/// A collection of commands that should be benchmarked134pub struct Commands<'a>(Vec<Command<'a>>);135136impl<'a> Commands<'a> {

fix build warning proposalDavid Carlierbefore adoptionf096c26

line 137why, one step back
137 pub fn from_cli_arguments(matches: &'a ArgMatches) -> Result<Commands<'a>> {

update to clap 4Benjamin Rombautbefore adoption8d38ef3

line 138why, one step back
138 let command_names = matches.get_many::<String>("command-name");

chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3

lines 139–143why, one step back
139 let command_strings = matches
140 .get_many::<String>("command")141 .unwrap_or_default()142 .map(|v| v.as_str())143 .collect::<Vec<_>>();

Shrink unsafe blockcactterbefore adoption2e8ce30

line 144why, one step back
144

update to clap 4Benjamin Rombautbefore adoption8d38ef3

line 145why, one step back
145 if let Some(args) = matches.get_many::<String>("parameter-scan") {

chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3

lines 146–148why, one step back
146 let step_size = matches
147 .get_one::<String>("parameter-step-size")148 .map(|s| s.as_str());

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 149–154why, one step back
149 Ok(Self(Self::get_parameter_scan_commands(
150 command_names,151 command_strings,152 args,153 step_size,154 )?))

update to clap 4Benjamin Rombautbefore adoption8d38ef3

line 155why, one step back
155 } else if let Some(args) = matches.get_many::<String>("parameter-list") {

chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3

lines 156–158why, one step back
156 let command_names = command_names.map_or(vec![], |names| {
157 names.map(|v| v.as_str()).collect::<Vec<_>>()158 });

update to clap 4Benjamin Rombautbefore adoption8d38ef3

line 159why, one step back
159 let args: Vec<_> = args.map(|v| v.as_str()).collect::<Vec<_>>();

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 160–175why, one step back
160 let param_names_and_values: Vec<(&str, Vec<String>)> = args
161 .chunks_exact(2)162 .map(|pair| {163 let name = pair[0];164 let list_str = pair[1];165 (name, tokenize(list_str))166 })167 .collect();168 {169 let duplicates =170 Self::find_duplicates(param_names_and_values.iter().map(|(name, _)| *name));171 if !duplicates.is_empty() {172 bail!("Duplicate parameter names: {}", &duplicates.join(", "));173 }174 }175

remove unneeded varBenjamin Rombautbefore adoptiona2e85a2

line 176why, one step back
176 let dimensions: Vec<usize> = std::iter::once(command_strings.len())

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 177–204why, one step back
177 .chain(
178 param_names_and_values179 .iter()180 .map(|(_, values)| values.len()),181 )182 .collect();183 let param_space_size = dimensions.iter().product();184 if param_space_size == 0 {185 return Ok(Self(Vec::new()));186 }187188 // `--command-name` should appear exactly once or exactly B times,189 // where B is the total number of benchmarks.190 let command_name_count = command_names.len();191 if command_name_count > 1 && command_name_count != param_space_size {192 return Err(OptionsError::UnexpectedCommandNameCount(193 command_name_count,194 param_space_size,195 )196 .into());197 }198199 let mut i = 0;200 let mut commands = Vec::with_capacity(param_space_size);201 let mut index = vec![0usize; dimensions.len()];202 'outer: loop {203 let name = command_names204 .get(i)

Fix clippy suggestionsDavid Peterbefore adoptionc7e5694

line 205why, one step back
205 .or_else(|| command_names.first())

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 206–216why, one step back
206 .copied();
207 i += 1;208209 let (command_index, params_indices) = index.split_first().unwrap();210 let parameters: Vec<_> = param_names_and_values211 .iter()212 .zip(params_indices)213 .map(|((name, values), i)| (*name, ParameterValue::Text(values[*i].clone())))214 .collect();215 commands.push(Command::new_parametrized(216 name,

remove unneeded varBenjamin Rombautbefore adoptiona2e85a2

line 217why, one step back
217 command_strings[*command_index],

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 218–234why, one step back
218 parameters,
219 ));220221 // Increment index, exiting loop on overflow.222 for (i, n) in index.iter_mut().zip(dimensions.iter()) {223 *i += 1;224 if *i < *n {225 continue 'outer;226 } else {227 *i = 0;228 }229 }230 break 'outer;231 }232233 Ok(Self(commands))234 } else {

chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3

lines 235–237why, one step back
235 let command_names = command_names.map_or(vec![], |names| {
236 names.map(|v| v.as_str()).collect::<Vec<_>>()237 });

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 238–241why, one step back
238 if command_names.len() > command_strings.len() {
239 return Err(OptionsError::TooManyCommandNames(command_strings.len()).into());240 }241

remove unneeded varBenjamin Rombautbefore adoption781a681

lines 242–243why, one step back
242 let mut commands = Vec::with_capacity(command_strings.len());
243 for (i, s) in command_strings.iter().enumerate() {

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 244–253why, one step back
244 commands.push(Command::new(command_names.get(i).copied(), s));
245 }246 Ok(Self(commands))247 }248 }249250 pub fn iter(&self) -> impl Iterator<Item = &Command<'a>> {251 self.0.iter()252 }253

Multiple output policiesDavid Peterbefore adoption99d24b7

lines 254–255why, one step back
254 pub fn num_commands(&self, has_reference_command: bool) -> usize {
255 self.0.len() + if has_reference_command { 1 } else { 0 }

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 256–297why, one step back
256 }
257258 /// Finds all the strings that appear multiple times in the input iterator, returning them in259 /// sorted order. If no string appears more than once, the result is an empty vector.260 fn find_duplicates<'b, I: IntoIterator<Item = &'b str>>(i: I) -> Vec<&'b str> {261 let mut counts = BTreeMap::<&'b str, usize>::new();262 for s in i {263 *counts.entry(s).or_default() += 1;264 }265 counts266 .into_iter()267 .filter_map(|(k, n)| if n > 1 { Some(k) } else { None })268 .collect()269 }270271 fn build_parameter_scan_commands<'b, T: Numeric>(272 param_name: &'b str,273 param_min: T,274 param_max: T,275 step: T,276 command_names: Vec<&'b str>,277 command_strings: Vec<&'b str>,278 ) -> Result<Vec<Command<'b>>, ParameterScanError> {279 let param_range = RangeStep::new(param_min, param_max, step)?;280 let param_count = param_range.size_hint().1.unwrap();281 let command_name_count = command_names.len();282283 // `--command-name` should appear exactly once or exactly B times,284 // where B is the total number of benchmarks.285 if command_name_count > 1 && command_name_count != param_count {286 return Err(ParameterScanError::UnexpectedCommandNameCount(287 command_name_count,288 param_count,289 ));290 }291292 let mut i = 0;293 let mut commands = vec![];294 for value in param_range {295 for cmd in &command_strings {296 let name = command_names297 .get(i)

Fix clippy suggestionsDavid Peterbefore adoptionc7e5694

line 298why, one step back
298 .or_else(|| command_names.first())

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 299–311why, one step back
299 .copied();
300 commands.push(Command::new_parametrized(301 name,302 cmd,303 vec![(param_name, ParameterValue::Numeric(value.into()))],304 ));305 i += 1;306 }307 }308 Ok(commands)309 }310311 fn get_parameter_scan_commands<'b>(

update to clap 4Benjamin Rombautbefore adoption8d38ef3

lines 312–314why, one step back
312 command_names: Option<ValuesRef<'b, String>>,
313 command_strings: Vec<&'b str>,314 mut vals: ValuesRef<'b, String>,

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 315–316why, one step back
315 step: Option<&str>,
316 ) -> Result<Vec<Command<'b>>, ParameterScanError> {

chore: run fmtBenjamin Rombautbefore adoptionfcaa6d3

lines 317–319why, one step back
317 let command_names = command_names.map_or(vec![], |names| {
318 names.map(|v| v.as_str()).collect::<Vec<_>>()319 });

update to clap 4Benjamin Rombautbefore adoption8d38ef3

lines 320–322why, one step back
320 let param_name = vals.next().unwrap().as_str();
321 let param_min = vals.next().unwrap().as_str();322 let param_max = vals.next().unwrap().as_str();

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 323–385why, one step back
323
324 // attempt to parse as integers325 if let (Ok(param_min), Ok(param_max), Ok(step)) = (326 param_min.parse::<i32>(),327 param_max.parse::<i32>(),328 step.unwrap_or("1").parse::<i32>(),329 ) {330 return Self::build_parameter_scan_commands(331 param_name,332 param_min,333 param_max,334 step,335 command_names,336 command_strings,337 );338 }339340 // try parsing them as decimals341 let param_min = Decimal::from_str(param_min)?;342 let param_max = Decimal::from_str(param_max)?;343344 if step.is_none() {345 return Err(ParameterScanError::StepRequired);346 }347348 let step = Decimal::from_str(step.unwrap())?;349 Self::build_parameter_scan_commands(350 param_name,351 param_min,352 param_max,353 step,354 command_names,355 command_strings,356 )357 }358}359360#[test]361fn test_get_command_line_nonoverlapping() {362 let cmd = Command::new_parametrized(363 None,364 "echo {foo} {bar}",365 vec![366 ("foo", ParameterValue::Text("{bar} baz".into())),367 ("bar", ParameterValue::Text("quux".into())),368 ],369 );370 assert_eq!(cmd.get_command_line(), "echo {bar} baz quux");371}372373#[test]374fn test_get_parameterized_command_name() {375 let cmd = Command::new_parametrized(376 Some("name-{bar}-{foo}"),377 "echo {foo} {bar}",378 vec![379 ("foo", ParameterValue::Text("baz".into())),380 ("bar", ParameterValue::Text("quux".into())),381 ],382 );383 assert_eq!(cmd.get_name(), "name-quux-baz");384}385

apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb

line 386why, one step back
386impl fmt::Display for Command<'_> {

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 387–510why, one step back
387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
388 write!(f, "{}", self.get_command_line())389 }390}391392#[test]393fn test_build_commands_cross_product() {394 use crate::cli::get_cli_arguments;395396 let matches = get_cli_arguments(vec![397 "hyperfine",398 "-L",399 "par1",400 "a,b",401 "-L",402 "par2",403 "z,y",404 "echo {par1} {par2}",405 "printf '%s\n' {par1} {par2}",406 ]);407 let result = Commands::from_cli_arguments(&matches).unwrap().0;408409 // Iteration order: command list first, then parameters in listed order (here, "par1" before410 // "par2", which is distinct from their sorted order), with parameter values in listed order.411 let pv = |s: &str| ParameterValue::Text(s.to_string());412 let cmd = |cmd: usize, par1: &str, par2: &str| {413 let expression = ["echo {par1} {par2}", "printf '%s\n' {par1} {par2}"][cmd];414 let params = vec![("par1", pv(par1)), ("par2", pv(par2))];415 Command::new_parametrized(None, expression, params)416 };417 let expected = vec![418 cmd(0, "a", "z"),419 cmd(1, "a", "z"),420 cmd(0, "b", "z"),421 cmd(1, "b", "z"),422 cmd(0, "a", "y"),423 cmd(1, "a", "y"),424 cmd(0, "b", "y"),425 cmd(1, "b", "y"),426 ];427 assert_eq!(result, expected);428}429430#[test]431fn test_build_parameter_list_commands() {432 use crate::cli::get_cli_arguments;433434 let matches = get_cli_arguments(vec![435 "hyperfine",436 "echo {foo}",437 "--parameter-list",438 "foo",439 "1,2",440 "--command-name",441 "name-{foo}",442 ]);443 let commands = Commands::from_cli_arguments(&matches).unwrap().0;444 assert_eq!(commands.len(), 2);445 assert_eq!(commands[0].get_name(), "name-1");446 assert_eq!(commands[1].get_name(), "name-2");447 assert_eq!(commands[0].get_command_line(), "echo 1");448 assert_eq!(commands[1].get_command_line(), "echo 2");449}450451#[test]452fn test_build_parameter_scan_commands() {453 use crate::cli::get_cli_arguments;454 let matches = get_cli_arguments(vec![455 "hyperfine",456 "echo {val}",457 "--parameter-scan",458 "val",459 "1",460 "2",461 "--parameter-step-size",462 "1",463 "--command-name",464 "name-{val}",465 ]);466 let commands = Commands::from_cli_arguments(&matches).unwrap().0;467 assert_eq!(commands.len(), 2);468 assert_eq!(commands[0].get_name(), "name-1");469 assert_eq!(commands[1].get_name(), "name-2");470 assert_eq!(commands[0].get_command_line(), "echo 1");471 assert_eq!(commands[1].get_command_line(), "echo 2");472}473474#[test]475fn test_parameter_scan_commands_int() {476 let commands = Commands::build_parameter_scan_commands(477 "val",478 1i32,479 7i32,480 3i32,481 vec![],482 vec!["echo {val}"],483 )484 .unwrap();485 assert_eq!(commands.len(), 3);486 assert_eq!(commands[2].get_name(), "echo 7");487 assert_eq!(commands[2].get_command_line(), "echo 7");488}489490#[test]491fn test_parameter_scan_commands_decimal() {492 let param_min = Decimal::from_str("0").unwrap();493 let param_max = Decimal::from_str("1").unwrap();494 let step = Decimal::from_str("0.33").unwrap();495496 let commands = Commands::build_parameter_scan_commands(497 "val",498 param_min,499 param_max,500 step,501 vec![],502 vec!["echo {val}"],503 )504 .unwrap();505 assert_eq!(commands.len(), 4);506 assert_eq!(commands[3].get_name(), "echo 0.99");507 assert_eq!(commands[3].get_command_line(), "echo 0.99");508}509510#[test]

Fix typo in unit test.Sendhil Panchadsarambefore adoption8c2ef10

line 511why, one step back
511fn test_parameter_scan_commands_names() {

Shrink unsafe blockcactterbefore adoption2e8ce30

lines 512–562why, one step back
512 let commands = Commands::build_parameter_scan_commands(
513 "val",514 1i32,515 3i32,516 1i32,517 vec!["name-{val}"],518 vec!["echo {val}"],519 )520 .unwrap();521 assert_eq!(commands.len(), 3);522 let command_names = commands523 .iter()524 .map(|c| c.get_name())525 .collect::<Vec<String>>();526 assert_eq!(command_names, vec!["name-1", "name-2", "name-3"]);527}528529#[test]530fn test_get_specified_command_names() {531 let commands = Commands::build_parameter_scan_commands(532 "val",533 1i32,534 3i32,535 1i32,536 vec!["name-a", "name-b", "name-c"],537 vec!["echo {val}"],538 )539 .unwrap();540 assert_eq!(commands.len(), 3);541 let command_names = commands542 .iter()543 .map(|c| c.get_name())544 .collect::<Vec<String>>();545 assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]);546}547548#[test]549fn test_different_command_name_count_with_parameters() {550 let result = Commands::build_parameter_scan_commands(551 "val",552 1i32,553 3i32,554 1i32,555 vec!["name-1", "name-2"],556 vec!["echo {val}"],557 );558 assert!(matches!(559 result.unwrap_err(),560 ParameterScanError::UnexpectedCommandNameCount(2, 3)561 ));562}